Skip to content

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

file.saveACopy refuses the document's own file without "overwrite" (#7437) (#7456)

Khawar Zamman Wani502d055c6c8c
diff --git a/Cargo.lock b/Cargo.lock
index 26920a968..132863df3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4812,6 +4812,7 @@ dependencies = [
"photocraft-vector",
"rayon",
"roxmltree",
+ "same-file",
"serde",
"serde_json",
"tempfile",
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 65dd1e16e..fb3bc3fbe 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -43,6 +43,11 @@ roxmltree = "0.20"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tempfile = "3"
+# `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a
+# file is that file (std's `MetadataExt::file_index` is unstable).
+[target.'cfg(windows)'.dependencies]
+same-file = "1"
+
# Printing on Unix: an IPP client for CUPS (pure Rust); the web build cannot print.
[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
photocraft-ipp = { workspace = true }
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index f99aefcff..1fb3fcf30 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -234,7 +234,12 @@ pub fn same_file(a: &str, b: &str) -> bool {
}
#[cfg(windows)]
{
- // NTFS and FAT compare names without case.
+ // The volume serial number and file index of each, as unix compares dev and inode, so a
+ // hard link (another name for the file) is the same file.
+ if let Ok(same) = same_file::is_same_file(a, b) {
+ return same;
+ }
+ // Should a file not open: 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();
}
@@ -481,6 +486,15 @@ fn revert(s: &mut Session) -> Result<Value> {
fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path", "file.saveACopy")?.to_string();
let d = s.active().ok_or(EngineError::NoDocument)?;
+ // A copy over the document's own file replaces it, and a flat or lossy format can't be
+ // undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the
+ // shell, after the OS has confirmed the replace.
+ if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) {
+ return Err(EngineError::BadParams {
+ cmd: "file.saveACopy".into(),
+ msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(),
+ });
+ }
let mut doc = (*d.doc).clone();
if p.get("layers").and_then(Value::as_bool) == Some(false) {
// "Layers" unchecked in Save a Copy: write the flattened image.
@@ -1639,7 +1653,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save a Copy…",
&["File"],
Some("Cmd+Alt+S"),
- r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,
+ r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,
native_doc,
save_a_copy
),
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index 624edfdd3..3ab50c4a7 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -135,6 +135,44 @@ fn save_a_copy_keeps_path_and_dirty_state() {
assert!(s.execute("file.saveACopy", json!({})).is_err());
}
+/// A copy over the document's own file, however the path is spelt, would replace it (a lossy
+/// re-encode can't be undone), so it is refused unless `overwrite` is passed (#7437).
+#[test]
+fn save_a_copy_refuses_the_documents_own_file() {
+ let dir = tmp("copy-own");
+ let path = png(&dir, "own.png", 6, 4, "#ff0000");
+ let bytes = std::fs::read(&path).unwrap();
+ let mut s = Session::new();
+ open_bytes_as(&mut s, &path, &bytes, None, Some(path.clone())).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ let link = join(&dir, "link.png");
+ std::fs::hard_link(&path, &link).unwrap();
+ let rev = s.active().unwrap().revision;
+ for p in [path.clone(), format!("{dir}/./own.png"), link] {
+ let r = s.execute("file.saveACopy", json!({"path": p}));
+ assert!(r.as_ref().is_err_and(|e| e.to_string().contains("overwrite")), "{p}: {r:?}");
+ assert!(s.execute("file.saveACopy", json!({"path": p, "overwrite": false})).is_err(), "{p}");
+ assert_eq!(std::fs::read(&path).unwrap(), bytes, "{p}");
+ let st = s.active().unwrap();
+ assert_eq!(st.path.as_deref(), Some(path.as_str()), "{p}");
+ assert_eq!(st.revision, rev, "{p}");
+ assert!(st.is_dirty(), "{p}");
+ }
+ let other = join(&dir, "other.png");
+ s.execute("file.saveACopy", json!({"path": other})).unwrap();
+ assert!(std::fs::metadata(&other).unwrap().len() > 0);
+ s.execute("file.saveACopy", json!({"path": path, "overwrite": true})).unwrap();
+ assert_ne!(std::fs::read(&path).unwrap(), bytes);
+ assert_eq!(s.active().unwrap().path.as_deref(), Some(path.as_str()));
+ assert!(s.active().unwrap().is_dirty());
+
+ // A document that was never saved has no file of its own: it copies anywhere, as before.
+ let mut fresh = session(4, 4, 8);
+ fresh.execute("file.saveACopy", json!({"path": path})).unwrap();
+ assert_eq!(fresh.active().unwrap().path, None);
+}
+
/// `tgaBits` picks the Targa's bits per pixel (byte 16 of the header); unset, a document with an
/// alpha channel is written as 32-bit, with the channel as the alpha.
#[test]
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
index 594fe8d49..bd55a549c 100644
--- a/crates/engine/src/web_cmds/tests.rs
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -476,11 +476,8 @@ fn same_file_sees_through_other_names_for_one_file() {
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");
- }
+ 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");
}