PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Tools leave hidden layers alone: painting or moving a hidden layer is refused (#571) (#872)
BFlat8ebdd367692f
diff --git a/crates/engine/src/hidden_target.rs b/crates/engine/src/hidden_target.rsnew file mode 100644index 000000000..249317354--- /dev/null+++ b/crates/engine/src/hidden_target.rs@@ -0,0 +1,115 @@+//! Photoshop refuses to paint on or move a hidden layer (#571): the painting and retouching+//! tools, the Paint Bucket, the Gradient and the Move tool stop with "the target layer is hidden"+//! instead of changing pixels nobody can see. A layer inside a hidden group is hidden too. An+//! alpha channel or Quick Mask target has no layer, so it is never refused.++use photocraft_doc::{Document, LayerId};+use serde_json::Value;++use crate::Session;++/// Photoshop's alert text.+pub const HIDDEN: &str = "Could not complete your request because the target layer is hidden.";++/// Commands that paint on, or move, the target layer.+const GATED: &[&str] = &[+ "paint.stroke",+ "paint.pencil",+ "paint.mixerBrush",+ "paint.colorReplacement",+ "paint.bucket",+ "paint.gradient",+ "paint.magicEraser",+ "paint.backgroundEraser",+ "paint.cloneStamp",+ "paint.healingBrush",+ "paint.spotHealing",+ "paint.patch",+ "paint.dodge",+ "paint.burn",+ "paint.sponge",+ "paint.blur",+ "paint.sharpen",+ "paint.smudge",+ "paint.historyBrush",+ "layer.translate",+];++/// Is the layer shown: it and every group around it visible.+fn shown(doc: &Document, id: LayerId) -> bool {+ doc.path_of(id).is_some_and(|path| (1..=path.len()).all(|n| path.get(..n).and_then(|p| doc.layer_at(p)).is_some_and(|l| l.visible)))+}++/// Why command `id` with `params` must not run: its target layer is hidden. `None` for other+/// commands, channel targets, and visible layers.+pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> {+ if !GATED.contains(&id) {+ return None;+ }+ let params = crate::channel_cmds::inject_target(s, id, params.clone());+ if crate::channel_cmds::is_channel_target(¶ms) {+ return None;+ }+ let st = s.active()?;+ let layer = params.get("layer").and_then(Value::as_u64).map(LayerId).or(st.active_layer)?;+ (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(HIDDEN)+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::HIDDEN;+ use crate::Session;++ fn session() -> (Session, u64) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();+ let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();+ (s, id)+ }++ fn pixel(s: &mut Session) -> serde_json::Value {+ s.execute("document.pixel", json!({"x": 10, "y": 10})).unwrap()+ }++ #[test]+ fn painting_or_moving_a_hidden_layer_is_refused() {+ let (mut s, id) = session();+ s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();+ let steps = s.active().unwrap().history.entries().len();+ for (cmd, p) in [+ ("paint.stroke", json!({"points": [[10, 10], [20, 20]], "color": "#ff0000"})),+ ("paint.bucket", json!({"x": 10, "y": 10})),+ ("paint.gradient", json!({"from": [0, 0], "to": [60, 60]})),+ ("layer.translate", json!({"dx": 5, "dy": 0})),+ ] {+ let e = s.execute(cmd, p).unwrap_err().to_string();+ assert!(e.contains(HIDDEN), "{cmd}: {e}");+ }+ assert_eq!(s.active().unwrap().history.entries().len(), steps, "nothing changed");+ // Shown again, it paints.+ s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap();+ s.execute("paint.stroke", json!({"points": [[10, 10], [12, 12]], "color": "#ff0000", "size": 9})).unwrap();+ assert_ne!(pixel(&mut s), json!([1.0, 1.0, 1.0, 1.0]));+ }++ #[test]+ fn a_layer_in_a_hidden_group_is_hidden() {+ let (mut s, id) = session();+ s.execute("layer.groupLayers", json!({})).unwrap();+ let g = s.active().unwrap().active_layer.unwrap().0;+ assert_ne!(g, id, "the new group is active");+ s.execute("layer.setProps", json!({"layer": g, "visible": false})).unwrap();+ s.execute("layer.select", json!({"layer": id})).unwrap();+ assert!(s.execute("paint.stroke", json!({"points": [[10, 10]]})).unwrap_err().to_string().contains(HIDDEN));+ }++ #[test]+ fn alpha_channels_of_a_hidden_layer_still_paint() {+ let (mut s, id) = session();+ s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();+ s.execute("channel.new", json!({})).unwrap();+ s.execute("paint.stroke", json!({"points": [[10, 10], [20, 20]], "target": {"channel": 0}})).unwrap();+ }+}diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex 0bbacbecf..fb8e34943 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -612,6 +612,10 @@ impl Session {if let Some(why) = self.job_conflict(id, spec.journal) {return Err(EngineError::Disabled(id.to_string(), why));}+ // Painting on or moving a hidden layer is refused, as in Photoshop (#571).+ if let Some(why) = crate::hidden_target::refusal(self, id, ¶ms) {+ return Err(EngineError::Other(why.into()));+ }self.coalesce_request = params.get("coalesce").and_then(Value::as_str).map(str::to_string);self.color_restrict = crate::channel_cmds::color_restriction(self, id, &run_params);self.jobs.spawn = background;diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 48aad0515..5bb1ffba8 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -41,6 +41,7 @@ pub mod fx_view_cmds;pub mod gallery_cmds;pub mod gradient_fill_cmds;pub mod group_view_cmds;+pub mod hidden_target;pub mod image_cmds;pub mod inspect;pub mod jobs;diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 12ab94bf9..93f0125b9 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2565,6 +2565,12 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)// Painting a type, shape, Smart Object or fill layer asks to rasterize it first// (⌥-click with the Clone Stamp or Healing Brush only sets the source).let sets_source = matches!(tool, Tool::CloneStamp | Tool::Healing) && mods.alt;+ // Painting on or moving a hidden layer is refused at the press, as in Photoshop (#571).+ if !sets_source && let Some(why) = hidden_target(app, tool) {+ app.ui.status = why.into();+ app.ui.status_error = true;+ return;+ }if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) {return;}@@ -2672,6 +2678,21 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}}+/// Why a press with `tool` must not start: it would paint on or move a hidden target layer (the+/// engine refuses the command; refusing the press keeps the live stroke from drawing first).+fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {+ let cmd = match tool {+ Tool::Move => "layer.translate",+ // The live Gradient makes a new Gradient Fill layer above the target, which Photoshop+ // allows over a hidden layer; only the classic one paints the target itself.+ Tool::Gradient if !app.ui.tool_options.gradient_classic => return None,+ // Every painting command follows the same target (layer, mask or channel) as a stroke.+ t if t.is_brushlike() || matches!(t, Tool::Gradient | Tool::PaintBucket | Tool::MagicEraser) => "paint.stroke",+ _ => return None,+ };+ photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({}))+}+/// Is document point `p` inside the active document's selection?fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool {let Some(sel) = app.session.active().and_then(|st| st.doc.selection.as_ref()) else { return false };diff --git a/crates/ui-egui/src/hidden_layer_tests.rs b/crates/ui-egui/src/hidden_layer_tests.rsnew file mode 100644index 000000000..c1753d3e1--- /dev/null+++ b/crates/ui-egui/src/hidden_layer_tests.rs@@ -0,0 +1,97 @@+//! #571: tools leave hidden layers alone, as in Photoshop. Auto-Select never picks a hidden layer,+//! and painting on or moving a hidden target layer is refused at the press with Photoshop's+//! "the target layer is hidden" instead of changing pixels nobody can see.++use photocraft_doc::LayerId;+use photocraft_geom::Rect;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::{ToolEvent, tool_event};+use crate::state::Tool;++/// A 64×64 document with a painted layer covering (8..24)², hidden and active.+fn app(tool: Tool) -> (PhotocraftApp, LayerId) {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.sync_views();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ let id = app.session.active().unwrap().active_layer.unwrap();+ app.session.execute("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap();+ app.ui.tool = tool;+ app.ui.extras.snap = false;+ (app, id)+}++fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) {+ let m = egui::Modifiers::NONE;+ tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m);+}++fn steps(app: &PhotocraftApp) -> usize {+ app.session.active().unwrap().history.entries().len()+}++fn bounds(app: &PhotocraftApp, id: LayerId) -> Rect {+ app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds()+}++#[test]+fn auto_select_skips_hidden_layers() {+ let (mut app, id) = app(Tool::Move);+ let bg = app.session.active().unwrap().doc.layers[0].id;+ drag(&mut app, [16.0, 16.0], [30.0, 16.0]);+ assert_eq!(app.session.active().unwrap().active_layer, Some(bg), "the visible layer under the pointer was picked");+ assert_eq!(bounds(&app, id), Rect::new(8, 8, 24, 24), "the hidden layer stayed put");+}++#[test]+fn moving_a_hidden_target_layer_is_refused() {+ let (mut app, id) = app(Tool::Move);+ app.ui.tool_options.move_auto_select = false;+ let n = steps(&app);+ drag(&mut app, [16.0, 16.0], [30.0, 16.0]);+ assert!(app.ui.status_error && app.ui.status.contains("target layer is hidden"), "{}", app.ui.status);+ assert_eq!((bounds(&app, id), steps(&app)), (Rect::new(8, 8, 24, 24), n));+}++#[test]+fn painting_a_hidden_layer_is_refused_at_the_press() {+ for tool in [Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::Gradient, Tool::CloneStamp] {+ let (mut app, id) = app(tool);+ // The live Gradient makes a new Gradient Fill layer; the classic one paints the target.+ app.ui.tool_options.gradient_classic = true;+ let n = steps(&app);+ tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ assert!(app.drag.is_none() && app.live_stroke.is_none(), "{tool:?}: no stroke started");+ assert!(app.ui.status.contains("target layer is hidden"), "{tool:?}: {}", app.ui.status);+ tool_event(&mut app, ToolEvent::Up { x: 40.0, y: 40.0 }, egui::Modifiers::NONE);+ assert_eq!((bounds(&app, id), steps(&app)), (Rect::new(8, 8, 24, 24), n), "{tool:?}");+ // Shown again, the same press paints.+ app.session.execute("layer.setProps", json!({"layer": id.0, "visible": true})).unwrap();+ app.ui.status.clear();+ tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ assert!(!app.ui.status.contains("hidden"), "{tool:?}");+ }+}++#[test]+fn the_live_gradient_still_works_over_a_hidden_layer() {+ // The live Gradient adds a Gradient Fill layer rather than painting the target, so a hidden+ // target doesn't stop it; the hidden layer's pixels stay as they were.+ let (mut app, id) = app(Tool::Gradient);+ app.ui.tool_options.gradient_classic = false;+ let layers = app.session.active().unwrap().doc.layers.len();+ drag(&mut app, [4.0, 30.0], [60.0, 30.0]);+ assert!(!app.ui.status.contains("hidden"), "{}", app.ui.status);+ assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "a Gradient Fill layer was added");+ assert_eq!(bounds(&app, id), Rect::new(8, 8, 24, 24));+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 6a9e0ab60..739882ded 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1491,6 +1491,9 @@ mod transform_undo_tests;#[cfg(test)]mod move_auto_select_tests;+#[cfg(test)]+mod hidden_layer_tests;+#[cfg(test)]mod marquee_tests;