diff --git a/crates/fastled-cli/src/install.rs b/crates/fastled-cli/src/install.rs index defa4c90..ace642a8 100644 --- a/crates/fastled-cli/src/install.rs +++ b/crates/fastled-cli/src/install.rs @@ -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 { let home = dirs::home_dir().context("cannot resolve home directory")?; Ok(home.join(".fastled")) @@ -403,82 +399,6 @@ pub fn ensure_fastled_repo(ref_opt: Option<&str>) -> Result { 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 { - 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 { - // 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 // --------------------------------------------------------------------------- @@ -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": { @@ -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!({ diff --git a/crates/fastled-cli/src/lib.rs b/crates/fastled-cli/src/lib.rs index 78a8f878..7148ccf4 100644 --- a/crates/fastled-cli/src/lib.rs +++ b/crates/fastled-cli/src/lib.rs @@ -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; @@ -216,18 +216,6 @@ 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) // --------------------------------------------------------------------------- @@ -235,9 +223,8 @@ enum ViewerMode { /// 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}"); @@ -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 ------------------------------------------------ @@ -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, @@ -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, - /// Internal plumbing flag: download a Chrome Web Store extension (by ID) - /// into ``~/.fastled/chrome-extensions//``, 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, - // Build mode (mutually exclusive). /// Build in debug mode. #[arg(long, conflicts_with_all = ["quick", "release"])] @@ -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"); @@ -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}"); @@ -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. @@ -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 { @@ -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 { @@ -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 @@ -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); } } @@ -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, @@ -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, diff --git a/crates/fastled-py/src/lib.rs b/crates/fastled-py/src/lib.rs index 56e1d14e..e6b2d7b7 100644 --- a/crates/fastled-py/src/lib.rs +++ b/crates/fastled-py/src/lib.rs @@ -6,7 +6,7 @@ use fastled_cli::wasm_build; use fastled_cli::{PromptChoice, SketchSelection}; use pyo3::exceptions::{PyRuntimeError, PyValueError}; use pyo3::prelude::*; -use pyo3::types::{PyBytes, PyDict, PyModule}; +use pyo3::types::{PyBytes, PyModule}; use serde_json::json; use std::collections::HashMap; use std::fs; @@ -106,27 +106,46 @@ fn zip_output(output_dir: &Path) -> io::Result> { Ok(zip.finish()?.into_inner()) } -fn discover_artifacts(output_dir: &Path) -> HashMap { - let mut artifacts = HashMap::new(); - let candidates = [ - ("js", output_dir.join("fastled.js")), - ("wasm", output_dir.join("fastled.wasm")), - ("dwarf", output_dir.join("fastled.wasm.dwarf")), - ("symbol_map", output_dir.join("fastled.js.symbols")), - ("frontend_assets", output_dir.join("assets")), - ]; - for (name, path) in candidates { - if path.exists() { - artifacts.insert(name.to_string(), path.to_string_lossy().into_owned()); - } +#[derive(Default)] +struct NativeBuildArtifacts { + js: Option, + wasm: Option, + dwarf: Option, + symbol_map: Option, + frontend_assets: Option, +} + +fn existing_path(path: PathBuf) -> Option { + path.exists().then_some(path) +} + +fn discover_artifacts(output_dir: &Path) -> NativeBuildArtifacts { + let frontend_assets = existing_path(output_dir.join("assets")) + .or_else(|| output_dir.exists().then_some(output_dir.to_path_buf())); + + NativeBuildArtifacts { + js: existing_path(output_dir.join("fastled.js")), + wasm: existing_path(output_dir.join("fastled.wasm")), + dwarf: existing_path(output_dir.join("fastled.wasm.dwarf")), + symbol_map: existing_path(output_dir.join("fastled.js.symbols")), + frontend_assets, } - if !artifacts.contains_key("frontend_assets") && output_dir.exists() { - artifacts.insert( - "frontend_assets".to_string(), - output_dir.to_string_lossy().into_owned(), - ); +} + +fn python_path(py: Python<'_>, path: &Path) -> PyResult> { + let pathlib = PyModule::import(py, "pathlib")?; + let cls = pathlib.getattr("Path")?; + Ok(cls + .call1((path.to_string_lossy().as_ref(),))? + .into_any() + .unbind()) +} + +fn python_optional_path(py: Python<'_>, path: Option<&Path>) -> PyResult> { + match path { + Some(path) => python_path(py, path), + None => Ok(py.None()), } - artifacts } // --------------------------------------------------------------------------- @@ -540,7 +559,7 @@ impl NativeBuildService { profile: bool, fastled_path: Option<&str>, force_clean: bool, - ) -> PyResult> { + ) -> PyResult> { let _ = build_mode_obj; let sketch_dir = PathBuf::from(sketch_dir); let output_dir = sketch_dir.join("fastled_js"); @@ -703,26 +722,36 @@ impl NativeBuildService { sketch_time: f64, strategy: String, output_dir: &Path, - ) -> PyResult> { - let payload = PyDict::new(py); - let artifacts = PyDict::new(py); - for (name, path) in discover_artifacts(output_dir) { - artifacts.set_item(name, path)?; - } - - payload.set_item("success", success)?; - payload.set_item("stdout", stdout)?; - payload.set_item("hash_value", py.None())?; - payload.set_item("zip_bytes", PyBytes::new(py, &zip_bytes))?; - payload.set_item("zip_time", zip_time)?; - payload.set_item("libfastled_time", 0.0)?; - payload.set_item("sketch_time", sketch_time)?; - payload.set_item("response_processing_time", 0.0)?; - payload.set_item("strategy", strategy)?; - payload.set_item("output_dir", output_dir.to_string_lossy().into_owned())?; - payload.set_item("artifacts", artifacts)?; - - Ok(payload.unbind()) + ) -> PyResult> { + let build_types = PyModule::import(py, "fastled.build_types")?; + let artifacts_cls = build_types.getattr("BuildArtifacts")?; + let payload_cls = build_types.getattr("NativeBuildPayload")?; + + let artifact_paths = discover_artifacts(output_dir); + let artifacts = artifacts_cls.call1(( + python_optional_path(py, artifact_paths.js.as_deref())?, + python_optional_path(py, artifact_paths.wasm.as_deref())?, + python_optional_path(py, artifact_paths.dwarf.as_deref())?, + python_optional_path(py, artifact_paths.symbol_map.as_deref())?, + python_optional_path(py, artifact_paths.frontend_assets.as_deref())?, + ))?; + + Ok(payload_cls + .call1(( + success, + stdout, + py.None(), + PyBytes::new(py, &zip_bytes), + zip_time, + 0.0, + sketch_time, + 0.0, + strategy, + python_path(py, output_dir)?, + artifacts, + ))? + .into_any() + .unbind()) } } diff --git a/requirements.testing.txt b/requirements.testing.txt index 25cb7d74..d79b6f7c 100644 --- a/requirements.testing.txt +++ b/requirements.testing.txt @@ -6,4 +6,3 @@ ruff pytest-xdist pyright httpx -playwright diff --git a/src/fastled/__init__.py b/src/fastled/__init__.py index cf1fa346..69d12771 100644 --- a/src/fastled/__init__.py +++ b/src/fastled/__init__.py @@ -45,7 +45,6 @@ def spawn_http_server( directory: Path | str = Path("."), port: int | None = None, open_browser: bool = True, - app: bool = False, enable_https: bool = False, ) -> subprocess.Popen: """Spawn the Rust CLI HTTP server as a subprocess.""" @@ -57,7 +56,6 @@ def spawn_http_server( proc: subprocess.Popen = spawn_http_server( directory, open_browser=open_browser, - app=app, ) return proc diff --git a/src/fastled/build_service.py b/src/fastled/build_service.py index a23ec345..253a1463 100644 --- a/src/fastled/build_service.py +++ b/src/fastled/build_service.py @@ -11,7 +11,12 @@ from typing import Any, cast from fastled._native import NativeBuildService as _NativeBuildService -from fastled.build_types import BuildRequest, BuildResult, BuildStrategy +from fastled.build_types import ( + BuildRequest, + BuildResult, + BuildStrategy, + NativeBuildPayload, +) from fastled.interrupts import handle_keyboard_interrupt from fastled.types import CompileResult @@ -30,39 +35,37 @@ def register_toolchain(self, fastled_path: Path | None, toolchain: Any) -> None: def build(self, request: BuildRequest) -> BuildResult: try: - payload = self._native.build( - str(request.sketch_dir), - request.build_mode.value, - request.build_mode, - request.profile, - _path_key(request.fastled_path), - request.force_clean, + payload = cast( + NativeBuildPayload, + self._native.build( + str(request.sketch_dir), + request.build_mode.value, + request.build_mode, + request.profile, + _path_key(request.fastled_path), + request.force_clean, + ), ) except KeyboardInterrupt as ki: handle_keyboard_interrupt(ki) raise compile_result = CompileResult( - success=bool(payload["success"]), - stdout=str(payload["stdout"]), - hash_value=cast(str | None, payload["hash_value"]), - zip_bytes=bytes(payload["zip_bytes"]), - zip_time=float(payload["zip_time"]), - libfastled_time=float(payload["libfastled_time"]), - sketch_time=float(payload["sketch_time"]), - response_processing_time=float(payload["response_processing_time"]), + success=payload.success, + stdout=payload.stdout, + hash_value=payload.hash_value, + zip_bytes=payload.zip_bytes, + zip_time=payload.zip_time, + libfastled_time=payload.libfastled_time, + sketch_time=payload.sketch_time, + response_processing_time=payload.response_processing_time, ) - artifacts = { - name: Path(path_str) - for name, path_str in cast(dict[str, str], payload["artifacts"]).items() - } - return BuildResult( compile_result=compile_result, - strategy=cast(BuildStrategy, payload["strategy"]), - output_dir=Path(str(payload["output_dir"])), - artifacts=artifacts, + strategy=cast(BuildStrategy, payload.strategy), + output_dir=Path(payload.output_dir), + artifacts=payload.artifacts, ) def detect_strategy(self, request: BuildRequest) -> BuildStrategy: diff --git a/src/fastled/build_types.py b/src/fastled/build_types.py index 4401fb00..f21a3555 100644 --- a/src/fastled/build_types.py +++ b/src/fastled/build_types.py @@ -6,7 +6,8 @@ from __future__ import annotations -from dataclasses import dataclass, field +from collections.abc import Iterator +from dataclasses import dataclass from pathlib import Path from typing import Literal @@ -15,6 +16,12 @@ BuildStrategy = Literal["cold", "incremental"] +def _optional_path(value: Path | str | None) -> Path | None: + if value is None: + return None + return value if isinstance(value, Path) else Path(value) + + @dataclass(frozen=True) class BuildRequest: sketch_dir: Path @@ -28,12 +35,84 @@ def output_dir(self) -> Path: return self.sketch_dir / "fastled_js" +@dataclass +class BuildArtifacts: + js: Path | None = None + wasm: Path | None = None + dwarf: Path | None = None + symbol_map: Path | None = None + frontend_assets: Path | None = None + + def __post_init__(self) -> None: + self.js = _optional_path(self.js) + self.wasm = _optional_path(self.wasm) + self.dwarf = _optional_path(self.dwarf) + self.symbol_map = _optional_path(self.symbol_map) + self.frontend_assets = _optional_path(self.frontend_assets) + + def as_dict(self) -> dict[str, Path]: + return { + name: path + for name, path in { + "js": self.js, + "wasm": self.wasm, + "dwarf": self.dwarf, + "symbol_map": self.symbol_map, + "frontend_assets": self.frontend_assets, + }.items() + if path is not None + } + + @classmethod + def from_mapping(cls, artifacts: dict[str, Path | str]) -> "BuildArtifacts": + return cls( + js=_optional_path(artifacts.get("js")), + wasm=_optional_path(artifacts.get("wasm")), + dwarf=_optional_path(artifacts.get("dwarf")), + symbol_map=_optional_path(artifacts.get("symbol_map")), + frontend_assets=_optional_path(artifacts.get("frontend_assets")), + ) + + def __getitem__(self, name: str) -> Path: + artifacts = self.as_dict() + if name not in artifacts: + raise KeyError(name) + return artifacts[name] + + def get(self, name: str, default: Path | None = None) -> Path | None: + return self.as_dict().get(name, default) + + def items(self) -> Iterator[tuple[str, Path]]: + return iter(self.as_dict().items()) + + +@dataclass +class NativeBuildPayload: + success: bool + stdout: str + hash_value: str | None + zip_bytes: bytes + zip_time: float + libfastled_time: float + sketch_time: float + response_processing_time: float + strategy: BuildStrategy + output_dir: Path + artifacts: BuildArtifacts + + def __post_init__(self) -> None: + if not isinstance(self.output_dir, Path): + self.output_dir = Path(self.output_dir) + if not isinstance(self.artifacts, BuildArtifacts): + raise TypeError("artifacts must be BuildArtifacts") + + @dataclass class BuildResult: compile_result: CompileResult strategy: BuildStrategy output_dir: Path - artifacts: dict[str, Path] = field(default_factory=dict) + artifacts: BuildArtifacts @property def success(self) -> bool: diff --git a/src/fastled/debug_symbols.py b/src/fastled/debug_symbols.py index a6ba2d94..e6452b76 100644 --- a/src/fastled/debug_symbols.py +++ b/src/fastled/debug_symbols.py @@ -2,6 +2,7 @@ import os import platform +from collections.abc import Mapping from dataclasses import dataclass from importlib import resources from pathlib import Path @@ -72,6 +73,30 @@ def source_roots(self) -> list[tuple[str, Path]]: return roots +@dataclass(frozen=True) +class DwarfPrefixConfig: + fastled_prefix: str = DEFAULT_FASTLED_PREFIX + sketch_prefix: str = DEFAULT_SKETCH_PREFIX + dwarf_prefix: str = DEFAULT_DWARF_PREFIX + + @classmethod + def from_mapping(cls, value: object) -> "DwarfPrefixConfig": + data: Mapping[str, object] = value if isinstance(value, dict) else {} + return cls( + fastled_prefix=_string_value( + data.get("fastled_prefix"), DEFAULT_FASTLED_PREFIX + ), + sketch_prefix=_string_value( + data.get("sketch_prefix"), DEFAULT_SKETCH_PREFIX + ), + dwarf_prefix=_string_value(data.get("dwarf_prefix"), DEFAULT_DWARF_PREFIX), + ) + + +def _string_value(value: object, default: str) -> str: + return value if isinstance(value, str) else default + + def load_debug_symbol_config( sketch_dir: Path, fastled_dir: Path | None = None, @@ -99,14 +124,14 @@ def load_debug_symbol_config( data = tomllib.load(handle) - dwarf = data.get("dwarf", {}) + dwarf = DwarfPrefixConfig.from_mapping(data.get("dwarf")) return DebugSymbolConfig( sketch_dir=sketch_dir, fastled_dir=fastled_dir, emsdk_path=emsdk_path, - fastled_prefix=dwarf.get("fastled_prefix", DEFAULT_FASTLED_PREFIX), - sketch_prefix=dwarf.get("sketch_prefix", DEFAULT_SKETCH_PREFIX), - dwarf_prefix=dwarf.get("dwarf_prefix", DEFAULT_DWARF_PREFIX), + fastled_prefix=dwarf.fastled_prefix, + sketch_prefix=dwarf.sketch_prefix, + dwarf_prefix=dwarf.dwarf_prefix, ) diff --git a/src/fastled/install/project_detection.py b/src/fastled/install/project_detection.py index 4b311eb1..516da94a 100644 --- a/src/fastled/install/project_detection.py +++ b/src/fastled/install/project_detection.py @@ -2,9 +2,36 @@ import json import shutil +from dataclasses import dataclass from pathlib import Path +@dataclass(frozen=True) +class LibraryJson: + name: str | None + repository_url: str + + @classmethod + def from_file(cls, path: Path) -> "LibraryJson | None": + try: + with open(path, "r") as f: + data = json.load(f) + except (json.JSONDecodeError, FileNotFoundError): + return None + if not isinstance(data, dict): + return None + repository = data.get("repository") + repository_url = "" + if isinstance(repository, dict): + url = repository.get("url") + repository_url = url if isinstance(url, str) else "" + name = data.get("name") + return cls( + name=name if isinstance(name, str) else None, + repository_url=repository_url, + ) + + def validate_vscode_project(no_interactive: bool = False) -> bool: """ Validate if current directory has a VSCode project. @@ -96,15 +123,8 @@ def generate_vscode_project() -> bool: def detect_fastled_project() -> bool: """Check if library.json contains FastLED.""" library_json = Path.cwd() / "library.json" - if not library_json.exists(): - return False - - try: - with open(library_json, "r") as f: - data = json.load(f) - return data.get("name") == "FastLED" - except (json.JSONDecodeError, KeyError): - return False + metadata = LibraryJson.from_file(library_json) + return metadata is not None and metadata.name == "FastLED" def is_fastled_repository() -> bool: @@ -128,15 +148,12 @@ def is_fastled_repository() -> bool: return False # Verify library.json has correct content - try: - with open(cwd / "library.json", "r") as f: - data = json.load(f) - if data.get("name") != "FastLED": - return False - repo_url = data.get("repository", {}).get("url", "") - if "FastLED/FastLED" not in repo_url: - return False - except (json.JSONDecodeError, KeyError, FileNotFoundError): + metadata = LibraryJson.from_file(cwd / "library.json") + if metadata is None: + return False + if metadata.name != "FastLED": + return False + if "FastLED/FastLED" not in metadata.repository_url: return False # Check for test files pattern diff --git a/src/fastled/install/vscode_config.py b/src/fastled/install/vscode_config.py index 30205117..86a15b49 100644 --- a/src/fastled/install/vscode_config.py +++ b/src/fastled/install/vscode_config.py @@ -1,46 +1,183 @@ """VSCode configuration generation for FastLED projects.""" import json +from dataclasses import dataclass, field from pathlib import Path +JsonObject = dict[str, object] + + +@dataclass +class LaunchJson: + version: str = "0.2.0" + configurations: list[JsonObject] | None = None + + @classmethod + def from_file(cls, path: Path) -> "LaunchJson": + data = _read_json_object(path, {"version": "0.2.0", "configurations": []}) + configurations = data.get("configurations") + return cls( + version=str(data.get("version", "0.2.0")), + configurations=[ + item for item in configurations if isinstance(item, dict) + ] + if isinstance(configurations, list) + else [], + ) + + def to_json(self) -> JsonObject: + return { + "version": self.version, + "configurations": self.configurations or [], + } + + +@dataclass(frozen=True) +class AutoDebugLaunchConfiguration: + name: str = "🎯 Auto Debug (Smart File Detection)" + config_type: str = "auto-debug" + request: str = "launch" + file_map: dict[str, str] | None = None + + def to_json(self) -> JsonObject: + return { + "name": self.name, + "type": self.config_type, + "request": self.request, + "map": self.file_map + or { + "*.ino": "Arduino: Run .ino with FastLED", + "*.py": "Python: Current File (UV)", + }, + } + + +@dataclass +class TasksJson: + version: str = "2.0.0" + tasks: list[JsonObject] | None = None + + @classmethod + def from_file(cls, path: Path) -> "TasksJson": + data = _read_json_object(path, {"version": "2.0.0", "tasks": []}) + tasks = data.get("tasks") + return cls( + version=str(data.get("version", "2.0.0")), + tasks=[item for item in tasks if isinstance(item, dict)] + if isinstance(tasks, list) + else [], + ) + + def to_json(self) -> JsonObject: + return {"version": self.version, "tasks": self.tasks or []} + + +@dataclass(frozen=True) +class TaskOptions: + cwd: str = "${workspaceFolder}" + + def to_json(self) -> JsonObject: + return {"cwd": self.cwd} + + +@dataclass(frozen=True) +class TaskGroup: + kind: str = "build" + is_default: bool = True + + def to_json(self) -> JsonObject: + return {"kind": self.kind, "isDefault": self.is_default} + + +@dataclass(frozen=True) +class TaskPresentation: + echo: bool = True + reveal: str = "always" + focus: bool = True + panel: str = "new" + show_reuse_message: bool = False + clear: bool = True + + def to_json(self) -> JsonObject: + return { + "echo": self.echo, + "reveal": self.reveal, + "focus": self.focus, + "panel": self.panel, + "showReuseMessage": self.show_reuse_message, + "clear": self.clear, + } + + +@dataclass(frozen=True) +class FastLedTask: + label: str + args: list[str] + detail: str + group: TaskGroup | str + task_type: str = "shell" + command: str = "fastled" + options: TaskOptions = field(default_factory=TaskOptions) + presentation: TaskPresentation = field(default_factory=TaskPresentation) + problem_matcher: list[str] | None = None + + def to_json(self) -> JsonObject: + group: JsonObject | str + if isinstance(self.group, TaskGroup): + group = self.group.to_json() + else: + group = self.group + return { + "type": self.task_type, + "label": self.label, + "command": self.command, + "args": self.args, + "options": self.options.to_json(), + "group": group, + "presentation": self.presentation.to_json(), + "detail": self.detail, + "problemMatcher": self.problem_matcher or [], + } + + +@dataclass(frozen=True) +class VscodeSettingsPatch: + values: JsonObject + + def to_json(self) -> JsonObject: + return dict(self.values) + + +def _read_json_object(path: Path, default: JsonObject) -> JsonObject: + if not path.exists(): + return dict(default) + try: + with open(path, "r") as f: + data = json.load(f) + except json.JSONDecodeError: + return dict(default) + return data if isinstance(data, dict) else dict(default) + def update_launch_json_for_arduino() -> None: """Update launch.json with Arduino debugging configuration.""" launch_json_path = Path.cwd() / ".vscode" / "launch.json" - # Default launch configuration - arduino_config = { - "name": "🎯 Auto Debug (Smart File Detection)", - "type": "auto-debug", - "request": "launch", - "map": { - "*.ino": "Arduino: Run .ino with FastLED", - "*.py": "Python: Current File (UV)", - }, - } - - if launch_json_path.exists(): - # Merge with existing - try: - with open(launch_json_path, "r") as f: - data = json.load(f) - except json.JSONDecodeError: - data = {"version": "0.2.0", "configurations": []} - else: - data = {"version": "0.2.0", "configurations": []} + arduino_config = AutoDebugLaunchConfiguration().to_json() + data = LaunchJson.from_file(launch_json_path) # Check if configuration already exists - configs = data.get("configurations", []) + configs = data.configurations or [] exists = any(cfg.get("name") == arduino_config["name"] for cfg in configs) if not exists: configs.insert(0, arduino_config) # Add at the beginning - data["configurations"] = configs + data.configurations = configs # Write back launch_json_path.parent.mkdir(exist_ok=True) with open(launch_json_path, "w") as f: - json.dump(data, f, indent=4) + json.dump(data.to_json(), f, indent=4) print(f"✅ Updated {launch_json_path}") @@ -49,58 +186,25 @@ def generate_fastled_tasks() -> None: """Generate/update tasks.json with FastLED build tasks.""" tasks_json_path = Path.cwd() / ".vscode" / "tasks.json" - # FastLED tasks fastled_tasks = [ - { - "type": "shell", - "label": "Run FastLED (Debug)", - "command": "fastled", - "args": ["${file}", "--debug", "--app"], - "options": {"cwd": "${workspaceFolder}"}, - "group": {"kind": "build", "isDefault": True}, - "presentation": { - "echo": True, - "reveal": "always", - "focus": True, - "panel": "new", - "showReuseMessage": False, - "clear": True, - }, - "detail": "Run FastLED with debug mode and app visualization", - "problemMatcher": [], - }, - { - "type": "shell", - "label": "Run FastLED (Quick)", - "command": "fastled", - "args": ["${file}", "--background-update"], - "options": {"cwd": "${workspaceFolder}"}, - "group": "build", - "presentation": { - "echo": True, - "reveal": "always", - "focus": True, - "panel": "new", - "showReuseMessage": False, - "clear": True, - }, - "detail": "Run FastLED with quick background update mode", - "problemMatcher": [], - }, + FastLedTask( + label="Run FastLED (Debug)", + args=["${file}", "--debug"], + group=TaskGroup(), + detail="Run FastLED with debug mode and Tauri visualization", + ).to_json(), + FastLedTask( + label="Run FastLED (Quick)", + args=["${file}", "--background-update"], + group="build", + detail="Run FastLED with quick background update mode", + ).to_json(), ] - if tasks_json_path.exists(): - # Merge with existing - try: - with open(tasks_json_path, "r") as f: - data = json.load(f) - except json.JSONDecodeError: - data = {"version": "2.0.0", "tasks": []} - else: - data = {"version": "2.0.0", "tasks": []} + data = TasksJson.from_file(tasks_json_path) # Get existing tasks - existing_tasks = data.get("tasks", []) + existing_tasks = data.tasks or [] existing_labels = {task.get("label") for task in existing_tasks} # Add new tasks if they don't exist @@ -108,12 +212,12 @@ def generate_fastled_tasks() -> None: if task["label"] not in existing_labels: existing_tasks.append(task) - data["tasks"] = existing_tasks + data.tasks = existing_tasks # Write back tasks_json_path.parent.mkdir(exist_ok=True) with open(tasks_json_path, "w") as f: - json.dump(data, f, indent=4) + json.dump(data.to_json(), f, indent=4) print(f"✅ Updated {tasks_json_path}") @@ -131,7 +235,7 @@ def update_vscode_settings_for_fastled() -> None: settings_json_path = Path.cwd() / ".vscode" / "settings.json" # FastLED repository-specific settings - updated to match the official FastLED repo - fastled_settings = { + fastled_settings = VscodeSettingsPatch({ # Terminal configuration "terminal.integrated.defaultProfile.windows": "Git Bash", "terminal.integrated.shellIntegration.enabled": False, @@ -319,20 +423,12 @@ def update_vscode_settings_for_fastled() -> None: # Inlay hints - Brighter gray for better visibility "editor.inlayHints.fontColor": "#808080", "editor.inlayHints.background": "#3C3C3C20", - } - - if settings_json_path.exists(): - # Merge with existing - try: - with open(settings_json_path, "r") as f: - data = json.load(f) - except json.JSONDecodeError: - data = {} - else: - data = {} + }) + + data = _read_json_object(settings_json_path, {}) # Update settings - data.update(fastled_settings) + data.update(fastled_settings.to_json()) # Write back settings_json_path.parent.mkdir(exist_ok=True) diff --git a/src/fastled/open_browser.py b/src/fastled/open_browser.py index 326fba4b..d375ec02 100644 --- a/src/fastled/open_browser.py +++ b/src/fastled/open_browser.py @@ -10,7 +10,6 @@ import weakref from pathlib import Path -from fastled._native import find_fastled_viewer from fastled._rust_cli import find_rust_fastled_cli from fastled.interrupts import handle_keyboard_interrupt @@ -41,7 +40,6 @@ def spawn_http_server( fastled_js: Path, port: int | None = None, open_browser: bool = True, - app: bool = False, enable_https: bool = True, sketch_dir: Path | None = None, fastled_path: Path | None = None, @@ -49,10 +47,9 @@ def spawn_http_server( """Spawn the Rust CLI HTTP server as a subprocess. The Rust binary's ``--serve-dir`` flag starts a native HTTP server and - auto-launches the Tauri viewer when the ``fastled-viewer`` binary is - available, so no Python-side viewer spawn is required. + auto-launches the Tauri viewer, so no Python-side viewer spawn is required. """ - del app, enable_https, sketch_dir, fastled_path # handled by Rust + del open_browser, enable_https, sketch_dir, fastled_path # handled by Rust cli = find_rust_fastled_cli() if cli is None: @@ -83,20 +80,6 @@ def spawn_http_server( # (URL line not seen yet) needs a small grace period. time.sleep(1.0) - if open_browser: - if actual_port: - url = f"http://localhost:{actual_port}" - else: - url = "http://localhost:8089" - - # The Rust CLI auto-launches the viewer; only fall back to the system - # browser when no viewer binary is present. - if find_fastled_viewer() is None: - print(f"Opening browser to {url}") - import webbrowser - - webbrowser.open(url=url, new=1, autoraise=True) - else: - print("FastLED viewer will be launched by the Rust CLI") + print("FastLED viewer will be launched by the Rust CLI") return proc diff --git a/src/fastled/playwright/chrome_extension_downloader.py b/src/fastled/playwright/chrome_extension_downloader.py deleted file mode 100644 index 21838317..00000000 --- a/src/fastled/playwright/chrome_extension_downloader.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Chrome Web Store extension downloader (thin Python shim). - -The actual CRX download + decode lives in `crates/fastled-cli/src/install.rs` -(`ensure_chrome_extension`) so the Python side no longer imports httpx. -This module just invokes the Rust binary via a hidden internal flag and -returns the local install path. -""" - -import subprocess -import sys -import warnings -from pathlib import Path - -from fastled._rust_cli import find_rust_fastled_cli as _find_rust_fastled_cli -from fastled.interrupts import handle_keyboard_interrupt - -CPP_DEVTOOLS_EXTENSION_ID = "pdcpmagijalfljmkmjngeonclgbbannb" -CPP_DEVTOOLS_EXTENSION_NAME = "cpp-devtools-support" - - -def download_cpp_devtools_extension() -> Path | None: - """Ensure the C++ DevTools (DWARF) Chrome extension is installed locally. - - Returns the install path, or ``None`` if the Rust binary is missing or - the download failed (a warning is emitted for caller-visibility). - """ - cli = _find_rust_fastled_cli() - if cli is None: - warnings.warn( - "Could not locate the Rust fastled CLI; " - "Chrome extension cannot be installed." - ) - return None - - cmd = [ - str(cli), - "--internal-ensure-chrome-extension", - CPP_DEVTOOLS_EXTENSION_ID, - CPP_DEVTOOLS_EXTENSION_NAME, - ] - - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=180) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - raise - except Exception as e: - warnings.warn(f"Failed to invoke fastled CLI for Chrome extension: {e}") - return None - - if result.returncode != 0: - sys.stderr.write(result.stderr) - warnings.warn( - "fastled --internal-ensure-chrome-extension failed " - f"(exit {result.returncode})" - ) - return None - - path_str = result.stdout.strip().splitlines()[-1] if result.stdout else "" - path = Path(path_str) - if not path.is_dir(): - warnings.warn(f"Rust binary returned non-existent extension path: {path_str!r}") - return None - return path - - -if __name__ == "__main__": - extension_path = download_cpp_devtools_extension() - if extension_path: - print(f"Extension downloaded to: {extension_path}") - else: - print("Failed to download extension") diff --git a/src/fastled/playwright/playwright_browser.py b/src/fastled/playwright/playwright_browser.py deleted file mode 100644 index c30a749b..00000000 --- a/src/fastled/playwright/playwright_browser.py +++ /dev/null @@ -1,807 +0,0 @@ -""" -Playwright browser integration for FastLED WASM compiler. - -This module provides a Playwright-based browser implementation that can be used -in a Playwright browser instead of the default system browser when -Playwright is available. -""" - -import asyncio -import os -import sys -import threading -import warnings -from pathlib import Path -from typing import Any - -from fastled.interrupts import handle_keyboard_interrupt -from fastled.playwright.resize_tracking import ResizeTracker - -# Set custom Playwright browser installation path -PLAYWRIGHT_DIR = Path.home() / ".fastled" / "playwright" -PLAYWRIGHT_DIR.mkdir(parents=True, exist_ok=True) - - -def get_chromium_executable_path() -> str | None: - """Get the path to the custom Chromium executable if it exists.""" - import glob - import platform - - playwright_dir = PLAYWRIGHT_DIR - - if platform.system() == "Windows": - chromium_pattern = str( - playwright_dir / "chromium-*" / "chrome-win" / "chrome.exe" - ) - elif platform.system() == "Darwin": # macOS - chromium_pattern = str( - playwright_dir - / "chromium-*" - / "chrome-mac" - / "Chromium.app" - / "Contents" - / "MacOS" - / "Chromium" - ) - else: # Linux - chromium_pattern = str( - playwright_dir / "chromium-*" / "chrome-linux" / "chrome" - ) - - matches = glob.glob(chromium_pattern) - return matches[0] if matches else None - - -class PlaywrightBrowser: - """Playwright browser manager for FastLED sketches.""" - - def __init__(self, headless: bool = False, enable_extensions: bool = True): - """Initialize the Playwright browser manager. - - Args: - headless: Whether to run the browser in headless mode - enable_extensions: Whether to enable Chrome extensions (C++ DevTools Support) - """ - - self.headless = headless - self.enable_extensions = enable_extensions - self.auto_resize = True # Always enable auto-resize - self.browser: Any = None - self.context: Any = None - self.page: Any = None - self.playwright: Any = None - self._should_exit = asyncio.Event() - self._extensions_dir: Path | None = None - self.resize_tracker: ResizeTracker | None = None - - # Initialize extensions if enabled - if self.enable_extensions: - self._setup_extensions() - - def _setup_extensions(self) -> None: - """Setup Chrome extensions for enhanced debugging.""" - try: - from fastled.playwright.chrome_extension_downloader import ( - download_cpp_devtools_extension, - ) - - extension_path = download_cpp_devtools_extension() - if extension_path and extension_path.exists(): - self._extensions_dir = extension_path - print( - f"[PYTHON] C++ DevTools Support extension ready: {extension_path}" - ) - else: - print("[PYTHON] Warning: C++ DevTools Support extension not available") - self.enable_extensions = False - except KeyboardInterrupt as ki: - print("\nClosing Playwright browser...") - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[PYTHON] Warning: Failed to setup Chrome extensions: {e}") - self.enable_extensions = False - - def _detect_device_scale_factor(self) -> float | None: - """Detect the system's device scale factor for natural browser behavior. - - Returns: - The detected device scale factor, or None if detection fails or - the value is outside reasonable bounds (0.5-4.0). - """ - try: - import tkinter - - root = tkinter.Tk() - root.withdraw() # Hide the window - scale_factor = root.winfo_fpixels("1i") / 72.0 - root.destroy() - - # Validate the scale factor is in a reasonable range - if 0.5 <= scale_factor <= 4.0: - return scale_factor - else: - print( - f"[PYTHON] Detected scale factor {scale_factor:.2f} is outside reasonable bounds (0.5-4.0)" - ) - return None - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[PYTHON] Could not detect device scale factor: {e}") - return None - - async def start(self) -> None: - """Start the Playwright browser.""" - if self.browser is None and self.context is None: - - from playwright.async_api import ( # type: ignore[reportMissingImports] - async_playwright, - ) - - self.playwright = async_playwright() - playwright = await self.playwright.start() - - if self.enable_extensions and self._extensions_dir: - # Use persistent context for extensions - user_data_dir = PLAYWRIGHT_DIR / "user-data" - user_data_dir.mkdir(parents=True, exist_ok=True) - - launch_kwargs = { - "headless": False, # Extensions require headed mode - "channel": "chromium", # Required for extensions - "args": [ - "--disable-dev-shm-usage", - "--disable-web-security", - "--allow-running-insecure-content", - f"--disable-extensions-except={self._extensions_dir}", - f"--load-extension={self._extensions_dir}", - ], - } - - # Get custom Chromium executable path if available - executable_path = get_chromium_executable_path() - if executable_path: - launch_kwargs["executable_path"] = executable_path - print( - f"[PYTHON] Using custom Chromium executable: {executable_path}" - ) - - self.context = await playwright.chromium.launch_persistent_context( - str(user_data_dir), **launch_kwargs - ) - - print( - "[PYTHON] Started Playwright browser with C++ DevTools Support extension" - ) - - else: - # Regular browser launch without extensions - executable_path = get_chromium_executable_path() - launch_kwargs = { - "headless": self.headless, - "args": [ - "--disable-dev-shm-usage", - "--disable-web-security", - "--allow-running-insecure-content", - ], - } - - if executable_path: - launch_kwargs["executable_path"] = executable_path - print( - f"[PYTHON] Using custom Chromium executable: {executable_path}" - ) - - self.browser = await playwright.chromium.launch(**launch_kwargs) - - if self.page is None: - if self.context: - # Using persistent context (with extensions) - if len(self.context.pages) > 0: - self.page = self.context.pages[0] - else: - self.page = await self.context.new_page() - elif self.browser: - # Using regular browser - # Detect system device scale factor for natural browser behavior - device_scale_factor = self._detect_device_scale_factor() - - # Create browser context with detected or default device scale factor - if device_scale_factor: - context = await self.browser.new_context( - device_scale_factor=device_scale_factor - ) - print( - f"[PYTHON] Created browser context with device scale factor: {device_scale_factor:.2f}" - ) - else: - context = await self.browser.new_context() - print( - "[PYTHON] Created browser context with default device scale factor" - ) - - self.page = await context.new_page() - - async def open_url(self, url: str) -> None: - """Open a URL in the Playwright browser. - - Args: - url: The URL to open - """ - if self.page is None: - await self.start() - - print(f"Opening FastLED sketch in Playwright browser: {url}") - if self.page is not None: - await self.page.goto(url) - - # Wait for the page to load - await self.page.wait_for_load_state("networkidle") - - # Verify device scale factor is working correctly - try: - device_pixel_ratio = await self.page.evaluate("window.devicePixelRatio") - print( - f"[PYTHON] Verified browser device pixel ratio: {device_pixel_ratio}" - ) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[PYTHON] Could not verify device pixel ratio: {e}") - - # Set up auto-resizing functionality if enabled - if self.auto_resize: - await self._setup_auto_resize() - - # Check if C++ DevTools extension is loaded - if self.enable_extensions and self._extensions_dir: - try: - # Check if the extension is available in the DevTools - extensions_available = await self.page.evaluate( - """ - () => { - // Check if chrome.devtools is available (extension context) - return typeof chrome !== 'undefined' && - typeof chrome.runtime !== 'undefined' && - chrome.runtime.id !== undefined; - } - """ - ) - - if extensions_available: - print( - "[PYTHON] ✅ C++ DevTools Support extension is active and ready for DWARF debugging" - ) - else: - print( - "[PYTHON] ⚠️ C++ DevTools Support extension may not be fully loaded" - ) - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[PYTHON] Could not verify extension status: {e}") - - async def _setup_auto_resize(self) -> None: - """Set up automatic window resizing based on content size.""" - if self.page is None: - print("[PYTHON] Cannot setup auto-resize: page is None") - return - - print( - "[PYTHON] Setting up browser window tracking with viewport-only adjustment" - ) - - # Create resize tracker instance - self.resize_tracker = ResizeTracker(self.page) - - # Start polling loop that tracks browser window changes and adjusts viewport only - asyncio.create_task(self._track_browser_adjust_viewport()) - - async def _track_browser_adjust_viewport(self) -> None: - """Track browser window changes and adjust viewport accordingly. - - This method polls for changes in the browser window size using the - ResizeTracker and handles any errors that occur. - """ - if self.resize_tracker is None: - print("[PYTHON] Cannot start tracking: resize_tracker is None") - return - - while not self._should_exit.is_set(): - try: - # Wait between polls - await asyncio.sleep(0.25) # Poll every 250ms - - # Check if page is still alive - if self.page is None or self.page.is_closed(): - print("[PYTHON] Page closed, signaling exit") - self._should_exit.set() - return - - # Update resize tracking - result = await self.resize_tracker.update() - - if result is not None: - assert isinstance(result, Exception) - # An exception occurred in resize tracking - error_message = str(result) - warnings.warn(f"[PYTHON] Error in resize tracking: {error_message}") - - # Be EXTREMELY conservative about browser close detection - # Only trigger shutdown on very specific errors that definitively indicate browser closure - browser_definitely_closed = any( - phrase in error_message.lower() - for phrase in [ - "browser has been closed", - "target closed", - "connection closed", - "target page, probably because the page has been closed", - "page has been closed", - "browser context has been closed", - ] - ) - - # Also check actual browser state before deciding to shut down - browser_state_indicates_closed = False - try: - if self.browser and hasattr(self.browser, "is_closed"): - browser_state_indicates_closed = self.browser.is_closed() - elif self.context and hasattr(self.context, "closed"): - browser_state_indicates_closed = self.context.closed - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception: - # If we can't check the state, don't assume it's closed - warnings.warn( - f"[PYTHON] Could not check browser state: {result}. Assuming browser is not closed." - ) - browser_state_indicates_closed = False - - if browser_definitely_closed or browser_state_indicates_closed: - if browser_definitely_closed: - print( - f'[PYTHON] Browser has been closed because "{error_message}" matched one of the error phrases or browser state indicates closed, shutting down gracefully...' - ) - elif browser_state_indicates_closed: - print( - "[PYTHON] Browser state indicates closed, shutting down gracefully..." - ) - self._should_exit.set() - return - else: - # For other errors, just log and continue - don't shut down - print( - f"[PYTHON] Recoverable error in resize tracking: {result}" - ) - # Add a small delay to prevent tight error loops - await asyncio.sleep(1.0) - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - error_message = str(e) - warnings.warn( - f"[PYTHON] Unexpected error in browser tracking loop: {error_message}" - ) - # Add a small delay to prevent tight error loops - await asyncio.sleep(1.0) - - warnings.warn("[PYTHON] Browser tracking loop exited.") - - async def wait_for_close(self) -> None: - """Wait for the browser to be closed.""" - if self.context: - # Wait for persistent context to be closed - try: - while not self.context.closed: - await asyncio.sleep(1) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception: - pass - elif self.browser: - try: - # Wait for the browser to be closed - while not self.browser.is_closed(): - await asyncio.sleep(1) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception: - pass - - async def close(self) -> None: - """Close the Playwright browser.""" - # Signal all tracking loops to exit - self._should_exit.set() - - try: - # Clean up resize tracker - self.resize_tracker = None - - if self.page: - await self.page.close() - self.page = None - - if self.context: - await self.context.close() - self.context = None - - if self.browser: - await self.browser.close() - self.browser = None - - if self.playwright: - # The playwright context manager may not have a stop() method in all versions - # Try stop() first, fall back to __aexit__ if needed - try: - if hasattr(self.playwright, "stop"): - await self.playwright.stop() - else: - # For async context managers, use __aexit__ - await self.playwright.__aexit__(None, None, None) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as stop_error: - print( - f"[PYTHON] Warning: Could not properly stop playwright: {stop_error}" - ) - # Try alternative cleanup methods - try: - if hasattr(self.playwright, "__aexit__"): - await self.playwright.__aexit__(None, None, None) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception: - pass # Ignore secondary cleanup failures - finally: - self.playwright = None - except KeyboardInterrupt as ki: - print("[PYTHON] Keyboard interrupt detected, closing Playwright browser") - self._should_exit.set() - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[PYTHON] Error closing Playwright browser: {e}") - self._should_exit.set() - - -def run_playwright_browser( - url: str, headless: bool = False, enable_extensions: bool = True -) -> None: - """Run Playwright browser in a separate process. - - Args: - url: The URL to open - headless: Whether to run in headless mode - enable_extensions: Whether to enable Chrome extensions (C++ DevTools Support) - """ - - async def main(): - browser = None - try: - browser = PlaywrightBrowser( - headless=headless, enable_extensions=enable_extensions - ) - await browser.start() - await browser.open_url(url) - - print("Playwright browser opened. Press Ctrl+C to close.") - await browser.wait_for_close() - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - # If we get an error that suggests browsers aren't installed, try to install them - if "executable doesn't exist" in str(e) or "Browser not found" in str(e): - print("🎭 Playwright browsers not found. Installing...") - if install_playwright_browsers(): - print("🎭 Retrying browser startup...") - # Try again with fresh browser instance - browser = PlaywrightBrowser( - headless=headless, enable_extensions=enable_extensions - ) - await browser.start() - await browser.open_url(url) - - print("Playwright browser opened. Press Ctrl+C to close.") - await browser.wait_for_close() - else: - print("❌ Failed to install Playwright browsers") - raise e - else: - raise e - finally: - if browser is not None: - try: - await browser.close() - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"Warning: Failed to close Playwright browser: {e}") - - try: - asyncio.run(main()) - except KeyboardInterrupt as ki: - print("\nPlaywright browser closed.") - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"Playwright browser failed: {e}. Falling back to default browser.") - import webbrowser - - webbrowser.open(url) - - -class PlaywrightBrowserProxy: - """Proxy object to manage Playwright browser lifecycle.""" - - def __init__(self): - self.process = None - self.browser_manager = None - self.monitor_thread = None - self._closing_intentionally = False - - def open( - self, url: str, headless: bool = False, enable_extensions: bool = True - ) -> None: - """Open URL with Playwright browser and keep it alive. - - Args: - url: The URL to open - headless: Whether to run in headless mode - enable_extensions: Whether to enable Chrome extensions (C++ DevTools Support) - """ - - try: - # Run Playwright in a separate process to avoid blocking - import multiprocessing - - self.process = multiprocessing.Process( - target=run_playwright_browser_persistent, - args=(url, headless, enable_extensions), - ) - self.process.start() - - # Start monitoring thread to exit main process when browser subprocess exits - self._start_monitor_thread() - - # Register cleanup - import atexit - - atexit.register(self.close) - - except KeyboardInterrupt as ki: - print("\nClosing Playwright browser...") - handle_keyboard_interrupt(ki) - except Exception as e: - warnings.warn( - f"Failed to start Playwright browser: {e}. Falling back to default browser." - ) - import webbrowser - - webbrowser.open(url) - - def _start_monitor_thread(self) -> None: - """Start a thread to monitor the browser process and exit main process when it terminates.""" - if self.monitor_thread is not None: - return - - def monitor_process(): - """Monitor the browser process and exit when it terminates.""" - if self.process is None: - return - - try: - # Wait for the process to terminate - self.process.join() - - # Check if the process terminated (and we didn't kill it ourselves) - if ( - self.process.exitcode is not None - and not self._closing_intentionally - ): - print("[MAIN] Browser closed, exiting main program") - # Force exit the entire program - os._exit(0) - - except KeyboardInterrupt as ki: - print("[MAIN] Browser monitor interrupted by user") - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"[MAIN] Error monitoring browser process: {e}") - - self.monitor_thread = threading.Thread(target=monitor_process, daemon=True) - self.monitor_thread.start() - - def close(self) -> None: - """Close the Playwright browser.""" - if self.process and self.process.is_alive(): - print("Closing Playwright browser...") - # Mark that we're intentionally closing to prevent monitor from triggering exit - self._closing_intentionally = True - self.process.terminate() - self.process.join(timeout=5) - if self.process.is_alive(): - self.process.kill() - self.process = None - - -def run_playwright_browser_persistent( - url: str, headless: bool = False, enable_extensions: bool = True -) -> None: - """Run Playwright browser in a persistent mode that stays alive until terminated. - - Args: - url: The URL to open - headless: Whether to run in headless mode - enable_extensions: Whether to enable Chrome extensions (C++ DevTools Support) - """ - - async def main(): - browser = None - try: - browser = PlaywrightBrowser( - headless=headless, enable_extensions=enable_extensions - ) - await browser.start() - await browser.open_url(url) - - print( - "Playwright browser opened. Browser will remain open until the FastLED process exits." - ) - - # Keep the browser alive until exit is signaled - while not browser._should_exit.is_set(): - await asyncio.sleep(0.1) - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - # If we get an error that suggests browsers aren't installed, try to install them - if "executable doesn't exist" in str(e) or "Browser not found" in str(e): - print("🎭 Playwright browsers not found. Installing...") - if install_playwright_browsers(): - print("🎭 Retrying browser startup...") - # Try again with fresh browser instance - browser = PlaywrightBrowser( - headless=headless, enable_extensions=enable_extensions - ) - await browser.start() - await browser.open_url(url) - - print( - "Playwright browser opened. Browser will remain open until the FastLED process exits." - ) - - # Keep the browser alive until exit is signaled - while not browser._should_exit.is_set(): - await asyncio.sleep(0.1) - else: - print("❌ Failed to install Playwright browsers") - raise e - else: - raise e - finally: - if browser is not None: - try: - await browser.close() - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"Warning: Failed to close Playwright browser: {e}") - - try: - asyncio.run(main()) - except KeyboardInterrupt as ki: - print("\nPlaywright browser closed.") - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"Playwright browser failed: {e}") - - -def open_with_playwright( - url: str, headless: bool = False, enable_extensions: bool = True -) -> PlaywrightBrowserProxy: - """Open URL with Playwright browser and return a proxy object for lifecycle management. - - This function can be used as a drop-in replacement for webbrowser.open(). - - Args: - url: The URL to open - headless: Whether to run in headless mode - enable_extensions: Whether to enable Chrome extensions (C++ DevTools Support) - - Returns: - PlaywrightBrowserProxy object for managing the browser lifecycle - """ - proxy = PlaywrightBrowserProxy() - proxy.open(url, headless, enable_extensions) - return proxy - - -def install_playwright_browsers() -> bool: - """Install Playwright browsers if not already installed. - - Installs browsers to ~/.fastled/playwright directory. - - Returns: - True if installation was successful or browsers were already installed - """ - - try: - import os - from pathlib import Path - - # Set custom browser installation path - playwright_dir = Path.home() / ".fastled" / "playwright" - playwright_dir.mkdir(parents=True, exist_ok=True) - - # Check if browsers are installed in the custom directory - import glob - import platform - - if platform.system() == "Windows": - chromium_pattern = str( - playwright_dir / "chromium-*" / "chrome-win" / "chrome.exe" - ) - elif platform.system() == "Darwin": # macOS - chromium_pattern = str( - playwright_dir / "chromium-*" / "chrome-mac" / "Chromium.app" - ) - else: # Linux - chromium_pattern = str( - playwright_dir / "chromium-*" / "chrome-linux" / "chrome" - ) - - if glob.glob(chromium_pattern): - print(f"✅ Playwright browsers already installed at: {playwright_dir}") - return True - - # If we get here, browsers need to be installed - print("Installing Playwright browsers...") - print(f"Installing to: {playwright_dir}") - import subprocess - - env = dict(os.environ) - env["PLAYWRIGHT_BROWSERS_PATH"] = str(playwright_dir.resolve()) - - result = subprocess.run( - [sys.executable, "-m", "playwright", "install", "chromium"], - env=env, - ) - - if result.returncode == 0: - print("✅ Playwright browsers installed successfully!") - print(f" Location: {playwright_dir}") - - # Also download the C++ DevTools Support extension - try: - from fastled.playwright.chrome_extension_downloader import ( - download_cpp_devtools_extension, - ) - - extension_path = download_cpp_devtools_extension() - if extension_path: - print( - "✅ C++ DevTools Support extension ready for DWARF debugging!" - ) - else: - print("⚠️ C++ DevTools Support extension download failed") - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - print(f"⚠️ Failed to setup C++ DevTools Support extension: {e}") - - return True - else: - print( - f"❌ Failed to install Playwright browsers (exit code: {result.returncode})" - ) - return False - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - raise - except Exception as e: - print(f"❌ Error installing Playwright browsers: {e}") - return False diff --git a/src/fastled/playwright/resize_tracking.py b/src/fastled/playwright/resize_tracking.py deleted file mode 100644 index 1ce095b0..00000000 --- a/src/fastled/playwright/resize_tracking.py +++ /dev/null @@ -1,133 +0,0 @@ -""" -Resize tracking for Playwright browser integration. - -This module provides a class to track browser window resize events and adjust -the viewport accordingly without using internal polling loops. -""" - -from typing import Any - -from fastled.interrupts import handle_keyboard_interrupt - - -class ResizeTracker: - """Tracks browser window resize events and adjusts viewport accordingly.""" - - def __init__(self, page: Any): - """Initialize the resize tracker. - - Args: - page: The Playwright page object to track - """ - self.page = page - self.last_outer_size: tuple[int, int] | None = None - - async def _get_window_info(self) -> dict[str, int] | None: - """Get browser window dimensions information. - - Returns: - Dictionary containing window dimensions or None if unable to retrieve - """ - if self.page is None: - return None - - try: - return await self.page.evaluate( - """ - () => { - return { - outerWidth: window.outerWidth, - outerHeight: window.outerHeight, - innerWidth: window.innerWidth, - innerHeight: window.innerHeight, - contentWidth: document.documentElement.clientWidth, - contentHeight: document.documentElement.clientHeight - }; - } - """ - ) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception: - return None - - async def set_viewport_size(self, width: int, height: int) -> None: - """Set the viewport size. - - Args: - width: The viewport width - height: The viewport height - """ - if self.page is None: - raise Exception("Page is None") - - await self.page.set_viewport_size({"width": width, "height": height}) - - async def update(self) -> Exception | None: - """Update the resize tracking and adjust viewport if needed. - - Returns: - None if successful, Exception if an error occurred - """ - try: - # Check if page is still alive - if self.page is None or self.page.is_closed(): - return Exception("Page closed") - - window_info = await self._get_window_info() - - if window_info: - current_outer = ( - window_info["outerWidth"], - window_info["outerHeight"], - ) - - # Check if window size changed - if ( - self.last_outer_size is None - or current_outer != self.last_outer_size - ): - - if self.last_outer_size is not None: - print("[PYTHON] *** BROWSER WINDOW RESIZED ***") - print( - f"[PYTHON] Outer window changed from {self.last_outer_size[0]}x{self.last_outer_size[1]} to {current_outer[0]}x{current_outer[1]}" - ) - - self.last_outer_size = current_outer - - # Set viewport to match the outer window size - outer_width = int(window_info["outerWidth"]) - outer_height = int(window_info["outerHeight"]) - - print( - f"[PYTHON] Setting viewport to match outer window size: {outer_width}x{outer_height}" - ) - - await self.set_viewport_size(outer_width, outer_height) - print("[PYTHON] Viewport set successfully") - - # Query the actual window dimensions after the viewport change - updated_window_info = await self._get_window_info() - - if updated_window_info: - print(f"[PYTHON] Updated window info: {updated_window_info}") - - # Update our tracking with the actual final outer size - self.last_outer_size = ( - updated_window_info["outerWidth"], - updated_window_info["outerHeight"], - ) - print( - f"[PYTHON] Updated last_outer_size to actual final size: {self.last_outer_size}" - ) - else: - print("[PYTHON] Could not get updated window info") - - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as e: - return e - - # Success case - return None diff --git a/src/fastled/types.py b/src/fastled/types.py index fc914515..6d9817e7 100644 --- a/src/fastled/types.py +++ b/src/fastled/types.py @@ -1,15 +1,29 @@ -from dataclasses import dataclass +from dataclasses import asdict, dataclass from enum import Enum -from typing import Any, Protocol +from typing import Protocol from fastled.print_filter import PrintFilterDefault +CompileResultValue = bool | str | bytes | float | None + class _BuildModeArgs(Protocol): debug: bool release: bool +@dataclass +class CompileResultSnapshot: + success: bool + stdout: str + hash_value: str | None + zip_bytes: bytes + zip_time: float + libfastled_time: float + sketch_time: float + response_processing_time: float + + @dataclass class CompileResult: success: bool @@ -24,8 +38,20 @@ class CompileResult: def __bool__(self) -> bool: return self.success - def to_dict(self) -> dict[str, Any]: - return self.__dict__.copy() + def to_dataclass(self) -> CompileResultSnapshot: + return CompileResultSnapshot( + success=self.success, + stdout=self.stdout, + hash_value=self.hash_value, + zip_bytes=self.zip_bytes, + zip_time=self.zip_time, + libfastled_time=self.libfastled_time, + sketch_time=self.sketch_time, + response_processing_time=self.response_processing_time, + ) + + def to_dict(self) -> dict[str, CompileResultValue]: + return asdict(self.to_dataclass()) def __post_init__(self): # Filter the stdout. diff --git a/test_native_playwright.py b/test_native_playwright.py deleted file mode 100644 index e261e24c..00000000 --- a/test_native_playwright.py +++ /dev/null @@ -1,246 +0,0 @@ -""" -Playwright browser test for native WASM compilation. - -Uses subprocess isolation to avoid asyncio/threading conflicts on Windows. -""" - -import json -import socket -import subprocess -import sys -import time -from pathlib import Path - -# Windows console defaults to cp1252, which can't encode emoji that FastLED -# prints to console (🔧, ✅, etc.). Reconfigure stdout/stderr to UTF-8 so the -# relevant-message dump near the end of main() doesn't UnicodeEncodeError. -sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined] -sys.stderr.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined] - -FASTLED_JS = Path.home() / "dev" / "fastled7" / "examples" / "Blink" / "fastled_js" - -# Inline server script - runs in its own subprocess -SERVER_SCRIPT = r""" -import sys, socket -from pathlib import Path -from flask import Flask, Response, send_from_directory -from flask_cors import CORS -from werkzeug.serving import make_server - -app = Flask(__name__) -CORS(app) -D = sys.argv[1] - -@app.after_request -def h(r): - r.headers["Cross-Origin-Embedder-Policy"] = "credentialless" - r.headers["Cross-Origin-Opener-Policy"] = "same-origin" - r.headers["Cache-Control"] = "no-cache" - return r - -@app.route("/") -def idx(): - return send_from_directory(D, "index.html") - -@app.route("/") -def f(p): - r = send_from_directory(D, p) - if p.endswith(".js"): r.headers["Content-Type"] = "text/javascript; charset=utf-8" - elif p.endswith(".wasm"): r.headers["Content-Type"] = "application/wasm" - elif p.endswith(".css"): r.headers["Content-Type"] = "text/css" - elif p.endswith(".json"): r.headers["Content-Type"] = "application/json" - return r - -srv = make_server("127.0.0.1", 0, app) -port = srv.server_address[1] -print(f"PORT:{port}", flush=True) -srv.serve_forever() -""" - -# Inline Playwright script - runs in its own subprocess -PLAYWRIGHT_SCRIPT = r""" -import json, os, sys, time -from pathlib import Path - -port = int(sys.argv[1]) -url = f"http://localhost:{port}/" - -# Only redirect PLAYWRIGHT_BROWSERS_PATH if the dir actually contains a -# Chromium install. The dir can exist with only user-data/ in it, in which -# case Playwright searches an empty location and fails to launch. -browsers_path = Path.home() / ".fastled" / "playwright" -if browsers_path.exists() and any(browsers_path.glob("chromium*")): - os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(browsers_path) - -from playwright.sync_api import sync_playwright - -console_msgs = [] -errors = [] - -with sync_playwright() as p: - browser = p.chromium.launch(headless=True, args=["--no-sandbox","--disable-web-security","--allow-insecure-localhost"]) - page = browser.new_page() - - page.on("console", lambda m: console_msgs.append(m.text)) - page.on("pageerror", lambda e: errors.append(str(e))) - - page.goto(url, wait_until="domcontentloaded") - - success_signals = [ - "extern_setup() completed", - "FastLED initialized", - "PROXY_TO_PTHREAD setup complete", - "async platform pump", - "main() pthread ready", - "extern_loop()", - ] - - setup_ok = False - deadline = time.time() + 45 - while time.time() < deadline: - for msg in console_msgs: - if any(sig in msg for sig in success_signals): - setup_ok = True - break - if setup_ok: - break - page.wait_for_timeout(500) - - if setup_ok: - page.wait_for_timeout(2000) - - try: title = page.title() - except: title = "?" - - try: - canvas = page.evaluate("() => { const c = document.querySelector('canvas'); return c ? {exists:true,w:c.width,h:c.height} : {exists:false}; }") - except: canvas = None - - try: sab = page.evaluate("typeof SharedArrayBuffer !== 'undefined'") - except: sab = None - - browser.close() - -print(json.dumps({ - "setup_ok": setup_ok, - "title": title, - "canvas": canvas, - "sab": sab, - "console_count": len(console_msgs), - "relevant": [m[:200] for m in console_msgs if any(kw in m.lower() for kw in ["fastled","worker","extern_setup","extern_loop","initialized","animation","error","failed","not defined","import.meta","mime","pthread","platform pump"])], - "errors": [e[:200] for e in errors], -})) -""" - - -def main() -> int: - if not FASTLED_JS.exists(): - print(f"ERROR: {FASTLED_JS} not found. Run native compile first.") - return 1 - - for f in ["index.html", "fastled.js", "fastled.wasm", "fastled_background_worker.js"]: - if not (FASTLED_JS / f).exists(): - print(f"ERROR: Missing {f}") - return 1 - - print("=" * 60) - print(" PLAYWRIGHT BROWSER TEST - NATIVE WASM BUILD") - print("=" * 60) - - # Step 1: Start server subprocess - print("\n[1/2] Starting HTTP server...") - server_proc = subprocess.Popen( - [sys.executable, "-u", "-c", SERVER_SCRIPT, str(FASTLED_JS.resolve())], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - encoding="utf-8", - errors="replace", - ) - - port = None - deadline = time.time() + 15 - while time.time() < deadline: - line = server_proc.stdout.readline().strip() # type: ignore - if line.startswith("PORT:"): - port = int(line.split(":")[1]) - break - - if port is None: - print("ERROR: Server didn't report port") - server_proc.kill() - return 1 - - # Wait until connectable - for _ in range(30): - try: - with socket.create_connection(("127.0.0.1", port), timeout=1): - break - except OSError: - time.sleep(0.3) - else: - print("ERROR: Server not connectable") - server_proc.kill() - return 1 - - print(f" Server ready on port {port}") - - # Step 2: Run Playwright in separate subprocess - print("\n[2/2] Running Playwright browser validation...") - try: - pw_result = subprocess.run( - [sys.executable, "-u", "-c", PLAYWRIGHT_SCRIPT, str(port)], - capture_output=True, - encoding="utf-8", - errors="replace", - timeout=90, - ) - result = json.loads(pw_result.stdout.strip().split("\n")[-1]) - except subprocess.TimeoutExpired: - print(" Playwright subprocess timed out after 90s") - result = {"setup_ok": False, "relevant": [], "errors": ["timeout"], "console_count": 0} - except Exception as e: - print(f" Playwright error: {e}") - if "pw_result" in locals(): - stdout = pw_result.stdout or "" # type: ignore - stderr = pw_result.stderr or "" # type: ignore - print(f" stdout: {stdout[:500]}") - print(f" stderr: {stderr[:500]}") - result = {"setup_ok": False, "relevant": [], "errors": [str(e)], "console_count": 0} - finally: - server_proc.kill() - server_proc.wait() - - # Report - print(f"\n Title: {result.get('title', '?')}") - print(f" Canvas: {result.get('canvas')}") - print(f" SharedArrayBuffer: {result.get('sab')}") - - print("\n" + "=" * 60) - print(" RESULTS") - print("=" * 60) - - relevant = result.get("relevant", []) - print(f"\nConsole messages ({result.get('console_count', 0)} total, {len(relevant)} relevant):") - for msg in relevant: - print(f" {msg}") - - page_errors = result.get("errors", []) - if page_errors: - print(f"\nPage errors ({len(page_errors)}):") - for err in page_errors: - print(f" ERROR: {err}") - - setup_ok = result.get("setup_ok", False) - print() - if setup_ok and not page_errors: - print("PASS: FastLED.js initialized (WASM loaded, worker active, no page errors)") - elif setup_ok: - print("WARN: FastLED.js initialized but page errors occurred") - else: - print("FAIL: FastLED.js did NOT complete initialization") - - return 0 if setup_ok else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/integration/test_animartrix_e2e.py b/tests/integration/test_animartrix_e2e.py index ba11b994..554650db 100644 --- a/tests/integration/test_animartrix_e2e.py +++ b/tests/integration/test_animartrix_e2e.py @@ -1,45 +1,33 @@ """ -End-to-end test for the Animartrix example. +End-to-end compile test for the Animartrix example. -This test: -1. Compiles ~/dev/fastled/examples/Animartrix using native EMSDK -2. Starts a server serving the compiled output -3. Opens the page in a headless Playwright browser -4. Verifies the page loads with no JavaScript errors +This test compiles ~/dev/fastled/examples/Animartrix using the native toolchain +and verifies the expected browser-ready output files are emitted. """ -import asyncio import os -import random import subprocess -import time import unittest from pathlib import Path import pytest # type: ignore[reportMissingImports] -from playwright.async_api import async_playwright # type: ignore[reportMissingImports] -from fastled import Test from fastled._rust_cli import find_rust_fastled_cli from fastled.interrupts import handle_keyboard_interrupt ANIMARTRIX_DIR = Path.home() / "dev" / "fastled" / "examples" / "Animartrix" FASTLED_JS_DIR = ANIMARTRIX_DIR / "fastled_js" -# Use a random port to avoid conflicts with other tests -TEST_PORT = random.randint(9200, 9400) - class AnimartrixE2ETest(unittest.TestCase): - """End-to-end test: compile Animartrix, serve it, open in browser, check for errors.""" + """End-to-end test: compile Animartrix and check browser-ready output.""" @pytest.mark.timeout(600) - def test_animartrix_compiles_and_runs_in_browser(self) -> None: - """Compile Animartrix, serve it, and verify no JS errors in the browser.""" + def test_animartrix_compiles_and_emits_browser_output(self) -> None: + """Compile Animartrix and verify expected output artifacts exist.""" if not ANIMARTRIX_DIR.exists(): self.skipTest(f"Animartrix example not found at {ANIMARTRIX_DIR}") - # Step 1: Compile the sketch original_dir = os.getcwd() try: os.chdir(str(ANIMARTRIX_DIR)) @@ -65,7 +53,6 @@ def test_animartrix_compiles_and_runs_in_browser(self) -> None: finally: os.chdir(original_dir) - # Verify output exists self.assertTrue( FASTLED_JS_DIR.exists(), f"Expected output dir {FASTLED_JS_DIR} to exist" ) @@ -77,75 +64,7 @@ def test_animartrix_compiles_and_runs_in_browser(self) -> None: "Expected fastled.wasm in output", ) - # Step 2: Serve and test in browser - asyncio.run(self._verify_browser_no_errors()) - - async def _verify_browser_no_errors(self) -> None: - """Start server, open page in Playwright, and check for JS errors.""" - proc = Test.spawn_http_server( - FASTLED_JS_DIR, - open_browser=False, - enable_https=False, - ) - - try: - time.sleep(2) - # The Rust server auto-assigns a port; use localhost default - server_url = "http://localhost:8089" - - async with async_playwright() as p: - browser = await p.chromium.launch(headless=True) - - try: - context = await browser.new_context() - page = await context.new_page() - - # Collect console errors - errors: list[str] = [] - page.on( - "console", - lambda msg: ( - errors.append(msg.text) if msg.type == "error" else None - ), - ) - page.on( - "pageerror", - lambda exc: errors.append(str(exc)), - ) - - # Navigate to the page - response = await page.goto( - server_url, - wait_until="domcontentloaded", - timeout=30000, - ) - - self.assertIsNotNone(response, "Failed to load page") - assert response is not None - self.assertEqual( - response.status, - 200, - f"Expected 200, got {response.status}", - ) - - # Wait for WASM to load and run briefly - await page.wait_for_timeout(5000) - - # Check for errors - if errors: - self.fail( - "Browser console errors detected:\n" - + "\n".join(f" - {e}" for e in errors) - ) - - print(f"Animartrix e2e test passed: {server_url}") - - finally: - await browser.close() - - finally: - proc.terminate() - time.sleep(1) + print(f"Animartrix compile test passed: {FASTLED_JS_DIR}") if __name__ == "__main__": diff --git a/tests/integration/test_playwright_integration.py b/tests/integration/test_playwright_integration.py deleted file mode 100644 index 381c90ec..00000000 --- a/tests/integration/test_playwright_integration.py +++ /dev/null @@ -1,62 +0,0 @@ -""" -Unit tests for Playwright integration. -""" - -import unittest -from unittest.mock import MagicMock, patch - -from fastled.playwright.playwright_browser import open_with_playwright - - -class PlaywrightIntegrationTester(unittest.TestCase): - """Test Playwright integration functionality.""" - - def test_open_with_playwright_fallback(self): - """Test that open_with_playwright falls back to webbrowser when Playwright is not available.""" - test_url = "http://localhost:8089" - - # Mock multiprocessing.Process to raise an exception, simulating Playwright not being available - with patch( - "multiprocessing.Process", side_effect=Exception("Playwright not available") - ): - with patch("webbrowser.open") as mock_webbrowser_open: - # Call the function - proxy = open_with_playwright(test_url) - - # Verify that webbrowser.open was called as fallback - mock_webbrowser_open.assert_called_once_with(test_url) - - # Verify that a proxy object was returned - self.assertIsNotNone(proxy) - - def test_open_with_playwright_when_available(self): - """Test that open_with_playwright uses Playwright when available.""" - test_url = "http://localhost:8089" - - # Mock the multiprocessing.Process to work normally (Playwright available) - # Also mock os._exit to prevent the monitor thread from killing the process - with patch("multiprocessing.Process") as mock_process_class: - mock_process = MagicMock() - # Make join() block so monitor thread doesn't race ahead - mock_process.join.side_effect = lambda *args, **kwargs: None - mock_process.exitcode = None # Process hasn't exited - mock_process.is_alive.return_value = False - mock_process_class.return_value = mock_process - - with patch("os._exit"): - # Call the function - proxy = open_with_playwright(test_url) - - # Verify that a new process was created and started - mock_process_class.assert_called_once() - mock_process.start.assert_called_once() - - # Verify that a proxy object was returned - self.assertIsNotNone(proxy) - - # Test cleanup - proxy.close() # Should not raise an exception - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/test_build_service.py b/tests/unit/test_build_service.py index 40dbe8c6..fdeb0209 100644 --- a/tests/unit/test_build_service.py +++ b/tests/unit/test_build_service.py @@ -1,6 +1,12 @@ from pathlib import Path - -from fastled.build_types import BuildRequest +from typing import cast + +from fastled.build_types import ( + BuildArtifacts, + BuildRequest, + BuildStrategy, + NativeBuildPayload, +) from fastled.types import BuildMode @@ -42,7 +48,7 @@ def build( profile: bool = False, fastled_path: str | None = None, force_clean: bool = False, - ) -> dict[str, object]: + ) -> NativeBuildPayload: del build_mode_obj strategy = self.detect_strategy( sketch_dir, build_mode, profile, fastled_path, force_clean @@ -57,28 +63,26 @@ def build( assets_dir.mkdir(exist_ok=True) (assets_dir / "main.js").write_text("asset") self.states[Path(sketch_dir).resolve()] = (build_mode, profile, fastled_path) - return { - "success": True, - "stdout": "Native Rust WASM build successful", - "hash_value": None, - "zip_bytes": b"zip", - "zip_time": 0.01, - "libfastled_time": 0.0, - "sketch_time": 0.02, - "response_processing_time": 0.0, - "strategy": strategy, - "output_dir": str(output_dir), - "artifacts": { - "js": str(output_dir / "fastled.js"), - "wasm": str(output_dir / "fastled.wasm"), - "frontend_assets": str(assets_dir), - **( - {"dwarf": str(output_dir / "fastled.wasm.dwarf")} - if build_mode == "DEBUG" - else {} - ), - }, - } + return NativeBuildPayload( + success=True, + stdout="Native Rust WASM build successful", + hash_value=None, + zip_bytes=b"zip", + zip_time=0.01, + libfastled_time=0.0, + sketch_time=0.02, + response_processing_time=0.0, + strategy=cast(BuildStrategy, strategy), + output_dir=output_dir, + artifacts=BuildArtifacts( + js=output_dir / "fastled.js", + wasm=output_dir / "fastled.wasm", + dwarf=(output_dir / "fastled.wasm.dwarf") + if build_mode == "DEBUG" + else None, + frontend_assets=assets_dir, + ), + ) def purge(self, sketch_dir: str) -> None: self.states.pop(Path(sketch_dir).resolve(), None) @@ -108,6 +112,10 @@ def test_build_service_starts_cold_then_turns_incremental( first = service.build(request) assert first.success is True assert first.strategy == "cold" + assert isinstance(first.artifacts, BuildArtifacts) + assert first.artifacts.js == sketch_dir / "fastled_js" / "fastled.js" + assert first.artifacts.wasm == sketch_dir / "fastled_js" / "fastled.wasm" + assert first.artifacts.frontend_assets == sketch_dir / "fastled_js" / "assets" assert first.artifacts["js"] == sketch_dir / "fastled_js" / "fastled.js" assert first.artifacts["wasm"] == sketch_dir / "fastled_js" / "fastled.wasm" assert first.artifacts["frontend_assets"] == sketch_dir / "fastled_js" / "assets" diff --git a/tests/unit/test_post_migration.py b/tests/unit/test_post_migration.py index 72471b4f..3e4f1023 100644 --- a/tests/unit/test_post_migration.py +++ b/tests/unit/test_post_migration.py @@ -133,8 +133,11 @@ def test_remaining_python_modules_document_wrapper_or_holdout_role(self) -> None def test_remaining_python_wrappers_delegate_to_native_helpers(self) -> None: for filename in self.WRAPPER_MODULES_WITH_NATIVE_DELEGATES: source = (SRC_DIR / filename).read_text() + expected_delegate = ( + "fastled._rust_cli" if filename == "open_browser.py" else "fastled._native" + ) self.assertIn( - "fastled._native", + expected_delegate, source, f"{filename} should delegate core behavior to native helpers", ) @@ -157,6 +160,11 @@ def test_remaining_python_holdouts_are_not_fallback_service_owners(self) -> None f"{filename} is a compatibility holdout, not a fallback service owner", ) + def test_rust_build_orchestration_has_no_python_cli_fallback(self) -> None: + source = (ROOT_DIR / "crates" / "fastled-cli" / "src" / "build.rs").read_text() + self.assertNotIn("python -m " + "fastled.app", source) + self.assertNotIn("run_build_" + "subprocess", source) + def test_types_do_not_import_legacy_args_at_runtime(self) -> None: source = (SRC_DIR / "types.py").read_text() self.assertNotIn("from fastled.args import Args", source) @@ -225,6 +233,27 @@ def test_legacy_native_toolchain_launchers_removed(self) -> None: self.assertFalse((native_tools / "launcher_emcc.cpp").exists()) self.assertFalse((native_tools / "launcher_wasmld.cpp").exists()) + def test_playwright_package_removed(self) -> None: + self.assertFalse((SRC_DIR / "playwright").exists()) + requirements = (ROOT_DIR / "requirements.testing.txt").read_text() + self.assertNotIn("playwright", requirements.lower()) + + def test_cli_removed_browser_mode_flags_and_extension_plumbing(self) -> None: + cli_source = (FASTLED_CLI_SRC_DIR / "lib.rs").read_text() + install_source = (FASTLED_CLI_SRC_DIR / "install.rs").read_text() + vscode_source = (SRC_DIR / "install" / "vscode_config.py").read_text() + + for source in (cli_source, install_source, vscode_source): + self.assertNotIn("--app", source) + self.assertNotIn("--legacy-browser", source) + self.assertNotIn("internal_ensure_chrome_extension", source) + self.assertNotIn("chrome-extensions", source) + self.assertNotIn("CHROME_CRX", source) + + self.assertIn("viewer::launch_tauri_viewer", cli_source) + self.assertNotIn("ViewerMode::Browser", cli_source) + self.assertNotIn("fn open_browser", cli_source) + class TestAllExportsValid(unittest.TestCase): """Bug 3: __all__ must not export stale symbols from the removed server code."""