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
84 changes: 2 additions & 82 deletions crates/fastled-cli/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ const FASTLED_REPO: &str = "FastLED/FastLED";
const FASTLED_LATEST_RELEASE_API: &str =
"https://api.github.com/repos/FastLED/FastLED/releases/latest";

const CHROME_CRX_URL: &str = "https://clients2.google.com/service/update2/crx?response=redirect&prodversion=114.0&acceptformat=crx2,crx3&x=id%3D{ID}%26uc";
const CHROME_USER_AGENT: &str =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36";

fn fastled_root() -> Result<PathBuf> {
let home = dirs::home_dir().context("cannot resolve home directory")?;
Ok(home.join(".fastled"))
Expand Down Expand Up @@ -403,82 +399,6 @@ pub fn ensure_fastled_repo(ref_opt: Option<&str>) -> Result<PathBuf> {
Ok(repo_dir)
}

// ---------------------------------------------------------------------------
// Chrome extension (CRX) download
// ---------------------------------------------------------------------------

/// Download a CRX from the Chrome Web Store, strip the CRX header, extract
/// the embedded ZIP into ``~/.fastled/chrome-extensions/{name}/``, and return
/// the install path.
///
/// Reuses the cached extension if `manifest.json` already exists at the
/// destination.
pub fn ensure_chrome_extension(extension_id: &str, name: &str) -> Result<PathBuf> {
let root = fastled_root()?;
let install_dir = root.join("chrome-extensions").join(name);
if install_dir.join("manifest.json").is_file() {
return Ok(install_dir);
}
fs::create_dir_all(&install_dir)
.with_context(|| format!("create chrome extension dir {}", install_dir.display()))?;

let crx_url = CHROME_CRX_URL.replace("{ID}", extension_id);

let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::limited(10))
.build()
.context("failed to build HTTP client for CRX download")?;

let bytes = client
.get(&crx_url)
.header("User-Agent", CHROME_USER_AGENT)
.header("Referer", "https://chrome.google.com")
.send()
.with_context(|| format!("GET {crx_url} failed"))?
.error_for_status()
.with_context(|| format!("CRX download returned error for {crx_url}"))?
.bytes()
.context("read CRX body")?;

// CRX file starts with a header; find the embedded ZIP magic.
let buf: &[u8] = &bytes;
let zip_start = find_zip_start(buf)
.with_context(|| format!("no ZIP magic found in CRX for {extension_id}"))?;

// Write the ZIP portion to a temp file and extract.
let tmp_zip = tempfile::NamedTempFile::new().context("create temp zip for CRX extraction")?;
{
use std::io::Write;
let mut handle = tmp_zip.as_file();
handle
.write_all(&buf[zip_start..])
.context("write CRX zip portion")?;
handle.flush().ok();
}
archive::extract_zip(tmp_zip.path(), &install_dir)?;

if !install_dir.join("manifest.json").is_file() {
let _ = fs::remove_dir_all(&install_dir);
anyhow::bail!(
"extension extraction failed: manifest.json not found in {}",
install_dir.display()
);
}
Ok(install_dir)
}

fn find_zip_start(bytes: &[u8]) -> Option<usize> {
// PK\x03\x04 is a normal ZIP local file header; PK\x05\x06 is an empty
// central directory end-of-archive marker. Mirror the Python search.
let local = [0x50u8, 0x4B, 0x03, 0x04];
let end = [0x50u8, 0x4B, 0x05, 0x06];
bytes
.windows(4)
.position(|w| w == local)
.or_else(|| bytes.windows(4).position(|w| w == end))
}

// ---------------------------------------------------------------------------
// User-facing install flow
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -770,7 +690,7 @@ fn generate_fastled_tasks() -> Result<()> {
"type": "shell",
"label": "Run FastLED (Debug)",
"command": "fastled",
"args": ["${file}", "--debug", "--app"],
"args": ["${file}", "--debug"],
"options": {"cwd": "${workspaceFolder}"},
"group": {"kind": "build", "isDefault": true},
"presentation": {
Expand All @@ -781,7 +701,7 @@ fn generate_fastled_tasks() -> Result<()> {
"showReuseMessage": false,
"clear": true
},
"detail": "Run FastLED with debug mode and app visualization",
"detail": "Run FastLED with debug mode and Tauri visualization",
"problemMatcher": []
}),
json!({
Expand Down
123 changes: 14 additions & 109 deletions crates/fastled-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use clap::Parser;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::process::ExitCode;

mod archive;
mod build;
Expand Down Expand Up @@ -216,28 +216,15 @@ fn run_native_compile_streaming(
}
}

// ---------------------------------------------------------------------------
// Viewer mode selector
// ---------------------------------------------------------------------------

/// Controls how the compiled output is displayed to the user.
enum ViewerMode {
/// Open the default system browser.
Browser,
/// Launch the native Tauri viewer pointing at the output directory.
TauriViewer,
}

// ---------------------------------------------------------------------------
// Compile + serve + watch (replaces Flask-based flow)
// ---------------------------------------------------------------------------

/// Compile a sketch, serve the output via the built-in HTTP server, and
/// watch for file changes to trigger recompilation.
///
/// Build output is streamed to the browser (or Tauri viewer) in real time
/// via SSE.
fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode {
/// Build output is streamed to the Tauri viewer in real time via SSE.
fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode {
let sketch_dir = PathBuf::from(dir);
if !sketch_dir.is_dir() {
eprintln!("fastled: sketch directory does not exist: {dir}");
Expand Down Expand Up @@ -281,14 +268,9 @@ fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode {
let url = format!("http://{addr}");
println!("Serving at {url}");

match mode {
ViewerMode::Browser => open_browser(&url),
ViewerMode::TauriViewer => {
if let Err(e) = viewer::launch_tauri_viewer(&output_dir) {
eprintln!("fastled: Tauri viewer failed: {e}, falling back to browser");
open_browser(&url);
}
}
if let Err(e) = viewer::launch_tauri_viewer(&output_dir) {
eprintln!("fastled: Tauri viewer failed: {e:#}");
return ExitCode::FAILURE;
}

// --- Initial compilation ------------------------------------------------
Expand Down Expand Up @@ -407,15 +389,6 @@ struct Cli {
#[arg(long)]
profile: bool,

/// Use Playwright app-like browser experience (downloads browsers if needed).
#[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,
Expand Down Expand Up @@ -459,12 +432,6 @@ struct Cli {
#[arg(long, value_name = "REF", num_args = 0..=1, default_missing_value = "__latest__", hide = true)]
internal_ensure_fastled_repo: Option<String>,

/// Internal plumbing flag: download a Chrome Web Store extension (by ID)
/// into ``~/.fastled/chrome-extensions/<NAME>/``, print the path to
/// stdout, and exit. Used by the Python playwright helpers.
#[arg(long, value_names = ["EXTENSION_ID", "NAME"], num_args = 2, hide = true)]
internal_ensure_chrome_extension: Vec<String>,

// Build mode (mutually exclusive).
/// Build in debug mode.
#[arg(long, conflicts_with_all = ["quick", "release"])]
Expand All @@ -479,16 +446,6 @@ struct Cli {
release: bool,
}

/// 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()
}

fn validate_init_ref_flags(cli: &Cli) -> Result<(), &'static str> {
if cli.latest && (cli.branch.is_some() || cli.commit.is_some()) {
return Err("--latest cannot be used with --branch or --commit");
Expand Down Expand Up @@ -948,7 +905,7 @@ fn run_native_just_compile(cli: &Cli, dir: &str) -> ExitCode {
///
/// This replaces the Flask-based `--serve-dir` implementation with a native
/// Rust server, eliminating the Python/Flask dependency for this code path.
fn serve_directory(dir: &str, cli: &Cli) -> ExitCode {
fn serve_directory(dir: &str) -> ExitCode {
let path = PathBuf::from(dir);
if !path.is_dir() {
eprintln!("fastled: --serve-dir path does not exist: {dir}");
Expand All @@ -969,14 +926,9 @@ fn serve_directory(dir: &str, cli: &Cli) -> ExitCode {
println!("Serving {dir} at {url}");
println!("Press Ctrl+C to stop...");

// Open the Tauri viewer or fall back to system browser.
if viewer::viewer_available() && !cli.no_https {
if let Err(e) = viewer::launch_tauri_viewer(&path) {
eprintln!("fastled: Tauri viewer failed: {e}, opening system browser");
open_browser(&url);
}
} else {
open_browser(&url);
if let Err(e) = viewer::launch_tauri_viewer(&path) {
eprintln!("fastled: Tauri viewer failed: {e:#}");
return ExitCode::FAILURE;
}

// Wait for Ctrl+C.
Expand All @@ -986,22 +938,6 @@ fn serve_directory(dir: &str, cli: &Cli) -> ExitCode {
})
}

/// Open a URL in the default system browser.
fn open_browser(url: &str) {
#[cfg(target_os = "windows")]
{
let _ = Command::new("cmd").args(["/c", "start", url]).spawn();
}
#[cfg(target_os = "macos")]
{
let _ = Command::new("open").arg(url).spawn();
}
#[cfg(target_os = "linux")]
{
let _ = Command::new("xdg-open").arg(url).spawn();
}
}

/// Library entry point — invoked from both the `fastled` binary in this crate
/// and the wheel-bundled `fastled` binary in `crates/fastled-py`.
pub fn run() -> ExitCode {
Expand Down Expand Up @@ -1032,30 +968,9 @@ pub fn run() -> ExitCode {
};
}

// Hidden plumbing: download a Chrome Web Store extension and print its
// local install path. Used by the Python playwright helpers.
if !cli.internal_ensure_chrome_extension.is_empty() {
if cli.internal_ensure_chrome_extension.len() != 2 {
eprintln!("fastled: --internal-ensure-chrome-extension requires EXTENSION_ID NAME");
return ExitCode::FAILURE;
}
let extension_id = &cli.internal_ensure_chrome_extension[0];
let name = &cli.internal_ensure_chrome_extension[1];
return match install::ensure_chrome_extension(extension_id, name) {
Ok(path) => {
println!("{}", path.display());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("fastled: failed to fetch Chrome extension: {e:#}");
ExitCode::FAILURE
}
};
}

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

if cli.install {
Expand Down Expand Up @@ -1102,11 +1017,9 @@ pub fn run() -> ExitCode {
}
}

let use_tauri = should_use_tauri_viewer(&cli);

// Normal compilation flow with Rust HTTP server + watch mode.
// Both browser and Tauri viewer paths use the same compile_and_serve()
// infrastructure so compilation output is streamed via SSE in real time.
// The Tauri viewer uses the same compile_and_serve() infrastructure so
// compilation output is streamed via SSE in real time.
//
// Conditions:
// - a sketch directory was provided
Expand All @@ -1117,12 +1030,7 @@ pub fn run() -> ExitCode {
return run_native_just_compile(&cli, dir);
}
if !cli.just_compile && cli.init.is_none() {
let mode = if use_tauri {
ViewerMode::TauriViewer
} else {
ViewerMode::Browser
};
return compile_and_serve(dir, &cli, mode);
return compile_and_serve(dir, &cli);
}
}

Expand Down Expand Up @@ -1166,8 +1074,6 @@ mod tests {
init: None,
just_compile: false,
profile: false,
app: false,
legacy_browser: false,
install: false,
dry_run: false,
no_interactive: false,
Expand All @@ -1178,7 +1084,6 @@ mod tests {
fastled_path: None,
purge: false,
internal_ensure_fastled_repo: None,
internal_ensure_chrome_extension: Vec::new(),
debug: false,
quick: false,
release: false,
Expand Down
Loading
Loading