PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Quick Export: Same Folder asks before replacing the document's own file (#6599) (#6632)
Zuujis1dcaa28b962f
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 43828b76b..bfaca603d 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -219,6 +219,29 @@ pub(crate) fn stem(path: &str) -> String {}}+/// Whether `a` and `b` name the same file: the same text, or, when both exist, the same file on+/// disk (a hard link, a different case on a case-insensitive volume, `./` or `..` in one of them).+pub fn same_file(a: &str, b: &str) -> bool {+ if a == b {+ return true;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) {+ return x.dev() == y.dev() && x.ino() == y.ino();+ }+ }+ #[cfg(windows)]+ {+ // NTFS and FAT compare names without case.+ if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) {+ return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase();+ }+ }+ false+}+pub(crate) fn join(dir: &str, name: &str) -> String {if dir.is_empty() {name.to_string()diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rsindex 595ad2195..25cd235b2 100644--- a/crates/engine/src/web_cmds.rs+++ b/crates/engine/src/web_cmds.rs@@ -1024,27 +1024,48 @@ fn export_preferences(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)}))}+/// The Quick Export format's extension (Export Preferences › Format).+fn quick_export_ext(s: &Session) -> String {+ serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into())+}++/// Where Quick Export writes the active document with no `path` given: `<name>.<format>` beside+/// its file, when Export Preferences › Location is Same Folder and the document has a file.+pub fn quick_export_target(s: &Session) -> Option<String> {+ let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder;+ let dp = s.active()?.path.as_deref().filter(|_| same)?;+ let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();+ Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s))))+}++/// Whether [`quick_export_target`] is the active document's own file (a document opened from+/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599).+pub fn quick_export_target_is_own_file(s: &Session) -> bool {+ let own = s.active().and_then(|d| d.path.as_deref());+ quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own))+}+/// File › Export › Quick Export as <format>: the format, quality, metadata, colour space and/// location from Export Preferences. `path` overrides the location ("ask" needs one).fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "file.export.quickExport";let prefs = s.prefs().export.clone();- let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into());- let d = s.active().ok_or(EngineError::NoDocument)?;- let doc = d.doc.clone();+ let fmt = quick_export_ext(s);let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) {Some(v) => v.to_string(),None => {- let same = serde_json::to_value(prefs.quick_export_location).ok().and_then(|v| v.as_str().map(str::to_string)).is_some_and(|v| v == "sameFolder");- match (&d.path, same) {- (Some(dp), true) => {- let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();- join(&dir, &format!("{}.{fmt}", stem(dp)))- }- _ => return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")),+ let Some(target) = quick_export_target(s) else {+ return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)"));+ };+ // The document's own file is never replaced by an export the user didn't name (#6599).+ if quick_export_target_is_own_file(s) {+ return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`")));}+ target}};+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let doc = d.doc.clone();let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();let mut o = serde_json::Map::new();o.insert(diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rsindex c3ffe6edc..1b91dcf72 100644--- a/crates/engine/src/web_cmds/tests.rs+++ b/crates/engine/src/web_cmds/tests.rs@@ -437,6 +437,54 @@ fn export_preferences_drive_quick_export() {s.execute("prefs.reset", json!({"path": "export"})).unwrap();}+/// #6599: with Location = Same Folder, a document opened from `photo.png` would be exported over+/// `photo.png` itself. Without a `path` that is refused and the file is left alone; named+/// explicitly (the save dialog's answer) it is written.+#[test]+fn quick_export_never_replaces_the_documents_own_file_unasked() {+ let dir = tmp("quick_own_file");+ let mut s = session(8);+ s.execute("file.export.exportPreferences", json!({"quickExportLocation": "sameFolder", "quickExportFormat": "png"})).unwrap();+ let own = format!("{dir}/photo.png");+ std::fs::write(&own, b"original").unwrap();+ s.active_mut().unwrap().path = Some(own.clone());+ assert_eq!(quick_export_target(&s), Some(own.clone()));+ assert!(quick_export_target_is_own_file(&s));+ let e = s.execute("file.export.quickExport", json!({})).unwrap_err().to_string();+ assert!(e.contains("own file"), "{e}");+ assert_eq!(std::fs::read(&own).unwrap(), b"original", "the source is untouched");+ s.execute("file.export.quickExport", json!({"path": own})).unwrap();+ assert_eq!(decode(&own).dimensions(), (64, 48));+ // Another format, or a PSD's earlier export beside it, is still written without asking.+ s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap();+ assert!(!quick_export_target_is_own_file(&s));+ assert_eq!(s.execute("file.export.quickExport", json!({})).unwrap()["path"], json!(format!("{dir}/photo.jpg")));+ s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png"})).unwrap();+ s.active_mut().unwrap().path = Some(format!("{dir}/photo.psd"));+ assert!(!quick_export_target_is_own_file(&s));+ assert_eq!(s.execute("file.export.quickExport", json!({})).unwrap()["path"], json!(own));+ s.execute("prefs.reset", json!({"path": "export"})).unwrap();+}++#[test]+fn same_file_sees_through_other_names_for_one_file() {+ let dir = tmp("same_file");+ let (a, b, c) = (format!("{dir}/a.png"), format!("{dir}/b.png"), format!("{dir}/c.png"));+ std::fs::write(&a, b"a").unwrap();+ std::fs::write(&c, b"c").unwrap();+ assert!(crate::file_cmds::same_file(&a, &a));+ assert!(crate::file_cmds::same_file(&a, &format!("{dir}/./a.png")));+ assert!(!crate::file_cmds::same_file(&a, &c));+ assert!(!crate::file_cmds::same_file(&a, &b), "a missing file is not the same file");+ #[cfg(unix)]+ {+ std::fs::hard_link(&a, &b).unwrap();+ assert!(crate::file_cmds::same_file(&a, &b), "a hard link is the same file");+ }+ #[cfg(windows)]+ assert!(crate::file_cmds::same_file(&a, &format!("{dir}/A.PNG")), "NTFS names ignore case");+}+#[test]fn webp_export_preferences_select_lossless_or_lossy_output() {let dir = tmp("quick_webp_quality");diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rsindex 9367045af..275221e05 100644--- a/crates/ui-egui/src/export_dialog.rs+++ b/crates/ui-egui/src/export_dialog.rs@@ -907,7 +907,10 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into());let same = serde_json::to_value(prefs.quick_export_location).ok().is_some_and(|v| v == "sameFolder");let saved = app.session.active().is_some_and(|d| d.path.is_some());- if same && saved {+ // Same Folder writes beside the document's file without asking, except when that would+ // replace the file itself (a document opened from photo.png): then the save dialog asks,+ // so replacing it is the user's choice (#6599).+ if same && saved && !photocraft_engine::web_cmds::quick_export_target_is_own_file(&app.session) {return quick_export(app, json!({}));}let st = app.session.active().ok_or("no document")?;diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex 6a3ccfcf9..bb827274f 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -838,6 +838,37 @@ fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() {assert!(!app.ui.status_error, "{}", app.ui.status);}+/// #6599: Quick Export as PNG with Location = Same Folder asks before replacing the document's+/// own file (a document opened from photo.png), and keeps writing beside a PSD without a prompt.+#[test]+fn same_folder_quick_export_asks_before_replacing_the_documents_own_file() {+ let dir = std::env::temp_dir().join(format!("photocraft-quick-own-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let own = dir.join("photo.png").to_string_lossy().into_owned();+ std::fs::write(&own, b"original").unwrap();+ let (mut app, open, _) = app();+ app.run("prefs.set", json!({"path": "export.quickExportLocation", "value": "sameFolder"})).unwrap();+ app.session.active_mut().unwrap().path = Some(own.clone());+ let ctx = egui::Context::default();+ menus::invoke(&mut app, &ctx, "file.export.quickExportAsPng", Value::Null).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert_eq!(open.borrow().len(), 1, "the save dialog asks");+ assert_eq!(std::fs::read(&own).unwrap(), b"original", "nothing written before the answer");+ answer(&open, Some(FileDialogAnswer::SaveTo(own.clone())));+ app.poll_file_dialog(&ctx, None);+ assert!(std::fs::read(&own).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"), "replaced once confirmed: {}", app.ui.status);++ // Beside a PSD, Same Folder still writes without a prompt.+ app.session.active_mut().unwrap().path = Some(dir.join("photo.psd").to_string_lossy().into_owned());+ std::fs::write(&own, b"earlier export").unwrap();+ menus::invoke(&mut app, &ctx, "file.export.quickExportAsPng", Value::Null).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert!(open.borrow().is_empty(), "no dialog");+ assert!(std::fs::read(&own).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));+ std::fs::remove_dir_all(&dir).ok();+}+#[test]fn cancelling_multi_layer_quick_export_writes_nothing() {let (mut app, open, written) = app();