Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 93 additions & 6 deletions crates/fastled-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use clap::Parser;
use std::path::PathBuf;
use std::process::{Command, ExitCode};

mod archive;
mod build;
mod keyboard;
mod project;
mod viewer;
mod watcher;

/// FastLED WASM compilation CLI.
Expand Down Expand Up @@ -46,6 +48,11 @@ struct Cli {
#[arg(long)]
app: bool,

/// Force the legacy Flask + browser viewer even when the native Tauri
/// viewer is available. Has no effect unless `--app` is also passed.
#[arg(long)]
legacy_browser: bool,

/// Install the FastLED development environment with VSCode configuration.
#[arg(long)]
install: bool,
Expand Down Expand Up @@ -128,9 +135,23 @@ fn find_python() -> String {
"python3".to_string()
}

/// Decide whether to use the native Tauri viewer for this invocation.
///
/// Returns `true` when:
/// * `--app` was requested, AND
/// * `--legacy-browser` was NOT passed, AND
/// * the `fastled-viewer` binary can be found.
fn should_use_tauri_viewer(cli: &Cli) -> bool {
cli.app && !cli.legacy_browser && viewer::viewer_available()
}

/// Convert the parsed `Cli` struct back into the argv that the Python CLI
/// expects, so we can pass it through verbatim.
fn rebuild_python_args(cli: &Cli) -> Vec<String> {
///
/// When `tauri_viewer` is `true` the Python process is asked only to compile
/// (via `--just-compile`); the Rust caller will subsequently launch the Tauri
/// viewer instead of delegating browser launching to Python.
fn rebuild_python_args(cli: &Cli, tauri_viewer: bool) -> Vec<String> {
let mut args: Vec<String> = Vec::new();

if let Some(dir) = &cli.directory {
Expand All @@ -147,13 +168,15 @@ fn rebuild_python_args(cli: &Cli) -> Vec<String> {
args.push(init_val.clone());
}
}
if cli.just_compile {
// When Tauri viewer is handling display, tell Python to only compile.
if cli.just_compile || tauri_viewer {
args.push("--just-compile".to_string());
}
if cli.profile {
args.push("--profile".to_string());
}
if cli.app {
// Pass --app through only when we are NOT taking over with the Tauri viewer.
if cli.app && !tauri_viewer {
args.push("--app".to_string());
}
if cli.install {
Expand Down Expand Up @@ -199,25 +222,89 @@ fn rebuild_python_args(cli: &Cli) -> Vec<String> {
args
}

/// Derive the expected build output directory from CLI arguments.
///
/// Mirrors `BuildRequest::output_dir()` in `build.rs`: the Python CLI always
/// writes compiled artefacts to `<sketch_dir>/fastled_js`.
fn output_dir_from_cli(cli: &Cli) -> Option<PathBuf> {
cli.directory
.as_ref()
.map(|d| PathBuf::from(d).join("fastled_js"))
}

fn main() -> ExitCode {
let cli = Cli::parse();

let use_tauri = should_use_tauri_viewer(&cli);

if use_tauri {
eprintln!("fastled: native Tauri viewer detected — compiling then launching viewer");
}

let python = find_python();
let py_args = rebuild_python_args(&cli);
let py_args = rebuild_python_args(&cli, use_tauri);

let status = Command::new(&python)
.args(["-m", "fastled.app"])
.args(&py_args)
.status();

match status {
let exit_code = match status {
Ok(s) => {
let code = s.code().unwrap_or(1);
ExitCode::from(code as u8)
}
Err(e) => {
eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}");
ExitCode::FAILURE
return ExitCode::FAILURE;
}
};

// If we are driving the Tauri viewer and the Python compile step succeeded,
// launch the native viewer pointing at the build output directory.
if use_tauri && exit_code == ExitCode::SUCCESS {
if let Some(out_dir) = output_dir_from_cli(&cli) {
match viewer::launch_tauri_viewer(&out_dir) {
Ok(mut child) => {
// Wait for the viewer to exit so the terminal session stays
// alive until the user closes the window.
let viewer_status = child.wait();
match viewer_status {
Ok(s) => {
let code = s.code().unwrap_or(1);
return ExitCode::from(code as u8);
}
Err(e) => {
eprintln!("fastled: error waiting for viewer: {e}");
return ExitCode::FAILURE;
}
}
}
Err(e) => {
eprintln!("fastled: failed to launch Tauri viewer: {e}");
eprintln!("fastled: falling back to legacy Flask browser");
// Re-run Python without --just-compile to use Flask fallback.
let fallback_args = rebuild_python_args(&cli, false);
let fallback_status = Command::new(&python)
.args(["-m", "fastled.app"])
.args(&fallback_args)
.status();
return match fallback_status {
Ok(s) => ExitCode::from(s.code().unwrap_or(1) as u8),
Err(e2) => {
eprintln!(
"fastled: fallback also failed to launch `{python} -m fastled.app`: {e2}"
);
ExitCode::FAILURE
}
};
}
}
} else {
eprintln!("fastled: --app with Tauri viewer requires a sketch directory argument");
return ExitCode::FAILURE;
}
}

exit_code
}
159 changes: 159 additions & 0 deletions crates/fastled-cli/src/viewer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! Tauri viewer discovery and launch utilities.
//!
//! Provides [`find_tauri_viewer`] to locate the `fastled-viewer` binary and
//! [`launch_tauri_viewer`] to spawn it against a compiled output directory.

use std::path::PathBuf;
use std::process::{Child, Command};

use anyhow::{Context, Result};

// ---------------------------------------------------------------------------
// Binary name (platform-aware)
// ---------------------------------------------------------------------------

#[cfg(windows)]
const VIEWER_EXE: &str = "fastled-viewer.exe";
#[cfg(not(windows))]
const VIEWER_EXE: &str = "fastled-viewer";

// ---------------------------------------------------------------------------
// Discovery
// ---------------------------------------------------------------------------

/// Search for the `fastled-viewer` (Tauri) binary.
///
/// Search order:
/// 1. Same directory as the currently running executable.
/// 2. `target/debug/` relative to the workspace root (detected via the
/// executable path heuristic or `CARGO_MANIFEST_DIR`).
/// 3. `target/release/` via the same heuristic.
/// 4. `PATH` — `which`-style lookup via [`Command::new`].
///
/// Returns `None` if the binary cannot be found.
pub fn find_tauri_viewer() -> Option<PathBuf> {
// 1. Sibling of the running executable.
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
let candidate = dir.join(VIEWER_EXE);
if candidate.is_file() {
return Some(candidate);
}
}
}

// 2. Walk up from the current executable to find a Cargo workspace root
// (directory that contains a `Cargo.toml` with `[workspace]`), then
// check `target/debug` and `target/release`.
if let Some(workspace_root) = find_workspace_root() {
for profile in &["debug", "release"] {
let candidate = workspace_root.join("target").join(profile).join(VIEWER_EXE);
if candidate.is_file() {
return Some(candidate);
}
}
}

// 3. Fall back to PATH lookup.
if is_on_path(VIEWER_EXE) {
// Return just the bare name so the OS resolves it through PATH.
return Some(PathBuf::from(VIEWER_EXE));
}

None
}

/// Return `true` when the Tauri viewer binary can be found.
#[inline]
pub fn viewer_available() -> bool {
find_tauri_viewer().is_some()
}

// ---------------------------------------------------------------------------
// Launch
// ---------------------------------------------------------------------------

/// Spawn the Tauri viewer, pointing it at `frontend_dir`.
///
/// The viewer is launched as a **detached child process** — the caller is not
/// expected to `wait()` on it; FastLED will keep running (serving files, etc.)
/// alongside the viewer window.
///
/// Returns the [`Child`] handle so the caller can optionally monitor the
/// process lifetime.
pub fn launch_tauri_viewer(frontend_dir: &std::path::Path) -> Result<Child> {
let binary = find_tauri_viewer()
.context("fastled-viewer binary not found; cannot launch Tauri viewer")?;

let child = Command::new(&binary)
.arg("--frontend-dir")
.arg(frontend_dir)
.spawn()
.with_context(|| format!("failed to spawn fastled-viewer from '{}'", binary.display()))?;

Ok(child)
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Walk up the filesystem from the current executable until a directory
/// containing a `Cargo.toml` file is found. This is a heuristic to locate
/// the workspace root during development; it will gracefully return `None` in
/// production installs where there is no `Cargo.toml`.
fn find_workspace_root() -> Option<PathBuf> {
let start = std::env::current_exe().ok()?;
let mut dir = start.parent()?.to_path_buf();

for _ in 0..10 {
if dir.join("Cargo.toml").is_file() {
return Some(dir.clone());
}
match dir.parent() {
Some(p) => dir = p.to_path_buf(),
None => break,
}
}
None
}

/// Check whether `name` resolves on PATH by attempting a no-op invocation.
fn is_on_path(name: &str) -> bool {
Command::new(name)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_viewer_available_does_not_panic() {
// We don't assert a specific value — the binary may or may not be
// present in CI. We only verify no panic occurs.
let _ = viewer_available();
}

#[test]
fn test_find_tauri_viewer_returns_option() {
// Same as above: just confirm the function runs without panicking.
let result = find_tauri_viewer();
// If found, the path must have a file name component.
if let Some(p) = result {
assert!(p.file_name().is_some(), "expected a non-empty path");
}
}

#[test]
fn test_find_workspace_root_does_not_panic() {
let _ = find_workspace_root();
}
}
Loading
Loading