Skip to content

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

Layer > New > Background from Layer; the Background stays at the bottom (#2626) (#2663)

Fabio Lussi9d3ba499ade0
diff --git a/crates/engine/src/background_cmds.rs b/crates/engine/src/background_cmds.rs
new file mode 100644
index 000000000..1da5ebc92
--- /dev/null
+++ b/crates/engine/src/background_cmds.rs
@@ -0,0 +1,261 @@
+//! Layer › New › Background from Layer, and the rule that keeps the Background at the bottom.
+//!
+//! Photoshop's Background is the locked, opaque layer at the bottom of the stack. Background from
+//! Layer turns the selected layer into it: transparent pixels take the background colour and the
+//! layer drops to the bottom. While a document has a Background nothing reorders it and no layer
+//! can go below it (Layer › Arrange, Reverse, dragging in the Layers panel); Layer from Background
+//! (`layer.new.layerFromBackground`) turns it back into a normal layer that moves freely.
+
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::extra_cmds::is_background;
+use crate::{EngineError, Result, Session};
+
+const CMD: &str = "layer.new.backgroundFromLayer";
+
+/// The document's Background layer, if it has one (always the bottom layer).
+pub(crate) fn background_id(doc: &Document) -> Option<LayerId> {
+ doc.layers.first().filter(|l| is_background(l)).map(|l| l.id)
+}
+
+/// Refuses an edit that moved the Background `bg` (taken before the edit) off the bottom of the
+/// stack, or put another layer below it. Called at the end of a `Session::edit` closure, so an
+/// `Err` leaves the document and history untouched.
+pub(crate) fn keep_background_at_bottom(bg: Option<LayerId>, doc: &Document) -> Result<()> {
+ match bg {
+ Some(id) if doc.layers.first().map(|l| l.id) != Some(id) => Err(EngineError::Other(
+ "the Background layer stays at the bottom of the stack (Layer › New › Layer from Background makes it a normal layer)".into(),
+ )),
+ _ => Ok(()),
+ }
+}
+
+/// Can `l` become the Background? Groups and adjustment layers have no pixels of their own.
+fn convertible(l: &Layer) -> std::result::Result<(), String> {
+ match l.content {
+ LayerContent::Group(_) | LayerContent::Adjustment(_) => {
+ Err(format!("{} {} layer can't become the Background", l.content.article(), l.content.kind_name()))
+ }
+ _ => Ok(()),
+ }
+}
+
+fn can_convert(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if background_id(&d.doc).is_some() {
+ return Err("the document already has a Background layer".into());
+ }
+ let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?;
+ convertible(l)
+}
+
+fn background_from_layer(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = match p.get("layer") {
+ None | Some(Value::Null) => crate::commands::layer_param(s, p)?,
+ Some(v) => LayerId(v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "`layer` must be a layer id".into() })?),
+ };
+ let bg = s.tools.background;
+ s.edit("Background From Layer", |doc, active| {
+ if background_id(doc).is_some() {
+ return Err(EngineError::Other("the document already has a Background layer".into()));
+ }
+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ convertible(l).map_err(EngineError::Other)?;
+ // Render the layer alone, as it looks (mask, opacity and effects applied), over the
+ // background colour: the Background is opaque and plain.
+ let mut only = l.clone();
+ only.visible = true;
+ only.clipped = false;
+ let visible = l.visible;
+ let fmt = doc.pixel_format();
+ let rest = std::mem::replace(&mut doc.layers, vec![only]);
+ let pixels = photocraft_compose::flatten_to_surface(doc, fmt, Some([bg[0], bg[1], bg[2]]));
+ doc.layers = rest;
+ let mut out = Layer::raster("Background", fmt);
+ out.id = id;
+ out.visible = visible;
+ out.locks.transparency = true;
+ out.locks.position = true;
+ *crate::pixels_mut(&mut out)? = pixels;
+ doc.remove(id).ok_or(EngineError::NoLayer(id))?;
+ doc.layers.insert(0, out);
+ *active = Some(id);
+ Ok(())
+ })?;
+ // The Background is the one targeted layer now.
+ s.select_layer(id)?;
+ Ok(json!({"layer": id.0}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: CMD,
+ label: "Background From Layer",
+ menu: &["Layer", "New"],
+ shortcut: None,
+ params: r##"{"layer":id?} (the active layer by default; transparent pixels take the background colour and the layer drops to the bottom as the locked Background)"##,
+ enabled: can_convert,
+ journal: true,
+ run: background_from_layer,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_geom::Rect;
+
+ /// Bottom to top: Layer 0 (the old Background, now a normal layer), A, B. A has a 4×4 red
+ /// square at (2, 2); the rest of it is transparent.
+ fn session(depth: u32) -> (Session, [LayerId; 3]) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 12, "depth": depth})).unwrap();
+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();
+ let l0 = doc(&s).layers[0].id;
+ let id = |s: &mut Session, name: &str| LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap());
+ let a = id(&mut s, "A");
+ s.execute("select.rect", json!({"x": 2, "y": 2, "width": 4, "height": 4})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let b = id(&mut s, "B");
+ (s, [l0, a, b])
+ }
+
+ fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+ }
+
+ fn order(s: &Session) -> Vec<LayerId> {
+ doc(s).layers.iter().map(|l| l.id).collect()
+ }
+
+ fn pixel(s: &Session, x: i32, y: i32) -> Vec<f32> {
+ doc(s).layers[0].surface().unwrap().read_region(Rect::new(x, y, x + 1, y + 1))
+ }
+
+ /// A Background (the white one `file.new` makes) with A and B above it.
+ fn with_background() -> (Session, [LayerId; 3]) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
+ let bg = doc(&s).layers[0].id;
+ let a = LayerId(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap());
+ let b = LayerId(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap());
+ (s, [bg, a, b])
+ }
+
+ #[test]
+ fn makes_the_layer_the_background_at_the_bottom() {
+ for depth in [8, 16, 32] {
+ let (mut s, [l0, a, b]) = session(depth);
+ s.tools.background = [0.0, 0.0, 1.0, 1.0];
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ assert!(s.is_enabled(CMD), "{depth}");
+ assert_eq!(s.execute(CMD, json!({})).unwrap()["layer"], a.0);
+ assert_eq!(order(&s), [a, l0, b], "{depth}: drops to the bottom");
+ let l = &doc(&s).layers[0];
+ assert!(is_background(l) && l.name == "Background", "{depth}");
+ assert_eq!(s.active().unwrap().active_layer, Some(a));
+ // Its pixels stay; transparency takes the background colour (blue).
+ let red = pixel(&s, 3, 3);
+ let blue = pixel(&s, 10, 10);
+ assert!((red[0] - 1.0).abs() < 1e-3 && red[2].abs() < 1e-3 && (red[3] - 1.0).abs() < 1e-3, "{depth}: {red:?}");
+ assert!(blue[0].abs() < 1e-3 && (blue[2] - 1.0).abs() < 1e-3 && (blue[3] - 1.0).abs() < 1e-3, "{depth}: {blue:?}");
+ // Now there is a Background: the item greys, Layer from Background is back.
+ assert!(!s.is_enabled(CMD));
+ assert!(s.execute(CMD, json!({"layer": b.0})).is_err(), "{depth}: one Background per document");
+ assert!(s.is_enabled("layer.new.layerFromBackground"));
+ // One step: undo restores the layer where it was, transparent.
+ assert!(s.undo());
+ assert_eq!(order(&s), [l0, a, b], "{depth}");
+ let l = doc(&s).layer(a).unwrap();
+ assert!(!is_background(l) && l.name == "A");
+ assert!(s.redo());
+ assert_eq!(order(&s), [a, l0, b], "{depth}");
+ assert!(is_background(&doc(&s).layers[0]));
+ }
+ }
+
+ #[test]
+ fn a_layer_in_a_group_leaves_it_and_keeps_its_look() {
+ let (mut s, [l0, a, b]) = session(8);
+ s.execute("layer.select", json!({"layer": b.0})).unwrap();
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ s.execute("layer.setProps", json!({"layer": b.0, "opacity": 0.5, "visible": false})).unwrap();
+ s.execute("layer.select", json!({"layer": b.0})).unwrap();
+ s.execute(CMD, json!({})).unwrap();
+ let d = doc(&s);
+ assert_eq!(d.layers[0].id, b);
+ assert!(d.layers[1..].iter().all(|l| l.id != b));
+ assert_eq!(d.layers[1].id, l0);
+ assert_eq!(d.layers[2].id, a);
+ let bg = &d.layers[0];
+ assert!(is_background(bg) && !bg.visible, "visibility is kept");
+ assert_eq!(bg.opacity, 1.0);
+ }
+
+ #[test]
+ fn refuses_groups_adjustments_missing_layers_and_bad_params() {
+ // No document.
+ let mut s = Session::new();
+ assert!(!s.is_enabled(CMD));
+ assert!(s.execute(CMD, json!({})).is_err());
+ // Already a Background: unavailable, for any layer.
+ let (mut s, [bg, a, _]) = with_background();
+ assert!(!s.is_enabled(CMD));
+ assert!(s.execute(CMD, json!({"layer": a.0})).is_err());
+ assert!(s.execute(CMD, json!({"layer": bg.0})).is_err());
+ // Bad params.
+ let (mut s, [_, a, _]) = session(8);
+ for p in [json!({"layer": "A"}), json!({"layer": -1}), json!({"layer": 1.5}), json!({"layer": 99999}), json!({"layer": [a.0]})] {
+ assert!(s.execute(CMD, p.clone()).is_err(), "{p}");
+ }
+ assert!(!doc(&s).layers.iter().any(is_background));
+ // A group or an adjustment layer can't become the Background.
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ assert!(!s.is_enabled(CMD), "the group is active");
+ assert!(s.execute(CMD, json!({})).is_err());
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ assert!(!s.is_enabled(CMD));
+ assert!(s.execute(CMD, json!({})).is_err());
+ assert!(!doc(&s).layers.iter().any(is_background));
+ }
+
+ #[test]
+ fn the_background_stays_at_the_bottom() {
+ let (mut s, [bg, a, b]) = with_background();
+ // Arrange: the Background doesn't move, and nothing goes below it. (The menu greys these
+ // for the Background in the shell's enable rules; here an agent asks anyway.)
+ for cmd in ["layer.arrange.bringForward", "layer.arrange.bringToFront", "layer.arrange.sendBackward", "layer.arrange.sendToBack"] {
+ assert!(s.execute(cmd, json!({"layer": bg.0})).is_err(), "{cmd}");
+ assert_eq!(order(&s), [bg, a, b], "{cmd}");
+ }
+ assert!(s.execute("layer.arrange.sendBackward", json!({"layer": a.0})).is_err());
+ s.execute("layer.arrange.sendToBack", json!({"layer": b.0})).unwrap();
+ assert_eq!(order(&s), [bg, b, a], "Send to Back stops above the Background");
+ // Dragging in the Layers panel (layer.moveTo).
+ assert!(s.execute("layer.moveTo", json!({"layer": bg.0, "target": a.0, "position": "above"})).is_err());
+ assert!(s.execute("layer.moveTo", json!({"layer": a.0, "target": bg.0, "position": "below"})).is_err());
+ assert!(s.execute("layer.moveTo", json!({"layer": a.0, "target": bg.0, "position": "below", "copy": true})).is_err());
+ assert!(s.execute("layer.moveTo", json!({"layers": [bg.0, a.0], "target": b.0, "position": "above"})).is_err());
+ assert_eq!(order(&s), [bg, b, a]);
+ s.execute("layer.moveTo", json!({"layer": a.0, "target": bg.0, "position": "above"})).unwrap();
+ assert_eq!(order(&s), [bg, a, b], "above the Background is fine");
+ // ⌥-dragging the Background copies it above; the copy is a normal layer.
+ s.execute("layer.moveTo", json!({"layer": bg.0, "target": b.0, "position": "above", "copy": true})).unwrap();
+ assert_eq!(doc(&s).layers.len(), 4);
+ assert_eq!(doc(&s).layers[0].id, bg);
+ assert!(s.undo());
+ // Reverse with the Background among the selected layers.
+ s.execute("layer.select", json!({"layer": bg.0})).unwrap();
+ s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
+ assert!(s.execute("layer.arrange.reverse", json!({})).is_err());
+ assert_eq!(order(&s), [bg, a, b]);
+ // As a normal layer it moves freely again.
+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();
+ s.execute("layer.arrange.bringToFront", json!({"layer": bg.0})).unwrap();
+ assert_eq!(order(&s), [a, b, bg]);
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index e7d086d3b..ecb89bd28 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1157,6 +1157,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::select_extra_cmds::specs());
v.extend(crate::paint_cmds::specs());
v.extend(crate::extra_cmds::specs());
+ v.extend(crate::background_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::exr_cmds::specs());
v.extend(crate::type_extra_cmds::specs());
@@ -1269,6 +1270,11 @@ pub fn adjustment_kind(a: &Adjustment) -> &'static str {
fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {
let id = layer_param(s, p)?;
s.edit("Arrange", |doc, _| {
+ // The Background stays at the bottom: it doesn't move and nothing goes below it.
+ let bg = crate::background_cmds::background_id(doc);
+ if bg == Some(id) {
+ return Err(EngineError::Other("the Background layer can't be moved".into()));
+ }
let steps = match delta {
i32::MAX => 10_000,
i32::MIN => -10_000,
@@ -1280,6 +1286,10 @@ fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {
if !doc.shift(id, dir) {
break;
}
+ if crate::background_cmds::keep_background_at_bottom(bg, doc).is_err() {
+ doc.shift(id, -dir);
+ break;
+ }
moved = true;
}
if moved { Ok(()) } else { Err(EngineError::Other("layer can't move further".into())) }
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 9408a32b1..5db8f5270 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -934,6 +934,7 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
}
let original_active = st.active_layer;
+ let background = crate::background_cmds::background_id(doc);
let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| {
let mut moved = Vec::with_capacity(moved_ids.len());
for &id in &moved_ids {
@@ -956,6 +957,7 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
siblings.splice(at..at, moved);
}
check_group_depth(doc, "Reorder Layer")?;
+ crate::background_cmds::keep_background_at_bottom(background, doc)?;
*active = if copy {
copies.last().copied()
} else if batch.is_some() {
@@ -1056,6 +1058,7 @@ fn rename_layer(s: &mut Session, p: &Value) -> Result<Value> {
fn reverse(s: &mut Session) -> Result<Value> {
let sel = selected(s);
s.edit("Reverse", |doc, _| {
+ let background = crate::background_cmds::background_id(doc);
let ids = top_level(doc, &sel);
if ids.len() < 2 {
return Err(EngineError::Other("select two or more layers to reverse".into()));
@@ -1067,7 +1070,7 @@ fn reverse(s: &mut Session) -> Result<Value> {
for (path, l) in paths.iter().zip(layers.into_iter().rev()) {
*doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l;
}
- Ok(())
+ crate::background_cmds::keep_background_at_bottom(background, doc)
})?;
Ok(Value::Null)
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e70781bd2..32d083423 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -15,6 +15,7 @@ mod allocation;
pub mod analysis_cmds;
pub mod artboard_cmds;
pub mod automate_cmds;
+pub mod background_cmds;
pub mod brush_cmds;
pub mod brush_key_cmds;
pub mod brush_preset_cmds;
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index ef309cfbb..d9f462790 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -273,6 +273,8 @@
Layer via Cut Vrstva vyjmutím
Layer From Background… Vrstva z pozadí…
Layer from Background… Vrstva z pozadí…
+ Background from Layer Pozadí z vrstvy
+ Background From Layer Pozadí z vrstvy
New Shape Layer Nová vrstva tvaru
New Type Layer Nová textová vrstva
New Fill Layer Nová vrstva výplně
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index a6d27a055..e555ee045 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -269,6 +269,8 @@
Layer via Cut Ebene durch Ausschneiden
Layer From Background… Ebene aus Hintergrund…
Layer from Background… Ebene aus Hintergrund…
+ Background from Layer Hintergrund aus Ebene
+ Background From Layer Hintergrund aus Ebene
New Shape Layer Neue Formebene
New Type Layer Neue Textebene
New Fill Layer Neue Füllebene
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 1ff892456..fdf1fbb52 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -1728,6 +1728,7 @@
Layer via Cut Επίπεδο μέσω αποκοπής
Layer From Background… Επίπεδο από φόντο…
Layer from Background… Επίπεδο από φόντο…
+ Background From Layer Φόντο από επίπεδο
New Shape Layer Νέο επίπεδο σχήματος
New Type Layer Νέο επίπεδο κειμένου
New Fill Layer Νέο επίπεδο γεμίσματος
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 25d173aba..ddf1f6178 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -265,6 +265,8 @@
Layer via Cut Capa vía corte
Layer From Background… Capa a partir del fondo…
Layer from Background… Capa a partir del fondo…
+ Background from Layer Fondo a partir de capa
+ Background From Layer Fondo a partir de capa
New Shape Layer Nueva capa de forma
New Type Layer Nueva capa de texto
New Fill Layer Nueva capa de relleno
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 5db463844..3817088d5 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -264,6 +264,7 @@
Layer via Cut Calque par coupe
Layer From Background… Calque d'après l'arrière-plan…
Layer from Background… Calque d'après l'arrière-plan…
+ Background From Layer Arrière-plan d'après le calque
New Shape Layer Nouveau calque de forme
New Type Layer Nouveau calque de texte
New Fill Layer Nouveau calque de remplissage
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index d969e4e9a..f5875a5b9 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -257,6 +257,7 @@
Layer via Cut Layer via Potong
Layer From Background… Layer dari Background…
Layer from Background… Layer dari Background…
+ Background From Layer Background dari Layer
New Shape Layer Layer Bentuk Baru
New Type Layer Layer Teks Baru
New Fill Layer Layer Isian Baru
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 7fbdbe548..cf3dcff59 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -265,6 +265,8 @@
Layer via Cut Livello tramite taglia
Layer From Background… Livello dallo sfondo…
Layer from Background… Livello dallo sfondo…
+ Background from Layer Sfondo da livello
+ Background From Layer Sfondo da livello
New Shape Layer Nuovo livello forma
New Type Layer Nuovo livello testo
New Fill Layer Nuovo livello riempimento
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 797049749..ee6b16b07 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -269,6 +269,7 @@
Layer via Cut 切り取ったレイヤー
Layer From Background… 背景からレイヤーへ…
Layer from Background… 背景からレイヤーへ…
+ Background From Layer レイヤーから背景
New Shape Layer 新規シェイプレイヤー
New Type Layer 新規文字レイヤー
New Fill Layer 新規塗りつぶしレイヤー
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 82c965fad..6427e87c0 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -252,6 +252,8 @@
Layer via Cut 잘라내어 레이어 만들기
Layer From Background… 배경에서 레이어 만들기…
Layer from Background… 배경에서 레이어 만들기…
+ Background from Layer 레이어에서 배경 만들기
+ Background From Layer 레이어에서 배경 만들기
New Shape Layer 새 모양 레이어
New Type Layer 새 문자 레이어
New Fill Layer 새 칠 레이어
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 241393018..26e93d035 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -261,6 +261,7 @@
Layer via Cut Laag via knippen
Layer From Background… Laag uit achtergrond…
Layer from Background… Laag uit achtergrond…
+ Background From Layer Achtergrond uit laag
New Shape Layer Nieuwe vormlaag
New Type Layer Nieuwe tekstlaag
New Fill Layer Nieuwe opvullaag
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 2226a6cc2..552c06cc7 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -267,6 +267,7 @@
Layer via Cut Warstwa przez wycięcie
Layer From Background… Warstwa z tła…
Layer from Background… Warstwa z tła…
+ Background From Layer Tło z warstwy
New Shape Layer Nowa warstwa kształtu
New Type Layer Nowa warstwa tekstowa
New Fill Layer Nowa warstwa wypełnienia
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 0d7205e3b..7d4e59b86 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -261,6 +261,7 @@
Layer via Cut Camada via recorte
Layer From Background… Camada a partir do plano de fundo…
Layer from Background… Camada a partir do plano de fundo…
+ Background From Layer Plano de fundo a partir da camada
New Shape Layer Nova camada de forma
New Type Layer Nova camada de texto
New Fill Layer Nova camada de preenchimento
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 3392f6120..c42dbd69c 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -152,6 +152,8 @@
Rename Layer Переименовать слой
Layer From Background… Слой из фона…
Layer from Background… Слой из фона…
+ Background from Layer Фон из слоя
+ Background From Layer Фон из слоя
Group Layers Сгруппировать слои
Group… Группировать…
Ungroup Layers Разгруппировать слои
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index caffa68e9..65f79f5c7 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -143,6 +143,7 @@
Rename Layer Перейменувати шар
Layer From Background… Шар із фону…
Layer from Background… Шар із фону…
+ Background From Layer Фон із шару
Group Layers Згрупувати шари
Group… Група…
Ungroup Layers Розгрупувати шари
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 0b38441b7..a35d98845 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -268,6 +268,7 @@
Layer via Cut 通过剪切创建图层
Layer From Background… 从背景创建图层…
Layer from Background… 从背景创建图层…
+ Background From Layer 从图层创建背景
Background from Layer 从图层创建背景
New Shape Layer 新建形状图层
New Type Layer 新建文字图层
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 8ad664506..aac9ceae9 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -273,6 +273,8 @@
Layer via Cut 剪下的圖層
Layer From Background… 從背景建立圖層…
Layer from Background… 從背景建立圖層…
+ Background from Layer 從圖層建立背景
+ Background From Layer 從圖層建立背景
New Shape Layer 新增形狀圖層
New Type Layer 新增文字圖層
New Fill Layer 新增填滿圖層
diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs
index 791095c1d..f2ac633ba 100644
--- a/crates/ui-egui/src/layer_row_ui/tests.rs
+++ b/crates/ui-egui/src/layer_row_ui/tests.rs
@@ -410,23 +410,25 @@ fn alt_dragging_the_only_layer_drops_a_copy_on_itself() {
fn dropping_below_the_bottom_row_lands_at_the_bottom_of_the_stack() {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ // Nothing can go below a Background (#2626), so the bottom layer is a normal one here.
+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();
for i in 0..2 {
s.execute("layer.new.layer", json!({"name": format!("L{i}")})).unwrap();
}
let mut h = harness(s, 1.0, "promedium", 290.0);
let names = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
- // Rows top to bottom: L1, L0, Background. The empty space starts under Background.
+ // Rows top to bottom: L1, L0, Layer 0. The empty space starts under Layer 0.
let top = recorded(&h.ctx)[0].row.center();
let bottom = recorded(&h.ctx)[2].row;
drag_from_to(&mut h, top, pos2(bottom.center().x, bottom.bottom() + 10.0), Modifiers::ALT);
- assert_eq!(names(&h), ["L1 copy", "Background", "L0", "L1"]);
+ assert_eq!(names(&h), ["L1 copy", "Layer 0", "L0", "L1"]);
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Duplicate Layer"));
- // Rows: L1, L0, Background, L1 copy. A plain drag of L0 to the empty space moves it to the
+ // Rows: L1, L0, Layer 0, L1 copy. A plain drag of L0 to the empty space moves it to the
// very bottom.
let grabbed = recorded(&h.ctx)[1].row.center();
let bottom = recorded(&h.ctx)[3].row;
drag_from_to(&mut h, grabbed, pos2(bottom.center().x, bottom.bottom() + 10.0), Modifiers::NONE);
- assert_eq!(names(&h), ["L0", "L1 copy", "Background", "L1"]);
+ assert_eq!(names(&h), ["L0", "L1 copy", "Layer 0", "L1"]);
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Reorder Layers"));
}
diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs
index ad9261b7e..94355aa51 100644
--- a/crates/ui-egui/src/menu_catalog.rs
+++ b/crates/ui-egui/src/menu_catalog.rs
@@ -245,6 +245,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Image", "Analysis"], "Place Scale Marker…", None, "image.analysis.placeScaleMarker"),
(&["Layer", "New"], "Layer…", Some("Cmd+Shift+N"), "layer.new.layer"),
(&["Layer", "New"], "Layer from Background…", None, "layer.new.layerFromBackground"),
+ (&["Layer", "New"], "Background from Layer", None, "layer.new.backgroundFromLayer"),
(&["Layer", "New"], "Group…", None, "layer.new.group"),
(&["Layer", "New"], "Group from Layers…", None, "layer.new.groupFromLayers"),
(&["Layer", "New"], "---", None, "---"),
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 2afb9fd44..b7d4fdb0d 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -3203,6 +3203,15 @@ fn layer_drop_payload(dragged: u64, target: LayerId, position: &str, selected: &
}
}
+/// Would this drop move the Background off the bottom, or put a layer below it? Photoshop
+/// refuses both (no drop indicator); ⌥-dragging the Background still copies it above.
+fn background_drop_refused(doc: &photocraft_doc::Document, payload: &Value, target: LayerId, position: &str, copy: bool) -> bool {
+ let Some(bg) = doc.layers.first().filter(|b| crate::doc_props_ui::is_background(doc, b)).map(|b| b.id) else { return false };
+ let moves_bg =
+ !copy && (payload["layer"].as_u64() == Some(bg.0) || payload["layers"].as_array().is_some_and(|a| a.iter().any(|v| v.as_u64() == Some(bg.0))));
+ moves_bg || (target == bg && position == "below")
+}
+
/// Drag a layer row to reorder: drop above, below, or inside an existing group. With ⌥ held on
/// release the layers stay put and copies land there instead (Photoshop).
/// Multi-layer moves are atomic (one undo step), using the engine's stable document order.
@@ -3271,6 +3280,11 @@ fn layer_drag_and_drop(
} else {
"below"
};
+ let Some(st) = app.session.active() else { return };
+ let mut payload = layer_drop_payload(dragged, l.id, position, &st.selected_layers());
+ if background_drop_refused(&st.doc, &payload, l.id, position, copy) {
+ return;
+ }
let painter = ui.painter();
match position {
"into" => {
@@ -3284,8 +3298,6 @@ fn layer_drag_and_drop(
}
}
if released {
- let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default();
- let mut payload = layer_drop_payload(dragged, l.id, position, &selected);
if copy && let Some(o) = payload.as_object_mut() {
o.insert("copy".into(), json!(true));
}
@@ -4405,6 +4417,31 @@ mod group_drag_selection_tests {
assert_eq!(layer_drop_payload(b.0, group, "below", &[a, b])["position"], "below");
}
+ #[test]
+ fn the_background_row_neither_moves_nor_takes_a_layer_below_it() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ let bg = s.active().unwrap().doc.layers[0].id;
+ let a = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
+ let doc = &s.active().unwrap().doc;
+ let refused = |dragged: LayerId, target: LayerId, pos: &str, sel: &[LayerId], copy: bool| {
+ background_drop_refused(doc, &layer_drop_payload(dragged.0, target, pos, sel), target, pos, copy)
+ };
+ assert!(refused(bg, a, "above", &[bg], false));
+ assert!(refused(a, bg, "below", &[a], false));
+ assert!(refused(a, bg, "below", &[a], true));
+ assert!(refused(a, a, "above", &[bg, a], false), "the Background is among the dragged layers");
+ assert!(!refused(a, bg, "above", &[a], false));
+ assert!(!refused(bg, a, "above", &[bg], true), "⌥-dragging copies the Background above");
+ // Without a Background every drop is fine.
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();
+ let l0 = s.active().unwrap().doc.layers[0].id;
+ let doc = &s.active().unwrap().doc;
+ assert!(!background_drop_refused(doc, &layer_drop_payload(l0.0, a, "above", &[l0]), a, "above", false));
+ }
+
#[test]
fn dragging_unselected_or_singular_row_remains_a_single_layer_move() {
let a = LayerId(10);
diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs
index 90181e7b5..db8de4e50 100644
--- a/crates/ui-egui/src/parity.rs
+++ b/crates/ui-egui/src/parity.rs
@@ -7,7 +7,7 @@ use crate::menu_catalog::CATALOG;
use crate::menus::is_live;
/// Minimum number of live catalog items. Raise it when parity grows; never lower it.
-pub const FLOOR: usize = 627;
+pub const FLOOR: usize = 629;
/// One top-level menu's coverage.
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md
index 9eb50a908..a479b2b7e 100644
--- a/docs/parity-checklist.md
+++ b/docs/parity-checklist.md
@@ -2,14 +2,14 @@
Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand.
-**628 of 628 menu items live (100.0%).**
+**629 of 629 menu items live (100.0%).**
| Menu | Live | Total | % |
|---|---:|---:|---:|
| File | 52 | 52 | 100% |
| Edit | 75 | 75 | 100% |
| Image | 61 | 61 | 100% |
-| Layer | 161 | 161 | 100% |
+| Layer | 162 | 162 | 100% |
| Type | 44 | 44 | 100% |
| Select | 25 | 25 | 100% |
| Filter | 75 | 75 | 100% |