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
4 changes: 2 additions & 2 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(&output_dir) {
let _viewer = match viewer::launch_tauri_viewer(&url) {
Ok(process) => process,
Err(e) => {
eprintln!("fastled: Tauri viewer failed: {e:#}");
Expand Down Expand Up @@ -356,7 +356,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
17 changes: 8 additions & 9 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 @@ -18,12 +17,12 @@ fn parse_internal_viewer_args() -> Option<Result<InternalViewerArgs, String>> {
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 requires a URL".to_string()));
};

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

fn run_internal_viewer(args: InternalViewerArgs) -> ExitCode {
if !args.frontend_dir.is_dir() {
if !args.url.starts_with("http://") && !args.url.starts_with("https://") {
eprintln!(
"fastled: --internal-viewer path does not exist: {}",
args.frontend_dir.display()
"fastled: --internal-viewer requires an http(s) URL, got: {}",
args.url
);
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 Down
72 changes: 10 additions & 62 deletions crates/fastled-cli/src/tauri_viewer.rs
Original file line number Diff line number Diff line change
@@ -1,75 +1,23 @@
use std::path::PathBuf;
use std::process::ExitCode;

pub struct ViewerOptions {
pub frontend_dir: PathBuf,
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 result = builder
let ViewerOptions {
url,
title,
width,
height,
} = options;

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
24 changes: 12 additions & 12 deletions crates/fastled-cli/src/viewer.rs
Original file line number Diff line number Diff line change
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, url: &str) -> Command {
let mut command = Command::new(binary);
command
.arg("--internal-viewer")
.arg(frontend_dir)
.arg(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, 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(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, 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, url);
let flags = VIEWER_CREATION_FLAGS | CREATE_SUSPENDED;
let create_ok = unsafe {
CreateProcessW(
Expand Down Expand Up @@ -338,28 +338,28 @@ 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 FastLED HTTP server `url`.
///
/// 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(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, 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, url);
let stdio = SpawnStdio {
stdin: StdioSource::Null,
stdout: StdioSource::Null,
Expand Down Expand Up @@ -512,12 +512,12 @@ mod tests {

#[test]
fn test_viewer_command_uses_internal_viewer_flag() {
let command = viewer_command(Path::new(FASTLED_EXE_NAMES[0]), Path::new("out"));
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", "http://127.0.0.1:8089"]);
}

#[test]
Expand Down
Loading