From d5a694ec73891e1ae1a3c3c24417c900fef4b2ad Mon Sep 17 00:00:00 2001 From: Cimos <10230773+Cimos@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:35:49 +1100 Subject: [PATCH 1/2] gui: reload and re-diff when inputs change Poll each loaded side's folder, zip, PDF or dropped files for size and mtime changes. After 500 ms of quiet the side is re-read and re-diffed, keeping the camera, selected layer, visibility and rulers when the layer stack is unchanged. A failed reload keeps the previous result with the error in the load banner. Native only; toggle in Settings > Input, on by default. Refs #423 --- CHANGELOG.md | 6 + crates/etchy-gui/src/main.rs | 584 ++++++++++++++++++++++++++++++++-- crates/etchy-gui/src/watch.rs | 344 ++++++++++++++++++++ docs/REQUIREMENTS.md | 1 + docs/design/GUI_SPEC.md | 11 +- 5 files changed, 922 insertions(+), 24 deletions(-) create mode 100644 crates/etchy-gui/src/watch.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index e6b834c..bda1460 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ Cut a new section here as part of tagging a release — see "Cutting a release" Diff-only controls are hidden or disabled. Opening or dropping an old revision turns it into a normal diff, and the welcome screen can show one loaded set alone, including in the web viewer (#466). +- Desktop viewer reloads and re-diffs when the opened files change on disk, + for example after a re-export, so it no longer has to be reopened. It waits + for half a second of quiet so a half-written fab pack is not read, keeps the + camera, selected layer and visibility, and briefly says it reloaded. A failed + reload keeps the previous result on screen with the error. Toggle in + Settings > Input, on by default (#423). ### Fixed - A drill or placement file that fails to parse is no longer reported as diff --git a/crates/etchy-gui/src/main.rs b/crates/etchy-gui/src/main.rs index dc7f7c0..8117221 100644 --- a/crates/etchy-gui/src/main.rs +++ b/crates/etchy-gui/src/main.rs @@ -22,6 +22,9 @@ mod lod; // module is (deliberately) dead — the pure helpers stay compiled + unit-tested. #[cfg_attr(not(feature = "pdf"), allow(dead_code))] mod pdfview; +// Reload on change (#423): native only, the web viewer has no files to watch. +#[cfg(not(target_arch = "wasm32"))] +mod watch; use eframe::egui; use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, StrokeKind}; @@ -148,10 +151,11 @@ mod native { /// What the command line loaded before the window opens. enum Seed { - /// Two revisions and their computed diff, at the PDF DPI used. - Pair(LoadedSource, LoadedSource, ComputedDiff, f32), - /// One Gerber set on its own (#466) and its single-set view. - Single(LoadedSource, BoardDiff), + /// Two revisions and their computed diff, at the PDF DPI used, plus + /// the paths they came from (watched for reloads, #423). + Pair(LoadedSource, LoadedSource, ComputedDiff, f32, [PathBuf; 2]), + /// One Gerber set on its own (#466), its single-set view and its path. + Single(LoadedSource, BoardDiff, PathBuf), } /// Load one Gerber directory or `.zip` for the single-set view (#466), @@ -159,7 +163,7 @@ mod native { fn load_single_seed(path: &Path) -> anyhow::Result { let src = load_source_any(path, label(path))?; let view = single_from_source(&src)?; - Ok(Seed::Single(src, view)) + Ok(Seed::Single(src, view, path.to_path_buf())) } /// Load both revisions from CLI paths — Gerber dirs/zips or schematic PDFs @@ -180,7 +184,13 @@ mod native { Err(_) => return Err(first), }, }; - Ok(Seed::Pair(old, new, diff, dpi)) + Ok(Seed::Pair( + old, + new, + diff, + dpi, + [old_path.to_path_buf(), new_path.to_path_buf()], + )) } /// Construct the app, restoring persisted settings. With a pair seed, both @@ -188,15 +198,16 @@ mod native { /// single-set view (#466); without one, the welcome screen shows (empty diff). fn build_app(cc: &eframe::CreationContext<'_>, seed: Option) -> ViewApp { match seed { - Some(Seed::Single(src, view)) => { + Some(Seed::Single(src, view, path)) => { // Built straight from the view so persisted per-board settings // (visible layers, #327) restore onto it like a diff's. let l = src.label().to_string(); let mut app = ViewApp::from_cc(cc, view, l.clone(), l); app.enter_single(src); + app.origin_new = Some(SourceOrigin::Path(path)); app } - Some(Seed::Pair(old, new, computed, seed_dpi)) => { + Some(Seed::Pair(old, new, computed, seed_dpi, [old_path, new_path])) => { let (ol, nl) = (old.label().to_string(), new.label().to_string()); let mut app = match computed { ComputedDiff::Board(diff) => ViewApp::from_cc(cc, diff, ol, nl), @@ -208,6 +219,8 @@ mod native { }; app.src_old = Some(old); app.src_new = Some(new); + app.origin_old = Some(SourceOrigin::Path(old_path)); + app.origin_new = Some(SourceOrigin::Path(new_path)); // The seed was rasterized before settings restore; honour a // different persisted DPI now (#223). If that re-rasterize // fails (caps), the setting must fall back to the DPI the @@ -1281,6 +1294,7 @@ fn input_rect(mode: Mode, full: Rect, px: f32) -> Rect { } /// Pan/zoom camera in world (nm) space. +#[derive(Clone)] struct Camera { center: [f64; 2], // world nm scale: f64, // pixels per nm @@ -1744,8 +1758,34 @@ struct ViewApp { brand_tex: Option, /// Which edge the activity rail lives on (Feature 8); persisted via #52. rail_side: RailSide, + /// Reload and re-diff when an opened input changes on disk (#423). On by + /// default; toggled in Settings > Input and persisted. Native only in + /// effect (the web viewer has nothing to watch), but kept on both + /// surfaces so one settings blob round-trips everywhere. + watch_inputs: bool, + /// Where each side was loaded from on disk (#423), so a change there can + /// be re-read. `None` for a side with no source or no files behind it. + #[cfg(not(target_arch = "wasm32"))] + origin_old: Option, + #[cfg(not(target_arch = "wasm32"))] + origin_new: Option, + /// The running watchers, one per side (#423). Rebuilt when the origins or + /// the toggle change; dropping one stops its thread. + #[cfg(not(target_arch = "wasm32"))] + watch_old: Option, + #[cfg(not(target_arch = "wasm32"))] + watch_new: Option, + /// "Reloaded after a file change" and when it was shown (#423), so a + /// reload never changes the screen without saying so. Cleared after + /// `RELOAD_NOTE_SECS`. + #[cfg(not(target_arch = "wasm32"))] + reload_note: Option<(String, f64)>, } +/// How long the reload notice stays up (#423). +#[cfg(not(target_arch = "wasm32"))] +const RELOAD_NOTE_SECS: f64 = 4.0; + /// A one-line note reconciling the export with the Overlay view's noise filter /// (#245/#91). The Overlay view hides diff regions below `min_area_mm2`, but the /// export includes ALL regions (the safe direction — an export must never hide a @@ -1858,6 +1898,17 @@ impl ViewApp { active_panel: Some(PanelTab::Layers), brand_tex: None, rail_side: RailSide::default(), + watch_inputs: true, + #[cfg(not(target_arch = "wasm32"))] + origin_old: None, + #[cfg(not(target_arch = "wasm32"))] + origin_new: None, + #[cfg(not(target_arch = "wasm32"))] + watch_old: None, + #[cfg(not(target_arch = "wasm32"))] + watch_new: None, + #[cfg(not(target_arch = "wasm32"))] + reload_note: None, } } @@ -2549,6 +2600,9 @@ struct Settings { rail_side: RailSide, /// The user's hotkey map (#201). Missing in pre-#201 configs → defaults. keymap: Keymap, + /// Reload when an opened input changes (#423). Missing in older configs → + /// on, the default. + watch_inputs: bool, } impl Default for Settings { @@ -2573,6 +2627,7 @@ impl Default for Settings { swipe_frac: 0.5, rail_side: RailSide::default(), keymap: Keymap::default(), + watch_inputs: true, } } } @@ -2730,6 +2785,7 @@ impl ViewApp { swipe_frac: self.swipe_frac, rail_side: self.rail_side, keymap: self.keymap, + watch_inputs: self.watch_inputs, } } @@ -2783,6 +2839,7 @@ impl ViewApp { self.swipe_frac = clamp_swipe_frac(s.swipe_frac); self.rail_side = s.rail_side; self.keymap = s.keymap; + self.watch_inputs = s.watch_inputs; } } @@ -2878,6 +2935,18 @@ impl ViewApp { }; match single_from_source(src) { Ok(view) => { + // The set becomes the new side; its origin moves with it so + // the reload watcher (#423) keeps covering it. + #[cfg(not(target_arch = "wasm32"))] + { + let origin = if self.src_old.is_some() { + self.origin_old.take() + } else { + self.origin_new.take() + }; + self.origin_old = None; + self.origin_new = origin; + } let src = self.src_old.take().or_else(|| self.src_new.take()); if let Some(src) = src { self.adopt_single(view, src); @@ -3034,11 +3103,146 @@ impl ViewApp { self.last_dir = Some(parent.to_path_buf()); } match load_source_any(path, derive_label(path)) { - Ok(src) => self.set_side(side, src), + Ok(src) => { + self.set_side(side, src); + if self.load_error.is_none() { + self.set_origin(side, SourceOrigin::Path(path.to_path_buf())); + } + } Err(e) => self.load_error = Some(format!("{e:#}")), } } + /// Record where a side now comes from (#423), after it loaded cleanly. + #[cfg(not(target_arch = "wasm32"))] + fn set_origin(&mut self, side: RevSide, origin: SourceOrigin) { + match side { + RevSide::Old => self.origin_old = Some(origin), + RevSide::New => self.origin_new = Some(origin), + } + } + + /// Start, stop or replace the per-side watchers (#423) so they cover + /// exactly the loaded sides' origins while the setting is on. Cheap when + /// nothing changed: it only compares path lists. + #[cfg(not(target_arch = "wasm32"))] + fn sync_watchers(&mut self, ctx: &egui::Context) { + fn want( + on: bool, + loaded: bool, + origin: &Option, + ) -> Option> { + if on && loaded { + origin.as_ref().map(SourceOrigin::roots) + } else { + None + } + } + fn sync( + slot: &mut Option, + roots: Option>, + ctx: &egui::Context, + ) { + let current = slot.as_ref().map(|w| w.roots().to_vec()); + if current == roots { + return; + } + *slot = roots.map(|r| { + let ctx = ctx.clone(); + watch::FileWatcher::spawn(r, move || ctx.request_repaint()) + }); + } + let old = want(self.watch_inputs, self.src_old.is_some(), &self.origin_old); + let new = want(self.watch_inputs, self.src_new.is_some(), &self.origin_new); + sync(&mut self.watch_old, old, ctx); + sync(&mut self.watch_new, new, ctx); + } + + /// Once per frame (#423): keep the watchers in step, and reload any side + /// whose files changed and then settled. + #[cfg(not(target_arch = "wasm32"))] + fn poll_watchers(&mut self, ctx: &egui::Context, now: f64) { + self.sync_watchers(ctx); + let old = self.watch_old.as_ref().is_some_and(|w| w.take_change()); + let new = self.watch_new.as_ref().is_some_and(|w| w.take_change()); + if old || new { + self.reload_sides(old, new, now); + } + if let Some((_, at)) = self.reload_note { + if now - at >= RELOAD_NOTE_SECS { + self.reload_note = None; + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64( + RELOAD_NOTE_SECS - (now - at), + )); + } + } + } + + /// Re-read the changed sides from disk and re-diff (#423), keeping the + /// camera, selection, visibility and rulers when the layer stack is the + /// same. Any failure, reading or diffing, leaves the previous result and + /// sources on screen with the error in the banner (the #330 path). + #[cfg(not(target_arch = "wasm32"))] + fn reload_sides(&mut self, old: bool, new: bool, now: f64) { + fn read(want: bool, origin: &Option) -> anyhow::Result> { + match (want, origin) { + (true, Some(o)) => o.reload().map(Some), + _ => Ok(None), + } + } + let fresh = read(old, &self.origin_old).and_then(|o| Ok((o, read(new, &self.origin_new)?))); + let (fresh_old, fresh_new) = match fresh { + Ok(pair) => pair, + Err(e) => { + self.load_error = Some(format!( + "reload after a file change: {e:#} (the previous result is still shown)" + )); + return; + } + }; + if fresh_old.is_none() && fresh_new.is_none() { + return; + } + let kept = self.keep_view(); + let prev_old = fresh_old.map(|s| self.src_old.replace(s)); + let prev_new = fresh_new.map(|s| self.src_new.replace(s)); + self.load_error = None; + self.rebuild_diff(); + if let Some(e) = self.load_error.take() { + if let Some(p) = prev_old { + self.src_old = p; + } + if let Some(p) = prev_new { + self.src_new = p; + } + self.load_error = Some(format!( + "reload after a file change: {e} (the previous result is still shown)" + )); + return; + } + let same_view = self.restore_view(kept); + let mut labels = Vec::new(); + if prev_old.is_some() { + labels.push(self.old_label.clone()); + } + if prev_new.is_some() { + labels.push(self.new_label.clone()); + } + let tail = if same_view { + "" + } else { + "; the layers changed, so the view was reset" + }; + self.reload_note = Some(( + format!( + "reloaded {} after a file change{tail}", + labels.join(" and ") + ), + now, + )); + } + /// The primary toolbar "Open" action for a side: a folder on native, the /// browser file picker on web. fn open_primary(&mut self, side: RevSide, _ctx: &egui::Context) { @@ -3104,7 +3308,18 @@ impl ViewApp { return; } match load_dropped_paths(&paths) { - Ok(loaded) => self.adopt_sources(side, loaded), + Ok(loaded) => { + self.adopt_sources(side, loaded); + if self.load_error.is_none() { + match drop_origins(&paths) { + DroppedOrigins::One(o) => self.set_origin(side, o), + DroppedOrigins::Pair { old, new } => { + self.origin_old = Some(old); + self.origin_new = Some(new); + } + } + } + } Err(e) => self.load_error = Some(format!("{e:#}")), } } @@ -3635,20 +3850,16 @@ fn is_fab_pack(p: &std::path::Path) -> bool { #[cfg(not(target_arch = "wasm32"))] fn load_dropped_paths(paths: &[std::path::PathBuf]) -> anyhow::Result { use anyhow::Context as _; - if paths.len() == 1 { - let p = &paths[0]; - if is_fab_pack(p) || is_pdf_input(p) { - return load_source_any(p, derive_label(p)).map(DroppedSources::One); + match drop_shape(paths) { + DropShape::Single(p) => { + return load_source_any(p, derive_label(p)).map(DroppedSources::One) } - } - if paths.len() == 2 && paths.iter().all(|p| is_fab_pack(p)) { - // Order by file name (#325); label the same way Open does (#329). - let mut pair: Vec<(String, &std::path::PathBuf)> = - paths.iter().map(|p| (path_label(p), p)).collect(); - pair.sort_by(|a, b| a.0.cmp(&b.0)); - let old = load_source_any(pair[0].1, derive_label(pair[0].1))?; - let new = load_source_any(pair[1].1, derive_label(pair[1].1))?; - return Ok(DroppedSources::Pair { old, new }); + DropShape::Pair(o, n) => { + let old = load_source_any(o, derive_label(o))?; + let new = load_source_any(n, derive_label(n))?; + return Ok(DroppedSources::Pair { old, new }); + } + DropShape::Loose => {} } if paths.iter().any(|p| p.is_dir()) { anyhow::bail!("a folder was dropped beside other files — {DROP_SHAPE_HINT}"); @@ -3679,6 +3890,153 @@ fn load_dropped_paths(paths: &[std::path::PathBuf]) -> anyhow::Result { + Single(&'a std::path::PathBuf), + Pair(&'a std::path::PathBuf, &'a std::path::PathBuf), + Loose, +} + +#[cfg(not(target_arch = "wasm32"))] +fn drop_shape(paths: &[std::path::PathBuf]) -> DropShape<'_> { + if paths.len() == 1 { + let p = &paths[0]; + if is_fab_pack(p) || is_pdf_input(p) { + return DropShape::Single(p); + } + } + if paths.len() == 2 && paths.iter().all(|p| is_fab_pack(p)) { + // Order by file name (#325); label the same way Open does (#329). + let mut pair: Vec<(String, &std::path::PathBuf)> = + paths.iter().map(|p| (path_label(p), p)).collect(); + pair.sort_by(|a, b| a.0.cmp(&b.0)); + return DropShape::Pair(pair[0].1, pair[1].1); + } + DropShape::Loose +} + +/// Where one side was loaded from on disk (#423), kept so a change there can +/// be re-read through the same loader. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug, PartialEq, Eq)] +enum SourceOrigin { + /// A folder, `.zip` fab pack or schematic `.pdf`. + Path(std::path::PathBuf), + /// Loose layer files dropped together as one set. + Files(Vec), +} + +#[cfg(not(target_arch = "wasm32"))] +impl SourceOrigin { + /// The paths to watch for this side. + fn roots(&self) -> Vec { + match self { + SourceOrigin::Path(p) => vec![p.clone()], + SourceOrigin::Files(ps) => ps.clone(), + } + } + + /// Read this side again, the same way it was first loaded. + fn reload(&self) -> anyhow::Result { + match self { + SourceOrigin::Path(p) => load_source_any(p, derive_label(p)), + SourceOrigin::Files(ps) => match load_dropped_paths(ps)? { + DroppedSources::One(src) => Ok(src), + DroppedSources::Pair { .. } => { + anyhow::bail!("the reloaded files now read as two revisions, not one") + } + }, + } + } +} + +/// The origins a native drop resolved to (#423), mirroring [`DroppedSources`]. +#[cfg(not(target_arch = "wasm32"))] +enum DroppedOrigins { + One(SourceOrigin), + Pair { + old: SourceOrigin, + new: SourceOrigin, + }, +} + +#[cfg(not(target_arch = "wasm32"))] +fn drop_origins(paths: &[std::path::PathBuf]) -> DroppedOrigins { + match drop_shape(paths) { + DropShape::Single(p) => DroppedOrigins::One(SourceOrigin::Path(p.clone())), + DropShape::Pair(o, n) => DroppedOrigins::Pair { + old: SourceOrigin::Path(o.clone()), + new: SourceOrigin::Path(n.clone()), + }, + DropShape::Loose => DroppedOrigins::One(SourceOrigin::Files(paths.to_vec())), + } +} + +/// The view state a reload keeps (#423): camera, selected layer (or page), +/// layer visibility, per-layer colours and rulers. Restored only when the +/// reloaded comparison has the same layer stack (or page counts), since all +/// of it is indexed per layer or in board coordinates. +#[cfg(not(target_arch = "wasm32"))] +struct KeptView { + key: String, + cam: Camera, + selected: usize, + visible_layers: Vec, + base_overrides: Vec<(usize, Color32)>, + measurements: Vec, + pdf_selected: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl ViewApp { + /// What identifies the shown comparison's layout, for [`KeptView`]. + fn view_key(&self) -> String { + match &self.pdf { + Some(p) => format!("pdf:{}:{}", p.old_pages, p.new_pages), + None => format!("board:{}", board_key(&self.diff)), + } + } + + fn keep_view(&self) -> KeptView { + KeptView { + key: self.view_key(), + cam: self.cam.clone(), + selected: self.selected, + visible_layers: self.visible_layers.clone(), + base_overrides: self.base_overrides.clone(), + measurements: self.measurements.clone(), + pdf_selected: self.pdf.as_ref().map(|p| p.selected), + } + } + + /// Put back a kept view after a reload, if the layout still matches. + /// Returns whether it was restored. + fn restore_view(&mut self, kept: KeptView) -> bool { + if kept.key != self.view_key() || !kept.cam.fitted { + return false; + } + self.cam = kept.cam; + if kept.selected < self.diff.layers.len() { + self.selected = kept.selected; + } + if kept.visible_layers.len() == self.visible_layers.len() { + self.visible_layers = kept.visible_layers; + } + self.base_overrides = kept.base_overrides; + self.measurements = kept.measurements; + if let (Some(pdf), Some(sel)) = (self.pdf.as_mut(), kept.pdf_selected) { + if sel < pdf.rows.len() { + pdf.selected = sel; + } + } + true + } +} + impl ViewApp { /// The top-bar brand mark's texture (#191): decode the embedded brand-icon /// PNG and upload it once, on first use; every later frame returns the cached @@ -3753,6 +4111,12 @@ impl eframe::App for ViewApp { } } self.handle_dropped_files(ui.ctx()); + // Reload on change (#423): native only. + #[cfg(not(target_arch = "wasm32"))] + { + let now = ui.ctx().input(|i| i.time); + self.poll_watchers(ui.ctx(), now); + } // Startup splash (foreground overlay; skipped once done). Drawn before the // panels so it covers the welcome screen too, but composited on top. @@ -4232,6 +4596,13 @@ impl eframe::App for ViewApp { ui.colored_label(C_REMOVED, format!("[!] load failed — {err}")); }); } + // A reload after a file change says so, briefly (#423). + #[cfg(not(target_arch = "wasm32"))] + if let Some((note, _)) = self.reload_note.clone() { + egui::Panel::top("reload_note").show_inside(ui, |ui| { + ui.colored_label(C_COPPER, note); + }); + } // Activity rail (Feature 1): a slim VS Code-style strip on `rail_side` // (Feature 8) — one icon per side panel top-down, the Settings cog pinned @@ -5134,6 +5505,14 @@ impl ViewApp { "Pan mouse button by ECAD tool: \ Altium = right-drag, KiCad = middle/right-drag.", ); + // The web viewer has no files on disk to watch (#423). + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut self.watch_inputs, "Reload when files change") + .on_hover_text( + "Re-read and re-diff an opened folder, zip, PDF or set of files when it \ + changes on disk, once it has been quiet for half a second. The camera, \ + selected layer and visibility are kept.", + ); } /// Settings → Colours: diff colours + per-theme canvas/grid (#53/#31/#52). @@ -8027,6 +8406,162 @@ mod tests { assert_eq!(app.new_label, "new"); } + /// Two revision folders on disk, each holding one copper layer, for the + /// reload tests (#423). + #[cfg(not(target_arch = "wasm32"))] + fn reload_fixture(tag: &str) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { + let root = std::env::temp_dir().join(format!("etchy-reload-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (old, new) = (root.join("rev-a"), root.join("rev-b")); + for d in [&old, &new] { + std::fs::create_dir_all(d).unwrap(); + std::fs::write(d.join("board-F_Cu.gtl"), MIN_GERBER).unwrap(); + } + (root, old, new) + } + + /// [`MIN_GERBER`] with a bigger pad: a real change on the same board. + const GROWN_GERBER: &[u8] = b"%FSLAX46Y46*%\n%MOMM*%\n%ADD10C,1.2*%\nD10*\nX0Y0D03*\nM02*\n"; + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn reload_rediffs_and_keeps_the_view() { + use super::{RevSide, SourceOrigin, ViewApp}; + let (root, old, new) = reload_fixture("keep"); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.load_side_path(RevSide::Old, &old); + app.load_side_path(RevSide::New, &new); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + assert_eq!(app.origin_new, Some(SourceOrigin::Path(new.clone()))); + assert!(!app.diff.layers[0].is_changed()); + + // The user has framed something and hidden the layer. + app.cam.fitted = true; + app.cam.center = [123.0, 456.0]; + app.cam.scale = 0.5; + app.visible_layers[0] = false; + + std::fs::write(new.join("board-F_Cu.gtl"), GROWN_GERBER).unwrap(); + app.reload_sides(false, true, 10.0); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + assert!(app.diff.layers[0].is_changed(), "the re-export was diffed"); + assert_eq!(app.cam.center, [123.0, 456.0], "camera kept"); + assert_eq!(app.cam.scale, 0.5); + assert!(!app.visible_layers[0], "visibility kept"); + let (note, at) = app.reload_note.clone().expect("a reload says so"); + assert!(note.contains("after a file change"), "got: {note}"); + assert!(!note.contains("reset"), "same layers, view kept: {note}"); + assert_eq!(at, 10.0); + std::fs::remove_dir_all(&root).ok(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn reload_with_a_new_layer_resets_the_view_and_says_so() { + use super::{RevSide, ViewApp}; + let (root, old, new) = reload_fixture("reset"); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.load_side_path(RevSide::Old, &old); + app.load_side_path(RevSide::New, &new); + app.cam.fitted = true; + app.cam.center = [123.0, 456.0]; + + std::fs::write(new.join("board-B_Cu.gbl"), MIN_GERBER).unwrap(); + app.reload_sides(false, true, 1.0); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + assert_eq!(app.diff.layers.len(), 2); + assert!(!app.cam.fitted, "a different stack re-fits"); + let (note, _) = app.reload_note.clone().unwrap(); + assert!(note.contains("view was reset"), "got: {note}"); + std::fs::remove_dir_all(&root).ok(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn failed_reload_keeps_the_previous_result_on_screen() { + use super::{LoadedSource, RevSide, ViewApp}; + let (root, old, new) = reload_fixture("fail"); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.load_side_path(RevSide::Old, &old); + app.load_side_path(RevSide::New, &new); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + + // The new side becomes a PDF-vs-Gerber pair: reading works, diffing + // fails, and the board pair must stay on screen and in the sources. + let new_pdf = root.join("rev-b.pdf"); + std::fs::write(&new_pdf, b"%PDF-1.7").unwrap(); + app.origin_new = Some(super::SourceOrigin::Path(new_pdf)); + app.reload_sides(false, true, 1.0); + let err = app.load_error.clone().expect("a failed reload fails loud"); + assert!(err.contains("reload after a file change"), "got: {err}"); + assert!(err.contains("previous result is still shown"), "got: {err}"); + assert!(matches!(app.src_new, Some(LoadedSource::Board(_)))); + assert_eq!(app.diff.layers.len(), 1); + assert!(app.reload_note.is_none()); + + // A read failure (the folder is gone) is reported the same way. + app.load_error = None; + app.origin_new = Some(super::SourceOrigin::Path(root.join("missing"))); + app.reload_sides(false, true, 2.0); + let err = app.load_error.clone().expect("a failed read fails loud"); + assert!(err.contains("reload after a file change"), "got: {err}"); + assert!(matches!(app.src_new, Some(LoadedSource::Board(_)))); + std::fs::remove_dir_all(&root).ok(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn drop_origins_follow_the_drop_shape() { + use super::{drop_origins, DroppedOrigins, SourceOrigin}; + let (root, old, new) = reload_fixture("shape"); + match drop_origins(&[new.clone(), old.clone()]) { + DroppedOrigins::Pair { old: o, new: n } => { + assert_eq!(o, SourceOrigin::Path(old.clone()), "old = first by name"); + assert_eq!(n, SourceOrigin::Path(new.clone())); + } + DroppedOrigins::One(_) => panic!("two folders are a pair"), + } + match drop_origins(std::slice::from_ref(&old)) { + DroppedOrigins::One(o) => assert_eq!(o, SourceOrigin::Path(old.clone())), + DroppedOrigins::Pair { .. } => panic!("one folder is one side"), + } + let loose = vec![old.join("board-F_Cu.gtl"), new.join("board-F_Cu.gtl")]; + match drop_origins(&loose) { + DroppedOrigins::One(o) => { + assert_eq!(o, SourceOrigin::Files(loose.clone())); + assert_eq!(o.roots(), loose); + } + DroppedOrigins::Pair { .. } => panic!("loose files are one set"), + } + std::fs::remove_dir_all(&root).ok(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn watchers_follow_the_toggle_and_the_loaded_sides() { + use super::{RevSide, ViewApp}; + let (root, old, new) = reload_fixture("toggle"); + let ctx = egui::Context::default(); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.sync_watchers(&ctx); + assert!(app.watch_old.is_none() && app.watch_new.is_none()); + app.load_side_path(RevSide::Old, &old); + app.load_side_path(RevSide::New, &new); + app.sync_watchers(&ctx); + assert_eq!( + app.watch_old.as_ref().unwrap().roots(), + std::slice::from_ref(&old) + ); + assert_eq!( + app.watch_new.as_ref().unwrap().roots(), + std::slice::from_ref(&new) + ); + app.watch_inputs = false; + app.sync_watchers(&ctx); + assert!(app.watch_old.is_none() && app.watch_new.is_none()); + std::fs::remove_dir_all(&root).ok(); + } + /// A one-layer Gerber set for the single-set tests (#466). fn single_board(label: &str, warnings: Vec) -> super::LoadedSource { let (board, fmt, _) = crate::loader::board_from_bytes(vec![( @@ -9194,6 +9729,8 @@ mod tests { let mut app2 = ViewApp::new(empty_diff(), "x".into(), "y".into()); app2.apply_settings(bare); assert_eq!(app2.base_opacity, BASE_OPACITY_FAINT); + // Reload on change (#423) is on for configs that predate it. + assert!(app2.watch_inputs); } #[test] @@ -9892,6 +10429,7 @@ mod tests { swipe_frac: 0.42, rail_side: RailSide::Right, keymap, + watch_inputs: false, }; let json = serde_json::to_string(&s).expect("serialize"); let back: Settings = serde_json::from_str(&json).expect("deserialize"); diff --git a/crates/etchy-gui/src/watch.rs b/crates/etchy-gui/src/watch.rs new file mode 100644 index 0000000..e50d5bd --- /dev/null +++ b/crates/etchy-gui/src/watch.rs @@ -0,0 +1,344 @@ +//! Reload on change (#423): notice when an opened input is re-exported and +//! say when it has settled, so the viewer can re-diff without being reopened. +//! +//! Change detection polls file sizes and modification times; no new +//! dependency and no OS watcher API, so it behaves the same on every desktop +//! platform and on network or FUSE mounts where file events are unreliable. +//! A folder is watched one level deep, matching how the loader reads it. +//! +//! [`Debouncer`] is pure logic over snapshots and a clock, so the quiet-period +//! rule is unit tested without touching the disk or sleeping. [`FileWatcher`] +//! runs it on a background thread and wakes the UI only when a reload is due, +//! so an idle viewer does not repaint just to poll. +//! +//! Native only: the web viewer gets bytes from the browser and has nothing to +//! watch. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime}; + +/// How long the inputs must stay unchanged before a reload fires. A CAD +/// export writes a fab pack file by file over a second or two; reloading in +/// the middle would diff a half-written set. +pub const QUIET: Duration = Duration::from_millis(500); + +/// How often the background thread re-reads the file metadata. +pub const POLL: Duration = Duration::from_millis(250); + +/// What one path looked like at one moment. `None` means the path did not +/// exist or could not be read, so a deleted or renamed file is a change too. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stamp { + pub len: u64, + pub modified: Option, +} + +/// The state of every watched file, keyed by path. Two snapshots compare +/// equal exactly when no watched file was added, removed, resized or touched. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Snapshot(BTreeMap>); + +#[cfg(test)] +impl Snapshot { + /// Build a snapshot from given entries, for tests. + pub fn from_entries(entries: impl IntoIterator)>) -> Self { + Self(entries.into_iter().collect()) + } +} + +fn stamp(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok()?; + Some(Stamp { + len: meta.len(), + modified: meta.modified().ok(), + }) +} + +/// Read the current state of `roots`. A file root is stamped directly. A +/// folder root contributes its own entry plus one per file directly inside +/// it, so adding, deleting or rewriting a layer file all register. A folder +/// that cannot be listed records `None` for itself, which differs from any +/// listing that worked. +pub fn take(roots: &[PathBuf]) -> Snapshot { + let mut map = BTreeMap::new(); + for root in roots { + if root.is_dir() { + match std::fs::read_dir(root) { + Ok(entries) => { + map.insert(root.clone(), stamp(root)); + for entry in entries.flatten() { + let p = entry.path(); + if p.is_file() { + let s = stamp(&p); + map.insert(p, s); + } + } + } + Err(_) => { + map.insert(root.clone(), None); + } + } + } else { + map.insert(root.clone(), stamp(root)); + } + } + Snapshot(map) +} + +/// The quiet-period rule. Fed a snapshot on every poll, it reports a reload +/// once the inputs differ from the last loaded state and have then held still +/// for `quiet`. Every further change during the wait restarts the clock, and +/// a change that is undone before the wait ends is dropped. +#[derive(Debug)] +pub struct Debouncer { + /// The state the viewer last loaded (or last reloaded for). + baseline: Snapshot, + /// A differing state and when it was first seen unchanged. + pending: Option<(Snapshot, Instant)>, + quiet: Duration, +} + +impl Debouncer { + pub fn new(baseline: Snapshot, quiet: Duration) -> Self { + Self { + baseline, + pending: None, + quiet, + } + } + + /// Feed the latest snapshot. Returns true when a reload is due; the new + /// state then becomes the baseline, so one export fires once. + pub fn observe(&mut self, now: Instant, snap: Snapshot) -> bool { + if snap == self.baseline { + self.pending = None; + return false; + } + match &self.pending { + Some((seen, since)) if *seen == snap => { + if now.duration_since(*since) >= self.quiet { + self.baseline = snap; + self.pending = None; + return true; + } + false + } + _ => { + self.pending = Some((snap, now)); + false + } + } + } +} + +/// A background poller over one set of input paths. Dropping it stops the +/// thread at its next poll. +pub struct FileWatcher { + roots: Vec, + stop: Arc, + rx: Receiver<()>, +} + +impl FileWatcher { + /// Start watching `roots`. The baseline is read here, on the caller's + /// thread, so a change made right after this call is never missed. + /// `wake` runs on the watcher thread whenever a reload becomes due. + pub fn spawn(roots: Vec, wake: impl Fn() + Send + 'static) -> Self { + let stop = Arc::new(AtomicBool::new(false)); + let (tx, rx): (Sender<()>, Receiver<()>) = std::sync::mpsc::channel(); + let baseline = take(&roots); + let thread_roots = roots.clone(); + let thread_stop = Arc::clone(&stop); + let spawned = std::thread::Builder::new() + .name("etchy-watch".into()) + .spawn(move || { + let mut deb = Debouncer::new(baseline, QUIET); + while !thread_stop.load(Ordering::Relaxed) { + std::thread::sleep(POLL); + if thread_stop.load(Ordering::Relaxed) { + break; + } + if deb.observe(Instant::now(), take(&thread_roots)) { + if tx.send(()).is_err() { + break; + } + wake(); + } + } + }); + // A thread that cannot start leaves a watcher that never fires; the + // viewer still works, it just will not auto-reload. + if let Err(e) = spawned { + eprintln!("etchy-gui: could not start the file watcher: {e}"); + } + Self { roots, stop, rx } + } + + /// The paths this watcher covers. + pub fn roots(&self) -> &[PathBuf] { + &self.roots + } + + /// True if at least one reload became due since the last call. Several + /// queued signals collapse into one reload. + pub fn take_change(&self) -> bool { + let mut any = false; + while self.rx.try_recv().is_ok() { + any = true; + } + any + } +} + +impl Drop for FileWatcher { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn snap(len: u64) -> Snapshot { + Snapshot::from_entries([( + PathBuf::from("a.gbr"), + Some(Stamp { + len, + modified: None, + }), + )]) + } + + const Q: Duration = Duration::from_millis(500); + + #[test] + fn unchanged_inputs_never_fire() { + let t0 = Instant::now(); + let mut d = Debouncer::new(snap(1), Q); + for ms in [0, 300, 600, 5000] { + assert!(!d.observe(t0 + Duration::from_millis(ms), snap(1))); + } + } + + #[test] + fn a_change_fires_once_after_the_quiet_period() { + let t0 = Instant::now(); + let mut d = Debouncer::new(snap(1), Q); + assert!(!d.observe(t0, snap(2)), "first sight only starts the clock"); + assert!(!d.observe(t0 + Duration::from_millis(250), snap(2))); + assert!(d.observe(t0 + Duration::from_millis(500), snap(2))); + // The settled state is the new baseline: no repeat fire. + assert!(!d.observe(t0 + Duration::from_millis(750), snap(2))); + assert!(!d.observe(t0 + Duration::from_millis(5000), snap(2))); + } + + #[test] + fn writes_during_the_wait_restart_the_clock() { + let t0 = Instant::now(); + let mut d = Debouncer::new(snap(1), Q); + let at = |ms| t0 + Duration::from_millis(ms); + assert!(!d.observe(at(0), snap(2))); + assert!(!d.observe(at(400), snap(3))); // still being written + assert!(!d.observe(at(800), snap(3)), "only 400 ms quiet so far"); + assert!(d.observe(at(900), snap(3))); + } + + #[test] + fn a_change_undone_before_the_wait_ends_is_dropped() { + let t0 = Instant::now(); + let mut d = Debouncer::new(snap(1), Q); + let at = |ms| t0 + Duration::from_millis(ms); + assert!(!d.observe(at(0), snap(2))); + assert!(!d.observe(at(250), snap(1))); + assert!(!d.observe(at(1000), snap(1))); + } + + #[test] + fn a_second_export_fires_again() { + let t0 = Instant::now(); + let mut d = Debouncer::new(snap(1), Q); + let at = |ms| t0 + Duration::from_millis(ms); + assert!(!d.observe(at(0), snap(2))); + assert!(d.observe(at(500), snap(2))); + assert!(!d.observe(at(2000), snap(3))); + assert!(d.observe(at(2500), snap(3))); + } + + fn scratch(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("etchy-watch-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn folder_snapshot_sees_added_rewritten_and_removed_files() { + let dir = scratch("folder"); + let roots = vec![dir.clone()]; + std::fs::write(dir.join("top.gtl"), b"G04*").unwrap(); + let s0 = take(&roots); + assert_eq!(take(&roots), s0, "nothing changed"); + + std::fs::write(dir.join("top.gtl"), b"G04 longer*").unwrap(); + let s1 = take(&roots); + assert_ne!(s1, s0, "a resized file is a change"); + + std::fs::write(dir.join("bot.gbl"), b"G04*").unwrap(); + let s2 = take(&roots); + assert_ne!(s2, s1, "an added file is a change"); + + std::fs::remove_file(dir.join("bot.gbl")).unwrap(); + assert_ne!(take(&roots), s2, "a removed file is a change"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn file_snapshot_sees_a_rewrite_and_a_delete() { + let dir = scratch("file"); + let f = dir.join("pack.zip"); + std::fs::write(&f, b"one").unwrap(); + let roots = vec![f.clone()]; + let s0 = take(&roots); + std::fs::write(&f, b"three").unwrap(); + let s1 = take(&roots); + assert_ne!(s1, s0); + std::fs::remove_file(&f).unwrap(); + let s2 = take(&roots); + assert_ne!(s2, s1); + assert_eq!(s2, Snapshot::from_entries([(f, None)])); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn watcher_signals_after_a_settled_change() { + let dir = scratch("thread"); + let f = dir.join("top.gtl"); + std::fs::write(&f, b"one").unwrap(); + let woke = Arc::new(AtomicBool::new(false)); + let w = Arc::clone(&woke); + let watcher = FileWatcher::spawn(vec![dir.clone()], move || { + w.store(true, Ordering::Relaxed); + }); + assert_eq!(watcher.roots(), std::slice::from_ref(&dir)); + std::fs::write(&f, b"a longer body").unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + let mut fired = false; + while Instant::now() < deadline { + if watcher.take_change() { + fired = true; + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + assert!(fired, "the watcher should report the rewrite"); + assert!(woke.load(Ordering::Relaxed), "and wake the UI"); + assert!(!watcher.take_change(), "one change, one signal"); + drop(watcher); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index d082dd6..150f5da 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -124,6 +124,7 @@ below is owner-locked; the shell merged to `main` 2026-07-07 (PR chain | VIEW-16 | **Export always produces findable output**: native writes `etchy-export/` next to the last opened input (absolute path in the toast); web downloads a single file directly and bundles a multi-file set into one zip (browsers block the 2nd+ automatic download). PDF mode exports the changed pages' overlay PNGs. | #222 | ✅ | | VIEW-17 | The Layers panel has a collapsible **Changes** list for the selected layer, largest first, with added/removed marker, area and available X2 labels. It shows the total count, caps visible rows at 200 with a `+N more` note, and says when X2 labels are unavailable. Clicking a row or using rebindable N/P frames and outlines the region; navigation wraps, and a bottom-left `change k / N` chip shows the position. Layer selection resets the cursor without moving the camera. PDF mode has no region list. | #419 | ✅ | | VIEW-18 | **Single-set view**: `etchy-gui ` opens one Gerber/Excellon set through the same loader as either side of a diff, failing loud on a bad path and surfacing load warnings the same way. It shows the layer list, visibility, pan/zoom and drill layers with no added/removed colouring, and is labelled as a single set, not a diff (title, canvas note, mode chip). Diff-only controls are replaced or disabled with a tooltip: the mode picker, N/P and the Changes list, and Export. Opening or dropping an old revision turns it into a normal diff; the welcome screen offers "View this set alone" when one set is loaded (web too). A lone PDF fails loud. Usage: `etchy-gui [ \| ]`. | #466 | ✅ | +| VIEW-19 | **Reload on change** (native only): the folders, zips, PDFs or dropped files behind each loaded side are watched by polling file sizes and modification times (a folder one level deep, like the loader). Once a side has changed and then stayed unchanged for 500 ms, it is re-read and re-diffed. The camera, selected layer or page, visibility, per-layer colours and rulers are kept when the layer stack (or page counts) is the same; otherwise the view resets and the notice says so. A brief "reloaded … after a file change" notice shows on success. A failed read or re-diff keeps the previous result and sources on screen with the error in the load banner (the #330 path). Toggle in Settings › Input, on by default, persisted. The web viewer has nothing to watch and shows no toggle. | #423 | ✅ | ## 8. Measure system diff --git a/docs/design/GUI_SPEC.md b/docs/design/GUI_SPEC.md index e7fd899..dceb63b 100644 --- a/docs/design/GUI_SPEC.md +++ b/docs/design/GUI_SPEC.md @@ -127,7 +127,16 @@ never re-sizes it (#212): - **Grid** — spacing, colours (display pitch adapts per VIEW-9; snap uses this). - **Measure** — units **mm / mil / inch** · snap-to-grid · crosshair + readout (the measure tool's one home, #211). -- **Input** — preset **Altium / KiCad** (pan buttons + clear/units keys). +- **Input** — preset **Altium / KiCad** (pan buttons + clear/units keys) · + **Reload when files change** (#423, VIEW-19; native only, on by default). + Each loaded side's folder, zip, PDF or dropped files are polled for size and + modification-time changes; after 500 ms with no further change the side is + re-read and re-diffed. Camera, selected layer or page, visibility, layer + colours and rulers are kept when the layer stack (or page counts) matches, + else the view resets. A copper "reloaded … after a file change" line shows + under the top bar for 4 s (it adds "the view was reset" when it did). A + failed read or re-diff keeps the previous result and sources, with the error + in the load banner. The web viewer has no toggle. - **Colours** — canvas/added/removed/per-layer colours, theme presets. - **Layers** — per-layer colour rows (square swatches). - **Hotkeys** — see §4. From 6f4716ee8c7368efa66a73ce8f310940cc5b9d42 Mon Sep 17 00:00:00 2001 From: Cimos <10230773+Cimos@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:52:44 +1100 Subject: [PATCH 2/2] gui: watch from load-time snapshot, honest reset note The reload watcher now starts from a snapshot taken just before the load reads the files, so a re-export landing before the watcher starts is still picked up. A reload only reports a view reset when the layer stack changed, not when the camera was never fitted. The changelog and the Settings tooltip now say the view is kept only when the layers are the same. --- CHANGELOG.md | 8 +- crates/etchy-gui/src/main.rs | 226 ++++++++++++++++++++++++++-------- crates/etchy-gui/src/watch.rs | 43 ++++++- 3 files changed, 217 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bda1460..b9c6fcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,9 +19,11 @@ Cut a new section here as part of tagging a release — see "Cutting a release" loaded set alone, including in the web viewer (#466). - Desktop viewer reloads and re-diffs when the opened files change on disk, for example after a re-export, so it no longer has to be reopened. It waits - for half a second of quiet so a half-written fab pack is not read, keeps the - camera, selected layer and visibility, and briefly says it reloaded. A failed - reload keeps the previous result on screen with the error. Toggle in + for half a second of quiet so a half-written fab pack is not read, and + briefly says it reloaded. If the layers are the same as before, the camera, + selected layer and visibility are kept; if a layer was added or removed, the + view is reset and the notice says so. A failed reload keeps the previous + result on screen with the error. Toggle in Settings > Input, on by default (#423). ### Fixed diff --git a/crates/etchy-gui/src/main.rs b/crates/etchy-gui/src/main.rs index 8117221..e2e2367 100644 --- a/crates/etchy-gui/src/main.rs +++ b/crates/etchy-gui/src/main.rs @@ -152,23 +152,42 @@ mod native { /// What the command line loaded before the window opens. enum Seed { /// Two revisions and their computed diff, at the PDF DPI used, plus - /// the paths they came from (watched for reloads, #423). - Pair(LoadedSource, LoadedSource, ComputedDiff, f32, [PathBuf; 2]), - /// One Gerber set on its own (#466), its single-set view and its path. - Single(LoadedSource, BoardDiff, PathBuf), + /// where they came from (watched for reloads, #423). + Pair( + LoadedSource, + LoadedSource, + ComputedDiff, + f32, + [SeedOrigin; 2], + ), + /// One Gerber set on its own (#466), its single-set view and origin. + Single(LoadedSource, BoardDiff, SeedOrigin), + } + + /// A CLI path and the state of its files just before the load read + /// them (#423). The watcher starts from that state, so a re-export + /// landing during a slow startup load still triggers a reload. + type SeedOrigin = (SourceOrigin, watch::Snapshot); + + fn seed_origin(path: &Path) -> SeedOrigin { + let origin = SourceOrigin::Path(path.to_path_buf()); + let baseline = origin.snapshot(); + (origin, baseline) } /// Load one Gerber directory or `.zip` for the single-set view (#466), /// through the same loader as either side of a diff. fn load_single_seed(path: &Path) -> anyhow::Result { + let origin = seed_origin(path); let src = load_source_any(path, label(path))?; let view = single_from_source(&src)?; - Ok(Seed::Single(src, view, path.to_path_buf())) + Ok(Seed::Single(src, view, origin)) } /// Load both revisions from CLI paths — Gerber dirs/zips or schematic PDFs /// (#63) — into sources + their computed diff. fn load_seed(old_path: &Path, new_path: &Path) -> anyhow::Result { + let origins = [seed_origin(old_path), seed_origin(new_path)]; let old = load_source_any(old_path, label(old_path))?; let new = load_source_any(new_path, label(new_path))?; // Persisted settings aren't restored yet at this point — seed a PDF pair @@ -184,13 +203,7 @@ mod native { Err(_) => return Err(first), }, }; - Ok(Seed::Pair( - old, - new, - diff, - dpi, - [old_path.to_path_buf(), new_path.to_path_buf()], - )) + Ok(Seed::Pair(old, new, diff, dpi, origins)) } /// Construct the app, restoring persisted settings. With a pair seed, both @@ -198,16 +211,16 @@ mod native { /// single-set view (#466); without one, the welcome screen shows (empty diff). fn build_app(cc: &eframe::CreationContext<'_>, seed: Option) -> ViewApp { match seed { - Some(Seed::Single(src, view, path)) => { + Some(Seed::Single(src, view, (origin, baseline))) => { // Built straight from the view so persisted per-board settings // (visible layers, #327) restore onto it like a diff's. let l = src.label().to_string(); let mut app = ViewApp::from_cc(cc, view, l.clone(), l); app.enter_single(src); - app.origin_new = Some(SourceOrigin::Path(path)); + app.set_origin(RevSide::New, origin, baseline); app } - Some(Seed::Pair(old, new, computed, seed_dpi, [old_path, new_path])) => { + Some(Seed::Pair(old, new, computed, seed_dpi, [(o_old, b_old), (o_new, b_new)])) => { let (ol, nl) = (old.label().to_string(), new.label().to_string()); let mut app = match computed { ComputedDiff::Board(diff) => ViewApp::from_cc(cc, diff, ol, nl), @@ -219,8 +232,8 @@ mod native { }; app.src_old = Some(old); app.src_new = Some(new); - app.origin_old = Some(SourceOrigin::Path(old_path)); - app.origin_new = Some(SourceOrigin::Path(new_path)); + app.set_origin(RevSide::Old, o_old, b_old); + app.set_origin(RevSide::New, o_new, b_new); // The seed was rasterized before settings restore; honour a // different persisted DPI now (#223). If that re-rasterize // fails (caps), the setting must fall back to the DPI the @@ -1769,8 +1782,17 @@ struct ViewApp { origin_old: Option, #[cfg(not(target_arch = "wasm32"))] origin_new: Option, + /// The state of each side's files just before the load read them (#423), + /// waiting to become the next watcher's baseline. Taken at load time, not + /// when the watcher starts a frame or more later, so a re-export landing + /// in between still triggers a reload. + #[cfg(not(target_arch = "wasm32"))] + baseline_old: Option, + #[cfg(not(target_arch = "wasm32"))] + baseline_new: Option, /// The running watchers, one per side (#423). Rebuilt when the origins or - /// the toggle change; dropping one stops its thread. + /// the toggle change, or when a new load leaves a fresh baseline; + /// dropping one stops its thread. #[cfg(not(target_arch = "wasm32"))] watch_old: Option, #[cfg(not(target_arch = "wasm32"))] @@ -1904,6 +1926,10 @@ impl ViewApp { #[cfg(not(target_arch = "wasm32"))] origin_new: None, #[cfg(not(target_arch = "wasm32"))] + baseline_old: None, + #[cfg(not(target_arch = "wasm32"))] + baseline_new: None, + #[cfg(not(target_arch = "wasm32"))] watch_old: None, #[cfg(not(target_arch = "wasm32"))] watch_new: None, @@ -2935,17 +2961,18 @@ impl ViewApp { }; match single_from_source(src) { Ok(view) => { - // The set becomes the new side; its origin moves with it so - // the reload watcher (#423) keeps covering it. + // The set becomes the new side; its origin, pending baseline + // and running watcher move with it, so the reload watcher + // (#423) keeps covering it without losing its baseline. #[cfg(not(target_arch = "wasm32"))] - { - let origin = if self.src_old.is_some() { - self.origin_old.take() - } else { - self.origin_new.take() - }; + if self.src_old.is_some() { + self.origin_new = self.origin_old.take(); + self.baseline_new = self.baseline_old.take(); + self.watch_new = self.watch_old.take(); + } else { self.origin_old = None; - self.origin_new = origin; + self.baseline_old = None; + self.watch_old = None; } let src = self.src_old.take().or_else(|| self.src_new.take()); if let Some(src) = src { @@ -3102,29 +3129,40 @@ impl ViewApp { if let Some(parent) = path.parent() { self.last_dir = Some(parent.to_path_buf()); } + // Snapshot before the read (#423): any change after it reloads. + let origin = SourceOrigin::Path(path.to_path_buf()); + let baseline = origin.snapshot(); match load_source_any(path, derive_label(path)) { Ok(src) => { self.set_side(side, src); if self.load_error.is_none() { - self.set_origin(side, SourceOrigin::Path(path.to_path_buf())); + self.set_origin(side, origin, baseline); } } Err(e) => self.load_error = Some(format!("{e:#}")), } } - /// Record where a side now comes from (#423), after it loaded cleanly. + /// Record where a side now comes from (#423), after it loaded cleanly, + /// with the snapshot of its files taken just before they were read. #[cfg(not(target_arch = "wasm32"))] - fn set_origin(&mut self, side: RevSide, origin: SourceOrigin) { + fn set_origin(&mut self, side: RevSide, origin: SourceOrigin, baseline: watch::Snapshot) { match side { - RevSide::Old => self.origin_old = Some(origin), - RevSide::New => self.origin_new = Some(origin), + RevSide::Old => { + self.origin_old = Some(origin); + self.baseline_old = Some(baseline); + } + RevSide::New => { + self.origin_new = Some(origin); + self.baseline_new = Some(baseline); + } } } /// Start, stop or replace the per-side watchers (#423) so they cover - /// exactly the loaded sides' origins while the setting is on. Cheap when - /// nothing changed: it only compares path lists. + /// exactly the loaded sides' origins while the setting is on. A load + /// leaves a fresh baseline, which always starts a new watcher from it. + /// Cheap when nothing changed: it only compares path lists. #[cfg(not(target_arch = "wasm32"))] fn sync_watchers(&mut self, ctx: &egui::Context) { fn want( @@ -3141,21 +3179,31 @@ impl ViewApp { fn sync( slot: &mut Option, roots: Option>, + baseline: &mut Option, ctx: &egui::Context, ) { - let current = slot.as_ref().map(|w| w.roots().to_vec()); - if current == roots { + let Some(r) = roots else { + // Off or unloaded: stop. A pending baseline stays, so turning + // the setting back on still compares against the load. + *slot = None; + return; + }; + let same = slot.as_ref().is_some_and(|w| w.roots() == r.as_slice()); + if same && baseline.is_none() { return; } - *slot = roots.map(|r| { - let ctx = ctx.clone(); - watch::FileWatcher::spawn(r, move || ctx.request_repaint()) - }); + // Without a load-time snapshot (none was recorded) the best + // available baseline is the state right now. + let base = baseline.take().unwrap_or_else(|| watch::take(&r)); + let ctx = ctx.clone(); + *slot = Some(watch::FileWatcher::spawn(r, base, move || { + ctx.request_repaint() + })); } let old = want(self.watch_inputs, self.src_old.is_some(), &self.origin_old); let new = want(self.watch_inputs, self.src_new.is_some(), &self.origin_new); - sync(&mut self.watch_old, old, ctx); - sync(&mut self.watch_new, new, ctx); + sync(&mut self.watch_old, old, &mut self.baseline_old, ctx); + sync(&mut self.watch_new, new, &mut self.baseline_new, ctx); } /// Once per frame (#423): keep the watchers in step, and reload any side @@ -3307,15 +3355,23 @@ impl ViewApp { if paths.is_empty() { return; } + // Snapshot before the read (#423): any change after it reloads. + let origins = drop_origins(&paths); + let mut baselines = match &origins { + DroppedOrigins::One(o) => vec![o.snapshot()], + DroppedOrigins::Pair { old, new } => vec![old.snapshot(), new.snapshot()], + } + .into_iter(); match load_dropped_paths(&paths) { Ok(loaded) => { self.adopt_sources(side, loaded); if self.load_error.is_none() { - match drop_origins(&paths) { - DroppedOrigins::One(o) => self.set_origin(side, o), + let mut next = || baselines.next().unwrap_or_default(); + match origins { + DroppedOrigins::One(o) => self.set_origin(side, o, next()), DroppedOrigins::Pair { old, new } => { - self.origin_old = Some(old); - self.origin_new = Some(new); + self.set_origin(RevSide::Old, old, next()); + self.set_origin(RevSide::New, new, next()); } } } @@ -3940,6 +3996,11 @@ impl SourceOrigin { } } + /// The current state of this side's files, for a watcher baseline. + fn snapshot(&self) -> watch::Snapshot { + watch::take(&self.roots()) + } + /// Read this side again, the same way it was first loaded. fn reload(&self) -> anyhow::Result { match self { @@ -4014,12 +4075,17 @@ impl ViewApp { } /// Put back a kept view after a reload, if the layout still matches. - /// Returns whether it was restored. + /// Returns false only when the layer stack (or page counts) changed and + /// the view was reset. A camera that was never fitted (the welcome + /// screen, or a reload before the first frame) is not put back, so the + /// view still fits itself, but that is not a reset. fn restore_view(&mut self, kept: KeptView) -> bool { - if kept.key != self.view_key() || !kept.cam.fitted { + if kept.key != self.view_key() { return false; } - self.cam = kept.cam; + if kept.cam.fitted { + self.cam = kept.cam; + } if kept.selected < self.diff.layers.len() { self.selected = kept.selected; } @@ -5510,8 +5576,9 @@ impl ViewApp { ui.checkbox(&mut self.watch_inputs, "Reload when files change") .on_hover_text( "Re-read and re-diff an opened folder, zip, PDF or set of files when it \ - changes on disk, once it has been quiet for half a second. The camera, \ - selected layer and visibility are kept.", + changes on disk, once it has been quiet for half a second. If the layers \ + are the same, the camera, selected layer and visibility are kept; if a \ + layer was added or removed, the view is reset.", ); } @@ -8562,6 +8629,63 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// A re-export that lands after the load read the files but before the + /// first frame starts the watcher is still picked up: the baseline is the + /// snapshot taken at load time, not when the watcher starts. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_change_between_load_and_watcher_start_still_reloads() { + use super::{RevSide, ViewApp}; + let (root, old, new) = reload_fixture("early"); + let ctx = egui::Context::default(); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.load_side_path(RevSide::Old, &old); + app.load_side_path(RevSide::New, &new); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + assert!(app.baseline_new.is_some(), "the load records its snapshot"); + + std::fs::write(new.join("board-F_Cu.gtl"), GROWN_GERBER).unwrap(); + app.sync_watchers(&ctx); + assert!(app.baseline_new.is_none(), "the watcher took the snapshot"); + let watcher = app.watch_new.as_ref().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let mut fired = false; + while std::time::Instant::now() < deadline { + if watcher.take_change() { + fired = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + assert!(fired, "the early re-export must trigger a reload"); + assert!( + !app.watch_old.as_ref().unwrap().take_change(), + "the untouched side stays quiet" + ); + std::fs::remove_dir_all(&root).ok(); + } + + /// Reloading the one loaded side on the welcome screen (camera never + /// fitted, layers unchanged) must not claim the view was reset. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_reload_of_one_side_on_the_welcome_screen_is_not_a_reset() { + use super::{RevSide, ViewApp}; + let (root, _old, new) = reload_fixture("welcome"); + let mut app = ViewApp::new(empty_diff(), "x".into(), "y".into()); + app.load_side_path(RevSide::New, &new); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + assert!(!app.cam.fitted, "nothing has been framed yet"); + + std::fs::write(new.join("board-F_Cu.gtl"), GROWN_GERBER).unwrap(); + app.reload_sides(false, true, 3.0); + assert!(app.load_error.is_none(), "{:?}", app.load_error); + let (note, _) = app.reload_note.clone().expect("a reload says so"); + assert!(note.contains("after a file change"), "got: {note}"); + assert!(!note.contains("reset"), "nothing was reset: {note}"); + std::fs::remove_dir_all(&root).ok(); + } + /// A one-layer Gerber set for the single-set tests (#466). fn single_board(label: &str, warnings: Vec) -> super::LoadedSource { let (board, fmt, _) = crate::loader::board_from_bytes(vec![( diff --git a/crates/etchy-gui/src/watch.rs b/crates/etchy-gui/src/watch.rs index e50d5bd..f04c250 100644 --- a/crates/etchy-gui/src/watch.rs +++ b/crates/etchy-gui/src/watch.rs @@ -144,13 +144,18 @@ pub struct FileWatcher { } impl FileWatcher { - /// Start watching `roots`. The baseline is read here, on the caller's - /// thread, so a change made right after this call is never missed. - /// `wake` runs on the watcher thread whenever a reload becomes due. - pub fn spawn(roots: Vec, wake: impl Fn() + Send + 'static) -> Self { + /// Start watching `roots` against `baseline`, the state the shown data + /// was read from. The loader takes that snapshot just before it reads the + /// files, so a re-export landing between the read and this call still + /// differs from the baseline and triggers a reload. `wake` runs on the + /// watcher thread whenever a reload becomes due. + pub fn spawn( + roots: Vec, + baseline: Snapshot, + wake: impl Fn() + Send + 'static, + ) -> Self { let stop = Arc::new(AtomicBool::new(false)); let (tx, rx): (Sender<()>, Receiver<()>) = std::sync::mpsc::channel(); - let baseline = take(&roots); let thread_roots = roots.clone(); let thread_stop = Arc::clone(&stop); let spawned = std::thread::Builder::new() @@ -321,7 +326,8 @@ mod tests { std::fs::write(&f, b"one").unwrap(); let woke = Arc::new(AtomicBool::new(false)); let w = Arc::clone(&woke); - let watcher = FileWatcher::spawn(vec![dir.clone()], move || { + let roots = vec![dir.clone()]; + let watcher = FileWatcher::spawn(roots.clone(), take(&roots), move || { w.store(true, Ordering::Relaxed); }); assert_eq!(watcher.roots(), std::slice::from_ref(&dir)); @@ -341,4 +347,29 @@ mod tests { drop(watcher); let _ = std::fs::remove_dir_all(&dir); } + + /// A change made after the load read the files but before the watcher + /// started is still reported, because the baseline is the load-time one. + #[test] + fn watcher_sees_a_change_made_before_it_started() { + let dir = scratch("early"); + let f = dir.join("top.gtl"); + std::fs::write(&f, b"one").unwrap(); + let roots = vec![dir.clone()]; + let at_load = take(&roots); + std::fs::write(&f, b"a longer body").unwrap(); + let watcher = FileWatcher::spawn(roots, at_load, || {}); + let deadline = Instant::now() + Duration::from_secs(10); + let mut fired = false; + while Instant::now() < deadline { + if watcher.take_change() { + fired = true; + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + assert!(fired, "the early rewrite must not be missed"); + drop(watcher); + let _ = std::fs::remove_dir_all(&dir); + } }