PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layers panel: the eyes on effect rows show and hide effects (#1664)
Chandirasegaranf338454f3670
diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rsindex 9fa3302f4..06028a400 100644--- a/crates/doc/src/effects.rs+++ b/crates/doc/src/effects.rs@@ -288,6 +288,18 @@ impl Effect {}}+ /// Switches this instance on or off, keeping its settings.+ pub fn set_enabled(&mut self, on: bool) {+ match self {+ Effect::DropShadow(s) | Effect::InnerShadow(s) => s.common.enabled = on,+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.common.enabled = on,+ Effect::Stroke(s) => s.common.enabled = on,+ Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => common.enabled = on,+ Effect::Satin(s) => s.common.enabled = on,+ Effect::BevelEmboss(b) => b.enabled = on,+ }+ }+/// Short label for UIs.pub fn label(&self) -> &'static str {match self {diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex acd12eb00..0cb419f09 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1165,6 +1165,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::plugin_cmds::specs());v.extend(crate::group_view_cmds::specs());v.extend(crate::fx_view_cmds::specs());+ v.extend(crate::fx_visibility_cmds::specs());v.extend(crate::mask_view_cmds::specs());v.extend(crate::actions_cmds::specs());vdiff --git a/crates/engine/src/fx_visibility_cmds.rs b/crates/engine/src/fx_visibility_cmds.rsnew file mode 100644index 000000000..bc24d84b1--- /dev/null+++ b/crates/engine/src/fx_visibility_cmds.rs@@ -0,0 +1,183 @@+//! Layers panel: the eyes on a layer's effects rows (#1622). The eye on the "Effects" row shows or+//! hides every effect of that layer; the eye on one effect's row shows or hides that effect. The+//! effects keep their settings either way, and each toggle is one history step.++use photocraft_doc::LayerId;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++const ID: &str = "layer.setEffectsVisible";++fn bad(msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: ID.into(), msg: msg.into() }+}++fn has_effects(s: &Session) -> std::result::Result<(), String> {+ let d = s.active().ok_or("no document open")?;+ if d.doc.walk().iter().any(|(_, _, l)| !l.effects.items.is_empty()) { Ok(()) } else { Err("no layer has effects".into()) }+}++/// `{"layer":id?,"index":n?,"visible":bool?}`: show or hide a layer's effects (no `visible`:+/// toggle). Without `index` it is the whole list (the "Effects" row); with it, the effect at that+/// position in the layer's list.+fn set_visible(s: &mut Session, p: &Value) -> Result<Value> {+ let want = match p.get("visible") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_bool().ok_or_else(|| bad("`visible` must be true or false"))?),+ };+ let index = match p.get("index") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("`index` must be an effect position (0, 1, …)"))?),+ };+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let id = match p.get("layer") {+ None | Some(Value::Null) => st.active_layer.ok_or_else(|| bad("no layer given and no active layer"))?,+ Some(v) => LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be a layer id"))?),+ };+ let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ if l.effects.items.is_empty() {+ return Err(bad(format!("layer {} has no effects", id.0)));+ }+ let (current, name) = match index {+ Some(i) => {+ let e = l.effects.items.get(i).ok_or_else(|| bad(format!("layer {} has no effect at index {i}", id.0)))?;+ (e.enabled(), e.label())+ }+ None => (l.effects.enabled, "Layer Effects"),+ };+ let visible = want.unwrap_or(!current);+ if visible != current {+ let label = format!("{} {name}", if visible { "Show" } else { "Hide" });+ s.edit(&label, |doc, _| {+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ match index {+ Some(i) => l.effects.items.get_mut(i).ok_or_else(|| bad(format!("layer {} has no effect at index {i}", id.0)))?.set_enabled(visible),+ None => l.effects.enabled = visible,+ }+ Ok(())+ })?;+ }+ Ok(json!({"layer": id.0, "index": index, "visible": visible}))+}++pub fn specs() -> Vec<CommandSpec> {+ vec![CommandSpec {+ id: ID,+ label: "Show/Hide Effects",+ menu: &[],+ shortcut: None,+ params: r##"{"layer":id?,"index":n?,"visible":bool?} (no index: all of the layer's effects, the "Effects" row; index: the effect at that position in the layer's list; no visible: toggle)"##,+ enabled: has_effects,+ run: set_visible,+ journal: true,+ }]+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A red layer with a drop shadow and a blue colour overlay, and the background (no effects).+ fn session() -> (Session, u64, u64) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();+ let bg = s.active().unwrap().doc.layers[0].id.0;+ let a = s.execute("layer.new.layer", json!({"name": "a"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();+ s.execute("layer.layerStyle.dropShadow", json!({"layer": a})).unwrap();+ s.execute("layer.layerStyle.colorOverlay", json!({"layer": a, "color": "#0000ff"})).unwrap();+ (s, a, bg)+ }++ /// (the whole list is on, each effect is on).+ fn state(s: &Session, id: u64) -> (bool, Vec<bool>) {+ let d = s.active().unwrap();+ let fx = &d.doc.layer(LayerId(id)).unwrap().effects;+ (fx.enabled, fx.items.iter().map(|e| e.enabled()).collect())+ }++ fn steps(s: &Session) -> usize {+ s.active().unwrap().history.past_len()+ }++ fn flat(s: &Session) -> photocraft_compose::Buffer {+ photocraft_compose::flatten(&s.active().unwrap().doc)+ }++ #[test]+ fn the_effects_row_eye_hides_and_shows_the_whole_list() {+ let (mut s, a, _) = session();+ let n = steps(&s);+ assert_eq!(s.execute(ID, json!({"layer": a})).unwrap(), json!({"layer": a, "index": null, "visible": false}));+ assert_eq!(state(&s, a), (false, vec![true, true]), "each effect keeps its own state");+ assert_eq!(steps(&s), n + 1, "one history step");+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Hide Layer Effects"));+ // The active layer is the default target.+ assert_eq!(s.execute(ID, json!({})).unwrap()["visible"], true);+ assert_eq!(state(&s, a), (true, vec![true, true]));+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Show Layer Effects"));+ }++ #[test]+ fn one_effect_eye_hides_only_that_effect_and_undoes() {+ let (mut s, a, _) = session();+ assert_eq!(s.execute(ID, json!({"layer": a, "index": 1})).unwrap()["visible"], false);+ assert_eq!(state(&s, a), (true, vec![true, false]));+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Hide Color Overlay"));+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(state(&s, a), (true, vec![true, true]));+ s.execute("edit.redo", json!({})).unwrap();+ assert_eq!(state(&s, a), (true, vec![true, false]));+ s.execute(ID, json!({"layer": a, "index": 1, "visible": true})).unwrap();+ assert_eq!(state(&s, a), (true, vec![true, true]));+ }++ #[test]+ fn hiding_changes_the_composite_and_keeps_the_settings() {+ let (mut s, a, _) = session();+ let before = s.active().unwrap().doc.layer(LayerId(a)).unwrap().effects.items.clone();+ let shown = flat(&s);+ s.execute(ID, json!({"layer": a, "visible": false})).unwrap();+ assert_ne!(flat(&s), shown, "hidden effects are not drawn");+ s.execute(ID, json!({"layer": a, "visible": true})).unwrap();+ assert_eq!(flat(&s), shown);+ assert_eq!(s.active().unwrap().doc.layer(LayerId(a)).unwrap().effects.items, before);+ }++ #[test]+ fn asking_for_the_current_state_adds_no_history_step() {+ let (mut s, a, _) = session();+ let n = steps(&s);+ assert_eq!(s.execute(ID, json!({"layer": a, "visible": true})).unwrap()["visible"], true);+ assert_eq!(s.execute(ID, json!({"layer": a, "index": 0, "visible": true})).unwrap()["visible"], true);+ assert_eq!(steps(&s), n);+ }++ #[test]+ fn bad_params_fail_gracefully() {+ let (mut s, a, bg) = session();+ let before = state(&s, a);+ for p in [+ json!({"layer": bg}),+ json!({"layer": 9999}),+ json!({"layer": "x"}),+ json!({"layer": -1}),+ json!({"layer": a, "index": 2}),+ json!({"layer": a, "index": -1}),+ json!({"layer": a, "index": 1.5}),+ json!({"layer": a, "index": "0"}),+ json!({"layer": a, "index": u64::MAX}),+ json!({"layer": a, "visible": "yes"}),+ json!({"layer": a, "visible": 1}),+ ] {+ assert!(s.execute(ID, p.clone()).is_err(), "{p}");+ }+ assert_eq!(state(&s, a), before, "a refused call changes nothing");+ let mut empty = Session::new();+ assert!(empty.execute(ID, json!({})).is_err());+ empty.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ assert!(empty.execute(ID, json!({})).is_err(), "no effects: disabled");+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 7fde8d11c..0401199de 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -39,6 +39,7 @@ pub mod filters_ext;pub mod float_cmds;mod frame_cmds;pub mod fx_view_cmds;+pub mod fx_visibility_cmds;pub mod gallery_cmds;pub mod gradient_fill_cmds;pub mod group_view_cmds;diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rsindex 44e8b04e7..c18eccc80 100644--- a/crates/ui-egui/src/layer_row_ui/tests.rs+++ b/crates/ui-egui/src/layer_row_ui/tests.rs@@ -152,6 +152,53 @@ fn a_configured_but_disabled_effect_stays_discoverable_in_the_panel() {assert!(effect_row.is_positive(), "a configured disabled effect remains visible for discovery");}+/// #1622: the eyes on the effects rows work. The "Effects" eye hides and shows the whole list, an+/// effect's eye only that effect; each click is one history step, keeps the effect's settings and+/// never opens the Layer Style dialog.+#[test]+fn the_eyes_on_the_effects_rows_hide_and_show_effects() {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();+ let id = s.execute("layer.new.layer", json!({"name": "Styled"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.layerStyle.dropShadow", json!({"layer": id})).unwrap();+ s.execute("layer.layerStyle.colorOverlay", json!({"layer": id})).unwrap();+ let mut h = harness(s, 1.0, "promedium", 290.0);+ // (the whole list is on, each effect is on).+ let fx = |h: &Harness<'_, PhotocraftApp>| {+ let fx = &h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects;+ (fx.enabled, fx.items.iter().map(Effect::enabled).collect::<Vec<_>>())+ };+ let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();+ let eye = |h: &Harness<'_, PhotocraftApp>, row: &str| {+ let r = h.get_by_label(row).rect();+ pos2(r.left() + 15.0, r.center().y)+ };+ let (settings, n) = (h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects.items.clone(), steps(&h));+ assert_eq!(fx(&h), (true, vec![true, true]));++ let p = eye(&h, "Color Overlay");+ click(&mut h, p);+ assert_eq!(fx(&h), (true, vec![true, false]), "only the clicked effect is hidden");+ assert_eq!(steps(&h), n + 1, "one history step");+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Hide Color Overlay"));+ // The row stays (its eye box empty), and a click there shows the effect again.+ let p = eye(&h, "Color Overlay");+ click(&mut h, p);+ assert_eq!(fx(&h), (true, vec![true, true]));++ let p = eye(&h, "Effects");+ click(&mut h, p);+ assert_eq!(fx(&h), (false, vec![true, true]), "the Effects eye hides the list; each effect keeps its own eye");+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Hide Layer Effects"));+ let p = eye(&h, "Effects");+ click(&mut h, p);+ assert_eq!(fx(&h), (true, vec![true, true]));++ assert_eq!(h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects.items, settings, "settings survive");+ assert_eq!(steps(&h), n + 4);+ assert!(h.state().ui.dialogs.is_empty(), "an eye click never opens the Layer Style dialog");+}+fn groups_open(s: &photocraft_engine::Session) -> Vec<bool> {s.active().unwrap().doc.walk().into_iter().filter_map(|(_, _, l)| if let LayerContent::Group(g) = &l.content { Some(g.expanded) } else { None }).collect()}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 557397cbc..3c5f075eb 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1560,7 +1560,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {crate::layer_reveal::scroll_to_row(ui, top);}if !l.effects.items.is_empty() && fx_collapsed.iter().all(|id| *id != l.id) {- effect_rows(app, ui, l, depth);+ effect_rows(app, ui, l, depth, &mut actions);}crate::smart_ui::filter_rows(app, ui, l, depth, &mut actions);}@@ -2772,8 +2772,9 @@ fn layer_drag_and_drop(}}-/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect).-fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize) {+/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye+/// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622).+fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) {let t = Tokens::get(ui.ctx());let indent = 30.0 + depth as f32 * 14.0 + 34.0;let mut rows: Vec<(String, bool, Option<&'static str>)> = vec![("Effects".into(), l.effects.enabled, None)];@@ -2793,9 +2794,19 @@ fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usiui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator));}let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 9.0), vec2(18.0, 18.0));+ // A hidden effect's eye box is left empty (still clickable), like a hidden layer's.if on {icons::paint(ui, eye, "eye", 12.0, t.icon);}+ // The whole eye column of the row takes the click, so it never opens the Layer Style dialog.+ let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom()));+ if ui.interact(eye_cell, ui.id().with(("fx-eye", l.id.0, i)), Sense::click()).clicked() {+ let mut params = json!({"layer": l.id.0, "visible": !on});+ if let (Some(index), Some(o)) = (i.checked_sub(1), params.as_object_mut()) {+ o.insert("index".into(), json!(index));+ }+ actions.push(("layer.setEffectsVisible".into(), params));+ }let x = rect.left() + indent + if i == 0 { 0.0 } else { 16.0 };if i == 0 {icons::paint(ui, Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 14.0)), "sparkles", 11.0, t.text_dim);