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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ members = [
]

[workspace.package]
version = "2.0.10"
version = "2.0.11"
edition = "2021"
rust-version = "1.85"
license = "MIT"
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ Useful flags:
| `--purge` | Clear cached FastLED downloads and stale WASM build artifacts |
| `--serve-dir <dir>` | Serve an existing directory without compiling |

Set `FASTLED_VIEWER_LOGS=1` to forward the viewer window's browser console output (`console.*`, uncaught errors, failed fetches) to the terminal's stderr, prefixed with `[viewer]` — useful when diagnosing a blank or broken viewer.

## Features

### Hot Reload
Expand Down
24 changes: 24 additions & 0 deletions crates/fastled-cli/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,16 @@ async fn build_stream(State(state): State<AppState>) -> Response {
.into_response()
}

/// `POST /viewer-log` — receive console/error lines forwarded from the Tauri
/// viewer's injected logging script (enabled via `FASTLED_VIEWER_LOGS`) and
/// echo them to stderr so viewer-side failures are diagnosable.
async fn viewer_log(body: String) -> Response {
for line in body.lines() {
eprintln!("[viewer] {line}");
}
StatusCode::NO_CONTENT.into_response()
}

// ---------------------------------------------------------------------------
// DWARF debug source handlers
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -423,6 +433,7 @@ pub async fn start_server(
.route("/", get(serve_index))
.route("/build-stream", get(build_stream))
.route("/dwarfsource", post(dwarf_source))
.route("/viewer-log", post(viewer_log))
.route("/debug/source-roots", get(debug_source_roots))
.route("/{*path}", get(serve_file))
.layer(SetResponseHeaderLayer::overriding(
Expand Down Expand Up @@ -485,6 +496,19 @@ mod tests {
(addr, dir)
}

#[tokio::test]
async fn test_viewer_log_endpoint_accepts_posts() {
let (addr, _dir) = setup_server().await;
let client = reqwest::Client::new();
let resp = client
.post(format!("http://{addr}/viewer-log"))
.body("error: something broke")
.send()
.await
.unwrap();
assert_eq!(resp.status(), 204);
}

#[tokio::test]
async fn test_loading_page_when_no_index_html() {
let (addr, _dir) = setup_server().await;
Expand Down
80 changes: 77 additions & 3 deletions crates/fastled-cli/src/tauri_viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,56 @@ pub struct ViewerOptions {
pub height: u32,
}

/// Injected when `FASTLED_VIEWER_LOGS` is enabled: forwards `console.*`,
/// uncaught errors, unhandled rejections, and failed fetches to the FastLED
/// HTTP server's `POST /viewer-log` endpoint, which echoes them to stderr.
const LOG_FORWARD_SCRIPT: &str = r#"
(() => {
const send = (line) => {
try { fetch('/viewer-log', { method: 'POST', body: line }); } catch (_) {}
};
const fmt = (args) => Array.from(args).map((a) => {
if (a instanceof Error) return a.stack || String(a);
if (typeof a === 'object' && a !== null) {
try { return JSON.stringify(a); } catch (_) { return String(a); }
}
return String(a);
}).join(' ');
for (const level of ['log', 'info', 'warn', 'error', 'debug']) {
const original = console[level].bind(console);
console[level] = (...args) => { original(...args); send(level + ': ' + fmt(args)); };
}
window.addEventListener('error', (e) => {
send('window.onerror: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')');
});
window.addEventListener('unhandledrejection', (e) => {
send('unhandledrejection: ' + fmt([e.reason]));
});
const originalFetch = window.fetch.bind(window);
window.fetch = async (...args) => {
const url = String(args[0] && args[0].url ? args[0].url : args[0]);
if (url.endsWith('/viewer-log')) return originalFetch(...args);
try {
const resp = await originalFetch(...args);
if (!resp.ok) send('fetch failed: ' + resp.status + ' ' + url);
return resp;
} catch (err) {
send('fetch error: ' + url + ' ' + String(err));
throw err;
}
};
})();
"#;

fn env_flag_enabled(value: Option<&str>) -> bool {
matches!(value, Some(v) if !v.is_empty() && v != "0")
}

fn viewer_logs_enabled() -> bool {
let value = std::env::var("FASTLED_VIEWER_LOGS").ok();
env_flag_enabled(value.as_deref())
}

pub fn run(options: ViewerOptions) -> ExitCode {
let ViewerOptions {
url,
Expand All @@ -19,10 +69,13 @@ pub fn run(options: ViewerOptions) -> ExitCode {
.setup(move |app| {
let url = tauri::WebviewUrl::External(url.parse()?);

let window = tauri::WebviewWindowBuilder::new(app, "main", url)
let mut builder = tauri::WebviewWindowBuilder::new(app, "main", url)
.title(&title)
.inner_size(width as f64, height as f64)
.build()?;
.inner_size(width as f64, height as f64);
if viewer_logs_enabled() {
builder = builder.initialization_script(LOG_FORWARD_SCRIPT);
}
let window = builder.build()?;

// Counteract WebView2 DPI auto-scaling while keeping the UI readable.
let scale = window.scale_factor().unwrap_or(1.0);
Expand All @@ -46,3 +99,24 @@ pub fn run(options: ViewerOptions) -> ExitCode {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn viewer_logs_flag_parsing() {
assert!(!env_flag_enabled(None));
assert!(!env_flag_enabled(Some("")));
assert!(!env_flag_enabled(Some("0")));
assert!(env_flag_enabled(Some("1")));
assert!(env_flag_enabled(Some("true")));
}

#[test]
fn log_forward_script_targets_server_endpoint() {
assert!(LOG_FORWARD_SCRIPT.contains("/viewer-log"));
assert!(LOG_FORWARD_SCRIPT.contains("unhandledrejection"));
assert!(LOG_FORWARD_SCRIPT.contains("window.addEventListener('error'"));
}
}
88 changes: 56 additions & 32 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,54 +40,77 @@ def _workspace_package_version() -> str:
return version


def _candidate_binaries() -> list[Path]:
def _candidate_binaries(root: Path) -> list[Path]:
candidates: list[Path] = []
target = os.environ.get("CARGO_BUILD_TARGET") or os.environ.get(
"FASTLED_RUST_TARGET"
)
if target:
candidates.append(ROOT / "target" / target / "release" / EXE_NAME)
candidates.append(root / "target" / target / "release" / EXE_NAME)
if sys.platform == "win32":
candidates.extend(
[
ROOT / "target" / "x86_64-pc-windows-msvc" / "release" / EXE_NAME,
ROOT / "target" / "aarch64-pc-windows-msvc" / "release" / EXE_NAME,
root / "target" / "x86_64-pc-windows-msvc" / "release" / EXE_NAME,
root / "target" / "aarch64-pc-windows-msvc" / "release" / EXE_NAME,
]
)
candidates.append(ROOT / "target" / "release" / EXE_NAME)
cargo_home = Path(os.environ.get("CARGO_HOME", Path.home() / ".cargo"))
candidates.append(cargo_home / "bin" / EXE_NAME)
candidates.append(root / "target" / "release" / EXE_NAME)
return candidates


def _copy_first_available_binary() -> bool:
PACKAGE_BIN_DIR.mkdir(parents=True, exist_ok=True)
dest = PACKAGE_BIN_DIR / EXE_NAME
for candidate in _candidate_binaries():
def _stale_bundled_binary_paths(root: Path) -> list[Path]:
paths = [root / "src" / "fastled" / "bin" / EXE_NAME]
build_dir = root / "build"
if build_dir.is_dir():
paths.extend(build_dir.glob(f"lib*/fastled/bin/{EXE_NAME}"))
return paths


def _remove_stale_bundled_binaries(root: Path) -> None:
for path in _stale_bundled_binary_paths(root):
if path.is_file():
path.unlink()


def _copy_first_available_binary(root: Path) -> bool:
bin_dir = root / "src" / "fastled" / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)
dest = bin_dir / EXE_NAME
for candidate in _candidate_binaries(root):
if candidate.is_file():
shutil.copy2(candidate, dest)
# copy2 preserves the source mtime; bump it so setuptools'
# mtime-based "newer" checks always replace stale build/lib copies.
os.utime(dest)
return True
return False


def ensure_bundled_fastled_binary() -> None:
dest = PACKAGE_BIN_DIR / EXE_NAME
if dest.is_file():
def ensure_bundled_fastled_binary(root: Path = ROOT) -> None:
dest = root / "src" / "fastled" / "bin" / EXE_NAME

if (root / "Cargo.toml").is_file():
# Source build: a pre-existing binary may predate the current source
# (issue #165 shipped a broken viewer for days this way), so always
# rebuild and never harvest stale copies from the tree or elsewhere.
_remove_stale_bundled_binaries(root)
command = [*_cargo_command(), "build", "--release", "--bin", "fastled"]
target = os.environ.get("FASTLED_RUST_TARGET")
if target:
command.extend(["--target", target])
subprocess.check_call(command, cwd=root)
if not _copy_first_available_binary(root):
raise RuntimeError("built fastled binary was not found")
return

if _copy_first_available_binary():
if dest.is_file():
# Building from an archive that already bundles the binary.
return

if not (ROOT / "Cargo.toml").is_file():
raise RuntimeError("Cargo.toml was not found; cannot build bundled fastled")

command = [*_cargo_command(), "build", "--release", "--bin", "fastled"]
target = os.environ.get("FASTLED_RUST_TARGET")
if target:
command.extend(["--target", target])
subprocess.check_call(command, cwd=ROOT)
if not _copy_first_available_binary():
raise RuntimeError("built fastled binary was not found")
raise RuntimeError(
"Cargo.toml was not found and no bundled fastled binary exists; "
"cannot build fastled"
)


class BinaryDistribution(Distribution):
Expand All @@ -105,10 +128,11 @@ def get_tag(self) -> tuple[str, str, str]:
return "py3", "none", platform


setup(
version=_workspace_package_version(),
distclass=BinaryDistribution,
cmdclass={
"bdist_wheel": bdist_wheel,
},
)
if __name__ == "__main__":
setup(
version=_workspace_package_version(),
distclass=BinaryDistribution,
cmdclass={
"bdist_wheel": bdist_wheel,
},
)
Loading
Loading