From 9b05dbed437051e34824125abb50d22fc440cc40 Mon Sep 17 00:00:00 2001 From: markmonkey <17867174+markmonkey@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:40:39 +0800 Subject: [PATCH] Reuse existing drawing tabs when reopening paths --- crates/ui-egui/src/lib.rs | 26 ++++- crates/ui-egui/src/opening.rs | 20 ++++ crates/ui-egui/tests/recent_files.rs | 4 +- crates/ui-egui/tests/reopen_drawing.rs | 153 +++++++++++++++++++++++++ docs/gaps.md | 2 +- docs/ui-parity.md | 4 +- 6 files changed, 204 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/tests/reopen_drawing.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 890732449..29169d945 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -740,7 +740,8 @@ impl CadApp { /// Open the drawing at `path`. Natively the file is read on a worker thread while an /// "Opening ..." card shows ([`opening`]); [`Self::finish_opening`] adds it when ready. On the - /// web it opens at once. + /// web it opens at once. An already open drawing is selected without re-reading it, retaining + /// its unsaved edits and view; window drops and Open Recent use this same entry point. pub fn open_path(&mut self, path: &Path) { // A LISP file (dropped on the window): loaded as APPLOAD loads it. if is_lisp_file(path) { @@ -750,6 +751,9 @@ impl CadApp { } return; } + if self.select_open_drawing(path) { + return; + } #[cfg(not(target_arch = "wasm32"))] { self.opening.start(path); @@ -768,6 +772,10 @@ impl CadApp { /// OPEN is reported. Called every frame. pub fn finish_opening(&mut self) { for (path, outcome) in self.opening.poll() { + // A drawing may have been opened or saved at this path while the read was pending. + if self.select_open_drawing(&path) { + continue; + } // A recent file that is gone can never be opened again: drop it from the list. A path // whose existence can't be checked (a folder that denies access) stays. if outcome.is_err() && matches!(path.try_exists(), Ok(false)) { @@ -785,6 +793,22 @@ impl CadApp { } } + /// Reuse the existing document through the normal tab-switch command, including symlink paths. + fn select_open_drawing(&mut self, path: &Path) -> bool { + let existing = self.session.docs.iter().position(|d| d.path.as_deref().is_some_and(|p| opening::same_path(Path::new(p), path))); + let Some(index) = existing else { return false }; + match self.run("document.switch", json!({"index": index})) { + Ok(_) => { + self.ui.start_tab = false; + if let Some(path) = self.session.docs.get(index).and_then(|d| d.path.clone()) { + self.remember_recent(path); + } + } + Err(error) => self.open_failed(error), + } + true + } + /// Load a LISP file: its routine runs and may wait for the user (APPLOAD typed or from the /// menu runs this way too). fn load_lisp(&mut self, name: &str, text: &str) { diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index d6ae999c8..ba2016781 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -13,6 +13,22 @@ use crate::theme::Tokens; type Outcome = Result; +/// Compare file paths without requiring the file to still exist. Native aliases are resolved so +/// a symlink and its target share a drawing; web paths can only be compared directly. +pub(crate) fn same_path(a: &Path, b: &Path) -> bool { + if a == b { + return true; + } + #[cfg(not(target_arch = "wasm32"))] + { + a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + struct Job { path: PathBuf, started: Instant, @@ -28,6 +44,10 @@ pub struct Opening { impl Opening { /// Start reading `path` on a worker thread. pub fn start(&mut self, path: &Path) { + // Repeated events can arrive before the first background read completes. + if self.jobs.iter().any(|j| same_path(&j.path, path)) { + return; + } let (tx, rx) = channel(); let p = path.to_path_buf(); let spawned = std::thread::Builder::new().name("cadcraft-open".into()).spawn(move || { diff --git a/crates/ui-egui/tests/recent_files.rs b/crates/ui-egui/tests/recent_files.rs index 34aa6e2e8..a8c3d6a10 100644 --- a/crates/ui-egui/tests/recent_files.rs +++ b/crates/ui-egui/tests/recent_files.rs @@ -70,11 +70,11 @@ fn opened_drawings_are_listed_newest_first_and_survive_a_restart() { let labels: Vec<_> = items.iter().map(|(l, _)| l.as_str()).collect(); assert_eq!(labels, ["plan.dxf", "section.dwg", "Clear Recent Files"]); - // Choosing an item opens that file and moves it to the top. + // Choosing an already open item selects its tab and moves it to the top. let before = app.session.docs.len(); menus::activate(&mut app, &items[1].1); settle(&mut app); - assert_eq!(app.session.docs.len(), before + 1); + assert_eq!(app.session.docs.len(), before); assert_eq!(app.session.state().ok().and_then(|s| s.path.clone()), Some(section.clone())); assert_eq!(app.ui.recent_files, [section.clone(), plan.clone()]); diff --git a/crates/ui-egui/tests/reopen_drawing.rs b/crates/ui-egui/tests/reopen_drawing.rs new file mode 100644 index 000000000..b5554dd20 --- /dev/null +++ b/crates/ui-egui/tests/reopen_drawing.rs @@ -0,0 +1,153 @@ +//! Reopening a path selects the existing drawing, preserving edits, even across Finder events. +#![cfg(not(target_arch = "wasm32"))] + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +struct Files(PathBuf); + +impl Files { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!("cadcraft-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&root).unwrap(); + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None }); + Self(root) + } + + fn drawing(&self, name: &str) -> PathBuf { + let path = self.0.join(name); + // Synthetic input: the test reader returns an empty drawing for any bytes. + std::fs::write(&path, b"0\nEOF\n").unwrap(); + path + } +} + +impl Drop for Files { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn app() -> CadApp { + CadApp::new(Session::empty(), Services::default()) +} + +fn open(app: &mut CadApp, path: &Path) { + app.open_path(path); +} + +fn settle(app: &mut CadApp) { + let deadline = Instant::now() + Duration::from_secs(10); + while app.opening.busy() { + app.finish_opening(); + assert!(Instant::now() < deadline, "background OPEN did not finish"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn reopening_dwg_and_dxf_preserves_edits_view_and_recent_files() { + let files = Files::new(); + for name in ["检查井 成果.dwg", "管网 检测.dxf"] { + let path = files.drawing(name); + let mut app = app(); + open(&mut app, &path); + settle(&mut app); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let before = app.session.state().unwrap().clone(); + app.run("new", json!({})).unwrap(); + let count = app.session.docs.len(); + app.ui.start_tab = true; + open(&mut app, &path); + assert!(!app.opening.busy(), "an existing drawing must not be re-read"); + let after = app.session.state().unwrap(); + assert_eq!(after.uid, before.uid); + assert_eq!(after.doc, before.doc); + assert_eq!(after.view(), before.view()); + assert_eq!(after.undo.len(), before.undo.len()); + assert!(after.is_dirty()); + assert_eq!(app.session.docs.len(), count); + assert!(!app.ui.start_tab); + assert_eq!(app.ui.recent_files.first().map(String::as_str), path.to_str()); + } +} + +#[test] +fn reopening_a_deleted_file_keeps_the_unsaved_drawing() { + let files = Files::new(); + let path = files.drawing("deleted.dxf"); + let mut app = app(); + open(&mut app, &path); + settle(&mut app); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + std::fs::remove_file(&path).unwrap(); + app.run("new", json!({})).unwrap(); + open(&mut app, &path); + assert!(!app.opening.busy()); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); +} + +#[test] +fn repeated_requests_while_loading_add_one_tab_per_file() { + let files = Files::new(); + let first = files.drawing("first.dxf"); + let second = files.drawing("second.dwg"); + let mut app = app(); + open(&mut app, &first); + open(&mut app, &first); + open(&mut app, &second); + open(&mut app, &first); + settle(&mut app); + assert_eq!(app.session.docs.len(), 2); + assert!(app.session.docs.iter().any(|d| d.path.as_deref() == first.to_str())); + assert!(app.session.docs.iter().any(|d| d.path.as_deref() == second.to_str())); +} + +#[cfg(unix)] +#[test] +fn symlinks_share_both_pending_reads_and_existing_dirty_tabs() { + let files = Files::new(); + let path = files.drawing("drawing.dxf"); + let alias = files.0.join("alias.dxf"); + std::os::unix::fs::symlink(&path, &alias).unwrap(); + let mut app = app(); + open(&mut app, &path); + open(&mut app, &alias); + settle(&mut app); + assert_eq!(app.session.docs.len(), 1); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + app.run("new", json!({})).unwrap(); + open(&mut app, &alias); + assert!(!app.opening.busy()); + assert_eq!(app.session.docs.len(), 2); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); +} + +#[test] +fn a_read_finishing_after_the_path_is_opened_keeps_existing_edits() { + let files = Files::new(); + let path = files.drawing("pending.dxf"); + let mut app = app(); + open(&mut app, &path); + // Simulate another OPEN/Save As assigning this path before the UI polls the background read. + app.run("new", json!({})).unwrap(); + app.session.state_mut().unwrap().path = path.to_str().map(str::to_string); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + settle(&mut app); + assert_eq!(app.session.docs.len(), 1); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); + assert_eq!(app.session.doc().unwrap().entity_count(), 1); +} diff --git a/docs/gaps.md b/docs/gaps.md index 289f0b4be..d3999acd4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -127,7 +127,7 @@ Detail: [localization-parity.md](localization-parity.md). |---|---|---| | P1 | Web build: plot shows raw PDF bytes (#134), no DWG (File > Open and save downloads fixed, #55, #133) | 3–5 | | P2 | Windows and Linux get little runtime testing; Linux Mint mouse delay (#25: the vsync fix landed, #183, the issue is open); Windows magnifier (#39: system-cursor option landed, #187, the issue is open) | 6–10 | -| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; open PRs #683 and #899) | 1–2 | +| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; Finder-delivery PRs #683, #1347 and #1503 are open) | 1–2 | ## Ecosystem and automation diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1c3bdd3be..facdadd60 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (WIPEOUT closure-aware grips; previously: re-audit of the evidence text against main 41d9b5e95: point entry, tracking, Dynamic Input, grips, scripts, views; percentages not re-measured; previously: distinct polyline midpoint grips) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (WIPEOUT closure-aware grips; previously: re-audit of the evidence text against main 41d9b5e95: point entry, tracking, Dynamic Input, grips, scripts, views; percentages not re-measured; previously: distinct polyline midpoint grips; previously: reopening a drawing path selects its existing tab) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -162,6 +162,7 @@ dimensions are edited). |---|---|---| | Menu bar | 11 menus, 491 leaf items | same 11 menus; 245/491 items covered at the 2026-10-10 re-measure, not re-measured since (the generated checklist now reads 298/491, engine commands only; 233 by `cargo xtask parity`, which counts engine commands only, plus 12 UI-only items: see [parity-checklist.md](parity-checklist.md)); once a menu is open, pointing at another title opens that menu (#1567) | | Tool Bar, File tabs, Start tab, layout tabs | yes | yes | +| Reopening an existing drawing through window drop / Open Recent | not re-measured | existing tab; edits, undo and view retained; native symlinks share a tab | | Tool Sets palette (Drafting, Modeling, … with flyouts) | yes | yes for 2D groups | | Properties Inspector, Quick Properties | yes | yes (every control acts or is visibly unavailable, #182); block references show read-only Position X/Y/Z from their stored insertion point; coordinate editing is still missing; numeric fields take feet and inches and show lengths in the drawing's units (#870) | | Layer Properties Manager (filters, states, VP overrides) | yes | yes | @@ -208,6 +209,7 @@ dimensions are edited). | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Shared path opening reuses existing drawing tabs and pending reads, preserving edits, undo and view | | 2026-10-27 | minor | WIPEOUT grips treat implicit and explicit closure alike; moving the first vertex carries the closing marker, and moving endpoints together keeps both corners editable. Open/closed polyline flags and coincident polyline vertices remain independent (#2256) | | 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. | | 2026-10-24 | minor | Re-audit against main 41d9b5e95: evidence text for TK and typed snap overrides, PolarSnap, Dynamic Input, hot-grip options, dynamic block grips, SCRIPT, ZOOM Realtime/Dynamic, named views and VPORTS; headline no longer lists selection cycling as missing; the 48% and the area percentages are not re-measured |