Reuse existing tabs when reopening saved designs (#2413) (#2414)

* claim: #2413

* Reuse existing model tabs when reopening saved designs (#2413)

* Expect Open Recent to reuse the existing design tab (#2413)

* Update tab-reuse regression for session visibility
This commit is contained in:
ChrisNo
2026-10-26 12:04:11 +00:00
committed by GitHub
parent 4d06daf87b
commit 7556e23fe7
4 changed files with 286 additions and 3 deletions
+141
View File
@@ -188,6 +188,49 @@ pub fn switch(app: &mut SolveApp, i: usize) {
app.docs.active = i;
}
/// Select an already-open saved design without reloading or framing it. Identity is derived
/// from the current session path so Save As immediately changes which file the tab owns.
pub(crate) fn reuse_path(app: &mut SolveApp, path: &str) -> Result<bool, String> {
solidcraft_engine::io::vfs::check(path).map_err(|e| e.to_string())?;
// Imports create unsaved designs, rather than owning their source file.
if solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path) {
return Ok(false);
}
let matches = |s: &Session| s.path.as_deref().is_some_and(|p| same_path(p, path));
let index = if matches(&app.session) {
Some(app.docs.active)
} else {
app.docs.slots.iter().position(|s| s.as_ref().is_some_and(|s| matches(&s.session)))
};
let Some(index) = index else { return Ok(false) };
if app.file_picker_busy() {
return Err("finish choosing a file before switching designs".into());
}
switch(app, index);
Ok(true)
}
fn same_path(a: &str, b: &str) -> bool {
if a == b {
return true;
}
#[cfg(not(target_arch = "wasm32"))]
{
// canonicalize resolves symlinks and Windows long names/case using the filesystem.
// Never lowercase: Windows can also host case-sensitive directories.
if let (Ok(a), Ok(b)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
return a == b;
}
// A deleted file can still select its live editing session. Path equality also
// accepts redundant separators and `.` without guessing how symlinks resolve `..`.
if let (Ok(a), Ok(b)) = (std::path::absolute(a), std::path::absolute(b)) {
return a == b;
}
}
// Browser VFS keys are exact strings, independent of the host's path conventions.
false
}
/// Open `session` in a new tab after the active one and switch to it (`fit`: frame its model).
pub fn open_tab(app: &mut SolveApp, session: Session) -> Result<(), String> {
if app.docs.slots.is_empty() {
@@ -939,6 +982,104 @@ pub(crate) fn saved_for_close(app: &mut SolveApp) {
#[cfg(test)]
mod tests {
#[test]
fn reopening_saved_design_preserves_dirty_session_and_view() {
let mut a = super::SolveApp::new(solidcraft_engine::Session::default(), Default::default());
let path = std::env::temp_dir().join(format!("solidcraft-reopen-{}.solidcraft", std::process::id()));
let path = path.to_string_lossy().into_owned();
a.session.execute("file.save", &serde_json::json!({"path": path})).unwrap();
a.session.execute("solid.box", &serde_json::json!({"length": 10, "width": 12, "height": 14})).unwrap();
a.session.selection = vec![solidcraft_engine::Sel::Body { name: "Body1".into() }];
a.cam.distance = 123.0;
a.session.visibility.hidden_profiles = vec![7];
let doc = a.session.doc.clone();
let undo = a.session.undo.len();
let cam = a.cam;
a.open_path(&path);
assert_eq!(a.docs.count(), 1);
assert!(std::sync::Arc::ptr_eq(&doc, &a.session.doc));
assert!(a.session.is_dirty());
assert_eq!(a.session.undo.len(), undo);
assert_eq!(a.cam, cam);
assert_eq!(a.session.selection.len(), 1);
assert_eq!(a.session.visibility.hidden_profiles, vec![7]);
super::new_tab(&mut a);
a.open_path(&path);
assert_eq!(a.docs.count(), 2);
assert_eq!(a.docs.active, 0);
assert!(std::sync::Arc::ptr_eq(&doc, &a.session.doc));
assert_eq!(a.cam, cam);
assert_eq!(a.session.selection.len(), 1);
assert_eq!(a.session.visibility.hidden_profiles, vec![7]);
assert_eq!(a.session.undo.len(), undo);
assert!(a.session.is_dirty());
std::fs::remove_file(&path).unwrap();
a.open_path(&path);
assert_eq!(a.docs.count(), 2);
assert!(std::sync::Arc::ptr_eq(&doc, &a.session.doc));
}
#[test]
fn reuse_tracks_save_as_missing_files_and_full_capacity() {
let mut a = app();
a.session.path = Some("original.solidcraft".into());
let original = a.session.doc.clone();
// Save As updates the live path; lookup must not retain the old identity.
a.session.path = Some("renamed.solidcraft".into());
assert!(!reuse_path(&mut a, "original.solidcraft").unwrap());
for _ in 1..MAX_OPEN {
new_tab(&mut a);
}
assert_eq!(a.docs.count(), MAX_OPEN);
assert!(reuse_path(&mut a, "renamed.solidcraft").unwrap());
assert_eq!(a.docs.active, 0);
assert!(std::sync::Arc::ptr_eq(&original, &a.session.doc));
assert!(!reuse_path(&mut a, "elsewhere/renamed.solidcraft").unwrap());
assert_eq!(a.docs.count(), MAX_OPEN);
a.home.open = true;
assert!(reuse_path(&mut a, "renamed.solidcraft").unwrap());
assert!(!a.home.open);
}
#[test]
fn reuse_does_not_claim_a_switch_while_a_picker_is_open() {
let mut a = app();
a.session.path = Some("picker.solidcraft".into());
new_tab(&mut a);
a.services.pick_open = Some(Box::new(|_| Box::pin(std::future::pending())));
a.pick_open(|_, _| {});
assert!(a.file_picker_busy());
assert!(reuse_path(&mut a, "picker.solidcraft").is_err());
assert_eq!(a.docs.active, 1);
assert_eq!(a.docs.count(), 2);
}
#[test]
fn saved_path_identity_uses_the_filesystem_without_folding_case() {
let dir = std::env::temp_dir().join(format!("solidcraft-tab-paths-{}", std::process::id()));
std::fs::create_dir_all(dir.join("other")).unwrap();
let path = dir.join("design.solidcraft");
std::fs::write(&path, b"identity test").unwrap();
let text = |p: &std::path::Path| p.to_string_lossy().into_owned();
assert!(same_path(&text(&path), &text(&dir.join("other/../design.solidcraft"))));
assert!(!same_path(&text(&path), &text(&dir.join("other/design.solidcraft"))));
#[cfg(windows)]
assert!(same_path(&text(&path), &text(&dir.join("DESIGN.solidcraft"))));
#[cfg(unix)]
{
let link = dir.join("alias.solidcraft");
std::os::unix::fs::symlink(&path, &link).unwrap();
assert!(same_path(&text(&path), &text(&link)));
std::fs::write(dir.join("DESIGN.solidcraft"), b"distinct").unwrap();
if std::fs::read(&path).unwrap() != b"distinct" {
assert!(!same_path(&text(&path), &text(&dir.join("DESIGN.solidcraft"))));
}
}
std::fs::remove_file(&path).unwrap();
assert!(same_path(&text(&path), &text(&dir.join("./design.solidcraft"))));
std::fs::remove_dir_all(dir).unwrap();
}
use super::*;
use crate::Services;
use egui::Color32;
+135 -1
View File
@@ -56,7 +56,7 @@ pub struct Request {
impl Request {
pub fn new(path: &str, kind: Kind) -> Self {
Request { path: path.into(), kind, reply: None, scope: None, options: Default::default() }
Request { path: path.into(), kind, reply: None, scope: solidcraft_engine::io::vfs::current_scope(), options: Default::default() }
}
fn insert(&self) -> bool {
self.kind == Kind::Insert
@@ -222,6 +222,9 @@ pub fn begin(app: &mut SolveApp, path: &str, insert: bool) {
/// Queue a file operation; on the web (no threads) it runs now.
pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String> {
if app.file_load.idle() && reuse_open(app, &request) {
return Ok(());
}
#[cfg(target_arch = "wasm32")]
{
if staged_kind(&request) {
@@ -284,6 +287,36 @@ pub(crate) fn queue(app: &mut SolveApp, request: Request) -> Result<(), String>
Ok(())
}
/// Answer each ordinary open separately, including queued requests for the same file.
/// Validate the caller's scope before looking at existing sessions or resolving paths.
fn reuse_open(app: &mut SolveApp, request: &Request) -> bool {
if request.kind != Kind::Open {
return false;
}
let reused = solidcraft_engine::io::vfs::scoped(request.scope.clone(), || {
solidcraft_engine::io::vfs::check(&request.path).map_err(|e| e.to_string())?;
// Let the command validate import-specific options, even for an existing tab.
if !request.options.is_empty() {
return Ok(false);
}
crate::documents::reuse_path(app, &request.path)
});
match reused {
Ok(false) => false,
Ok(true) => {
let s = &app.session;
request.answer(Ok(json!({"path": request.path, "features": s.doc.features.len(),
"errors": s.model.results.iter().filter(|r| r.error.is_some()).count(), "name": s.doc.name})));
true
}
Err(e) => {
app.set_status(e.clone(), true);
request.answer(Err(e));
true
}
}
}
/// A control-channel (MCP) `doc.open` or STEP/mesh import runs like File > Open: off the window
/// thread, answered when the file is in. Other requests come back to be handled now.
pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Option<crate::control::ControlRequest> {
@@ -350,6 +383,9 @@ fn start(app: &mut SolveApp) {
return;
}
let Some(request) = app.file_load.queued.pop_front() else { return };
if reuse_open(app, &request) {
return;
}
if matches!(request.kind, Kind::Open | Kind::Recover { .. })
&& app.docs.count() >= crate::documents::MAX_OPEN
&& !crate::documents::active_is_blank(app)
@@ -846,6 +882,7 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label(id)))]), false);
request.answer(r);
}
Ok(_) if reuse_open(app, request) => {}
Ok(made) if running.matches(&app.session) => {
// Not meshed yet: framing it while it goes in must not mesh it here.
app.open_meshing_next = true;
@@ -1070,6 +1107,103 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
mod tests {
use super::*;
fn completed_open(app: &mut SolveApp, request: Request, session: Session) {
let (tx, rx) = std::sync::mpsc::channel();
tx.send(Ok(Made { session, result: json!({"loaded": true}), thumbnail: false })).unwrap();
app.file_load.running = Some(Running {
request,
base: app.session.doc.clone(),
base_revision: app.session.revision,
before: Vec::new(),
rx,
phase: Arc::new(AtomicU8::new(0)),
progress: Arc::new(Progress::default()),
preview_rx: None,
preview: None,
partial_rx: None,
built: None,
staged: None,
});
}
#[test]
fn repeated_queued_opens_reply_once_and_keep_one_session() {
let mut app = SolveApp::new(Session::default(), Default::default());
let mut session = Session::default();
session.path = Some("queued.solidcraft".into());
let mut first = Request::new("queued.solidcraft", Kind::Open);
let (tx, first_reply) = std::sync::mpsc::channel();
first.reply = Some(tx);
completed_open(&mut app, first, session);
let mut replies = vec![first_reply];
for _ in 0..3 {
let mut request = Request::new("queued.solidcraft", Kind::Open);
let (tx, rx) = std::sync::mpsc::channel();
request.reply = Some(tx);
replies.push(rx);
begin_request(&mut app, request).unwrap();
}
let ctx = egui::Context::default();
tick(&mut app, &ctx);
let loaded = app.session.doc.clone();
app.session.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4})).unwrap();
let dirty = app.session.doc.clone();
assert!(!Arc::ptr_eq(&loaded, &dirty));
for _ in 0..3 {
tick(&mut app, &ctx);
}
assert!(app.file_load.idle());
assert_eq!(app.docs.count(), 1);
assert!(Arc::ptr_eq(&dirty, &app.session.doc));
assert!(app.session.is_dirty());
for rx in replies {
assert_eq!(rx.try_recv().unwrap()["ok"], true);
assert!(rx.try_recv().is_err());
}
}
#[test]
fn finished_open_reuses_existing_dirty_tab_and_scope_still_applies() {
let mut app = SolveApp::new(Session::default(), Default::default());
app.session.path = Some("existing.solidcraft".into());
app.session.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4})).unwrap();
let dirty = app.session.doc.clone();
let undo = app.session.undo.len();
let camera = app.cam;
crate::documents::new_tab(&mut app);
let mut loaded = Session::default();
loaded.path = Some("existing.solidcraft".into());
let mut request = Request::new("existing.solidcraft", Kind::Open);
let (tx, rx) = std::sync::mpsc::channel();
request.reply = Some(tx);
completed_open(&mut app, request, loaded);
tick(&mut app, &egui::Context::default());
assert_eq!(rx.try_recv().unwrap()["result"]["features"], 1);
assert_eq!(app.docs.count(), 2);
assert_eq!(app.docs.active, 0);
assert!(Arc::ptr_eq(&dirty, &app.session.doc));
assert_eq!(app.session.undo.len(), undo);
assert_eq!(app.cam, camera);
assert!(app.session.is_dirty());
let mut denied = Request::new("existing.solidcraft", Kind::Open);
denied.scope = Some(Default::default());
let (tx, rx) = std::sync::mpsc::channel();
denied.reply = Some(tx);
begin_request(&mut app, denied).unwrap();
assert_eq!(rx.try_recv().unwrap()["ok"], false);
assert!(rx.try_recv().is_err());
assert!(app.file_load.idle());
assert!(Arc::ptr_eq(&dirty, &app.session.doc));
// ui.file dispatch carries its scope on the calling thread; preserve it in the queue.
solidcraft_engine::io::vfs::scoped(Some(Default::default()), || {
begin(&mut app, "existing.solidcraft", false);
});
assert!(app.status.as_ref().is_some_and(|s| s.2 && s.0.contains("outside the folders")));
assert!(!reuse_open(&mut app, &Request::new("existing.solidcraft", Kind::Insert)));
assert!(!reuse_open(&mut app, &Request::new("existing.solidcraft", Kind::Recover { id: "test".into(), dir: None })));
}
#[test]
fn drawing_insert_and_drop_reuse_the_active_sketch_or_create_xy() {
let mut h = crate::scenario::Harness::new();
+8
View File
@@ -1507,6 +1507,14 @@ impl SolveApp {
}
pub fn open_path(&mut self, path: &str) {
match documents::reuse_path(self, path) {
Ok(true) => return,
Err(e) => {
self.set_status(e, true);
return;
}
Ok(false) => {}
}
self.home.open = false;
documents::prepare_open(self);
if let Ok(r) = self.run("doc.open", json!({ "path": path })) {
+2 -2
View File
@@ -154,7 +154,7 @@ fn home_tab_and_file_recent_open_designs() {
{"click":{"handle":"tab:home"}},
{"click":{"handle":"home:recent:0"}},
{"until":{"file_busy":false}},
{"expect":{"home":false,"bodies":1,"documents":2}},
{"expect":{"home":false,"bodies":1,"documents":1}},
{"click":{"handle":"appbar:folder"}},
{"widget":"Open Recent"}
]))
@@ -162,7 +162,7 @@ fn home_tab_and_file_recent_open_designs() {
h.run(&json!([
{"widget":path},
{"until":{"file_busy":false}},
{"expect":{"home":false,"bodies":1,"documents":3}}
{"expect":{"home":false,"bodies":1,"documents":1}}
]))
.unwrap();
}