Skip to content

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

Layers: Cmd/Ctrl-click New Layer adds the layer below the current one (#4475)

Sean Hellwig1460187522a4
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index f2fd637b9..3850ba0cb 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -1169,6 +1169,16 @@ impl Document {
id
}
+ /// Insert `layer` directly below the layer `below` (or at the bottom of the root if None).
+ pub fn insert_below(&mut self, below: Option<LayerId>, layer: Layer) -> LayerId {
+ let id = layer.id;
+ match below.and_then(|b| self.path_of(b)).and_then(|path| self.siblings_mut(&path)) {
+ Some((sib, idx)) => sib.insert(idx, layer),
+ None => self.layers.insert(0, layer),
+ }
+ id
+ }
+
pub fn remove(&mut self, id: LayerId) -> Option<Layer> {
let path = self.path_of(id)?;
let (sib, idx) = self.siblings_mut(&path)?;
@@ -1366,6 +1376,17 @@ mod tests {
assert!(d.layer(a).is_none());
}
+ #[test]
+ fn insert_below_lands_under_the_reference() {
+ let mut d = doc();
+ let bg = d.layers[0].id;
+ let a = d.insert_above(Some(bg), Layer::raster("A", d.pixel_format()));
+ let b = d.insert_below(Some(a), Layer::raster("B", d.pixel_format()));
+ let names: Vec<_> = d.layers.iter().map(|l| l.name.as_str()).collect();
+ assert_eq!(names, ["Background", "B", "A"]);
+ assert_eq!(d.layers[1].id, b);
+ }
+
#[test]
fn groups_walk_and_paths() {
let mut d = doc();
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 2a769f068..2b28a9946 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -573,7 +573,7 @@ fn build() -> Vec<CommandSpec> {
"Layer…",
["Layer", "New"],
Some("Cmd+Shift+N"),
- r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error)}"##,
+ r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)}"##,
has_doc,
crate::new_layer::run
),
diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs
index ca814e6d4..a6f4cefd3 100644
--- a/crates/engine/src/new_layer.rs
+++ b/crates/engine/src/new_layer.rs
@@ -24,7 +24,8 @@ pub fn neutral_color(mode: BlendMode) -> Option<([f32; 3], &'static str)> {
}
}
-/// `layer.new.layer`: a pixel layer above the active one, joining the clip group it lands in.
+/// `layer.new.layer`: a pixel layer above the active one (below it with `position: below`, the
+/// Layers panel's ⌘/Ctrl-click), joining the clip group it lands in.
pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let flag = |k: &str| match p.get(k) {
None | Some(Value::Null) => Ok(false),
@@ -49,6 +50,14 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
};
let neutral =
if fill_neutral { Some(neutral_color(mode).ok_or_else(|| bad(format!("{} has no neutral color to fill with", mode.label())))?.0) } else { None };
+ let below = match p.get("position") {
+ None | Some(Value::Null) => false,
+ Some(v) => match v.as_str() {
+ Some("above") => false,
+ Some("below") => true,
+ _ => return Err(bad("`position` must be above or below")),
+ },
+ };
let name = match p.get("name") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_str().ok_or_else(|| bad("`name` must be a string"))?.to_string()),
@@ -65,7 +74,11 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let px = photocraft_raster::from_rgba(&surface.format(), [rgb[0], rgb[1], rgb[2], 1.0]);
surface.fill_rect(bounds, &px);
}
- let id = doc.insert_above(*active, layer);
+ // Nothing may sit under the Background: below it the layer lands above it instead.
+ let id = match *active {
+ Some(a) if below && doc.layer(a).is_some() && !doc.is_background(a) => doc.insert_below(Some(a), layer),
+ _ => doc.insert_above(*active, layer),
+ };
crate::clip_group::settle(doc, &[id], &Default::default(), clip);
*active = Some(id);
Ok(id)
@@ -158,6 +171,24 @@ mod tests {
assert_eq!(l.surface().unwrap().tile_count(), 0);
}
+ /// `position: below` (⌘/Ctrl-click on the panel button) lands under the active layer; the
+ /// Background stays at the bottom, so below it the layer lands above it.
+ #[test]
+ fn position_below_lands_under_the_active_layer() {
+ let mut s = busy("rgb", 8);
+ let names = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
+ s.execute("layer.new.layer", json!({"name": "A"})).unwrap();
+ let below = s.execute("layer.new.layer", json!({"name": "Below", "position": "below"})).unwrap()["layer"].as_u64().unwrap();
+ assert_eq!(names(&s), ["Background", "Below", "A"]);
+ assert_eq!(s.active().unwrap().active_layer, Some(photocraft_doc::LayerId(below)));
+ s.execute("layer.new.layer", json!({"name": "Above", "position": "above"})).unwrap();
+ assert_eq!(names(&s), ["Background", "Below", "Above", "A"]);
+ let bg = s.active().unwrap().doc.layers[0].id.0;
+ s.execute("layer.select", json!({"layer": bg})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "OverBg", "position": "below"})).unwrap();
+ assert_eq!(names(&s), ["Background", "OverBg", "Below", "Above", "A"]);
+ }
+
/// Bad params are errors, never panics, and change nothing.
#[test]
fn bad_params_are_errors() {
@@ -175,6 +206,8 @@ mod tests {
json!({"fillNeutral": "yes"}),
json!({"clipToPrevious": 1}),
json!({"name": 7}),
+ json!({"position": "sideways"}),
+ json!({"position": 1}),
] {
assert!(s.execute("layer.new.layer", p.clone()).is_err(), "{p}");
}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 9de772632..7e35088bf 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -2480,9 +2480,17 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
trash.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(label)));
let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer"));
if new_layer.clicked() {
- // A click makes the layer; ⌥-click asks first (the New Layer dialog), as in Photoshop.
- let alt = ui.input(|i| i.modifiers.alt);
- actions.push(("layer.new.layer".into(), if alt { Value::Null } else { json!({}) }));
+ // A click makes the layer above the selection; ⌥-click asks first (the New Layer
+ // dialog) and ⌘/Ctrl-click adds it below, as in Photoshop.
+ let (alt, below) = ui.input(|i| (i.modifiers.alt, i.modifiers.command));
+ let params = if alt {
+ Value::Null
+ } else if below {
+ json!({"position": "below"})
+ } else {
+ json!({})
+ };
+ actions.push(("layer.new.layer".into(), params));
}
actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate"));
let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group"));