PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Background layer: double-click, masks and cut behave like Photoshop (#266) (#266)
Multipad-cyber8713e26f5a86
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 7857f3c7e..4fdbf61cd 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -278,12 +278,11 @@ fn build() -> Vec<CommandSpec> {),cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{}", has_pixel_layer, |s, p| {let id = layer_param(s, p)?;+ let bg = s.tools.background;s.edit("Clear", |doc, _| {let sel = doc.selection.clone();let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());- let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;- pixels::clear_surface(l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?, area, sel.as_ref());- Ok(())+ crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg)})?;Ok(Value::Null)}),@@ -1059,6 +1058,9 @@ fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask>) -> Result<Value> {let id = layer_param(s, p)?;s.edit(label, |doc, _| {+ if mask.is_some() {+ crate::extra_cmds::background_to_layer_for_mask(doc, id);+ }doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = mask;Ok(())})?;diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rsindex c87ba0b22..e29368721 100644--- a/crates/engine/src/edit_cmds.rs+++ b/crates/engine/src/edit_cmds.rs@@ -88,12 +88,24 @@ fn copy(s: &mut Session, merged: bool) -> Result<Value> {Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]}))}-fn clear_selected(doc: &mut Document, id: LayerId) -> Result<()> {+fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Result<()> {let sel = doc.selection.clone();let canvas = doc.bounds();- let surf = doc.layer_mut(id).and_then(|l| l.surface_mut()).ok_or(EngineError::Other("the active layer has no pixels".into()))?;let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas));- crate::pixels::clear_surface(surf, area, sel.as_ref());+ clear_area(doc, id, area, sel.as_ref(), background)+}++/// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold+/// transparency, so there the area is filled with the background colour instead (Photoshop).+pub(crate) fn clear_area(doc: &mut Document, id: LayerId, area: Rect, sel: Option<&Surface>, background: [f32; 4]) -> Result<()> {+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ let bg = crate::extra_cmds::is_background(l);+ let surf = l.surface_mut().ok_or(EngineError::Other("the active layer has no pixels".into()))?;+ if bg {+ crate::pixels::fill_surface(surf, area, background, sel, true);+ } else {+ crate::pixels::clear_surface(surf, area, sel);+ }surf.prune();Ok(())}@@ -149,10 +161,11 @@ fn layer_via(s: &mut Session, cut: bool) -> Result<Value> {if clip.bounds.is_empty() {return Err(EngineError::Other("Could not complete the command: the selected area is empty".into()));}+ let bg = s.tools.background;let label = if cut { "Layer Via Cut" } else { "Layer Via Copy" };let nid = s.edit(label, |doc, active| {if cut {- clear_selected(doc, id)?;+ clear_selected(doc, id, bg)?;}let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format());*crate::pixels_mut(&mut l)? = clip.surface;@@ -396,7 +409,8 @@ pub fn specs() -> Vec<CommandSpec> {spec!("edit.cut", "Cut", &["Edit"], Some("Cmd+X"), "{}", has_pixels, |s, _| {let r = copy(s, false)?;let id = active_id(s)?;- s.edit("Cut Pixels", |doc, _| clear_selected(doc, id))?;+ let bg = s.tools.background;+ s.edit("Cut Pixels", |doc, _| clear_selected(doc, id, bg))?;Ok(r)}),spec!("edit.copy", "Copy", &["Edit"], Some("Cmd+C"), "{}", has_pixels, |s, _| copy(s, false)),@@ -525,6 +539,36 @@ mod tests {assert!((cb.width() as i32 - 80).abs() <= 3 && (cb.height() as i32 - 40).abs() <= 3, "size ~ 80x40: {cb:?}");}+ #[test]+ fn cut_and_clear_on_the_background_fill_with_the_background_colour() {+ // The Background keeps its transparency lock: cutting fills with the background colour.+ let fresh = || {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();+ s.tools.background = [1.0, 0.0, 0.0, 1.0];+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();+ s+ };+ let px = |s: &Session, i: usize, x: i32, y: i32| s.active().unwrap().doc.layers[i].surface().unwrap().pixel(x, y);+ for cmd in ["edit.cut", "edit.clear", "layer.new.layerViaCut"] {+ let mut s = fresh();+ s.execute(cmd, json!({})).unwrap();+ let d = &s.active().unwrap().doc;+ assert!(crate::extra_cmds::is_background(&d.layers[0]), "{cmd}: still the Background");+ assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour");+ assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched");+ }+ // Layer via Cut still lifts the original pixels onto the new layer.+ let mut s = fresh();+ s.execute("layer.new.layerViaCut", json!({})).unwrap();+ assert_eq!(px(&s, 1, 8, 8), vec![1.0, 1.0, 1.0, 1.0]);+ // Once it's a normal layer, cutting makes transparency again.+ let mut s = fresh();+ s.execute("layer.new.layerFromBackground", json!({})).unwrap();+ s.execute("edit.clear", json!({})).unwrap();+ assert_eq!(px(&s, 0, 8, 8)[3], 0.0);+ }+#[test]fn cut_clears_and_layer_via_copy_cut() {let mut s = session();diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rsindex 1ee63dd6d..3b70b4907 100644--- a/crates/engine/src/extra_cmds.rs+++ b/crates/engine/src/extra_cmds.rs@@ -42,7 +42,7 @@ fn has_clip_and_selection(s: &Session) -> std::result::Result<(), String> {d.doc.selection.as_ref().map(|_| ()).ok_or_else(|| "Paste Into needs a selection".into())}-fn is_background(l: &Layer) -> bool {+pub(crate) fn is_background(l: &Layer) -> bool {l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_))}@@ -333,15 +333,27 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {fn layer_from_background(s: &mut Session) -> Result<Value> {let id = s.edit("Layer From Background", |doc, active| {let l = doc.layers.first_mut().filter(|l| is_background(l)).ok_or(EngineError::Other("the document has no Background layer".into()))?;- l.name = "Layer 0".into();- l.locks.transparency = false;- l.locks.position = false;+ unlock_background(l);*active = Some(l.id);Ok(l.id)})?;Ok(json!({"layer": id.0}))}+fn unlock_background(l: &mut Layer) {+ l.name = "Layer 0".into();+ l.locks.transparency = false;+ l.locks.position = false;+}++/// Before `id` gets a layer mask: the Background can't have one, so it becomes a normal layer+/// first ("Layer 0"), as when adding a mask to it in Photoshop. Other layers are left alone.+pub(crate) fn background_to_layer_for_mask(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) {+ if let Some(l) = doc.layers.first_mut().filter(|l| l.id == id && is_background(l)) {+ unlock_background(l);+ }+}+fn toggle_mask(s: &mut Session, p: &Value, key: &str) -> Result<Value> {let id = layer_param(s, p)?;let label = if key == "enabled" { "Enable/Disable Layer Mask" } else { "Link/Unlink Layer Mask" };@@ -818,6 +830,38 @@ mod tests {assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0));}+ #[test]+ fn a_mask_turns_the_background_into_a_layer() {+ for (cmd, needs_selection) in [+ ("layer.layerMask.revealAll", false),+ ("layer.layerMask.hideAll", false),+ ("layer.layerMask.revealSelection", true),+ ("layer.layerMask.hideSelection", true),+ ] {+ let mut s = session(8);+ let bg = doc(&s).layers[0].id;+ if needs_selection {+ s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();+ }+ s.execute(cmd, json!({"layer": bg.0})).unwrap();+ let l = &doc(&s).layers[0];+ assert!(l.mask.is_some() && l.name == "Layer 0" && !l.locks.transparency && !l.locks.position, "{cmd}");+ assert!(!s.is_enabled("layer.new.layerFromBackground"), "{cmd}");+ // One step: undo brings the locked Background back, without a mask.+ assert!(s.undo());+ let l = &doc(&s).layers[0];+ assert!(l.mask.is_none() && l.name == "Background" && l.locks.transparency, "{cmd}");+ }+ // Other layers keep their name and locks.+ let mut s = session(8);+ let top = doc(&s).layers[1].id;+ s.execute("layer.setProps", json!({"layer": top.0, "locks": {"position": true}})).unwrap();+ s.execute("layer.layerMask.revealAll", json!({"layer": top.0})).unwrap();+ let l = doc(&s).layer(top).unwrap();+ assert!(l.mask.is_some() && l.name != "Layer 0" && l.locks.position);+ assert_eq!(doc(&s).layers[0].name, "Background");+ }+#[test]fn layer_utilities() {let mut s = session(8);diff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/layer_menu_cmds.rsindex d3276f3b7..113719dcb 100644--- a/crates/engine/src/layer_menu_cmds.rs+++ b/crates/engine/src/layer_menu_cmds.rs@@ -179,6 +179,7 @@ fn hide_selection(s: &mut Session, p: &Value) -> Result<Value> {let mut mask = LayerMask::reveal_all();mask.surface.write_region(bounds, &v);mask.surface.prune();+ crate::extra_cmds::background_to_layer_for_mask(doc, id);doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(mask);doc.selection = None;Ok(Value::Null)diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 6a77644ab..30294b85c 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1673,10 +1673,15 @@ fn layer_row(actions.push(("ui.maskTarget".into(), json!(false)));}}- // Double-click the name to rename in place (Photoshop ergonomics).+ // Double-click the name to rename in place (Photoshop ergonomics). The Background can't be+ // renamed while it's locked, so a double-click turns it into a normal layer instead.let rename_id = egui::Id::new(("rename", l.id.0));if resp.double_clicked() {- ctx.data_mut(|d| d.insert_temp(rename_id, l.name.clone()));+ if crate::doc_props_ui::is_background(doc, l) {+ actions.push(("layer.new.layerFromBackground".into(), json!({})));+ } else {+ ctx.data_mut(|d| d.insert_temp(rename_id, l.name.clone()));+ }}if let Some(mut text) = ctx.data(|d| d.get_temp::<String>(rename_id)) {let edit_rect = Rect::from_min_max(pos2(x - 3.0, rect.center().y - 11.0), pos2(name_right.max(x + 40.0), rect.center().y + 11.0));