PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layer: Duplicate Layer to a new document, as in Photoshop (#4805)
Abdul karim miaca5755f5b059
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 2b28a9946..12ec82c61 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -601,9 +601,25 @@ fn build() -> Vec<CommandSpec> {"Duplicate Layer…",["Layer"],None,- r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name)} (no layer: every selected layer)"##,+ r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##,has_layer,|s, p| {+ if let Some(d) = p.get("document") {+ if d.as_str() == Some("new") {+ return crate::layer_copy_cmds::duplicate_to_new_document(s, p);+ }+ let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64));+ if !same {+ return Err(EngineError::BadParams {+ cmd: "layer.duplicate".into(),+ msg: if d.as_u64().is_some() {+ "the destination is another open document (use layer.copyToDocument)".into()+ } else {+ "`document` must be a document index or \"new\"".into()+ },+ });+ }+ }let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false);let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string);if crate::layer_multi_cmds::multi(s, p) {diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rsindex 9a42778de..d08955fdf 100644--- a/crates/engine/src/layer_copy_cmds.rs+++ b/crates/engine/src/layer_copy_cmds.rs@@ -213,6 +213,66 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"document": dest, "layers": new.iter().map(|l| l.0).collect::<Vec<_>>(), "offset": [dx, dy]}))}+/// `layer.duplicate` with `"document": "new"`: Photoshop's Duplicate Layer… ›+/// Document: New. A new document the size of the source's canvas holds just the duplicated+/// layers at their canvas positions (a transparent background elsewhere); the source is+/// untouched and the new document becomes active. Mode, depth, resolution, profile,+/// patterns and global light come along so the copies render the same.+pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Value> {+ let src = s.active_index().ok_or(EngineError::NoDocument)?;+ let sdoc = s.documents().get(src).ok_or(EngineError::NoDocument)?.doc.clone();+ let ids = match crate::commands::explicit_layer(s, p)? {+ Some(id) => vec![id],+ None => s.active().ok_or(EngineError::NoDocument)?.selected_layers(),+ };+ if let Some(missing) = ids.iter().find(|id| sdoc.layer(**id).is_none()) {+ return Err(EngineError::NoLayer(*missing));+ }+ let ids = crate::layer_multi_cmds::top_level(&sdoc, &ids);+ if ids.is_empty() {+ return Err(bad("no layers to copy"));+ }+ if !layered(sdoc.mode) {+ return Err(EngineError::Other(format!("layers can't be duplicated with a {:?} document", sdoc.mode)));+ }+ let doc_name = p.get("documentName").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("{} copy", sdoc.name));+ let mut nd = Document::new(doc_name, sdoc.size, sdoc.mode, sdoc.depth);+ nd.resolution_dpi = sdoc.resolution_dpi;+ nd.icc_profile.clone_from(&sdoc.icc_profile);+ nd.patterns.clone_from(&sdoc.patterns);+ nd.global_light = sdoc.global_light;+ for id in &ids {+ let mut l = sdoc.layer(*id).ok_or(EngineError::NoLayer(*id))?.duplicate();+ if ids.len() == 1+ && let Some(name) = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty())+ {+ l.name = name.to_string();+ }+ nd.layers.push(l);+ }+ // Contents ids belong to a document: fresh ones keep the copies independent of the+ // source while preserving sharing within the batch (as `adapt_copies` does).+ let mut contents = HashMap::new();+ let smart_ids: Vec<_> = nd.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Smart(_)).then_some(l.id)).collect();+ for id in smart_ids {+ if let Some(l) = nd.layer_mut(id)+ && let LayerContent::Smart(sm) = &mut l.content+ {+ sm.contents_id = *contents.entry(sm.contents_id).or_insert_with(SmartContentsId::fresh);+ }+ }+ let new_ids: Vec<LayerId> = nd.layers.iter().map(|l| l.id).collect();+ let index = s.add_document(nd, None);+ crate::layer_multi_cmds::reselect(s, new_ids.clone(), new_ids.last().copied());+ let mut out = json!({"document": index, "layers": new_ids.iter().map(|l| l.0).collect::<Vec<_>>()});+ if let [one] = new_ids.as_slice()+ && let Some(map) = out.as_object_mut()+ {+ map.insert("layer".into(), json!(one.0));+ }+ Ok(out)+}+pub fn specs() -> Vec<CommandSpec> {vec![CommandSpec {id: CMD,diff --git a/crates/engine/src/layer_copy_cmds/tests.rs b/crates/engine/src/layer_copy_cmds/tests.rsindex 476df1879..a81ebbdc4 100644--- a/crates/engine/src/layer_copy_cmds/tests.rs+++ b/crates/engine/src/layer_copy_cmds/tests.rs@@ -1,5 +1,5 @@use photocraft_color::{ColorMode, PixelFormat, SampleType};-use photocraft_doc::{Document, LayerId, Pattern};+use photocraft_doc::{Document, LayerContent, LayerId, Pattern};use photocraft_geom::Rect;use photocraft_raster::Surface;use serde_json::{Value, json};@@ -218,6 +218,118 @@ fn copied_link_groups_are_distinct_from_each_other_and_destination() {assert_ne!(first, second);}+/// One painted layer, `depth`-bit RGB, as the only layer above the Background.+fn one_doc(depth: u32) -> (Session, LayerId) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();+ let paint = LayerId(s.execute("layer.new.layer", json!({"name": "paint"})).unwrap()["layer"].as_u64().unwrap());+ s.execute("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 10})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ s.execute("select.deselect", json!({})).unwrap();+ (s, paint)+}++#[test]+fn duplicate_to_a_new_document_keeps_size_pixels_and_place_at_every_depth() {+ for depth in [8, 16, 32] {+ let (mut s, paint) = one_doc(depth);+ let source_before = doc(&s, 0).clone();+ let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap();+ assert_eq!(r["document"], 1);+ assert_eq!(s.active_index(), Some(1), "the new document becomes active");+ let (src, dst) = (doc(&s, 0), doc(&s, 1));+ assert_eq!(*src, source_before, "the source is untouched");+ assert_eq!(dst.size, src.size, "same canvas, as Photoshop");+ assert_eq!((dst.mode, dst.depth, dst.resolution_dpi), (src.mode, src.depth, src.resolution_dpi));+ assert_eq!(dst.name, format!("{} copy", src.name));+ let layers = r["layers"].as_array().unwrap();+ assert_eq!(layers.len(), 1);+ let id = LayerId(layers[0].as_u64().unwrap());+ assert_eq!(r["layer"], id.0);+ assert_ne!(id, paint, "a copy has its own id");+ assert_eq!(dst.layers.len(), 1, "just the duplicated layer");+ assert_eq!(dst.layers[0].name, "paint");+ assert_eq!(bounds(&s, 1, id), Rect::new(4, 6, 14, 16), "same canvas position");+ assert_eq!(+ dst.layers[0].surface().unwrap().read_region(Rect::new(4, 6, 14, 16)),+ src.layer(paint).unwrap().surface().unwrap().read_region(Rect::new(4, 6, 14, 16)),+ "depth {depth}: identical pixels"+ );+ assert_eq!(s.active().unwrap().selected_layers(), vec![id]);+ }+}++#[test]+fn duplicate_to_a_new_document_names_the_copy_and_the_document() {+ let (mut s, _) = one_doc(8);+ let r = s.execute("layer.duplicate", json!({"document": "new", "name": "Ink", "documentName": "Card"})).unwrap();+ assert_eq!(doc(&s, 1).name, "Card");+ assert_eq!(doc(&s, 1).layers[0].name, "Ink");+ assert_eq!(r["layer"].as_u64(), r["layers"][0].as_u64());+}++#[test]+fn duplicate_to_a_new_document_carries_every_selected_layer_in_order() {+ let (mut s, paint) = one_doc(8);+ let bg = doc(&s, 0).layers[0].id;+ s.execute("layer.select", json!({"layer": paint.0, "mode": "add"})).unwrap();+ s.execute("layer.select", json!({"layer": bg, "mode": "add"})).unwrap();+ let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap();+ let names: Vec<&str> = doc(&s, 1).layers.iter().map(|l| l.name.as_str()).collect();+ assert_eq!(names, ["Background", "paint"]);+ assert_eq!(r["layers"].as_array().unwrap().len(), 2);+ assert!(r.get("layer").is_none(), "no single layer to report");+ // A duplicated Background stays a Background: the new document has no destination one.+ let back = &doc(&s, 1).layers[0];+ assert!(back.locks.transparency && back.locks.position);+}++#[test]+fn duplicate_to_a_new_document_cuts_smart_objects_loose_as_a_batch() {+ let (mut s, _) = one_doc(8);+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let original = s.active().unwrap().active_layer.unwrap();+ let sibling = LayerId(s.execute("layer.duplicate", json!({})).unwrap()["layer"].as_u64().unwrap());+ let contents = |s: &Session, i: usize, id: LayerId| {+ let LayerContent::Smart(sm) = &doc(s, i).layer(id).unwrap().content else { panic!("smart object") };+ sm.contents_id+ };+ assert_eq!(contents(&s, 0, original), contents(&s, 0, sibling), "instances share contents");+ s.execute("layer.select", json!({"layer": original.0, "mode": "add"})).unwrap();+ s.execute("layer.select", json!({"layer": sibling.0, "mode": "add"})).unwrap();+ let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap();+ let ids: Vec<LayerId> = r["layers"].as_array().unwrap().iter().map(|id| LayerId(id.as_u64().unwrap())).collect();+ assert_eq!(contents(&s, 1, ids[0]), contents(&s, 1, ids[1]), "sharing survives within the batch");+ assert_ne!(contents(&s, 1, ids[0]), contents(&s, 0, original), "independent of the source");+}++#[test]+fn duplicate_destinations_that_are_not_new_fail_cleanly() {+ let (mut s, _) = one_doc(8);+ for p in [+ json!({"document": 1}),+ json!({"document": 7}),+ json!({"document": true}),+ json!({"document": 1.5}),+ json!({"document": []}),+ json!({"document": {}}),+ json!({"document": "other"}),+ json!({"document": "new", "layer": 999_999}),+ ] {+ let before = (doc(&s, 0).clone(), s.documents().len(), s.active_index());+ let err = s.execute("layer.duplicate", p.clone()).unwrap_err().to_string();+ if p == json!({"document": 1}) {+ assert!(err.contains("layer.copyToDocument"), "{p}: {err}");+ }+ assert_eq!(s.active_index(), before.2, "{p}: the source stays active");+ assert_eq!(s.documents().len(), before.1, "{p}: no document created");+ assert_eq!(*doc(&s, 0), before.0, "{p}: the source is untouched");+ }+ // One open document: same-document duplicates still work, and stay enabled.+ assert!(s.is_enabled("layer.duplicate"));+ s.execute("layer.duplicate", json!({})).unwrap();+}+#[test]fn a_named_duplicate_takes_the_name_in_one_step() {let (mut s, paint) = two_docs(40, 30, 8);diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 1adc9051d..f65bcecbe 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -221,6 +221,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {ui.set_min_width(w);ui.set_max_width(w);}+ // Duplicate Layer… is a fixed small grid (labels + 260 pt fields ≈ 352 pt):+ // the generic 380 pt minimum left a dead strip on its right.+ if crate::duplicate_layer_ui::owns(&d.fields) {+ ui.set_min_width(360.0);+ ui.set_max_width(360.0);+ }if color_picker {ui.set_width(crate::color_picker_ui::CONTENT_WIDTH);}diff --git a/crates/ui-egui/src/duplicate_layer_ui.rs b/crates/ui-egui/src/duplicate_layer_ui.rsindex b1e7d6d99..c1b76c0ea 100644--- a/crates/ui-egui/src/duplicate_layer_ui.rs+++ b/crates/ui-egui/src/duplicate_layer_ui.rs@@ -18,11 +18,16 @@ pub fn open(app: &mut PhotocraftApp) -> Result<Value, String> {fields.insert(MARK.into(), json!(true));fields.insert("__command".into(), json!("layer.duplicate"));fields.insert("destination".into(), json!(index));+ // Photoshop's document-`Name` starts empty; the engine defaults it when empty.+ fields.insert("documentName".into(), json!(""));fields.insert("document".into(), json!(st.doc.id.0));fields.insert("selected".into(), json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()));// Several selected layers keep their names, as in Photoshop's Duplicate Layers.if selected.len() > 1 {fields.insert("__label".into(), json!("Duplicate Layers…"));+ } else if layer.is_group() {+ fields.insert("__label".into(), json!("Duplicate Group…"));+ fields.insert("name".into(), json!(st.doc.copy_name(&layer.name)));} else {fields.insert("__label".into(), json!("Duplicate Layer…"));fields.insert("name".into(), json!(st.doc.copy_name(&layer.name)));@@ -32,9 +37,14 @@ pub fn open(app: &mut PhotocraftApp) -> Result<Value, String> {}pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {- let documents: Vec<(usize, String)> = app.session.documents().iter().enumerate().map(|(i, d)| (i, d.doc.name.clone())).collect();- let options: Vec<(usize, &str)> = documents.iter().map(|(i, n)| (*i, n.as_str())).collect();- let mut destination = fields.get("destination").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).unwrap_or(0);+ let documents: Vec<(String, String)> = app.session.documents().iter().enumerate().map(|(i, d)| (i.to_string(), d.doc.name.clone())).collect();+ let mut options: Vec<(String, &str)> = documents.iter().map(|(k, n)| (k.clone(), n.as_str())).collect();+ options.push(("new".to_string(), tl!("New")));+ let mut destination = match fields.get("destination") {+ Some(Value::String(s)) if s == "new" => "new".to_string(),+ Some(Value::Number(n)) => n.to_string(),+ _ => String::new(),+ };egui::Grid::new("duplicate-layer").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {if let Some(name) = fields.get("name").and_then(Value::as_str) {let mut name = name.to_string();@@ -48,8 +58,20 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Valui.label(tl!("Document"));crate::widgets::dropdown(ui, "duplicate-layer-document", &mut destination, &options, 260.0);ui.end_row();+ // Photoshop's document-`Name` is only there when the destination is a new document.+ if destination == "new" {+ let mut doc_name = fields.get("documentName").and_then(Value::as_str).unwrap_or("").to_string();+ ui.label(tl!("Name:"));+ ui.add(egui::TextEdit::singleline(&mut doc_name).desired_width(260.0));+ fields.insert("documentName".into(), json!(doc_name));+ ui.end_row();+ }});- fields.insert("destination".into(), json!(destination));+ if destination == "new" {+ fields.insert("destination".into(), json!("new"));+ } else if let Ok(i) = destination.parse::<u64>() {+ fields.insert("destination".into(), json!(i));+ }}pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Value, String> {@@ -60,16 +82,29 @@ pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<V{return Err("The document or selected layers changed. Choose Duplicate Layer again.".into());}- let destination = fields.get("destination").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or("no destination document")?;let mut params = Map::new();if let Some(name) = fields.get("name").and_then(Value::as_str) {params.insert("name".into(), json!(name));}- if destination == index {- app.run_command("layer.duplicate", Value::Object(params))- } else {- params.insert("document".into(), json!(destination));- app.run_command("layer.copyToDocument", Value::Object(params))+ match fields.get("destination") {+ Some(Value::String(s)) if s == "new" => {+ if let Some(doc_name) = fields.get("documentName").and_then(Value::as_str).filter(|n| !n.is_empty()) {+ params.insert("documentName".into(), json!(doc_name));+ }+ params.insert("document".into(), json!("new"));+ app.run_command("layer.duplicate", Value::Object(params))+ }+ Some(Value::Number(n)) => {+ let destination =+ n.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < app.session.documents().len()).ok_or("no destination document")?;+ if destination == index {+ app.run_command("layer.duplicate", Value::Object(params))+ } else {+ params.insert("document".into(), json!(destination));+ app.run_command("layer.copyToDocument", Value::Object(params))+ }+ }+ _ => Err("no destination document".into()),}}@@ -114,6 +149,42 @@ mod tests {assert!(names(&app, 1).contains(&"Ink copy".to_string()));}+ #[test]+ fn a_new_destination_makes_a_named_document_holding_just_the_copy() {+ let mut app = make_app();+ let dialog = invoke(&mut app);+ let fields = &mut app.ui.dialog_mut(dialog).unwrap().fields;+ fields.insert("destination".into(), json!("new"));+ fields.insert("documentName".into(), json!("Card"));+ crate::dialogs::confirm(&mut app, dialog).unwrap();+ assert_eq!(app.session.documents().len(), 2);+ assert_eq!(app.session.active_index(), Some(1));+ assert_eq!(app.session.documents()[1].doc.name, "Card");+ assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched");+ assert!(names(&app, 1).contains(&"Ink copy".to_string()));+ }++ #[test]+ fn a_new_destination_without_a_name_defaults_it_and_refuses_a_dead_index() {+ let mut app = make_app();+ let dialog = invoke(&mut app);+ app.ui.dialog_mut(dialog).unwrap().fields.insert("destination".into(), json!("new"));+ crate::dialogs::confirm(&mut app, dialog).unwrap();+ assert_eq!(app.session.documents()[1].doc.name, "Poster copy");+ let dialog = invoke(&mut app);+ app.ui.dialog_mut(dialog).unwrap().fields.insert("destination".into(), json!(7));+ assert!(crate::dialogs::confirm(&mut app, dialog).is_err());+ assert_eq!(app.session.documents().len(), 2);+ }++ #[test]+ fn a_single_group_gets_the_group_title() {+ let mut app = make_app();+ app.session.execute("layer.new.group", json!({"name": "Pack"})).unwrap();+ let _dialog = invoke(&mut app);+ assert_eq!(app.ui.dialogs[0].fields["__label"], "Duplicate Group…");+ }+#[test]fn a_changed_document_refuses_and_direct_runs_stay_dialog_free() {let mut app = make_app();