fix(layers): count new layer names up from the highest Layer N (#17366)

`layer.new.layer` without a name and the New Layer dialog took the first
free "Layer N", so a document holding "Layer 7" was offered "Layer 1"
again. `Document::next_layer_suggestion` names one above the highest
exact "Layer <number>" name, 1 when none exists; the command default and
the dialog prefill share that one helper, so an empty or spaces-only
Name gets the name the dialog showed. The other callers of
`next_layer_name` (groups, shapes, Layer from Background) keep the
first-free rule.

Fixes #17366
This commit is contained in:
hnoerenberg committed 2026-11-28 19:11:26 +01:00
1 parent f7d76f5be4
commit 2025c854d2
5 files changed
+111 -3

No files matched your search

+10
View File
@@ -1377,6 +1377,16 @@ impl Document {
(1..=names.len() + 1).map(|n| format!("{base} {n}")).find(|n| !names.contains(n.as_str())).unwrap_or_else(|| base.to_string())
}
/// The "Layer N" a new plain layer is suggested: N is one above the highest number among the
/// names that are exactly "Layer <number>", or 1 when no layer has such a name (#17365). Only
/// Layer > New > Layer and its dialog use this; other callers keep [`Self::next_layer_name`].
/// Names are gathered as `next_layer_name` gathers them (every layer, compared exactly), and a
/// number too large to hold is not counted, like a name that is not "Layer <number>".
pub fn next_layer_suggestion(&self) -> String {
let highest = self.walk().into_iter().filter_map(|(_, _, l)| l.name.strip_prefix("Layer ")).filter_map(|digits| digits.parse::<u64>().ok()).max();
format!("Layer {}", highest.unwrap_or(0).saturating_add(1))
}
/// 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".
+2
View File
@@ -330,6 +330,8 @@ pub struct Session {
mod embed_all_linked_tests;
#[cfg(test)]
mod fill_layer_mode_tests;
#[cfg(test)]
mod new_layer_name_counter_tests;
#[cfg(test)]
mod second_keys_zoom_actions_tests;
+1 -1
View File
@@ -42,7 +42,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let NewLayer { clip, mode, opacity, label, neutral, below, name } = parse(p)?;
let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto };
let id = s.edit("New Layer", |doc, active| {
let name = name.clone().unwrap_or_else(|| doc.next_layer_name("Layer"));
let name = name.clone().unwrap_or_else(|| doc.next_layer_suggestion());
let mut layer = Layer::raster(name, doc.pixel_format());
layer.blend = mode;
layer.opacity = opacity;
@@ -0,0 +1,80 @@
//! #17366: the default "Layer N" for `layer.new.layer` without a name counts up from the highest
//! layer named exactly "Layer <number>", instead of taking the first free number. The New Layer
//! dialog proposes the same name from the same helper; its test in
//! `crates/ui-egui/src/dialogs/new_layer_ui.rs` pins that the prefilled name equals the name the
//! command gives, by behaviour rather than by naming one function twice.
//!
//! Not measured in the issue: whether numbered layers inside groups count. Names are gathered as
//! `Document::next_layer_name` gathers them today: every layer in the document, compared exactly.
//! Layer from Background keeps its own measured lowest-free rule (#14821), pinned below.
use photocraft_doc::LayerId;
use serde_json::json;
use crate::Session;
fn doc(s: &Session) -> &photocraft_doc::Document {
&s.active().unwrap().doc
}
/// A document with the white Background `file.new` makes and top-level layers named `others` above
/// it, then `layer.new.layer` without a name: the name the made layer ends with.
fn default_name(others: &[&str]) -> String {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
for n in others {
s.execute("layer.new.layer", json!({ "name": n })).unwrap();
}
s.execute("layer.new.layer", json!({})).unwrap();
doc(&s).layers.last().unwrap().name.clone()
}
#[test]
fn the_default_counts_up_from_the_highest_layer_n() {
// The issue's measured cases plus a gap: the highest name decides, not the first free number.
let cases: Vec<(Vec<&str>, &str)> = vec![
(vec!["Red"], "Layer 1"),
(vec!["Layer 1", "Layer 2"], "Layer 3"),
(vec!["Layer 7"], "Layer 8"),
(vec!["Layer 1", "Layer 7"], "Layer 8"),
(vec!["Layer 2", "Layer 5"], "Layer 6"),
];
for (others, want) in cases {
assert_eq!(default_name(&others), want, "other layers: {others:?}");
}
}
/// Measured in the issue: after deleting Layer 2 and renaming Layer 1 to Layer 7, the next layer
/// takes Layer 8, not Layer 1 or Layer 2.
#[test]
fn deleting_and_renaming_moves_the_counter_up() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({ "name": "Layer 1" })).unwrap();
let second = LayerId(s.execute("layer.new.layer", json!({ "name": "Layer 2" })).unwrap()["layer"].as_u64().unwrap());
s.execute("layer.delete", json!({ "layer": second.0 })).unwrap();
let first = doc(&s).layers.iter().find(|l| l.name == "Layer 1").unwrap().id;
s.execute("layer.setProps", json!({ "layer": first.0, "name": "Layer 7" })).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
assert_eq!(doc(&s).layers.last().unwrap().name, "Layer 8");
}
#[test]
fn names_that_are_not_exactly_layer_number_do_not_count() {
// "Layer 3 copy", "layer 4" and "Layer x" hold no number the counter may follow, so the
// document has no numbered layer and the default starts at Layer 1.
let others = vec!["Layer 3 copy", "layer 4", "Layer x", "Red"];
assert_eq!(default_name(&others), "Layer 1", "only exact \"Layer <number>\" names count");
}
/// #14821 measured Layer from Background as its own lowest-free rule, counting from 0. The shared
/// counter must not change what that command names the converted Background.
#[test]
fn layer_from_background_keeps_the_lowest_free_name() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
let bg = doc(&s).layers[0].id;
s.execute("layer.new.layer", json!({ "name": "Layer 7" })).unwrap();
s.execute("layer.new.layerFromBackground", json!({})).unwrap();
assert_eq!(doc(&s).layer(bg).unwrap().name, "Layer 0", "the highest Layer N does not move this command's counter");
}
+18 -2
View File
@@ -35,7 +35,7 @@ pub(crate) fn opacity_param() -> Param {
/// Open the dialog for the active document, with the name the layer would get.
pub fn open(app: &mut PhotocraftApp) -> Result<DialogId, String> {
let name = app.session.active().ok_or("no document open")?.doc.next_layer_name("Layer");
let name = app.session.active().ok_or("no document open")?.doc.next_layer_suggestion();
Ok(params::open_param(app, COMMAND, DialogFields::new(), Value::Null, move |fields: &mut DialogFields| {
let neutral_modes: Vec<String> =
BlendMode::LAYER_MODES.into_iter().filter(|m| neutral_color(*m).is_some()).map(|mode| mode.key().to_string()).collect();
@@ -127,7 +127,7 @@ pub(crate) mod testing {
mod tests {
use serde_json::json;
use super::testing::{set, top};
use super::testing::{fields, set, top};
use super::*;
fn app() -> Box<PhotocraftApp> {
@@ -187,6 +187,22 @@ mod tests {
assert_eq!(opacity_param().unit, Some(UnitKind::Percent));
}
/// #17366: the dialog's prefilled name is the name `layer.new.layer` gives when the Name field
/// is empty or spaces only — the suggestion and the command default come from one rule.
#[test]
fn the_prefilled_name_is_the_name_the_command_would_give() {
let mut app = app();
app.run("layer.new.layer", json!({ "name": "Layer 7" })).unwrap();
let ctx = app.ctx().clone();
crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap();
let id = top(&app);
let prefill = fields(&app, id).text("name").map(|n| n.to_string()).unwrap_or_default();
assert_eq!(prefill, "Layer 8", "the prefill counts up from the highest Layer N");
set(&mut app, id, "name", json!(" ")).unwrap();
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert_eq!(top_layer(&app).name.as_str(), prefill, "spaces only gets the name the dialog suggested");
}
#[test]
fn params_follow_photoshop_rules() {
let mut f = DialogFields::new();