Skip to content
Closed
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
7 changes: 5 additions & 2 deletions crates/fastled-cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ 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(&output_dir) {
// Point the viewer at the HTTP server, not the artifact directory:
// the server hosts the loading page + SSE build stream while
// index.html does not exist yet (#151).
let _viewer = match viewer::launch_tauri_viewer(&url) {
Ok(process) => process,
Err(e) => {
eprintln!("fastled: Tauri viewer failed: {e:#}");
Expand Down Expand Up @@ -379,7 +382,7 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode {
println!("Press Ctrl+C to stop...");

let _viewer = if launch_viewer {
match viewer::launch_tauri_viewer(&path) {
match viewer::launch_tauri_viewer(&url) {
Ok(process) => Some(process),
Err(e) => {
eprintln!("fastled: Tauri viewer failed: {e:#}");
Expand Down
28 changes: 13 additions & 15 deletions crates/fastled-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::path::PathBuf;
use std::process::ExitCode;

#[cfg(feature = "viewer")]
mod tauri_viewer;

struct InternalViewerArgs {
frontend_dir: PathBuf,
url: String,
title: String,
width: u32,
height: u32,
Expand All @@ -14,16 +13,22 @@ struct InternalViewerArgs {
fn parse_internal_viewer_args() -> Option<Result<InternalViewerArgs, String>> {
let mut args = std::env::args_os().skip(1);
let first = args.next()?;
if first != "--internal-viewer" {
if first != "--internal-viewer-url" {
return None;
}

let Some(frontend_dir) = args.next() else {
return Some(Err("--internal-viewer requires a directory".to_string()));
let Some(url) = args.next() else {
return Some(Err("--internal-viewer-url requires a URL".to_string()));
};
let url = url.to_string_lossy().into_owned();
if !url.starts_with("http://") && !url.starts_with("https://") {
return Some(Err(format!(
"--internal-viewer-url must be an http(s) URL, got: {url}"
)));
}

let mut parsed = InternalViewerArgs {
frontend_dir: PathBuf::from(frontend_dir),
url,
title: "FastLED Viewer".to_string(),
width: 800,
height: 600,
Expand Down Expand Up @@ -65,18 +70,10 @@ fn parse_internal_viewer_args() -> Option<Result<InternalViewerArgs, String>> {
}

fn run_internal_viewer(args: InternalViewerArgs) -> ExitCode {
if !args.frontend_dir.is_dir() {
eprintln!(
"fastled: --internal-viewer path does not exist: {}",
args.frontend_dir.display()
);
return ExitCode::FAILURE;
}

#[cfg(feature = "viewer")]
{
tauri_viewer::run(tauri_viewer::ViewerOptions {
frontend_dir: args.frontend_dir,
url: args.url,
title: args.title,
width: args.width,
height: args.height,
Expand All @@ -85,6 +82,7 @@ fn run_internal_viewer(args: InternalViewerArgs) -> ExitCode {

#[cfg(not(feature = "viewer"))]
{
let _ = args;
eprintln!("fastled: this fastled binary was built without viewer support");
ExitCode::FAILURE
}
Expand Down
67 changes: 9 additions & 58 deletions crates/fastled-cli/src/tauri_viewer.rs
Original file line number Diff line number Diff line change
@@ -1,75 +1,26 @@
use std::path::PathBuf;
use std::process::ExitCode;

pub struct ViewerOptions {
pub frontend_dir: PathBuf,
/// HTTP URL of the embedded fastled server (e.g. `http://127.0.0.1:8089/`).
///
/// The viewer must load the server URL — not files off disk — so the
/// loading page, SSE build stream, and post-build reload all work while
/// `index.html` does not exist yet (issue #151).
pub url: String,
pub title: String,
pub width: u32,
pub height: u32,
}

pub fn run(options: ViewerOptions) -> ExitCode {
let mut builder = tauri::Builder::default();
let serve_dir = options.frontend_dir.clone();

builder = builder.register_asynchronous_uri_scheme_protocol(
"fastled",
move |_ctx, request, responder| {
let path = request.uri().path();
let relative = path.trim_start_matches('/');
let relative = if relative.is_empty() {
"index.html"
} else {
relative
};
let file_path = serve_dir.join(relative);

let mime = match file_path.extension().and_then(|e| e.to_str()).unwrap_or("") {
"html" => "text/html",
"js" => "application/javascript",
"wasm" => "application/wasm",
"css" => "text/css",
"json" => "application/json",
"png" => "image/png",
"svg" => "image/svg+xml",
"ico" => "image/x-icon",
"ttf" | "otf" => "font/ttf",
"woff" => "font/woff",
"woff2" => "font/woff2",
"map" => "application/json",
_ => "application/octet-stream",
};

match std::fs::read(&file_path) {
Ok(data) => {
let response = tauri::http::Response::builder()
.status(200)
.header("Content-Type", mime)
.header("Cross-Origin-Opener-Policy", "same-origin")
.header("Cross-Origin-Embedder-Policy", "require-corp")
.body(data)
.unwrap();
responder.respond(response);
}
Err(_) => {
let response = tauri::http::Response::builder()
.status(404)
.body(b"Not Found".to_vec())
.unwrap();
responder.respond(response);
}
}
},
);

let title = options.title;
let width = options.width;
let height = options.height;
let url = options.url;

let result = builder
let result = tauri::Builder::default()
.setup(move |app| {
let url =
tauri::WebviewUrl::CustomProtocol("fastled://localhost/index.html".parse()?);
let url = tauri::WebviewUrl::External(url.parse()?);

let window = tauri::WebviewWindowBuilder::new(app, "main", url)
.title(&title)
Expand Down
42 changes: 26 additions & 16 deletions crates/fastled-cli/src/viewer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Tauri viewer launch utilities.
//!
//! The viewer is hosted by this same `fastled` executable. The normal CLI
//! process self-spawns with a hidden `--internal-viewer` flag so packaging only
//! process self-spawns with a hidden `--internal-viewer-url` flag so packaging only
//! needs one binary while the Tauri event loop still runs in its own process.

use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -162,11 +162,11 @@ impl Drop for ViewerProcess {
}

#[cfg(any(not(windows), test))]
fn viewer_command(binary: &Path, frontend_dir: &Path) -> Command {
fn viewer_command(binary: &Path, server_url: &str) -> Command {
let mut command = Command::new(binary);
command
.arg("--internal-viewer")
.arg(frontend_dir)
.arg("--internal-viewer-url")
.arg(server_url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
Expand Down Expand Up @@ -214,13 +214,13 @@ fn quote_windows_arg(arg: &std::ffi::OsStr) -> String {
}

#[cfg(windows)]
fn viewer_command_line(binary: &Path, frontend_dir: &Path) -> Vec<u16> {
fn viewer_command_line(binary: &Path, server_url: &str) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;

let args = [
binary.as_os_str(),
std::ffi::OsStr::new("--internal-viewer"),
frontend_dir.as_os_str(),
std::ffi::OsStr::new("--internal-viewer-url"),
std::ffi::OsStr::new(server_url),
];
let command_line = args
.iter()
Expand All @@ -234,7 +234,7 @@ fn viewer_command_line(binary: &Path, frontend_dir: &Path) -> Vec<u16> {
}

#[cfg(windows)]
fn spawn_hidden_viewer(binary: &Path, frontend_dir: &Path) -> Result<ViewerProcess> {
fn spawn_hidden_viewer(binary: &Path, server_url: &str) -> Result<ViewerProcess> {
use std::mem::{size_of, zeroed};
use std::ptr::{null, null_mut};

Expand Down Expand Up @@ -278,7 +278,7 @@ fn spawn_hidden_viewer(binary: &Path, frontend_dir: &Path) -> Result<ViewerProce
startup_info.wShowWindow = 0; // SW_HIDE

let mut process_info: PROCESS_INFORMATION = unsafe { zeroed() };
let mut command_line = viewer_command_line(binary, frontend_dir);
let mut command_line = viewer_command_line(binary, server_url);
let flags = VIEWER_CREATION_FLAGS | CREATE_SUSPENDED;
let create_ok = unsafe {
CreateProcessW(
Expand Down Expand Up @@ -338,28 +338,32 @@ fn spawn_hidden_viewer(binary: &Path, frontend_dir: &Path) -> Result<ViewerProce
})
}

/// Spawn the Tauri viewer, pointing it at `frontend_dir`.
/// Spawn the Tauri viewer, pointing it at the embedded HTTP server URL.
///
/// The viewer must load the server URL rather than artifacts off disk so the
/// loading page, SSE build stream, and post-build reload work before the
/// first compile finishes (issue #151).
///
/// The viewer is launched without inheriting or creating a terminal window, but
/// it remains contained by this process. Keep the returned [`ViewerProcess`]
/// alive while FastLED is serving; if FastLED exits or is killed, the
/// viewer/WebView2 process tree is torn down too.
///
/// Returns a process handle whose lifetime controls the viewer lifetime.
pub fn launch_tauri_viewer(frontend_dir: &std::path::Path) -> Result<ViewerProcess> {
pub fn launch_tauri_viewer(server_url: &str) -> Result<ViewerProcess> {
let binary =
find_tauri_viewer().context("fastled binary not found; cannot launch Tauri viewer")?;

#[cfg(windows)]
{
spawn_hidden_viewer(&binary, frontend_dir)
spawn_hidden_viewer(&binary, server_url)
}

#[cfg(not(windows))]
{
let group =
ContainedProcessGroup::new().context("failed to create viewer process group")?;
let mut command = viewer_command(&binary, frontend_dir);
let mut command = viewer_command(&binary, server_url);
let stdio = SpawnStdio {
stdin: StdioSource::Null,
stdout: StdioSource::Null,
Expand Down Expand Up @@ -510,14 +514,20 @@ mod tests {
assert!(find_viewer_in_arch_dirs(&missing).is_none());
}

/// Guards the instant-launch wiring (#151): the viewer must be spawned
/// with the HTTP server URL so it can render the loading page and SSE
/// build stream before `index.html` exists — never a bare directory path.
#[test]
fn test_viewer_command_uses_internal_viewer_flag() {
let command = viewer_command(Path::new(FASTLED_EXE_NAMES[0]), Path::new("out"));
fn test_viewer_command_uses_internal_viewer_url_flag() {
let command = viewer_command(Path::new(FASTLED_EXE_NAMES[0]), "http://127.0.0.1:8089/");
let args = command
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>();
assert_eq!(args, vec!["--internal-viewer", "out"]);
assert_eq!(
args,
vec!["--internal-viewer-url", "http://127.0.0.1:8089/"]
);
}

#[test]
Expand Down
Loading