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
42 changes: 37 additions & 5 deletions crates/fastled-cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode {
let url = format!("http://{addr}");
println!("Serving at {url}");

let _viewer = match viewer::launch_tauri_viewer(&url) {
let mut viewer = match viewer::launch_tauri_viewer(&url) {
Ok(process) => process,
Err(e) => {
eprintln!("fastled: Tauri viewer failed: {e:#}");
Expand Down Expand Up @@ -115,6 +115,15 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode {
let rx = file_watcher.start();

loop {
// The viewer window is the app from the user's perspective: once
// it is gone (closed or crashed), shut the CLI down cleanly. An
// in-flight compile always finishes first because this check only
// runs between loop ticks.
if !viewer.is_alive() {
println!("\nViewer window closed; shutting down.");
break;
}

let should_rebuild = match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(changed) => {
println!("\nChanges detected in {changed:?}");
Expand Down Expand Up @@ -355,7 +364,7 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode {
println!("Serving {dir} at {url}");
println!("Press Ctrl+C to stop...");

let _viewer = if launch_viewer {
let viewer = if launch_viewer {
match viewer::launch_tauri_viewer(&url) {
Ok(process) => Some(process),
Err(e) => {
Expand All @@ -367,9 +376,32 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode {
None
};

// Wait for Ctrl+C.
tokio::signal::ctrl_c().await.ok();
println!("\nShutting down...");
match viewer {
Some(mut viewer) => {
// Exit on Ctrl+C or when the viewer window is closed.
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
loop {
tokio::select! {
_ = &mut ctrl_c => {
println!("\nShutting down...");
break;
}
_ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {
if !viewer.is_alive() {
println!("\nViewer window closed; shutting down.");
break;
}
}
}
}
}
None => {
// Headless serve has no viewer to watch; run until Ctrl+C.
tokio::signal::ctrl_c().await.ok();
println!("\nShutting down...");
}
}
ExitCode::SUCCESS
})
}
Expand Down
40 changes: 33 additions & 7 deletions crates/fastled-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,9 @@ pub fn run() -> ExitCode {
return commands::run_internal_dwarf_smoke(&cli);
}

if let Some(ref serve_dir) = cli.internal_serve_dir_headless {
return commands::serve_directory(serve_dir, false);
}

// Handle --serve-dir natively with the Rust HTTP server (no Python needed).
if let Some(ref serve_dir) = cli.serve_dir {
return commands::serve_directory(serve_dir, true);
// Handle serve-dir modes natively with the Rust HTTP server.
if let Some((serve_dir, launch_viewer)) = serve_dir_request(&cli) {
return commands::serve_directory(serve_dir, launch_viewer);
}

if cli.install {
Expand Down Expand Up @@ -138,6 +134,17 @@ pub fn run() -> ExitCode {
ExitCode::FAILURE
}

/// Map serve-dir CLI flags to `(directory, launch_viewer)`.
///
/// `--internal-serve-dir-headless` is the no-UI serve path: it never launches
/// a viewer, so viewer-exit shutdown can never apply to it.
fn serve_dir_request(cli: &cli::Cli) -> Option<(&str, bool)> {
if let Some(ref dir) = cli.internal_serve_dir_headless {
return Some((dir, false));
}
cli.serve_dir.as_deref().map(|dir| (dir, true))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -198,6 +205,25 @@ mod tests {
}
}

#[test]
fn serve_dir_request_headless_never_launches_viewer() {
let mut cli = base_cli();
cli.internal_serve_dir_headless = Some("some/dir".to_string());
assert_eq!(serve_dir_request(&cli), Some(("some/dir", false)));
}

#[test]
fn serve_dir_request_serve_dir_launches_viewer() {
let mut cli = base_cli();
cli.serve_dir = Some("some/dir".to_string());
assert_eq!(serve_dir_request(&cli), Some(("some/dir", true)));
}

#[test]
fn serve_dir_request_none_without_serve_flags() {
assert_eq!(serve_dir_request(&base_cli()), None);
}

#[test]
fn collect_debug_source_paths_finds_wasm_and_source_map_entries() {
let temp = tempfile::tempdir().expect("tempdir");
Expand Down
92 changes: 92 additions & 0 deletions crates/fastled-cli/src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,33 @@ impl ViewerProcess {
pub fn pid(&self) -> u32 {
self.child.id()
}

/// Non-blocking liveness probe: `true` while the viewer process is still
/// running, `false` once it has exited (window closed or crashed).
#[cfg(windows)]
pub fn is_alive(&mut self) -> bool {
process_handle_is_alive(self.process)
}

/// Non-blocking liveness probe: `true` while the viewer process is still
/// running, `false` once it has exited (window closed or crashed).
///
/// Reaping the child here is safe: the surviving
/// [`ContainedProcessGroup`] kill-on-drop is a best-effort `killpg`, so a
/// reaped leader does not break group cleanup.
#[cfg(not(windows))]
pub fn is_alive(&mut self) -> bool {
// An error from try_wait means we can no longer observe the child;
// treat it as dead so the CLI shuts down instead of running forever.
!matches!(self.child.try_wait(), Ok(Some(_)) | Err(_))
}
}

#[cfg(windows)]
fn process_handle_is_alive(process: windows_sys::Win32::Foundation::HANDLE) -> bool {
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
unsafe { WaitForSingleObject(process, 0) == WAIT_TIMEOUT }
}

#[cfg(windows)]
Expand Down Expand Up @@ -526,4 +553,69 @@ mod tests {
assert_eq!(VIEWER_CREATION_FLAGS & 0x0800_0000, 0x0800_0000);
assert_eq!(VIEWER_CREATION_FLAGS & 0x0000_0200, 0x0000_0200);
}

#[test]
#[cfg(windows)]
fn test_process_handle_liveness_alive_to_dead() {
use std::os::windows::io::AsRawHandle;

// ping -n 5 keeps the child alive for several seconds.
let mut child = Command::new("ping")
.args(["-n", "5", "127.0.0.1"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn ping");
let handle = child.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;

assert!(
process_handle_is_alive(handle),
"expected freshly spawned process to be alive"
);

child.kill().expect("kill ping");
child.wait().expect("wait ping");

assert!(
!process_handle_is_alive(handle),
"expected exited process to be dead"
);
}

#[test]
#[cfg(not(windows))]
fn test_viewer_process_is_alive_alive_to_dead() {
let group = ContainedProcessGroup::new().expect("process group");
let mut command = Command::new("sleep");
command.arg("30");
let stdio = SpawnStdio {
stdin: StdioSource::Null,
stdout: StdioSource::Null,
stderr: StdioSource::Null,
..SpawnStdio::default()
};
let child = group.spawn(&mut command, stdio).expect("spawn sleep");
let mut viewer = ViewerProcess {
_group: group,
child,
};

assert!(
viewer.is_alive(),
"expected freshly spawned process to be alive"
);

viewer.child.kill().expect("kill sleep");

// The kill is asynchronous from the probe's perspective; poll briefly.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while viewer.is_alive() {
assert!(
std::time::Instant::now() < deadline,
"expected killed process to be observed dead within 5s"
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
}
}
Loading