Skip to content

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

Layer copies are numbered: "Layer 1 copy 2", not "Layer 1 copy copy" (#897)

jason4short059546680c0a
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 035e3daa3..153fe6bd2 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -894,6 +894,23 @@ impl Document {
(1..=names.len() + 1).map(|n| format!("{base} {n}")).find(|n| !names.contains(n.as_str())).unwrap_or_else(|| base.to_string())
}
+ /// Name for a copy of a layer named `name`, unique in the document: "Layer 1 copy", then
+ /// "Layer 1 copy 2", "Layer 1 copy 3"… A name that already ends in "copy" (or "copy N") is
+ /// numbered from its root rather than growing another "copy".
+ pub fn copy_name(&self, name: &str) -> String {
+ let root = match name.rsplit_once(" copy") {
+ Some((root, rest)) if rest.is_empty() || rest.strip_prefix(' ').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) => root,
+ _ => name,
+ };
+ let names: std::collections::HashSet<&str> = self.walk().into_iter().map(|(_, _, l)| l.name.as_str()).collect();
+ let first = format!("{root} copy");
+ if !names.contains(first.as_str()) {
+ return first;
+ }
+ // At most `names.len() + 1` candidates are needed, so the search always succeeds.
+ (2..=names.len() + 2).map(|n| format!("{root} copy {n}")).find(|n| !names.contains(n.as_str())).unwrap_or(first)
+ }
+
/// Top-most layer id, useful as the default active layer.
pub fn top_layer(&self) -> Option<LayerId> {
self.layers.last().map(|l| l.id)
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 6da63b698..171576bd2 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -457,7 +457,7 @@ fn build() -> Vec<CommandSpec> {
// A copy of the Background layer is an ordinary, unlocked layer (Photoshop).
let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id);
let mut dup = src.duplicate();
- dup.name = format!("{} copy", dup.name);
+ dup.name = doc.copy_name(&dup.name);
if from_background {
dup.locks = Default::default();
}
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index 73b47faf1..dc4f00b06 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -203,7 +203,7 @@ fn layer_via(s: &mut Session, cut: bool) -> Result<Value> {
let nid = s.edit("Layer Via Copy", |doc, active| {
let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let mut dup = src.duplicate();
- dup.name = format!("{} copy", src.name);
+ dup.name = doc.copy_name(&src.name);
dup.locks = Default::default();
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index 64768b0d8..0862ddca9 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -457,7 +457,7 @@ fn apply_content_aware_fill(
}
"duplicate" => {
let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
- dup.name = format!("{} copy", dup.name);
+ dup.name = doc.copy_name(&dup.name);
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
nid
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index cc54e4500..08e5b1f87 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -725,7 +725,7 @@ pub fn duplicate_selected(s: &mut Session) -> Result<Value> {
let mut new_active = None;
for id in top_level(doc, &sel) {
let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
- dup.name = format!("{} copy", dup.name);
+ dup.name = doc.copy_name(&dup.name);
let nid = doc.insert_above(Some(id), dup);
if Some(id) == old_active {
new_active = Some(nid);
@@ -833,6 +833,29 @@ pub fn specs() -> Vec<CommandSpec> {
mod tests {
use super::*;
+ #[test]
+ fn duplicates_are_numbered_not_stacked() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap();
+ let name = |s: &Session| {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone()
+ };
+ s.execute("layer.duplicate", json!({})).unwrap();
+ assert_eq!(name(&s), "Layer 1 copy");
+ // Duplicating the copy (the active layer) numbers it rather than adding "copy" again.
+ s.execute("layer.duplicate", json!({})).unwrap();
+ assert_eq!(name(&s), "Layer 1 copy 2");
+ s.execute("layer.duplicate", json!({})).unwrap();
+ assert_eq!(name(&s), "Layer 1 copy 3");
+ let doc = &s.active().unwrap().doc;
+ assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4");
+ // Names that merely contain "copy" keep it.
+ assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy");
+ assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy");
+ }
+
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap();
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
index 2578e7f09..8d6e31ffd 100644
--- a/crates/engine/src/smart_cmds.rs
+++ b/crates/engine/src/smart_cmds.rs
@@ -591,7 +591,7 @@ fn via_copy(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("New Smart Object via Copy", |doc, active| {
let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let mut copy = src.duplicate();
- copy.name = format!("{} copy", src.name);
+ copy.name = doc.copy_name(&src.name);
if let LayerContent::Smart(sm) = &mut copy.content {
// Independent contents: resolve to embedded bytes and drop the shared PSD uuid.
if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) {
diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rs
index 7d79dd4f2..3a9b0dcaf 100644
--- a/crates/engine/src/smartselect_cmds.rs
+++ b/crates/engine/src/smartselect_cmds.rs
@@ -191,7 +191,7 @@ fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {
let src = src_layer
.surface()
.ok_or_else(|| EngineError::Other(format!("the active layer is a {} layer without pixels", src_layer.content.kind_name())))?;
- let name = format!("{} copy", src_layer.name);
+ let name = d.doc.copy_name(&src_layer.name);
let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() };
let reg = region.as_ref().unwrap_or(&empty);
let pixels = if decontaminate { matting::decontaminate(src, reg, params.radius, amount) } else { src.clone() };