Skip to content

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

Duplicate Layer from the menu opens a dialog for the copy's name and destination document (#3348) (#3440)

prekabreki9829d7ea3785
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 60db05e4a..362c20269 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -564,17 +564,21 @@ 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)} (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)} (no layer: every selected layer)"##,
has_layer,
|s, p| {
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) {
return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers");
}
let id = layer_param(s, p)?;
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let nid = s.edit("Duplicate Layer", |doc, active| {
- let dup = layer_copy(doc, id)?;
+ let mut dup = layer_copy(doc, id)?;
+ if let Some(name) = &name {
+ dup.name.clone_from(name);
+ }
let nid = doc.insert_above(Some(id), dup);
if !in_place {
crate::artboard_cmds::place_copy(doc, nid)?;
diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rs
index eb2d4d318..29eff4c8d 100644
--- a/crates/engine/src/layer_copy_cmds.rs
+++ b/crates/engine/src/layer_copy_cmds.rs
@@ -169,6 +169,9 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
}
copies.layers.push(l);
}
+ if let (Some(name), [l]) = (p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()), copies.layers.as_mut_slice()) {
+ l.name = name.to_string();
+ }
adapt_copies(s, &mut copies, &ddoc)?;
// Placement: centred on the destination's canvas, centred on a point, or offset from where
// the layers are in the source (default: the same canvas position).
@@ -216,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Copy Layers to Document",
menu: &[],
shortcut: None,
- params: r##"{"document":index (destination),"layers":[id,…]?=the source's selected layers,"source":index?=active,"center":bool=false (centre on the destination's canvas),"at":[x,y]? (centre the copies on this point),"offset":[dx,dy]?=[0,0] (from their place in the source)}"##,
+ params: r##"{"document":index (destination),"layers":[id,…]?=the source's selected layers,"source":index?=active,"center":bool=false (centre on the destination's canvas),"at":[x,y]? (centre the copies on this point),"offset":[dx,dy]?=[0,0] (from their place in the source),"name":str? (one layer: the copy's name)}"##,
enabled,
run: copy_to_document,
journal: true,
diff --git a/crates/engine/src/layer_copy_cmds/tests.rs b/crates/engine/src/layer_copy_cmds/tests.rs
index cf6902ca7..476df1879 100644
--- a/crates/engine/src/layer_copy_cmds/tests.rs
+++ b/crates/engine/src/layer_copy_cmds/tests.rs
@@ -217,3 +217,16 @@ fn copied_link_groups_are_distinct_from_each_other_and_destination() {
assert!(first.is_some() && second.is_some());
assert_ne!(first, second);
}
+
+#[test]
+fn a_named_duplicate_takes_the_name_in_one_step() {
+ let (mut s, paint) = two_docs(40, 30, 8);
+ let before = s.active().unwrap().history.past_len();
+ let same = LayerId(s.execute("layer.duplicate", json!({"name": "Ink"})).unwrap()["layer"].as_u64().unwrap());
+ assert_eq!(doc(&s, 0).layer(same).unwrap().name, "Ink");
+ assert_eq!(s.active().unwrap().history.past_len(), before + 1);
+ s.undo();
+ s.execute("layer.select", json!({"layer": paint.0})).unwrap();
+ let r = s.execute("layer.copyToDocument", json!({"document": 1, "name": "Ink"})).unwrap();
+ assert_eq!(doc(&s, 1).layer(copied(&r)).unwrap().name, "Ink");
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 6b77968d8..3e59cdcdd 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -234,6 +234,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields),
DialogKind::Command if crate::mask_trash_prompt::owns(&fields) => crate::mask_trash_prompt::body(ui, &fields),
DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),
+ DialogKind::Command if crate::duplicate_layer_ui::owns(&fields) => crate::duplicate_layer_ui::body(app, ui, &mut fields),
DialogKind::Command if crate::tool_reset::owns(&fields) => crate::tool_reset::body(ui),
DialogKind::Command if crate::crop_presets::owns(&fields) => crate::crop_presets::body(app, ui, &mut fields),
DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields),
@@ -484,6 +485,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields),
DialogKind::Command if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields),
DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields),
+ DialogKind::Command if crate::duplicate_layer_ui::owns(&d.fields) => crate::duplicate_layer_ui::confirm(app, &d.fields),
DialogKind::Command if crate::tool_reset::owns(&d.fields) => crate::tool_reset::confirm(app),
DialogKind::Command if crate::crop_presets::owns(&d.fields) => crate::crop_presets::confirm(app, &d.fields),
DialogKind::Command if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields),
diff --git a/crates/ui-egui/src/duplicate_layer_ui.rs b/crates/ui-egui/src/duplicate_layer_ui.rs
new file mode 100644
index 000000000..b1e7d6d99
--- /dev/null
+++ b/crates/ui-egui/src/duplicate_layer_ui.rs
@@ -0,0 +1,129 @@
+//! Layer › Duplicate Layer… dialog (#3348): the copy's name and its destination document, as in
+//! Photoshop. Only the menu, palette and Layers panel menu open it; ⌘J, Alt-drag and dragging onto
+//! the New Layer button still duplicate at once.
+use crate::{PhotocraftApp, state::DialogKind};
+use serde_json::{Map, Value, json};
+const MARK: &str = "__duplicateLayer";
+
+pub fn owns(fields: &Map<String, Value>) -> bool {
+ fields.contains_key(MARK)
+}
+
+pub fn open(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let index = app.session.active_index().ok_or("no document")?;
+ let st = app.session.active().ok_or("no document")?;
+ let selected = st.selected_layers();
+ let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?;
+ let mut fields = Map::new();
+ fields.insert(MARK.into(), json!(true));
+ fields.insert("__command".into(), json!("layer.duplicate"));
+ fields.insert("destination".into(), json!(index));
+ 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 {
+ fields.insert("__label".into(), json!("Duplicate Layer…"));
+ fields.insert("name".into(), json!(st.doc.copy_name(&layer.name)));
+ }
+ let id = app.ui.open_dialog(DialogKind::Command, fields);
+ Ok(json!({"dialog": id}))
+}
+
+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);
+ 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();
+ ui.label(tl!("Name:"));
+ ui.add(egui::TextEdit::singleline(&mut name).desired_width(260.0));
+ fields.insert("name".into(), json!(name));
+ ui.end_row();
+ }
+ ui.label(egui::RichText::new(tl!("Destination")).font(crate::theme::semibold(13.0)));
+ ui.end_row();
+ ui.label(tl!("Document"));
+ crate::widgets::dropdown(ui, "duplicate-layer-document", &mut destination, &options, 260.0);
+ ui.end_row();
+ });
+ fields.insert("destination".into(), json!(destination));
+}
+
+pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Value, String> {
+ let index = app.session.active_index().ok_or("The document is closed")?;
+ let st = app.session.active().ok_or("The document is closed")?;
+ if fields.get("document").and_then(Value::as_u64) != Some(st.doc.id.0)
+ || fields.get("selected") != Some(&json!(st.selected_layers().iter().map(|id| id.0).collect::<Vec<_>>()))
+ {
+ 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))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn make_app() -> PhotocraftApp {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width":8,"height":8,"name":"Poster"})).unwrap();
+ s.execute("layer.new.layer", json!({"name":"Ink"})).unwrap();
+ PhotocraftApp::new(s, crate::Services::default())
+ }
+ fn invoke(app: &mut PhotocraftApp) -> u64 {
+ let ctx = egui::Context::default();
+ crate::menus::invoke(app, &ctx, "layer.duplicate", json!({})).unwrap()["dialog"].as_u64().unwrap()
+ }
+ fn names(app: &PhotocraftApp, i: usize) -> Vec<String> {
+ app.session.documents()[i].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect()
+ }
+
+ #[test]
+ fn the_menu_opens_the_dialog_and_ok_duplicates_under_the_typed_name() {
+ let mut app = make_app();
+ let dialog = invoke(&mut app);
+ assert_eq!(app.session.active().unwrap().doc.layer_count(), 2, "nothing is copied until OK");
+ assert_eq!(app.ui.dialogs[0].fields["name"], "Ink copy");
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("name".into(), json!("Shadow"));
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ assert!(names(&app, 0).contains(&"Shadow".to_string()));
+ assert_eq!(app.session.active().unwrap().doc.layer_count(), 3);
+ }
+
+ #[test]
+ fn another_destination_document_receives_the_copy() {
+ let mut app = make_app();
+ app.session.execute("file.new", json!({"width":8,"height":8,"name":"Card"})).unwrap();
+ app.session.set_active(0);
+ let dialog = invoke(&mut app);
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("destination".into(), json!(1));
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ assert_eq!(app.session.documents()[0].doc.layer_count(), 2);
+ assert!(names(&app, 1).contains(&"Ink copy".to_string()));
+ }
+
+ #[test]
+ fn a_changed_document_refuses_and_direct_runs_stay_dialog_free() {
+ let mut app = make_app();
+ let dialog = invoke(&mut app);
+ app.session.execute("file.new", json!({"width":8,"height":8})).unwrap();
+ assert!(crate::dialogs::confirm(&mut app, dialog).is_err());
+ app.session.set_active(0);
+ app.run("layer.duplicate", json!({})).unwrap();
+ app.run("layer.new.layerViaCopy", json!({})).unwrap();
+ assert!(app.ui.dialogs.is_empty());
+ assert_eq!(app.session.active().unwrap().doc.layer_count(), 4);
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 0fe1945e7..a0e610a36 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -68,6 +68,7 @@ pub mod discard_ui;
pub mod distort_ui;
pub mod doc_props_ui;
pub mod dock;
+pub mod duplicate_layer_ui;
pub mod enable_rules;
pub mod eraser_ui;
pub mod export_dialog;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 541586c98..4d5ab5a0e 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -279,6 +279,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
}
Ok(Value::Null)
}
+ "layer.duplicate" if params.as_object().is_none_or(|o| o.is_empty()) => crate::duplicate_layer_ui::open(app),
"file.new" if params.as_object().is_none_or(|o| o.is_empty()) => {
let fields = app.new_document_fields();
let d = app.ui.open_dialog(DialogKind::NewDocument, fields);