PhotoCraft: An open-source, photo editor written by scratch in pure Rust
channel.merge: reject a repeated source index instead of closing an unrelated document (#1179)
wstock278e29413159
diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rsindex 35f443f89..8687d4dcb 100644--- a/crates/engine/src/channel_cmds.rs+++ b/crates/engine/src/channel_cmds.rs@@ -1315,7 +1315,15 @@ fn merge(s: &mut Session, p: &Value) -> Result<Value> {if srcs.len() < mode.color_channels() {return Err(bad(cmd, format!("{mode:?} needs {} grayscale documents, got {}", mode.color_channels(), srcs.len())));}- let first = s.documents()[srcs[0]].doc.clone();+ // Each source closes by its *current* index, so a repeated index would shift the later+ // removals onto a document that was never named (#934). Refuse it rather than guess.+ let mut seen = std::collections::HashSet::new();+ if let Some(dup) = srcs.iter().find(|i| !seen.insert(**i)) {+ return Err(bad(cmd, format!("document {dup} is listed more than once")));+ }+ let Some(first) = srcs.first().and_then(|&i| s.documents().get(i)).map(|d| d.doc.clone()) else {+ return Err(bad(cmd, "bad document index"));+ };let mut planes = Vec::new();for &i in &srcs {let d = &s.documents()[i].doc;diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rsindex 9d571862a..87dca83c9 100644--- a/crates/engine/src/channel_cmds/tests.rs+++ b/crates/engine/src/channel_cmds/tests.rs@@ -450,6 +450,29 @@ fn split_and_merge_channels() {assert!(s.execute("channel.merge", json!({"mode": "cmyk"})).is_err());}+#[test]+fn merge_rejects_a_repeated_source_and_keeps_unrelated_documents() {+ // #934: `documents: [0, 0, 1]` passed validation, then the close loop ran `close(1)`,+ // `close(0)`, `close(0)` and the last call removed the unrelated RGB document at index 2.+ let mut s = session();+ s.execute("channel.split", json!({})).unwrap();+ assert_eq!(s.documents().len(), 3);+ s.execute("file.new", json!({"width": 40, "height": 20})).unwrap();+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();+ let keep = s.documents()[3].doc.id;+ let before: Vec<_> = s.documents().iter().map(|d| d.doc.id).collect();+ let err = s.execute("channel.merge", json!({"mode": "rgb", "documents": [0, 0, 1]})).unwrap_err();+ assert!(err.to_string().contains("more than once"), "{err}");+ let after: Vec<_> = s.documents().iter().map(|d| d.doc.id).collect();+ assert_eq!(after, before, "a rejected merge closes nothing");+ assert!(s.documents().iter().any(|d| d.doc.id == keep));+ assert!(s.set_active(3) && s.undo(), "the unrelated document keeps its history");+ // Distinct indices still merge and close exactly the named sources.+ s.execute("channel.merge", json!({"mode": "rgb", "documents": [0, 1, 2]})).unwrap();+ assert_eq!(s.documents().len(), 2);+ assert!(s.documents().iter().any(|d| d.doc.id == keep));+}+#[test]fn duplicate_to_other_document() {let mut s = session();