Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Opening a file that is already open shows its tab instead of a second copy (fixes #6598) (#6630)

Marco Arnulfoe196d8e47c24
diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs
index d752f7ce7..53e908bec 100644
--- a/crates/ui-egui/src/file_open.rs
+++ b/crates/ui-egui/src/file_open.rs
@@ -107,6 +107,9 @@ impl PhotocraftApp {
/// Read and open the file at `path` (see [`open_file`](Self::open_file)).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(&mut self, path: &str) -> Result<Vec<String>, String> {
+ if self.show_if_open(path) {
+ return Ok(Vec::new());
+ }
// Documents opening in the background are read on the worker too (a 2 GB PSB read
// would block the window). Preset files (brushes, gradients) go the usual way.
let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
@@ -133,6 +136,10 @@ impl PhotocraftApp {
let batch = crate::jobs_ui::begin_batch(self);
let mut opened = 0;
for (seq, abs) in paths.iter().enumerate() {
+ // Not a member of the set: its tab is already in place.
+ if self.show_if_open(abs) {
+ continue;
+ }
let order = crate::jobs_ui::OpenOrder { batch, seq };
let pending = self.jobs.opens.len();
match self.open_path(abs) {
@@ -152,6 +159,26 @@ impl PhotocraftApp {
opened
}
+ /// Show the document already open from the file at `path`, or its tab while it is still
+ /// opening in the background, as Photoshop does, rather than open a second copy bound to the
+ /// same file (#6598). True when there was one.
+ pub(crate) fn show_if_open(&mut self, path: &str) -> bool {
+ let canon = canonical(path);
+ let same = |p: &str| same_file(p, path, canon.as_deref());
+ if let Some(i) = self.session.documents().iter().position(|d| d.path.as_deref().is_some_and(same)) {
+ self.session.set_active(i);
+ self.jobs.focus = None;
+ } else if let Some(o) = self.jobs.opens.iter().find(|o| o.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) {
+ // A template still loading opens as another Untitled, as it does once loaded.
+ self.jobs.focus = Some(o.job);
+ } else {
+ return false;
+ }
+ // The document count didn't change, so the Home screen wouldn't give way by itself.
+ self.ui.chrome.home = None;
+ true
+ }
+
/// Show "Couldn't open <name>: <error>" as an error (status bar + notice).
pub fn open_failed(&mut self, name: &str, err: &str) {
self.failed({
@@ -338,5 +365,25 @@ fn absolute(p: &str) -> String {
p.to_string()
}
+/// `path` with symlinks, `.` and `..` and (on case-insensitive volumes) letter case resolved;
+/// `None` when it can't be (a missing file).
+#[cfg(not(target_arch = "wasm32"))]
+fn canonical(path: &str) -> Option<std::path::PathBuf> {
+ std::fs::canonicalize(path).ok()
+}
+
+#[cfg(target_arch = "wasm32")]
+fn canonical(_path: &str) -> Option<std::path::PathBuf> {
+ None
+}
+
+/// Whether an open document's path `p` names the file at `path` (`canon`: its [`canonical`]
+/// form). The cheap comparisons come first: `p` is resolved on disk only when they fail, so an
+/// open of a file that isn't open costs one resolution per document. A file moved or deleted
+/// since it was opened only matches its old path as written.
+fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool {
+ p == path || canon.is_some_and(|c| std::path::Path::new(p) == c || canonical(p).is_some_and(|q| q == c))
+}
+
#[cfg(test)]
mod tests;
diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs
index 4d6581cd6..b43a10a64 100644
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@ -928,3 +928,61 @@ fn opening_type_in_a_missing_font_warns() {
// The importer's own warning for the same font isn't doubled.
assert_eq!(app.open_bytes("warned.psd", b"x").unwrap(), vec![warning]);
}
+
+/// #6598: opening a file that is already open shows its document, as Photoshop does, rather than
+/// a second copy bound to the same file (saving one would overwrite the other). The path is
+/// compared as the file it names: another spelling of it, a symlink to it or, with background
+/// opens, a file still opening finds the same tab.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn opening_an_open_file_again_shows_its_tab() {
+ let (dir, paths) = files("already-open", &["a.psd", "b.psd"], b"x");
+ let (a, b) = (&paths[0], &paths[1]);
+ let (mut app, _) = app_with(Vec::new());
+ app.open_path(a).unwrap();
+ app.open_path(b).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.ui.chrome.home = Some(2);
+ // Open Recent, File › Open, a drop: all go through `open_path`.
+ #[allow(unused_mut)]
+ let mut spellings = vec![a.clone(), dir.join(".").join("a.psd").to_string_lossy().into_owned()];
+ #[cfg(unix)]
+ {
+ let link = dir.join("link.psd");
+ std::os::unix::fs::symlink(a, &link).unwrap();
+ spellings.push(link.to_string_lossy().into_owned());
+ }
+ for again in spellings {
+ app.session.set_active(1);
+ app.ui.chrome.home = Some(2);
+ app.open_path(&again).unwrap();
+ assert_eq!(doc_names(&app), ["a.psd", "b.psd"], "{again}");
+ assert_eq!(app.session.active_index(), Some(0), "{again}");
+ assert_eq!(app.ui.chrome.home, None, "the Home screen gives way to the document");
+ }
+ assert!(app.session.documents()[1].is_dirty(), "b keeps its unsaved changes");
+ // A set holding an open file opens only the others.
+ let (dir2, more) = files("already-open-set", &["c.psd"], b"x");
+ assert_eq!(app.open_paths(&[b.clone(), more[0].clone()]), 1);
+ assert_eq!(doc_names(&app), ["a.psd", "b.psd", "c.psd"]);
+ // In the background: an open document, then a file still opening, show their tabs.
+ app.background_jobs = true;
+ app.open_path(a).unwrap();
+ assert!(app.jobs.opens.is_empty());
+ assert_eq!(app.session.active_index(), Some(0));
+ let (dir3, late) = files("already-open-bg", &["d.psd"], b"x");
+ app.open_path(&late[0]).unwrap();
+ let job = app.jobs.opens[0].job;
+ app.jobs.focus = None;
+ app.open_path(&late[0]).unwrap();
+ assert_eq!(app.jobs.opens.len(), 1, "one tab for the file still opening");
+ assert_eq!(app.jobs.focus, Some(job));
+ // A template still loading opens again as another Untitled, as it does once loaded.
+ let (dir4, template) = files("already-open-template", &["e.psdt"], b"x");
+ app.open_path(&template[0]).unwrap();
+ app.open_path(&template[0]).unwrap();
+ assert_eq!(app.jobs.opens.len(), 3, "two Untitleds from the template");
+ for d in [dir, dir2, dir3, dir4] {
+ let _ = std::fs::remove_dir_all(&d);
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index d322e2641..074d87a8b 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -2090,9 +2090,11 @@ mod open_recent_tests {
let ctx = egui::Context::default();
invoke(&mut app, &ctx, "file.open", json!({ "path": p })).unwrap();
assert_eq!(app.ui.recent_files.first().map(String::as_str), Some(p.as_str()));
- // Re-open via the recent entry.
+ // Re-open via the recent entry once closed (an open file shows its tab instead, #6598).
+ app.session.close(0);
invoke(&mut app, &ctx, "file.openRecent.0", json!({})).unwrap();
- assert_eq!(app.session.documents().len(), 2);
+ assert_eq!(app.session.documents().len(), 1);
+ assert_eq!(app.session.active().and_then(|d| d.path.as_deref()), Some(p.as_str()));
let _ = std::fs::remove_file(&path);
}
}