diff --git a/Cargo.lock b/Cargo.lock index b98f0dd9..9440e653 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -305,6 +305,31 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags 2.11.0", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -394,6 +419,7 @@ version = "2.0.6" dependencies = [ "anyhow", "clap", + "crossterm", "notify", "reqwest", "serde", @@ -1013,9 +1039,15 @@ dependencies = [ "bitflags 2.11.0", "libc", "plain", - "redox_syscall", + "redox_syscall 0.7.4", ] +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1028,6 +1060,15 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.29" @@ -1205,6 +1246,29 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + [[package]] name = "pbkdf2" version = "0.12.2" @@ -1363,6 +1427,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.11.0", +] + [[package]] name = "redox_syscall" version = "0.7.4" @@ -1428,6 +1501,19 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.11.0", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.52.0", +] + [[package]] name = "rustix" version = "1.1.4" @@ -1437,7 +1523,7 @@ dependencies = [ "bitflags 2.11.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.12.1", "windows-sys 0.61.2", ] @@ -1504,6 +1590,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "security-framework" version = "3.7.0" @@ -1616,6 +1708,37 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -1740,7 +1863,7 @@ dependencies = [ "fastrand", "getrandom 0.4.2", "once_cell", - "rustix", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -2118,6 +2241,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -2127,6 +2266,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" @@ -2345,7 +2490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix", + "rustix 1.1.4", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e56731d8..212b76be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" anyhow = "1" strsim = "0.11" +crossterm = "0.28" [profile.release] debug = "line-tables-only" diff --git a/crates/fastled-cli/Cargo.toml b/crates/fastled-cli/Cargo.toml index f244e404..72651a48 100644 --- a/crates/fastled-cli/Cargo.toml +++ b/crates/fastled-cli/Cargo.toml @@ -24,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } anyhow = { workspace = true } strsim = { workspace = true } +crossterm = { workspace = true } tempfile = "3" [dev-dependencies] diff --git a/crates/fastled-cli/src/build.rs b/crates/fastled-cli/src/build.rs new file mode 100644 index 00000000..888dfcc9 --- /dev/null +++ b/crates/fastled-cli/src/build.rs @@ -0,0 +1,292 @@ +//! Build orchestration for WASM compilation. +//! +//! Ports the high-level build request / result abstraction from +//! `build_types.py` and `build_service.py` to Rust. +//! +//! The actual WASM compilation remains in Python. [`run_build`] delegates +//! to `python -m fastled.app --just-compile` as a subprocess, keeping the +//! Rust layer as a thin orchestration shell. +//! +//! This module is included as a library component; the CLI main loop will +//! integrate it in a later phase. + +// Not yet wired into the CLI entry point — suppress dead-code warnings. +#![allow(dead_code)] + +use std::path::PathBuf; +use std::process::Command; +use std::time::Instant; + +use anyhow::{Context, Result}; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +/// Mirrors `BuildMode` from `types.py`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BuildMode { + Quick, + Debug, + Release, +} + +impl BuildMode { + /// Return the CLI flag string that the Python CLI expects. + pub fn as_flag(&self) -> &'static str { + match self { + BuildMode::Quick => "--quick", + BuildMode::Debug => "--debug", + BuildMode::Release => "--release", + } + } + + /// Return a human-readable label. + pub fn label(&self) -> &'static str { + match self { + BuildMode::Quick => "QUICK", + BuildMode::Debug => "DEBUG", + BuildMode::Release => "RELEASE", + } + } +} + +impl std::fmt::Display for BuildMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.label()) + } +} + +/// Mirrors `BuildRequest` from `build_types.py`. +#[derive(Debug, Clone)] +pub struct BuildRequest { + /// Directory that contains the FastLED sketch. + pub sketch_dir: PathBuf, + /// Which optimisation profile to use. + pub build_mode: BuildMode, + /// Enable C++ build-system profiling output. + pub profile: bool, + /// Optional path to a local FastLED source tree. + pub fastled_path: Option, + /// Discard cached artefacts and start from scratch. + pub force_clean: bool, +} + +impl BuildRequest { + /// Derive the conventional output directory for this request. + pub fn output_dir(&self) -> PathBuf { + self.sketch_dir.join("fastled_js") + } +} + +/// Mirrors `BuildResult` from `build_types.py`. +#[derive(Debug)] +pub struct BuildResult { + /// Whether the compilation succeeded. + pub success: bool, + /// Directory that received the compiled artefacts. + pub output_dir: PathBuf, + /// Wall-clock seconds spent in the Python subprocess. + pub duration_secs: f64, + /// Combined stdout + stderr from the Python subprocess. + pub output: String, +} + +// --------------------------------------------------------------------------- +// Subprocess helper +// --------------------------------------------------------------------------- + +/// Locate a Python executable. +/// +/// Priority order (mirrors `find_python` in `main.rs`): +/// 1. `VIRTUAL_ENV/Scripts/python.exe` (Windows) or `VIRTUAL_ENV/bin/python` +/// 2. `python` on PATH +/// 3. `python3` on PATH +fn find_python() -> String { + if let Ok(venv) = std::env::var("VIRTUAL_ENV") { + #[cfg(windows)] + let candidate = format!("{}/Scripts/python.exe", venv); + #[cfg(not(windows))] + let candidate = format!("{}/bin/python", venv); + + if std::path::Path::new(&candidate).exists() { + return candidate; + } + } + + if Command::new("python") + .args(["--version"]) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) + { + return "python".to_string(); + } + + "python3".to_string() +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Run a WASM build by calling the Python CLI as a subprocess. +/// +/// Delegates to `python -m fastled.app --just-compile [flags]`. +/// The actual Emscripten / WASM compilation stays entirely in Python; this +/// function only constructs the command, measures elapsed time, and wraps the +/// result. +pub fn run_build(request: &BuildRequest) -> Result { + let python = find_python(); + let output_dir = request.output_dir(); + + let mut cmd = Command::new(&python); + cmd.args(["-m", "fastled.app", "--just-compile"]); + cmd.arg(&request.sketch_dir); + cmd.arg(request.build_mode.as_flag()); + + if request.profile { + cmd.arg("--profile"); + } + if let Some(fp) = &request.fastled_path { + cmd.arg("--fastled-path"); + cmd.arg(fp); + } + + let start = Instant::now(); + let output = cmd + .output() + .with_context(|| format!("failed to launch `{python} -m fastled.app`"))?; + let duration_secs = start.elapsed().as_secs_f64(); + + let combined = { + let mut s = String::new(); + s.push_str(&String::from_utf8_lossy(&output.stdout)); + if !output.stderr.is_empty() { + s.push('\n'); + s.push_str(&String::from_utf8_lossy(&output.stderr)); + } + s + }; + + Ok(BuildResult { + success: output.status.success(), + output_dir, + duration_secs, + output: combined, + }) +} + +// --------------------------------------------------------------------------- +// Unit tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + // ------------------------------------------------------------------ + // BuildMode + // ------------------------------------------------------------------ + + #[test] + fn test_build_mode_flags() { + assert_eq!(BuildMode::Quick.as_flag(), "--quick"); + assert_eq!(BuildMode::Debug.as_flag(), "--debug"); + assert_eq!(BuildMode::Release.as_flag(), "--release"); + } + + #[test] + fn test_build_mode_labels() { + assert_eq!(BuildMode::Quick.label(), "QUICK"); + assert_eq!(BuildMode::Debug.label(), "DEBUG"); + assert_eq!(BuildMode::Release.label(), "RELEASE"); + } + + #[test] + fn test_build_mode_display() { + assert_eq!(format!("{}", BuildMode::Quick), "QUICK"); + assert_eq!(format!("{}", BuildMode::Debug), "DEBUG"); + assert_eq!(format!("{}", BuildMode::Release), "RELEASE"); + } + + #[test] + fn test_build_mode_equality() { + assert_eq!(BuildMode::Quick, BuildMode::Quick); + assert_ne!(BuildMode::Quick, BuildMode::Debug); + assert_ne!(BuildMode::Debug, BuildMode::Release); + } + + // ------------------------------------------------------------------ + // BuildRequest + // ------------------------------------------------------------------ + + #[test] + fn test_build_request_construction() { + let sketch = PathBuf::from("/tmp/my_sketch"); + let req = BuildRequest { + sketch_dir: sketch.clone(), + build_mode: BuildMode::Quick, + profile: false, + fastled_path: None, + force_clean: false, + }; + + assert_eq!(req.sketch_dir, sketch); + assert_eq!(req.build_mode, BuildMode::Quick); + assert!(!req.profile); + assert!(req.fastled_path.is_none()); + assert!(!req.force_clean); + } + + #[test] + fn test_build_request_output_dir() { + let sketch = PathBuf::from("/tmp/my_sketch"); + let req = BuildRequest { + sketch_dir: sketch.clone(), + build_mode: BuildMode::Debug, + profile: false, + fastled_path: None, + force_clean: false, + }; + + assert_eq!(req.output_dir(), sketch.join("fastled_js")); + } + + #[test] + fn test_build_request_with_fastled_path() { + let sketch = PathBuf::from("/tmp/my_sketch"); + let fl_path = PathBuf::from("/opt/fastled"); + let req = BuildRequest { + sketch_dir: sketch, + build_mode: BuildMode::Release, + profile: true, + fastled_path: Some(fl_path.clone()), + force_clean: true, + }; + + assert_eq!(req.fastled_path, Some(fl_path)); + assert!(req.profile); + assert!(req.force_clean); + assert_eq!(req.build_mode, BuildMode::Release); + } + + // ------------------------------------------------------------------ + // BuildResult + // ------------------------------------------------------------------ + + #[test] + fn test_build_result_fields() { + let result = BuildResult { + success: true, + output_dir: PathBuf::from("/tmp/my_sketch/fastled_js"), + duration_secs: 2.5, + output: "Build OK".to_string(), + }; + + assert!(result.success); + assert_eq!(result.duration_secs, 2.5); + assert_eq!(result.output, "Build OK"); + } +} diff --git a/crates/fastled-cli/src/keyboard.rs b/crates/fastled-cli/src/keyboard.rs new file mode 100644 index 00000000..e6d5471c --- /dev/null +++ b/crates/fastled-cli/src/keyboard.rs @@ -0,0 +1,138 @@ +//! Non-blocking keyboard input detection. +//! +//! Ports the core behaviour of `keyboard.py` (`SpaceBarWatcher`) to Rust +//! using the [`crossterm`] crate for cross-platform terminal raw-mode support. +//! +//! The public surface is intentionally minimal for Phase 2e: +//! * [`check_for_space`] — poll once and return immediately. +//! * [`start_listener`] — spawn a background thread and return a channel. +//! +//! The module is included as a library component; the CLI main loop will +//! integrate it in a later phase. + +// Not yet wired into the CLI entry point — suppress dead-code warnings. +#![allow(dead_code)] + +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; +use crossterm::terminal; + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Check once (non-blocking) whether a space bar key press is pending. +/// +/// Returns `true` if a space (or Enter) is available in the terminal event +/// queue right now; `false` otherwise. +/// +/// This function enables raw mode momentarily to read the event. If the +/// terminal is not interactive (e.g. piped stdin in CI), it returns `false` +/// rather than panicking. +pub fn check_for_space() -> bool { + // poll(Duration::ZERO) returns Ok(true) if an event is ready immediately. + match terminal::enable_raw_mode() { + Ok(()) => {} + Err(_) => return false, // Not an interactive terminal — non-fatal. + } + let result = event::poll(Duration::ZERO) + .map(|ready| { + if !ready { + return false; + } + matches!( + event::read(), + Ok(Event::Key(KeyEvent { + code: KeyCode::Char(' ') | KeyCode::Enter, + .. + })) + ) + }) + .unwrap_or(false); + let _ = terminal::disable_raw_mode(); + result +} + +/// Spawn a background thread that continuously reads keyboard events and +/// sends them through the returned channel. +/// +/// The thread exits when the channel receiver is dropped or when a +/// `Ctrl+C` / `Esc` event is received. +/// +/// # Platform notes +/// Raw mode is enabled for the duration of the listener's life. The caller +/// is responsible for disabling it if needed after the receiver is dropped. +pub fn start_listener() -> mpsc::Receiver { + let (tx, rx) = mpsc::channel::(); + + thread::spawn(move || { + if terminal::enable_raw_mode().is_err() { + return; // Not interactive — just exit the thread. + } + + loop { + // Block up to 100 ms so we can yield the thread periodically. + match event::poll(Duration::from_millis(100)) { + Ok(true) => { + if let Ok(Event::Key(key)) = event::read() { + // Quit the listener on Ctrl+C or Esc. + let is_ctrl_c = key.code == KeyCode::Char('c') + && key.modifiers.contains(KeyModifiers::CONTROL); + let is_esc = key.code == KeyCode::Esc; + + if tx.send(key).is_err() || is_ctrl_c || is_esc { + break; + } + } + } + Ok(false) => { + // Timeout — nothing to do; loop and poll again. + // The `tx.send(key).is_err()` path above handles receiver + // drop detection on the next real key event. + } + Err(_) => break, + } + } + + let _ = terminal::disable_raw_mode(); + }); + + rx +} + +// --------------------------------------------------------------------------- +// Unit tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + /// In a non-interactive test environment (no TTY), `check_for_space` + /// must return `false` without panicking. + #[test] + fn test_check_for_space_returns_false_when_no_key_pressed() { + // CI / test runners pipe stdin, so raw mode will either fail or no + // key will be available. Either way we must get `false`. + let result = check_for_space(); + assert!( + !result, + "expected false when no key pressed in non-interactive mode" + ); + } + + /// `start_listener` must return a live receiver without panicking, even + /// if the terminal is not interactive. + #[test] + fn test_start_listener_returns_receiver() { + let rx = start_listener(); + // Drop the receiver immediately; the background thread must shut down + // gracefully rather than panicking. + drop(rx); + // Give the thread a moment to exit cleanly. + std::thread::sleep(Duration::from_millis(150)); + } +} diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index 0187a936..b7e4cb56 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -2,6 +2,8 @@ use clap::Parser; use std::process::{Command, ExitCode}; mod archive; +mod build; +mod keyboard; mod project; mod watcher; diff --git a/crates/fastled-py/src/lib.rs b/crates/fastled-py/src/lib.rs index ed8c242f..62d64ec2 100644 --- a/crates/fastled-py/src/lib.rs +++ b/crates/fastled-py/src/lib.rs @@ -47,6 +47,19 @@ fn project_available() -> bool { true } +/// Return whether the native Rust build orchestration module is available in +/// this build. +/// +/// ```python +/// from fastled._native import build_available +/// if build_available(): +/// print("native build orchestration ready") +/// ``` +#[pyfunction] +fn build_available() -> bool { + true +} + /// FastLED native extension module. #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { @@ -54,5 +67,6 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(watch_available, m)?)?; m.add_function(wrap_pyfunction!(archive_available, m)?)?; m.add_function(wrap_pyfunction!(project_available, m)?)?; + m.add_function(wrap_pyfunction!(build_available, m)?)?; Ok(()) }