diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index b7e4cb56..9377ccdc 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -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. @@ -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, @@ -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 { +/// +/// 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 { let mut args: Vec = Vec::new(); if let Some(dir) = &cli.directory { @@ -147,13 +168,15 @@ fn rebuild_python_args(cli: &Cli) -> Vec { 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 { @@ -199,25 +222,89 @@ fn rebuild_python_args(cli: &Cli) -> Vec { 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 `/fastled_js`. +fn output_dir_from_cli(cli: &Cli) -> Option { + 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 } diff --git a/crates/fastled-cli/src/viewer.rs b/crates/fastled-cli/src/viewer.rs new file mode 100644 index 00000000..8143a861 --- /dev/null +++ b/crates/fastled-cli/src/viewer.rs @@ -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 { + // 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 { + 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 { + 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(); + } +} diff --git a/crates/fastled-py/src/lib.rs b/crates/fastled-py/src/lib.rs index 62d64ec2..a176ae54 100644 --- a/crates/fastled-py/src/lib.rs +++ b/crates/fastled-py/src/lib.rs @@ -1,4 +1,69 @@ use pyo3::prelude::*; +use std::path::PathBuf; +use std::process::Command; + +// --------------------------------------------------------------------------- +// Internal: Tauri viewer discovery (mirrors viewer.rs in fastled-cli) +// --------------------------------------------------------------------------- + +#[cfg(windows)] +const VIEWER_EXE: &str = "fastled-viewer.exe"; +#[cfg(not(windows))] +const VIEWER_EXE: &str = "fastled-viewer"; + +fn find_tauri_viewer_path() -> Option { + // 1. Sibling of the running shared library / 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 looking for a Cargo workspace root, + // then check target/debug and target/release. + if let Some(root) = find_workspace_root_py() { + for profile in &["debug", "release"] { + let candidate = root.join("target").join(profile).join(VIEWER_EXE); + if candidate.is_file() { + return Some(candidate); + } + } + } + + // 3. PATH lookup. + let on_path = Command::new(VIEWER_EXE) + .arg("--version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false); + if on_path { + return Some(PathBuf::from(VIEWER_EXE)); + } + + None +} + +fn find_workspace_root_py() -> Option { + 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 +} + +// --------------------------------------------------------------------------- +// PyO3 functions +// --------------------------------------------------------------------------- /// Return the native module version. #[pyfunction] @@ -60,6 +125,22 @@ fn build_available() -> bool { true } +/// Return whether the native Tauri viewer binary (`fastled-viewer`) can be +/// found alongside the CLI, in the Cargo target directory, or on PATH. +/// +/// Python callers can use this to decide whether to prefer the native viewer +/// over the legacy Flask + Playwright browser experience. +/// +/// ```python +/// from fastled._native import viewer_available +/// if viewer_available(): +/// print("native viewer ready") +/// ``` +#[pyfunction] +fn viewer_available() -> bool { + find_tauri_viewer_path().is_some() +} + /// FastLED native extension module. #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { @@ -68,5 +149,6 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(archive_available, m)?)?; m.add_function(wrap_pyfunction!(project_available, m)?)?; m.add_function(wrap_pyfunction!(build_available, m)?)?; + m.add_function(wrap_pyfunction!(viewer_available, m)?)?; Ok(()) }