From 22467aeb3e28d29c3e5af7b9c2b655cc329113e2 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:12:20 +0000 Subject: [PATCH 01/31] ui-egui: Paint Bucket Shift+click on the pasteboard sets its colour (#12534) With the Paint Bucket, Shift+click on the pasteboard sets the pasteboard colour to the foreground colour, as in the reference application: the custom colour and Custom chosen, through the same prefs.set write the pasteboard menu's Select Custom Color... uses. No history state, no document change. Shift+click on the image still fills; other modifiers and an active selection keep today's behaviour. --- crates/ui-egui/src/canvas/tool_input.rs | 26 ++++- crates/ui-egui/src/lib.rs | 2 + .../paint_bucket_pasteboard_color_tests.rs | 103 ++++++++++++++++++ 3 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 18663f2cffd..505cedfa8f0 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -478,6 +478,28 @@ fn bucket_click(app: &mut PhotocraftApp, x: f64, y: f64) { } } +/// Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour to the foreground colour, as +/// in the reference application (#12534): the custom colour, and use it, as the pasteboard menu's +/// Select Custom Color… does. It is a preference, so no history state and no document change. +/// Only a plain ⇧ with no selection: other modifiers and an active selection were not measured and +/// keep today's fill. True when it handled the click. +fn bucket_pasteboard_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { + let plain_shift = mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd; + let Some(st) = app.session.active() else { return false }; + let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); + let outside = x.is_finite() && y.is_finite() && (x < 0.0 || y < 0.0 || x >= w || y >= h); + if !plain_shift || !outside || st.doc.selection.is_some() { + return false; + } + let [r, g, b, _] = app.session.tools.foreground; + let color = crate::color_picker_ui::hex([r, g, b]); + if let Err(e) = app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": color}})) { + app.ui.status = e; + app.ui.status_error = true; + } + true +} + /// The Brush's chosen Clear paints as Normal on the Background, and its Mode then reads Normal /// (#11897): at the press of a Brush stroke on the Background's own pixels, Clear (chosen in the /// options bar, not a held `~`) is turned off, so the stroke is sent as Normal. A Background whose @@ -636,7 +658,9 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: return; } Tool::PaintBucket => { - bucket_click(app, x, y); + if !bucket_pasteboard_click(app, x, y, mods) { + bucket_click(app, x, y); + } return; } Tool::RedEye => { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c0..8eac7006212 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -933,6 +933,8 @@ mod move_shift_click_tests; #[cfg(test)] mod move_target_default_tests; +#[cfg(test)] +mod paint_bucket_pasteboard_color_tests; #[cfg(test)] mod wand_press_inside_selection_tests; diff --git a/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs new file mode 100644 index 00000000000..0cc6b35c2b7 --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs @@ -0,0 +1,103 @@ +//! #12534: with the Paint Bucket, ⇧-click on the pasteboard sets the pasteboard colour to the +//! foreground colour, as the reference application does: the custom colour becomes the foreground +//! and the pasteboard right-click menu shows Custom checked. The press adds no history state and +//! leaves the document alone. ⇧-click on the image still fills, and the gestures the issue did not +//! measure (other modifiers held, a selection active) keep today's behaviour. + +use egui::Modifiers; +use photocraft_engine::prefs::CanvasColor; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::canvas_tool_menu::{mode_checked, open_pasteboard}; +use crate::state::Tool; + +/// The foreground the tests pick: not the default black, so a fill and the pasteboard colour show it. +const FOREGROUND: &str = "#3366cc"; + +/// A 200 x 150 white document with the Paint Bucket and a blue foreground. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.run("tools.setColors", json!({"foreground": FOREGROUND})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods); +} + +fn pasteboard(app: &PhotocraftApp) -> (CanvasColor, String) { + let i = &app.session.prefs().interface; + (i.canvas_color, i.canvas_custom_color.clone()) +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn revision(app: &PhotocraftApp) -> u64 { + app.session.active().unwrap().revision +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +fn shift_click_on_the_pasteboard_sets_the_custom_colour_to_the_foreground() { + // Above-left of the image and past its bottom-right corner: both are pasteboard. + for p in [[-30.0, -30.0], [230.0, 170.0]] { + let mut app = app(); + assert_eq!(pasteboard(&app).0, CanvasColor::Default); + click(&mut app, p, Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string()), "at {p:?}"); + // The pasteboard menu then shows Custom checked, and only Custom. + assert!(open_pasteboard(&mut app, &egui::Context::default(), Tool::PaintBucket, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(mode_checked(&app, &menu, "pasteboard.custom")); + assert!(!mode_checked(&app, &menu, "pasteboard.default")); + } +} + +#[test] +fn shift_click_on_the_pasteboard_adds_no_history_state_and_keeps_the_document() { + let mut app = app(); + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); + assert!(!app.session.active().unwrap().is_dirty()); + assert_eq!(pixel(&app, 0, 0), [255, 255, 255]); +} + +#[test] +fn shift_click_on_the_image_fills_as_a_plain_click_does() { + let mut app = app(); + let before = steps(&app); + click(&mut app, [50.0, 50.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before + 1, "the fill was applied"); + assert_eq!(pixel(&app, 50, 50), [0x33, 0x66, 0xcc]); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "the pasteboard colour is untouched"); +} + +#[test] +fn unmeasured_pasteboard_gestures_keep_the_pasteboard_colour() { + // A plain click, ⇧ with another modifier, and ⇧ with a selection active are not this gesture. + for (mods, select) in + [(Modifiers::NONE, false), (Modifiers::SHIFT | Modifiers::ALT, false), (Modifiers::SHIFT | Modifiers::COMMAND, false), (Modifiers::SHIFT, true)] + { + let mut app = app(); + if select { + app.run("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + } + click(&mut app, [-30.0, -30.0], mods); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "{mods:?}, selection {select}"); + } +} From 838c7260defbc975e2995a5efe77faf65d4538a4 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sat, 14 Nov 2026 05:30:00 -0600 Subject: [PATCH 02/31] ui-egui: run the bucket pasteboard gesture before the rasterize guard (#12534) --- crates/ui-egui/src/canvas/tool_input.rs | 8 +++++--- .../src/paint_bucket_pasteboard_color_tests.rs | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 505cedfa8f0..2dfd4772cbc 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -559,6 +559,10 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: match ev { ToolEvent::Down { x, y, pressure } => { + // The pasteboard gesture only sets a preference, so it runs before any painting guard. + if tool == Tool::PaintBucket && bucket_pasteboard_click(app, x, y, mods) { + return; + } // 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; @@ -658,9 +662,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: return; } Tool::PaintBucket => { - if !bucket_pasteboard_click(app, x, y, mods) { - bucket_click(app, x, y); - } + bucket_click(app, x, y); return; } Tool::RedEye => { diff --git a/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs index 0cc6b35c2b7..cd818090361 100644 --- a/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs +++ b/crates/ui-egui/src/paint_bucket_pasteboard_color_tests.rs @@ -77,6 +77,22 @@ fn shift_click_on_the_pasteboard_adds_no_history_state_and_keeps_the_document() assert_eq!(pixel(&app, 0, 0), [255, 255, 255]); } +#[test] +fn shift_click_on_the_pasteboard_with_a_type_layer_active_sets_the_colour_without_a_rasterize_prompt() { + // The active layer is a Type layer: a painting press on it would ask to rasterize it + // first, but this gesture only sets a preference, so it runs before that prompt and + // leaves the layer and the document alone. + let mut app = app(); + app.run("type.create", json!({"x": 10, "y": 40, "text": "Hello"})).unwrap(); + app.ui.tool = Tool::PaintBucket; + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string())); + assert!(app.ui.dialogs.is_empty(), "no rasterize prompt: {:?}", app.ui.dialogs.iter().map(|d| &d.kind).collect::>()); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); +} + #[test] fn shift_click_on_the_image_fills_as_a_plain_click_does() { let mut app = app(); From abb5c2371487013dfe4b5fb6ea0a3eb94501aea0 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:40:59 +0100 Subject: [PATCH 03/31] Actions: load every recorded Content-Aware Fill value and empty steps (#14254) A recorded cafWorkspace step now imports every sampling, colour adaptation, rotation and output value the reference workspace shows, and saves each back to the same descriptor. An empty descriptor plays with the settings the fill workspace remembers (New Layer before any), resolved in playback_params, and saves back empty; playing never changes what is remembered. Fixes #14254 --- crates/engine/src/cmd/actions_cmds.rs | 3 + crates/engine/src/cmd/atn_cmds.rs | 5 + .../cmd/atn_cmds/caf_action_values_tests.rs | 217 ++++++++++++++++++ .../src/cmd/atn_cmds/steps_content_aware.rs | 59 ++++- .../engine/tests/it/atn_content_aware_fill.rs | 46 ++-- crates/ui-egui/src/dialogs/caf_ui.rs | 5 +- docs/atn.md | 42 ++-- 7 files changed, 320 insertions(+), 57 deletions(-) create mode 100644 crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index c854dfa6319..6f8b66c2c3b 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -236,6 +236,9 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { { object.remove("__atnCustom"); } + if id == "edit.contentAwareFill" { + crate::atn_cmds::caf_remembered(&mut p, s.prefs()); + } if id == "layer.setProps" && let Some(target) = p.get("_actionLayer") { diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index feb8a1a3dd3..1e47e841800 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -85,6 +85,8 @@ use events::{EVENTS, event_and_descriptor, event_for}; use fields::Mapped; use files::{load, save}; pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings}; +pub use steps_content_aware::CAF_WORKSPACE_PREFS; +pub(crate) use steps_content_aware::caf_remembered; #[cfg(test)] use steps_doc::crop_from; pub(crate) use steps_gallery::RECORDED_EVENT; @@ -185,6 +187,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +mod caf_action_values_tests; + #[cfg(test)] mod layer_props_tests; diff --git a/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs new file mode 100644 index 00000000000..28c019e11f9 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -0,0 +1,217 @@ +//! Recorded `cafWorkspace` steps: every measured value maps to the command and back, and an +//! empty step plays with the workspace's remembered settings (#14254). +use super::*; + +const CMD: &str = "edit.contentAwareFill"; +const MARK: &str = "_atnCafRemembered"; + +/// A seven-key step with these enumerations and every boolean off. +fn workspace(sampling: &str, color: &str, rotation: &str, output: &str) -> Descriptor { + desc("null") + .with("cafSamplingRegion", enm("cafSamplingRegion", sampling)) + .with("cafSampleAllLayers", D::Boolean(false)) + .with("cafColorAdaptationLevel", enm("cafColorAdaptationLevel", color)) + .with("cafRotationAmount", enm("cafRotationAmount", rotation)) + .with("cafScale", D::Boolean(false)) + .with("cafMirror", D::Boolean(false)) + .with("cafOutput", enm("cafOutput", output)) +} + +/// The params [`workspace`] imports as. +fn params(sampling: &str, color: &str, rotation: &str, output: &str) -> Value { + json!({"sampling":sampling,"sampleAllLayers":false,"colorAdaptation":color, + "rotationAdaptation":rotation,"scale":false,"mirror":false,"output":output}) +} + +fn item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::name("cafWorkspace"), dictionary: b"Content-Aware Fill".to_vec(), descriptor: Some(d), ..Default::default() } +} + +fn file(d: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item(d)], ..Default::default() }], + ..Default::default() + }) + .unwrap() +} + +/// The single step a one-step file imports as. +fn load(d: Descriptor) -> Action { + let loaded = import(&file(d)).unwrap(); + assert!(loaded.unsupported.is_empty(), "{:?}", loaded.unsupported); + loaded.actions.into_iter().next().unwrap() +} + +/// The item Save Actions writes for one step, or `None` when it cannot write it. +fn exported(p: Value) -> Option { + let a = Action::new("A", vec![(CMD.into(), p)]); + let (bytes, skipped) = export("S", &[&a], &[], false).ok()?; + assert!(skipped.is_empty()); + atn::parse(&bytes).ok()?.actions.into_iter().next()?.items.into_iter().next() +} + +#[test] +fn every_measured_value_imports_to_its_param_and_saves_back_unchanged() { + let base = ("cafSamplingRegionRectangular", "cafColorAdaptationDefault", "cafRotationAmountNone", "cafOutputToNewLayer"); + let mut cases = Vec::new(); + for (wire, value) in [("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")] { + cases.push((workspace(wire, base.1, base.2, base.3), params(value, "default", "none", "new"))); + } + for (wire, value) in [ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), + ] { + cases.push((workspace(base.0, wire, base.2, base.3), params("rectangular", value, "none", "new"))); + } + for (wire, value) in [ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), + ] { + cases.push((workspace(base.0, base.1, wire, base.3), params("rectangular", "default", value, "new"))); + } + for (wire, value) in [("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")] { + cases.push((workspace(base.0, base.1, base.2, wire), params("rectangular", "default", "none", value))); + } + for (d, p) in cases { + let action = load(d.clone()); + assert_eq!(action.steps, vec![(CMD.to_string(), p.clone())]); + assert_eq!(exported(p.clone()), Some(item(d.clone())), "{p}"); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(d)); + } +} + +#[test] +fn an_empty_step_imports_as_remembered_and_saves_back_empty() { + let action = load(desc("null")); + assert_eq!(action.steps, vec![(CMD.to_string(), json!({MARK: true}))]); + assert_eq!(exported(json!({MARK: true})), Some(item(desc("null")))); + // A differently named empty descriptor comes back as recorded. + let mut named = desc("null"); + named.name = UnicodeString::new_nul("Recorded CAF"); + let action = load(named.clone()); + assert_eq!(action.steps[0].1[MARK], json!(true)); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(named)); +} + +#[test] +fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { + for p in [json!({MARK: true, "output": "current"}), json!({MARK: false}), json!({MARK: "yes"}), json!({MARK: true, "seed": 2})] { + assert_eq!(exported(p.clone()), None, "{p}"); + } +} + +/// White 8 x 8 with a red square selected for the fill. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); + s.execute("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); + s.execute("edit.fill", json!({"contents":"foreground"})).unwrap(); + s +} + +fn remember(s: &mut Session, settings: Value) { + s.edit_prefs(|p| p.dialogs.insert(CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// Play `d` as a one-step action and return the result. +fn play(s: &mut Session, d: Descriptor) -> Value { + s.actions.list = vec![load(d)]; + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 1); + result +} + +/// Every layer's pixels, in stack order. +fn pixels(s: &Session) -> Vec> { + let doc = &s.active().unwrap().doc; + doc.layers.iter().map(|l| (0..64).map(|i| l.surface().unwrap().rgba(i % 8, i / 8)).collect()).collect() +} + +/// What running the command itself with `p` leaves. +fn native(p: Value) -> Vec> { + let mut s = session(); + s.execute(CMD, p).unwrap(); + pixels(&s) +} + +#[test] +fn an_empty_step_fills_a_new_layer_before_anything_is_remembered() { + let mut s = session(); + let layers = s.active().unwrap().doc.layers.len(); + let past = s.active().unwrap().history.past_len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert_eq!(pixels(&s), native(json!({"output":"new"}))); + assert!(!s.prefs().dialogs.contains_key(CAF_WORKSPACE_PREFS), "playing remembers nothing"); +} + +#[test] +fn an_empty_step_plays_with_the_remembered_settings_and_steps_never_change_them() { + let settings = json!({"showOverlay":false,"opacity":20.0,"sampling":"rectangular","sampleAllLayers":false, + "colorAdaptation":"high","rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers, "remembered Current Layer"); + let used = json!({"sampling":"rectangular","sampleAllLayers":false,"colorAdaptation":"high", + "rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + assert_eq!(pixels(&s), native(used)); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + + // A step's own values are not remembered: the next empty step still uses Current Layer. + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, workspace("cafSamplingRegionAuto", "cafColorAdaptationNone", "cafRotationAmountLow", "cafOutputToNewLayer")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + let next = crate::actions_cmds::playback_params(&s, CMD, &json!({MARK: true})).unwrap(); + assert_eq!(next["output"], "current"); +} + +#[test] +fn remembered_settings_fill_only_what_the_step_does_not_name() { + let resolve = |s: &Session, p: Value| crate::actions_cmds::playback_params(s, CMD, &p).unwrap(); + let mut s = Session::new(); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"output":"new"})); + // Only the command's settings come over, never the overlay's. + remember(&mut s, json!({"showOverlay":true,"opacity":50.0,"color":[1,2,3],"excluded":true,"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true, "output": "current"})), json!({"sampling":"auto","output":"current"})); + // A mark that isn't `true` is dropped without bringing the remembered settings in. + assert_eq!(resolve(&s, json!({MARK: false, "output": "current"})), json!({"output":"current"})); + // Steps without the mark and other commands are left alone. + assert_eq!(resolve(&s, json!({"output":"current"})), json!({"output":"current"})); + let other = crate::actions_cmds::playback_params(&s, "edit.fill", &json!({MARK: true})).unwrap(); + assert_eq!(other, json!({MARK: true})); +} + +#[test] +fn damaged_remembered_settings_are_skipped_without_a_panic() { + let resolve = |s: &Session| crate::actions_cmds::playback_params(s, CMD, &json!({MARK: true})).unwrap(); + let mut s = Session::new(); + for damaged in [json!(3), json!(null), json!([]), json!({"output":5,"scale":"yes","sampling":true,"mirror":null})] { + remember(&mut s, damaged.clone()); + assert_eq!(resolve(&s), json!({"output":"new"}), "{damaged}"); + } + // A remembered value the command refuses fails the step with an error, not a panic. + let mut s = session(); + remember(&mut s, json!({"output":"sideways"})); + s.actions.list = vec![load(desc("null"))]; + let before = s.active().unwrap().doc.clone(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_some(), "{result}"); + assert_eq!(s.active().unwrap().doc, before); +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs index 3e30609ea2b..2d11728a8cb 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs @@ -6,17 +6,38 @@ use super::{D, Descriptor, Map, Value}; const CMD: &str = "edit.contentAwareFill"; const SOURCE: &str = "_atnCafDescriptor"; -// The measured row bounds these values; its ellipses are not additional enum bindings. -const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionRectangular", "rectangular")]; -const COLOR: &[(&str, &str)] = &[("cafColorAdaptationDefault", "default")]; -const ROTATION: &[(&str, &str)] = &[("cafRotationAmountNone", "none")]; -// Current Layer is also explicit in the primary Action Manager example cited in docs/atn.md. -const OUTPUT: &[(&str, &str)] = &[("cafOutputToNewLayer", "new"), ("cafOutputToCurrentLayer", "current")]; +// Every value the workspace showed when such a step was played with dialogs on (#14254). +const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")]; +const COLOR: &[(&str, &str)] = &[ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), +]; +const ROTATION: &[(&str, &str)] = &[ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), +]; +const OUTPUT: &[(&str, &str)] = &[("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")]; const KEYS: &[&str] = &["cafSamplingRegion", "cafSampleAllLayers", "cafColorAdaptationLevel", "cafRotationAmount", "cafScale", "cafMirror", "cafOutput"]; const PARAMS: &[&str] = &["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; +/// Marks a step recorded with an empty descriptor: it plays with the workspace's remembered +/// settings ([`caf_remembered`]) instead of fixed values. +const REMEMBERED: &str = "_atnCafRemembered"; +/// The `prefs.dialogs` key under which the Content-Aware Fill workspace remembers its settings. +pub const CAF_WORKSPACE_PREFS: &str = "edit.contentAwareFill.workspace"; -/// All seven settings are recorded. Missing keys have no measured Photoshop default here. +/// All seven settings are recorded, or none: an empty descriptor uses the remembered settings. +/// Other missing keys have no measured Photoshop default here. fn recorded(d: &Descriptor) -> Option { + if d.items.is_empty() { + let mut p = Map::new(); + p.insert(REMEMBERED.into(), true.into()); + return Some(Value::Object(p)); + } if d.items.len() != KEYS.len() || KEYS.iter().any(|name| d.items.iter().filter(|(key, _)| key.is(name)).count() != 1) { return None; } @@ -39,11 +60,15 @@ fn recorded(d: &Descriptor) -> Option { fn descriptor(p: &Value) -> Option { let object = p.as_object()?; if !super::events::pixel_target(p) - || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE)) + || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE | REMEMBERED)) || p.get("seed").is_some_and(|seed| seed.as_u64() != Some(1)) { return None; } + if let Some(remembered) = p.get(REMEMBERED) { + // Values next to the mark would be dropped by an empty descriptor. + return (remembered.as_bool() == Some(true) && !PARAMS.iter().any(|param| object.contains_key(*param))).then(|| desc("null")); + } let enumeration = |key: &str, param: &str, table: &[(&str, &str)], default: &str| { let value = match p.get(param) { None => default, @@ -67,6 +92,24 @@ fn descriptor(p: &Value) -> Option { ) } +/// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and +/// before any were remembered it writes to a new layer. Playing never changes what is remembered. +pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) { + let Some(object) = p.as_object_mut() else { return }; + if object.remove(REMEMBERED).and_then(|v| v.as_bool()) != Some(true) { + return; + } + let saved = prefs.dialogs.get(CAF_WORKSPACE_PREFS); + for (param, flag) in PARAMS.iter().map(|param| (*param, matches!(*param, "sampleAllLayers" | "scale" | "mirror"))) { + // Only well-typed values: a damaged entry must not turn into another setting. + let value = saved.and_then(|v| v.get(param)).filter(|v| if flag { v.is_boolean() } else { v.is_string() }); + if let Some(value) = value.filter(|_| !object.contains_key(param)) { + object.insert(param.into(), value.clone()); + } + } + object.entry("output").or_insert_with(|| "new".into()); +} + /// Import the verified seven-field form, retaining noncanonical wire data for an unchanged save. pub(super) fn caf_from(d: &Descriptor) -> Mapped { let Some(mut p) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index c5d6aaa46bc..9eefe6b455c 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -151,10 +151,11 @@ fn caf_edited_settings_export_without_stale_wire_metadata() { } /// Missing defaults, malformed/repeated fields and unrepresented workspace state stay complete. +/// An empty descriptor plays with the remembered settings (`atn_cmds/caf_action_values_tests.rs`). #[test] fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { let base = descriptor(); - let mut cases = vec![Descriptor::new("null"), base.clone().with("extra", D::Boolean(true))]; + let mut cases = vec![base.clone().with("extra", D::Boolean(true))]; for i in 0..base.items.len() { let mut missing = base.clone(); missing.items.remove(i); @@ -166,20 +167,9 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { wrong.items[i].1 = D::Integer(0); cases.push(wrong); } - for (i, key, value) in [ - (0, "cafSamplingRegion", "cafSamplingRegionAuto"), - (0, "cafSamplingRegion", "cafSamplingRegionCustom"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationNone"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationHigh"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationVeryHigh"), - (2, "cafColorAdaptationLevel", "unknown"), - (3, "cafRotationAmount", "cafRotationAmountLow"), - (3, "cafRotationAmount", "cafRotationAmountMedium"), - (3, "cafRotationAmount", "cafRotationAmountHigh"), - (3, "cafRotationAmount", "cafRotationAmountFull"), - (3, "cafRotationAmount", "unknown"), - (6, "cafOutput", "cafOutputToDuplicateLayer"), - ] { + for (i, key, value) in + [(0, "cafSamplingRegion", "unknown"), (2, "cafColorAdaptationLevel", "unknown"), (3, "cafRotationAmount", "unknown"), (6, "cafOutput", "unknown")] + { let mut d = base.clone(); d.items[i].1 = enm(key, value); cases.push(d); @@ -221,17 +211,10 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio assert_eq!(a.steps, vec![(CMD.into(), current.clone())]); } for (key, value) in [ - ("sampling", json!("auto")), - ("sampling", json!("custom")), ("sampling", json!("unknown")), - ("output", json!("duplicate")), - ("colorAdaptation", json!("none")), - ("colorAdaptation", json!("high")), - ("colorAdaptation", json!("veryHigh")), - ("rotationAdaptation", json!("low")), - ("rotationAdaptation", json!("medium")), - ("rotationAdaptation", json!("high")), - ("rotationAdaptation", json!("full")), + ("output", json!("unknown")), + ("colorAdaptation", json!("unknown")), + ("rotationAdaptation", json!("unknown")), ("sampleAllLayers", json!(0)), ("scale", Value::Null), ("mirror", json!("true")), @@ -249,9 +232,16 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio p[key] = value; assert!(exported(p.clone()).is_none(), "{p}"); } - for p in [json!({}), json!({"output":"new"}), json!([])] { - assert!(exported(p.clone()).is_none(), "unrepresented native default: {p}"); - } + // The command's own defaults (Auto, Current Layer) are written out explicitly. + let mut defaults = params(); + defaults["sampling"] = json!("auto"); + defaults["output"] = json!("current"); + let a = load(exported(json!({})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![(CMD.into(), defaults.clone())]); + defaults["output"] = json!("new"); + let a = load(exported(json!({"output":"new"})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![(CMD.into(), defaults)]); + assert!(exported(json!([])).is_none()); } fn session(depth: u32) -> Session { diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index f81ab2e864c..13c3fc04f74 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -60,8 +60,9 @@ const UNDO_LIMIT: usize = 100; const MAX_OUTLINE_SEGMENTS: usize = 200_000; /// Photoshop's overlay colour as it shows (a 50 % tint of grey 200 reads 171, 204, 153). const OVERLAY_COLOR: [u8; 3] = [142, 208, 106]; -/// The `prefs.dialogs` key under which the settings are remembered. -const REMEMBERED: &str = "edit.contentAwareFill.workspace"; +/// The `prefs.dialogs` key under which the settings are remembered (an empty recorded step plays +/// with them). +const REMEMBERED: &str = photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS; const CMD: &str = "edit.contentAwareFill"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/docs/atn.md b/docs/atn.md index 4370e3375e0..2d8cf8f49ba 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -394,35 +394,39 @@ stored descriptor no longer describes it. ### Content-Aware Fill recordings -`cafWorkspace` maps Rectangular / Default color adaptation / None rotation with New Layer or -Current Layer output to `edit.contentAwareFill`, retaining all seven keys and the three booleans: -Sample All Layers, Scale and Mirror. The selection comes from the preceding selection step. -New Layer is in the measured reference; Current Layer and the enumeration type IDs are explicit -in [Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). +`cafWorkspace` maps every value the reference workspace shows to `edit.contentAwareFill`, +retaining all seven keys and the three booleans: Sample All Layers, Scale and Mirror. The +selection comes from the preceding selection step. The values were measured by playing each +step with dialogs on (#14254); the enumeration type IDs are explicit in +[Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). -| Recorded key, in order | Supported value | Native parameter | +| Recorded key, in order | Supported values | Native parameter | |---|---|---| -| `cafSamplingRegion` | `cafSamplingRegionRectangular` | `sampling: "rectangular"` | +| `cafSamplingRegion` | `cafSamplingRegionAuto`, `…Rectangular`, `…Custom` | `sampling: "auto"`, `"rectangular"`, `"custom"` | | `cafSampleAllLayers` | boolean | `sampleAllLayers` | -| `cafColorAdaptationLevel` | `cafColorAdaptationDefault` | `colorAdaptation: "default"` | -| `cafRotationAmount` | `cafRotationAmountNone` | `rotationAdaptation: "none"` | +| `cafColorAdaptationLevel` | `cafColorAdaptationNone`, `…Default`, `…High`, `…VeryHigh` | `colorAdaptation: "none"`, `"default"`, `"high"`, `"veryHigh"` | +| `cafRotationAmount` | `cafRotationAmountNone`, `…Low`, `…Medium`, `…High`, `…Full` | `rotationAdaptation: "none"`, `"low"`, `"medium"`, `"high"`, `"full"` | | `cafScale` | boolean | `scale` | | `cafMirror` | boolean | `mirror` | -| `cafOutput` | `cafOutputToNewLayer`, `cafOutputToCurrentLayer` | `output: "new"`, `"current"` | +| `cafOutput` | `cafOutputToCurrentLayer`, `…NewLayer`, `…DuplicateLayer` | `output: "current"`, `"new"`, `"duplicate"` | + +An empty descriptor (no keys) plays with the settings the fill workspace remembers +(`prefs.dialogs["edit.contentAwareFill.workspace"]`), New Layer before any are remembered; it +imports as `{"_atnCafRemembered": true}`, which `playback_params` resolves, and saves back +empty. Playing a step never changes what is remembered. Descriptor types, source identity and key order survive save while its native settings are unchanged. Editing a supported setting exports the new values in canonical form instead of restoring stale source values; malformed preservation data still refuses export. -Native export writes the seven keys explicitly; the known native boolean, color -adaptation, rotation and Current Layer output defaults are supported when sampling is explicitly -Rectangular. A native call using the Auto sampling default cannot yet be exported. +Native export writes the seven keys explicitly, including the command's own defaults (Auto +sampling, Current Layer output). -The reference's ellipses do not establish additional enum forms. Auto/Custom sampling, -other adaptation levels, Duplicate Layer output, absent keys, unknown settings and -malformed or repeated fields remain complete kept steps. Native layer targets, sampling/fill -edits and nondefault seeds also refuse export rather than lose their settings. Playback uses -the existing native fill and its selection, authorization, job and Undo/Redo behavior. The -remaining CAF forms and the other recorded tools in #10710 are still separate work. +Steps that carry only some of the seven keys (not measured), unknown settings and malformed +or repeated fields remain complete kept steps. Native layer targets, sampling/fill edits and +nondefault seeds also refuse export rather than lose their settings. Playback uses the existing +native fill and its selection, authorization, job and Undo/Redo behavior; Custom sampling +without a painted sampling area fails the step with the command's error. The other recorded +tools in #10710 are still separate work. ### Layer Style menu recordings From ddb59bf5cf6d6cce1033516a6fb5594d08f808f7 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:57:53 +0100 Subject: [PATCH 04/31] Folder Batch: an empty Content-Aware Fill step uses the remembered settings Batch scratch sessions start from default preferences, so an empty recorded step fell back to a new layer there. Copy only the remembered Content-Aware Fill workspace into each scratch session, next to the action preferences; other remembered dialog values keep their defaults. --- .../cmd/atn_cmds/caf_action_values_tests.rs | 22 +++++++++++++++++++ crates/engine/src/cmd/file_cmds/batch_run.rs | 10 ++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs index 28c019e11f9..c44459c1ca4 100644 --- a/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -215,3 +215,25 @@ fn damaged_remembered_settings_are_skipped_without_a_panic() { assert!(result.get("failed").is_some(), "{result}"); assert_eq!(s.active().unwrap().doc, before); } + +#[test] +fn folder_batch_plays_an_empty_step_with_the_remembered_settings() { + let dir = tempfile::tempdir().unwrap(); + let join = |name: &str| dir.path().join(name).to_string_lossy().into_owned(); + let mut source = session(); + source.execute("file.saveACopy", json!({"path": join("in.png")})).unwrap(); + let steps = json!([["select.rect", {"x":3,"y":3,"width":2,"height":2}], [CMD, {MARK: true}]]); + // The layer count of each output: Current Layer fills the background, New Layer adds one. + let layers = |s: &mut Session, out: &str| { + let result = s.execute("file.automate.batch", json!({"input":[join("in.png")],"output":join(out),"format":"psd","steps":steps})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let bytes = std::fs::read(dir.path().join(out).join("in.psd")).unwrap(); + photocraft_io::import("in.psd", &bytes).unwrap().document.layers.len() + }; + let mut s = Session::new(); + assert_eq!(layers(&mut s, "default"), 2, "nothing remembered: a new layer"); + remember(&mut s, json!({"output":"current"})); + assert_eq!(layers(&mut s, "remembered"), 1, "the remembered Current Layer"); + // Playing in Batch remembers nothing in the caller either. + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&json!({"output":"current"}))); +} diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 050b476cedd..c53b00be57a 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -919,6 +919,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let authorize = s.authorize; let raw_ppi = super::open::raw_open_resolution(s); let action_prefs = s.prefs().actions.clone(); + // An empty recorded Content-Aware Fill step plays with the remembered workspace settings. + let caf_workspace = s.prefs().dialogs.get(crate::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); let prefs = s.prefs.clone(); let color_settings = s.color.settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); @@ -1051,7 +1053,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { scratch.actions = actions.clone(); scratch.actions.playback_steps = carried.get(); scratch.actions.script_steps = script_steps.get(); - scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); + scratch.prefs.edit(|prefs| { + prefs.actions = action_prefs.clone(); + // Only this entry: the scratch session keeps every other remembered dialog value at its default. + if let Some(workspace) = &caf_workspace { + prefs.dialogs.insert(crate::atn_cmds::CAF_WORKSPACE_PREFS.into(), workspace.clone()); + } + }); let owns_history = scratch.action_history.is_none() && scratch.prefs().actions.create_single_history_state; if owns_history { crate::actions_cmds::begin_document_history(scratch, &action_name); From f398e8798b324ea9249ed75cd16f179d93a33acb Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:26:55 +0100 Subject: [PATCH 05/31] Content-Aware Fill: a refused fill keeps the last remembered settings (#14254) Apply and OK write the recorded settings to prefs only after the fill runs, so a refused fill no longer changes what an empty recorded step plays with. The CAF export test helper now fails when a successful save writes no readable item. --- .../src/cmd/atn_cmds/caf_action_values_tests.rs | 6 ++++-- crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs | 9 ++++++--- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs index 1b4bb5f9d4f..9380424ebda 100644 --- a/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -44,12 +44,14 @@ fn load(d: Descriptor) -> Action { loaded.actions.into_iter().next().unwrap() } -/// The item Save Actions writes for one step, or `None` when it cannot write it. +/// The item Save Actions writes for one step, or `None` when it refuses the step. A save that succeeds must +/// write a readable file holding the item. fn exported(p: Value) -> Option { let a = Action::new("A", vec![ActionStep::new(CMD, p)]); let (bytes, skipped) = export("S", &[&a], &[], false).ok()?; assert!(skipped.is_empty()); - atn::parse(&bytes).ok()?.actions.into_iter().next()?.items.into_iter().next() + let saved = atn::parse(&bytes).expect("a successful save writes a readable file"); + Some(saved.actions.into_iter().next().and_then(|a| a.items.into_iter().next()).expect("the saved file holds the step")) } #[test] diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 9527bc2453d..aec8cd6b521 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -139,12 +139,15 @@ fn remember(app: &mut PhotocraftApp, command: &FillCommand) { app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), Value::Object(settings))); } -/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported. +/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported and keeps the +/// settings of the last fill that ran. pub(super) fn apply(app: &mut PhotocraftApp, command: &FillCommand) -> Result<(), String> { let layer = app.caf.as_ref().ok_or("Content-Aware Fill is not open")?.layer; - remember(app, command); match app.run(CMD, plan_params(command, layer)) { - Ok(_) => Ok(()), + Ok(_) => { + remember(app, command); + Ok(()) + } Err(e) => { report(app, &e); Err(e) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 5915e4f2cd4..9897c421792 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -274,6 +274,22 @@ fn apply_and_ok_keep_the_settings_for_an_empty_recorded_step() { assert_eq!(saved(&app).unwrap()["output"], "duplicate", "OK remembers too"); } +/// A fill the engine refuses leaves the settings of the last fill that ran for an empty recorded step (#14254). +#[test] +fn a_refused_fill_keeps_the_last_remembered_settings() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + assert!(ui(&mut app, json!({"apply": true})).is_err(), "the engine refuses the locked layer"); + assert_eq!(saved(&app), Some(remembered.clone()), "a refused Apply remembers nothing"); + assert!(ui(&mut app, json!({"commit": true})).is_err(), "the engine refuses OK too"); + assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); +} + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { let c = app.caf.as_ref().unwrap(); From fb58427852960dc28efa64ef1dd5b8b3740157ba Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:46:17 +0100 Subject: [PATCH 06/31] Content-Aware Fill test: lock the workspace's own layer for the refused fill The first Apply can leave another layer active, so the refusal test locks the layer the workspace fills and waits for its preview before Apply. --- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 9897c421792..9d7bc0c26bd 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -282,9 +282,14 @@ fn a_refused_fill_keeps_the_last_remembered_settings() { open(&mut app).unwrap(); ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); let remembered = saved(&app).expect("the Apply that ran remembers its settings"); - app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + // The workspace's layer: the fill may have left another layer active. + let layer = app.caf.as_ref().unwrap().layer; + app.session.execute("layer.setProps", json!({"layer": layer.0, "locks": {"pixels": true}})).unwrap(); + let before = facts(&app)["previewRevision"].as_u64().unwrap(); ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); - assert!(ui(&mut app, json!({"apply": true})).is_err(), "the engine refuses the locked layer"); + settle(&mut app, |d| d["previewRevision"].as_u64().unwrap() > before && d["previewError"].is_null()); + ui(&mut app, json!({"apply": true})).unwrap(); + assert!(facts(&app)["error"].as_str().is_some_and(|e| e.contains("locked")), "the engine refuses the locked layer: {}", facts(&app)); assert_eq!(saved(&app), Some(remembered.clone()), "a refused Apply remembers nothing"); assert!(ui(&mut app, json!({"commit": true})).is_err(), "the engine refuses OK too"); assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); From b2cefc400e945226acbffa3ba9653bda685a7bdd Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:13:48 +0100 Subject: [PATCH 07/31] Content-Aware Fill: a background fill remembers its settings when its job is applied (#14254) With background jobs on (the desktop app), Apply and OK start the fill as a job and return before it lands. Its settings now wait in JobsUi and reach prefs.dialogs only when the job is applied, so a failed or cancelled fill keeps the last remembered settings. --- crates/ui-egui/src/dialogs/caf_ui.rs | 2 +- .../ui-egui/src/dialogs/caf_ui/lifecycle.rs | 41 +++++++++++++++---- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 37 +++++++++++++++++ crates/ui-egui/src/jobs_ui.rs | 3 ++ 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index ab2b7d2a096..49296ec59e7 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -37,7 +37,7 @@ mod lifecycle; mod preview; pub use lifecycle::open; -pub(crate) use lifecycle::{describe, take}; +pub(crate) use lifecycle::{describe, on_job_event, take}; use preview::{Base, compute_preview, plan_params}; /// Longest side of the document proxy shown in the view (px). diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index aec8cd6b521..737227e7b48 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -6,6 +6,7 @@ use craft::imaging::ui::fill::{FillCommand, FillEvent, FillLimits, FillOpen, Fil use craft::ui::dialog::{DialogId, dialog_id}; use craft::ui::runtime::env::Label; use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS}; +use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -131,12 +132,32 @@ fn report(app: &mut PhotocraftApp, e: &str) { /// The settings an empty recorded Content-Aware Fill step plays with (#14254). const RECORDED_SETTINGS: [&str; 7] = ["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; -/// Keeps `command`'s settings in `prefs.dialogs` too, where an empty recorded step reads them: the workspace -/// remembers its own copy in the framework's store, which the engine can't see. -fn remember(app: &mut PhotocraftApp, command: &FillCommand) { - let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return }; +/// `command`'s settings that an empty recorded step plays with. +fn recorded(command: &FillCommand) -> Option { + let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return None }; settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); - app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), Value::Object(settings))); + Some(Value::Object(settings)) +} + +/// Keeps `settings` in `prefs.dialogs` too, where an empty recorded step reads them: the workspace remembers its +/// own copy in the framework's store, which the engine can't see. +fn remember(app: &mut PhotocraftApp, settings: Value) { + app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// The background job a command's reply says is still running. +fn pending_job(reply: &Value) -> Option { + (reply.get("pending") == Some(&Value::Bool(true))).then(|| reply.get("job").and_then(Value::as_u64).map(JobId)).flatten() +} + +/// A background fill ended: its settings are remembered only when it was applied, not when it failed or was +/// cancelled (#14254). +pub(crate) fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + let Some(i) = app.jobs.caf_settings.iter().position(|(job, _)| *job == e.id) else { return }; + let (_, settings) = app.jobs.caf_settings.remove(i); + if matches!(e.outcome, JobOutcome::Done(_)) { + remember(app, settings); + } } /// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported and keeps the @@ -144,8 +165,14 @@ fn remember(app: &mut PhotocraftApp, command: &FillCommand) { pub(super) fn apply(app: &mut PhotocraftApp, command: &FillCommand) -> Result<(), String> { let layer = app.caf.as_ref().ok_or("Content-Aware Fill is not open")?.layer; match app.run(CMD, plan_params(command, layer)) { - Ok(_) => { - remember(app, command); + Ok(reply) => { + if let Some(settings) = recorded(command) { + match pending_job(&reply) { + // A background fill can still fail or be cancelled: its settings wait for the job's end. + Some(job) => app.jobs.caf_settings.push((job, settings)), + None => remember(app, settings), + } + } Ok(()) } Err(e) => { diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 9d7bc0c26bd..fef671fa6b4 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -295,6 +295,43 @@ fn a_refused_fill_keeps_the_last_remembered_settings() { assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); } +/// A background fill (the desktop app) remembers its settings once its job is applied; a job that fails or is +/// cancelled leaves the last remembered ones (#14254). +#[test] +fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { + use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + app.background_jobs = true; + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + let id = app.caf.as_ref().unwrap().id; + let command = app.framework.dialogs.get_by_id::(id).unwrap().workspace().command(); + super::lifecycle::apply(&mut app, &command).unwrap(); + assert_eq!(saved(&app), Some(remembered), "nothing is remembered while the fill runs"); + assert_eq!(app.jobs.caf_settings.len(), 1, "the fill runs as a background job"); + let ctx = ctx(&app); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while app.session.has_jobs() { + assert!(std::time::Instant::now() < deadline, "the fill job did not end"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let applied = saved(&app).expect("the applied fill remembers its settings"); + assert_eq!((&applied["colorAdaptation"], &applied["mirror"]), (&json!("high"), &json!(true))); + assert!(app.jobs.caf_settings.is_empty()); + for outcome in [JobOutcome::Failed("refused".into()), JobOutcome::Cancelled] { + let job = JobId(u64::MAX); + app.jobs.caf_settings.push((job, json!({"output": "duplicate"}))); + let event = JobEvent { id: job, command: CMD.into(), label: String::new(), document: None, outcome: outcome.clone(), error: None }; + crate::caf_ui::on_job_event(&mut app, &event); + assert_eq!(saved(&app), Some(applied.clone()), "{outcome:?} remembers nothing"); + assert!(app.jobs.caf_settings.is_empty(), "{outcome:?} ends the wait"); + } +} + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { let c = app.caf.as_ref().unwrap(); diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index a92adf7fe8f..a4d211db0d8 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -184,6 +184,8 @@ pub struct JobsUi { /// The file being placed in the background, if any. One at a time: files dropped meanwhile /// wait in the app's drop queue. pub place: Option, + /// Content-Aware Fill settings waiting for their background fill: remembered when it is applied (#14254). + pub(crate) caf_settings: Vec<(JobId, Value)>, } /// Run command `id`: in the background when background jobs are on and the command is a job @@ -608,6 +610,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } // A Free Transform commit's session ends with its job (then reported like any job). crate::transform_tool::on_job_event(app, &e); + crate::caf_ui::on_job_event(app, &e); if crate::prefs_ui::on_recovery_event(app, &e) { return; } From 5299ae0fab0ad4a02f3b3043b8982125284aeb52 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 19 Nov 2026 14:58:29 +0000 Subject: [PATCH 08/31] Cover translucent raster interiors with Inside and Center strokes --- crates/compose/src/effects.rs | 3 + crates/compose/src/effects/composite.rs | 6 +- crates/compose/src/effects/distance.rs | 59 ++++++----- .../src/effects/stroke_partial_alpha_tests.rs | 100 ++++++++++++++++++ crates/compose/src/fx_cache.rs | 2 + crates/gpu/src/fx.rs | 25 ++++- crates/gpu/src/fx/builders.rs | 9 +- crates/gpu/src/fx/tests.rs | 3 +- crates/gpu/src/fx_passes.rs | 4 +- crates/gpu/src/setup.rs | 8 +- crates/gpu/tests/it/parity.rs | 23 ++++ 11 files changed, 200 insertions(+), 42 deletions(-) create mode 100644 crates/compose/src/effects/stroke_partial_alpha_tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 57a836fc1e8..951fa032c73 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -251,3 +251,6 @@ mod tests; #[cfg(test)] mod satin_size_one_tests; + +#[cfg(test)] +mod stroke_partial_alpha_tests; diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 3d638c8a4ea..b246b3713ed 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -1,5 +1,5 @@ use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; -use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; +use super::distance::{INSIDE_EPS, Metric, dist_outside_by, local_coverage, stroke_inside_distance, stroke_outside_exact}; use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; use super::{ Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, @@ -110,7 +110,7 @@ pub(crate) fn build_maps_prepared( let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); let (din, dout, dout_exact) = if has_stroke { ( - Some(dist_inside_by(&shape, Metric::Chamfer)), + Some(stroke_inside_distance(&shape, matches!(layer.content, photocraft_doc::LayerContent::Raster(_)))), chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), ) @@ -185,7 +185,7 @@ pub fn premerges_layer(layer: &Layer) -> bool { /// compositor paints them. The shape Stroke Emboss bevels (#8639). fn stroke_band(shape: &Map, st: &photocraft_doc::StrokeFx) -> Map { let (in_w, out_w) = stroke_widths(st); - let din = (in_w > 0.0).then(|| dist_inside_by(shape, Metric::Chamfer)); + let din = (in_w > 0.0).then(|| stroke_inside_distance(shape, false)); let metric = if stroke_outside_exact(out_w) { Metric::Euclidean } else { Metric::Chamfer }; let dout = (out_w > 0.0).then(|| dist_outside_by(shape, metric)); let mut band = Map::new(shape.w, shape.h, 0.0); diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs index 1b93cd8ac64..b7ba3da1104 100644 --- a/crates/compose/src/effects/distance.rs +++ b/crates/compose/src/effects/distance.rs @@ -325,30 +325,6 @@ fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { /// Distance from each pixel centre inside the shape to the shape's edge /// (≤ 0 outside). pub(super) fn dist_inside(s: &Map) -> Vec { - dist_inside_by(s, Metric::Euclidean) -} - -pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at - // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. - let cov = local_coverage(s); - let start = - s.v.iter() - .zip(&cov.v) - .map(|(&a, &c)| { - if a <= INSIDE_EPS { - 0.0 - } else if c < 1.0 - INSIDE_EPS { - c - } else { - CHAMFER_INF - } - }) - .collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } let outside = covered(s, |a| a <= INSIDE_EPS); let (d, _) = edt_nearest(&outside, s.w, s.h); par_fill(s.w, s.h, 0.0f32, |y, row| { @@ -359,6 +335,36 @@ pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { }) } +/// Chamfer distance for Inside and Center strokes. +pub(super) fn stroke_inside_distance(s: &Map, raster: bool) -> Vec { + // Partly covered edge pixels start at their local coverage. Keep these sub-pixel + // distances for the antialiased outline. + let mut seeds = local_coverage(s).v; + for (seed, &alpha) in seeds.iter_mut().zip(&s.v) { + *seed = if alpha <= INSIDE_EPS { + 0.0 + } else if *seed < 1.0 - INSIDE_EPS { + *seed + } else { + CHAMFER_INF + }; + } + let (mut distances, _) = chamfer_from(seeds, s.w, s.h); + for (distance, &alpha) in distances.iter_mut().zip(&s.v) { + let d = *distance; + *distance = if alpha <= INSIDE_EPS { + -0.5 + } else if raster && alpha < 1.0 && d > 1.0 { + // Translucent raster interiors also take the stroke. Apply the distance + // locally, so it cannot move the stroke boundary in nearby opaque pixels. + 0.0 + } else { + d - 0.5 + }; + } + distances +} + /// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage /// from the fill's own opacity on shape layers. pub(super) fn local_coverage(s: &Map) -> Map { @@ -770,6 +776,8 @@ pub enum FieldKind { ChokeInside, /// Stroke distance inside the shape. StrokeInside, + /// Inside stroke distance with translucent raster pixels covered. + StrokeInsideRaster, /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). @@ -792,7 +800,8 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), - FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), + FieldKind::StrokeInside => stroke_inside_distance(&s, false), + FieldKind::StrokeInsideRaster => stroke_inside_distance(&s, true), FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), diff --git a/crates/compose/src/effects/stroke_partial_alpha_tests.rs b/crates/compose/src/effects/stroke_partial_alpha_tests.rs new file mode 100644 index 00000000000..0e4277b884e --- /dev/null +++ b/crates/compose/src/effects/stroke_partial_alpha_tests.rs @@ -0,0 +1,100 @@ +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Effect, FxCommon, FxPaint, Layer, StrokeFx, StrokePosition}; +use photocraft_geom::{Rect, Size}; + +/// The three squares and blue stroke measured in issue #15002. +fn fixture(depth: SampleType, position: StrokePosition) -> Document { + let mut doc = Document::with_background("Stroke partial alpha", Size::new(240, 120), ColorMode::Rgb, depth, Color::WHITE); + let mut layer = Layer::raster("Orange squares", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (100, 0.5), (180, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 40, 40), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + layer.effects.items.push(Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: if position == StrokePosition::Center { 6.0 } else { 5.0 }, + position, + paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)), + overprint: false, + })); + doc.layers.push(layer); + doc +} + +#[test] +fn stroke_partial_alpha_matches_the_measured_square_columns() { + const BLUE: [i32; 3] = [0, 0, 255]; + const ORANGE: [i32; 3] = [255, 128, 0]; + const WHITE: [i32; 3] = [255; 3]; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for position in [StrokePosition::Inside, StrokePosition::Center, StrokePosition::Outside] { + let doc = fixture(depth, position); + let buf = crate::render(&doc, doc.bounds()); + let close = |x, y, expected: [i32; 3]| { + let pixel = buf.get(x, y); + let actual = [pixel[0], pixel[1], pixel[2]].map(|c| (c * 255.0).round() as i32); + assert!( + actual.iter().zip(expected).all(|(a, b)| (a - b).abs() <= 1), + "{depth:?} {position:?} at ({x}, {y}): {actual:?}, expected {expected:?}" + ); + assert!((pixel[3] - 1.0).abs() < 1e-6); + }; + for (x, inside, outside) in [(120, [127, 127, 255], [128, 64, 127]), (200, [191, 191, 255], [64, 32, 191])] { + for y in 40..80 { + close( + x, + y, + match position { + StrokePosition::Inside => inside, + StrokePosition::Center => BLUE, + StrokePosition::Outside => outside, + }, + ); + } + match position { + StrokePosition::Inside => close(x, 39, WHITE), + StrokePosition::Center => { + close(x, 36, WHITE); + close(x, 37, inside); + close(x, 38, BLUE); + close(x, 39, BLUE); + } + StrokePosition::Outside => { + close(x, 34, WHITE); + close(x, 35, inside); + close(x, 36, BLUE); + close(x, 39, BLUE); + } + } + } + let (first, last) = match position { + StrokePosition::Inside => (40, 44), + StrokePosition::Center => (37, 42), + StrokePosition::Outside => (35, 39), + }; + close(40, first - 1, WHITE); + for y in first..=last { + close(40, y, BLUE); + } + close(40, last + 1, ORANGE); + close(40, 60, ORANGE); + } + } +} + +#[test] +fn the_raster_distance_preserves_the_opaque_interior_and_subpixel_outline() { + use super::{FieldKind, distance_field}; + + let row = [0.0, 0.25, 0.75, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.0]; + let source = row.repeat(9); + let inside = distance_field(FieldKind::StrokeInside, source.clone(), row.len(), 9, 6.0); + let raster = distance_field(FieldKind::StrokeInsideRaster, source, row.len(), 9, 6.0); + let mid = row.len() * 4; + // Opaque pixels retain their distances even beside a translucent area. + assert_eq!(raster[mid..mid + 8], inside[mid..mid + 8]); + assert_eq!(raster[mid + 8], inside[mid + 8], "the existing subpixel seed is retained"); + assert!(inside[mid + 11] > 0.5, "the old outline did not reach this interior"); + assert_eq!(raster[mid + 11], 0.0, "the translucent interior is covered"); + assert_eq!(raster[mid + 15], inside[mid + 15], "the fully transparent pixel stays outside"); +} diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 791a102c59e..99208407c4a 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -229,6 +229,8 @@ pub(crate) fn effect_maps_with(layer: &Layer, rect: Rect, cx: &C } let mut h = std::collections::hash_map::DefaultHasher::new(); cx.layer_keys.identity(layer, cx.doc).hash(&mut h); + // Converting a layer can reuse its exact tiles and ID but change how its stroke reads alpha. + std::mem::discriminant(&layer.content).hash(&mut h); (region.x0, region.y0, region.x1, region.y1).hash(&mut h); (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); let key = h.finish(); diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 4f265a32025..5a19067a7b7 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -296,22 +296,41 @@ fn offset(angle: f32, distance: f32) -> (f32, f32) { ((-a.cos() * distance).round(), (a.sin() * distance).round()) } +/// Which shape supplies the distance fields for a layer style stroke. +#[derive(Clone, Copy)] +pub(crate) enum StrokeShape { + Raster, + VectorOutline, + Other, +} + +impl StrokeShape { + pub(crate) fn of(layer: &Layer) -> Self { + match &layer.content { + LayerContent::Raster(_) => Self::Raster, + LayerContent::Shape(_) if photocraft_compose::effect_outline(layer).is_none() => Self::VectorOutline, + _ => Self::Other, + } + } +} + /// The map program of one enabled effect (`build_maps`), without pattern sources. #[cfg(test)] pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> MapProgram { - program_with(e, light, vector_shape, &[], (0.0, 0.0)) + let shape = if vector_shape { StrokeShape::VectorOutline } else { StrokeShape::Raster }; + program_with(e, light, shape, &[], (0.0, 0.0)) } /// The map program of one enabled effect (`build_maps`); bevel textures tile `patterns` from /// `anchor` (`effects::TextureCtx`). -pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { +pub(crate) fn program_with(e: &Effect, light: &GlobalLight, stroke_shape: StrokeShape, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { let mut b = B { stages: Vec::new(), fields: Vec::new() }; let maps = match e { Effect::DropShadow(s) | Effect::InnerShadow(s) => b.shadow(s, light, matches!(e, Effect::InnerShadow(_))), Effect::OuterGlow(g) | Effect::InnerGlow(g) => b.glow(g, matches!(e, Effect::InnerGlow(_))), Effect::Satin(s) => b.satin(s), Effect::BevelEmboss(bv) => b.bevel(bv, light, patterns, anchor), - Effect::Stroke(st) => b.stroke(st, vector_shape), + Effect::Stroke(st) => b.stroke(st, stroke_shape), Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(), }; MapProgram { key: b.key(maps), maps, stages: b.stages, fields: b.fields } diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index a3a2311201b..24fe70102f6 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use photocraft_compose::effects::{self as fx, BevelGeom, BevelPaint, FieldKind}; use photocraft_doc::{Bevel, BevelTechnique, BevelTexture, GlobalLight, Glow, GlowSource, GlowTechnique, Pattern, Satin, Shadow, StrokeFx}; -use super::{B, In, contour_lut, offset, stage}; +use super::{B, In, StrokeShape, contour_lut, offset, stage}; use crate::plan::{Kernel, stroke_widths}; /// A flag as the shaders read it: 1.0 or 0.0. @@ -156,13 +156,13 @@ impl B { } /// Stroke stages, the outside band into map 0 and the inside band into map 1. Returns 2. - pub(super) fn stroke(&mut self, st: &StrokeFx, vector_shape: bool) -> usize { + pub(super) fn stroke(&mut self, st: &StrokeFx, shape: StrokeShape) -> usize { // Stroke bands: map 0 outside, map 1 inside. let (in_w, out_w) = stroke_widths(st); if out_w > 0.0 { // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); // the CPU picks the same field by the same width (`stroke_outside_exact`). - let kind = match (vector_shape, fx::stroke_outside_exact(out_w)) { + let kind = match (matches!(shape, StrokeShape::VectorOutline), fx::stroke_outside_exact(out_w)) { (true, true) => FieldKind::StrokeOutsideVector, (true, false) => FieldKind::StrokeOutsideVectorChamfer, (false, true) => FieldKind::StrokeOutsideExact, @@ -171,7 +171,8 @@ impl B { self.stroke_band(kind, out_w, 0); } if in_w > 0.0 { - self.stroke_band(FieldKind::StrokeInside, in_w, 1); + let kind = if matches!(shape, StrokeShape::Raster) { FieldKind::StrokeInsideRaster } else { FieldKind::StrokeInside }; + self.stroke_band(kind, in_w, 1); } 2 } diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index d796288eeb0..fcc3b51be7b 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -122,6 +122,7 @@ fn banded_fields_match_whole_region_within_reach() { FieldKind::ChokeInside, FieldKind::StrokeOutside, FieldKind::StrokeInside, + FieldKind::StrokeInsideRaster, FieldKind::StrokeOutsideExact, FieldKind::StrokeOutsideVector, FieldKind::StrokeOutsideVectorChamfer, @@ -266,7 +267,7 @@ fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); - assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); + assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInsideRaster), "{:?}", inner.fields); // The shadow / softer-glow spread is unchanged: still the chamfer. let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; s.spread = 0.5; diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index 615677d8403..a02b81b6112 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -114,10 +114,10 @@ impl Compositor { // Programs, and the distance fields they read (max reach per field). // Filled shapes stroke their outline (the effect shape); others estimate it. - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); + let stroke_shape = fx::StrokeShape::of(layer); let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); let progs: Vec = - layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); + layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, anchor)).collect(); let want = field_reaches(&progs); e.fields.retain(|k, _| want.contains_key(k)); // Each field to recompute: over which rectangle, exact up to which reach. diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index 9f4d44ac430..bc72e6a35cc 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -4,7 +4,7 @@ use super::kit::{Kit, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; use super::pipelines::{NO_EFFECT_MAPS, Pipelines}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; +use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; /// Classification of a synchronous compositor pipeline build failure. /// @@ -356,14 +356,14 @@ impl Compositor { /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. pub(crate) fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { - let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); + let stroke_shape = fx::StrokeShape::of(f.layer); let progs: Vec = f .layer .effects .items .iter() .filter(|e| e.enabled()) - .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) + .map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, (0.0, 0.0))) .collect(); let want = field_reaches(&progs); // Distance fields are exact one pixel inside the window they are computed from. @@ -394,7 +394,7 @@ impl Compositor { if noisy { return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); } - for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { + for s in fx::program_with(e, &doc.global_light, fx::StrokeShape::Other, &doc.patterns, (0.0, 0.0)).stages { if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index e12030fe529..b4b0a7570a6 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -1974,6 +1974,29 @@ fn semi_transparent_normal_stroke_knocks_out_the_layer_beneath_it() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +#[test] +fn stroke_on_partial_raster_alpha_matches_on_gpu_across_page_boundaries() { + let Some(mut g) = gpu() else { return }; + let mut doc = Document::with_background("Partial alpha strokes", Size::new(540, 300), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut layer = Layer::raster("Orange blocks", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (236, 0.5), (460, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 44, 220), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + doc.layers.push(layer); + for (position, size) in [(StrokePosition::Inside, 5.0), (StrokePosition::Center, 6.0), (StrokePosition::Outside, 5.0)] { + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(size, position, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + let stats = fx_check(&mut g, &doc, &format!("{position:?} stroke across pages")); + assert!(stats.passes > 0, "the GPU rendered the effect"); + } + + // Retouching the same tile from translucent to opaque must invalidate its inside field. + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(5.0, StrokePosition::Inside, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + fx_check(&mut g, &doc, "cached inside stroke"); + doc.layers[1].surface_mut().unwrap().fill_rect(Rect::from_xywh(248, 112, 24, 32), &[1.0, 128.0 / 255.0, 0.0, 1.0]); + fx_check(&mut g, &doc, "inside stroke after changing partial alpha"); +} + #[test] fn exterior_effects_merge_from_the_shape_at_any_fill() { // Drop shadows and outer glows alone: the merge builds the layer from its shape (fill inside From 174d230ae2fddb38505823ea1b6bdbec6db77599 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 19 Nov 2026 15:03:41 +0000 Subject: [PATCH 09/31] Check stroke alpha over a transparent canvas --- .../src/effects/stroke_partial_alpha_tests.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/compose/src/effects/stroke_partial_alpha_tests.rs b/crates/compose/src/effects/stroke_partial_alpha_tests.rs index 0e4277b884e..4f58458169b 100644 --- a/crates/compose/src/effects/stroke_partial_alpha_tests.rs +++ b/crates/compose/src/effects/stroke_partial_alpha_tests.rs @@ -98,3 +98,20 @@ fn the_raster_distance_preserves_the_opaque_interior_and_subpixel_outline() { assert_eq!(raster[mid + 11], 0.0, "the translucent interior is covered"); assert_eq!(raster[mid + 15], inside[mid + 15], "the fully transparent pixel stays outside"); } + +#[test] +fn stroke_partial_alpha_keeps_intrinsic_alpha_for_inside_and_fills_it_for_center() { + for position in [StrokePosition::Inside, StrokePosition::Center] { + let mut doc = fixture(SampleType::U8, position); + let background = doc.layers[0].id; + doc.remove(background).unwrap(); + let pixels = crate::render(&doc, doc.bounds()); + for (x, source_alpha) in [(120, 128.0 / 255.0), (200, 64.0 / 255.0)] { + let actual = pixels.get(x, 60); + let expected_alpha = if position == StrokePosition::Inside { source_alpha } else { 1.0 }; + assert_eq!(&actual[..3], &[0.0, 0.0, 1.0], "{position:?} at x={x}"); + assert!((actual[3] - expected_alpha).abs() < 1e-6, "{position:?} at x={x}: {actual:?}"); + } + assert_eq!(pixels.get(80, 60), [0.0; 4]); + } +} From ec37ad57458e4be75c2bb6f550f4a0105517b4a2 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 19 Nov 2026 15:06:44 +0000 Subject: [PATCH 10/31] Paint solid Normal inside strokes without a temporary buffer --- crates/compose/src/effects/composite.rs | 64 ++++++++++++++++++------- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index b246b3713ed..f7f82fce130 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -318,6 +318,30 @@ fn inside(a: f32) -> bool { a > INSIDE_EPS } +/// Coverage of an inside stroke before the layer applies its own alpha. +#[inline] +fn inside_stroke_coverage(alpha: f32, distance: f32, limit: f32) -> f32 { + if inside(alpha) { (limit - distance).clamp(0.0, 1.0) } else { 0.0 } +} + +/// A Normal stroke replaces the layer beneath its band by coverage, then adds its own paint. +#[inline] +fn replace_under_stroke(pixel: &mut [f32; 4], paint: [f32; 4], coverage: f32) { + if paint[3] <= 0.0 { + return; + } + let kept = pixel[3] * (1.0 - coverage.clamp(0.0, 1.0)); + let alpha = kept + paint[3]; + if alpha > 0.0 { + *pixel = [ + (pixel[0] * kept + paint[0] * paint[3]) / alpha, + (pixel[1] * kept + paint[1] * paint[3]) / alpha, + (pixel[2] * kept + paint[2] * paint[3]) / alpha, + alpha.min(1.0), + ]; + } +} + /// An effect map as a fraction of the shape's own coverage. fn relative_to_shape(m: Map, shape: &Map) -> Map { let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); @@ -570,25 +594,31 @@ impl<'a> EffectPass<'a> { if in_w <= 0.0 { continue; } - let mut m = Map::new(self.w, self.h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - if st.common.blend == BlendMode::Normal { - // A Normal stroke replaces the layer under it instead of blending with it - // (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the - // stroke colour at 50 % alpha, not a 50/50 mix. - let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; - paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns); - for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { - if s[3] <= 0.0 { + let limit = in_w + 0.5; + let opacity = st.common.opacity; + if let (BlendMode::Normal, FxPaint::Color(color)) = (st.common.blend, &st.paint) { + // Solid colour is constant, so we can paint and replace in one pass. + let [r, g, b] = rgb(color); + for ((pixel, &a), &distance) in lay.px.iter_mut().zip(&shape.v).zip(&fields.din) { + let coverage = inside_stroke_coverage(a, distance, limit); + let alpha = coverage * opacity; + if alpha <= 0.0 { continue; } - let kept = p[3] * (1.0 - cov.clamp(0.0, 1.0)); - let alpha = kept + s[3]; - if alpha > 0.0 { - *p = [(p[0] * kept + s[0] * s[3]) / alpha, (p[1] * kept + s[1] * s[3]) / alpha, (p[2] * kept + s[2] * s[3]) / alpha, alpha.min(1.0)]; - } + let paint = psblend::composite(BlendMode::Normal, [0.0; 4], [r, g, b, alpha], 1.0); + replace_under_stroke(pixel, paint, coverage); + } + continue; + } + let mut m = Map::new(self.w, self.h, 0.0); + for ((coverage, &a), &distance) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { + *coverage = inside_stroke_coverage(a, distance, limit); + } + if st.common.blend == BlendMode::Normal { + let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; + paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, opacity, self.patterns); + for ((pixel, &paint), &coverage) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { + replace_under_stroke(pixel, paint, coverage); } } else { paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns); From b7fc38d2217ef4b2372bb14dc414fec840059165 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:15:09 +0100 Subject: [PATCH 11/31] Content-Aware Fill: keep the settings an empty recorded step reads across a restart (#14254) The startup move of the dialogs' memories took edit.contentAwareFill.workspace out of Preferences.dialogs, so after a restart an empty recorded step fell back to New Layer. The entry now stays, and is copied into the framework's store only while that holds none. --- crates/ui-egui/src/dialogs.rs | 16 ++++++++-- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 35 ++++++++++++++++++++++ crates/ui-egui/src/dialogs/tests.rs | 20 +++++++++++++ 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4b7963e120d..86e6da4c8c0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -619,6 +619,10 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) /// Preference entries the engine reads itself, by key: the engine has no settings store, so they cannot move. const ENGINE_READ: &[&str] = &["ui.layersPanelOptions", "file.print", "file.export.saveForWebLegacy"]; +/// Preference entries the engine reads that a workspace also remembers in the framework's store: they stay, and are +/// copied there only while it holds none. An empty recorded Content-Aware Fill step plays with the engine's copy (#14254). +const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; + /// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not /// by the shape of the value. fn dont_show_again_keys() -> [&'static str; 4] { @@ -666,7 +670,8 @@ fn convert_blend_mode(key: &str, value: &mut Value) { /// Moves the dialogs' last-used values out of `Preferences.dialogs` into the remembered section of `host`, once, before /// the first frame. Entries the engine reads and the don't-show-again entries stay; a second run finds nothing to move -/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too. +/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too, and a shared entry +/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers. pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let keys: Vec = prefs.dialogs.keys().cloned().collect(); for key in keys { @@ -675,7 +680,14 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let mut value = without_nulls(old.clone()); convert_blend_mode(&key, &mut value); let Ok(table) = toml::Table::try_from(&value) else { continue }; - Remembered::::new(scope).store(host, &table); + let remembered = Remembered::::new(scope); + if ENGINE_READ_SHARED.contains(&key.as_str()) { + if remembered.recall(host).is_none() { + remembered.store(host, &table); + } + continue; + } + remembered.store(host, &table); prefs.dialogs.remove(&key); } } diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index fef671fa6b4..9a16352b45a 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -332,6 +332,41 @@ fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { } } +/// After a restart an empty recorded step still plays with the last fill's settings: the startup move of the dialogs' +/// memories leaves the engine's copy in the preferences (#14254). +#[test] +fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString}; + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "commit": true})).unwrap(); + close_all(&mut app); + let prefs = app.session.prefs().clone(); + + // A new app over the saved preferences, moved as startup does. + let mut restarted = app_with_selection(); + restarted.session.edit_prefs(|p| *p = prefs); + restarted.framework.move_memories(&mut restarted.session); + let item = AtnItem { + event: AtnEvent::name("cafWorkspace"), + dictionary: b"Content-Aware Fill".to_vec(), + descriptor: Some(Descriptor::new("null")), + ..Default::default() + }; + let file = AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item], ..Default::default() }], + ..Default::default() + }; + let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); + restarted.session.actions.list.push(imported.actions.into_iter().next().unwrap()).unwrap(); + let layers = restarted.session.active().unwrap().doc.layers.len(); + let result = restarted.session.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(result["ran"], 1, "{result}"); + assert_eq!(restarted.session.active().unwrap().doc.layers.len(), layers, "Current Layer, not a new layer"); +} + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { let c = app.caf.as_ref().unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 6d9c82f67ed..cf9cd9ba289 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -160,6 +160,26 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.filter.gaussianBlur"), Some(toml::Table::new())); } +/// The Content-Aware Fill settings an empty recorded step reads stay in the preferences; the workspace's own memory +/// gets them only while it has none (#14254). +#[test] +fn the_move_keeps_the_content_aware_fill_settings_and_never_replaces_the_workspaces() { + let host = Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "0" }).settings(Arc::new(MemorySections::default())).build(); + let key = photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS; + let workspace = Remembered::::new(params::memory_scope(key)); + let output = |table: Option| table.and_then(|t| t.get("output").cloned()); + let mut prefs = photocraft_engine::prefs::Preferences::default(); + prefs.dialogs.insert(key.into(), json!({"output": "current"})); + move_memories(&mut prefs, &host); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "current"})), "the engine's copy stays"); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "an empty workspace memory gets it"); + + prefs.dialogs.insert(key.into(), json!({"output": "new"})); + move_memories(&mut prefs, &host); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "the workspace's own memory wins"); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "new"}))); +} + struct MarkA; struct MarkB; From 8d9a5dd403069d911878c7ea21cd301136667aa3 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:15:09 +0100 Subject: [PATCH 12/31] Content-Aware Fill: refuse to save a native step without sampleAllLayers (#14254) Without sampleAllLayers the command samples the visible composite when the active layer is empty, which neither recorded value says; saving it as false changed what the step fills from. --- .../src/cmd/atn_cmds/steps_content_aware.rs | 7 ++++++- crates/engine/tests/it/atn_content_aware_fill.rs | 16 ++++++++++++---- docs/atn.md | 3 ++- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs index 2d11728a8cb..73eee2cb9d0 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_content_aware.rs @@ -56,7 +56,9 @@ fn recorded(d: &Descriptor) -> Option { Some(Value::Object(p)) } -/// Write only represented native options, making their defaults explicit in all seven fields. +/// Write only represented native options, making their defaults explicit in all seven fields. A step without +/// `sampleAllLayers` is refused: the command then samples the composite when the layer is empty, which neither +/// recorded value says. fn descriptor(p: &Value) -> Option { let object = p.as_object()?; if !super::events::pixel_target(p) @@ -69,6 +71,9 @@ fn descriptor(p: &Value) -> Option { // Values next to the mark would be dropped by an empty descriptor. return (remembered.as_bool() == Some(true) && !PARAMS.iter().any(|param| object.contains_key(*param))).then(|| desc("null")); } + if !object.contains_key(PARAMS[1]) { + return None; + } let enumeration = |key: &str, param: &str, table: &[(&str, &str)], default: &str| { let value = match p.get(param) { None => default, diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index aec3f8a8f1a..3e8ce71595a 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -202,13 +202,17 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { /// Known native defaults become explicit values; unsupported defaults/options cannot disappear. #[test] fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_options() { - for p in [json!({"sampling":"rectangular","output":"new"}), json!({"sampling":"rectangular","output":"new","seed":1,"target":"pixels"}), params()] { + for p in [ + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new"}), + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new","seed":1,"target":"pixels"}), + params(), + ] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, params())]); } let mut current = params(); current["output"] = json!("current"); - for p in [json!({"sampling":"rectangular"}), current.clone()] { + for p in [json!({"sampling":"rectangular","sampleAllLayers":false}), current.clone()] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, current.clone())]); } @@ -238,12 +242,16 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio let mut defaults = params(); defaults["sampling"] = json!("auto"); defaults["output"] = json!("current"); - let a = load(exported(json!({})).unwrap().descriptor.unwrap()); + let a = load(exported(json!({"sampleAllLayers":false})).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults.clone())]); defaults["output"] = json!("new"); - let a = load(exported(json!({"output":"new"})).unwrap().descriptor.unwrap()); + let a = load(exported(json!({"sampleAllLayers":false,"output":"new"})).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults)]); assert!(exported(json!([])).is_none()); + // Without `sampleAllLayers` an empty layer samples the composite, and a recorded false would not. + for p in [json!({}), json!({"output":"new"}), json!({"colorAdaptation":"none"}), json!({"sampling":"rectangular"})] { + assert!(exported(p.clone()).is_none(), "unrepresented sampling: {p}"); + } } fn session(depth: u32) -> Session { diff --git a/docs/atn.md b/docs/atn.md index e20de57d9be..2d16f026b1f 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -436,7 +436,8 @@ Descriptor types, source identity and key order survive save while its native se unchanged. Editing a supported setting exports the new values in canonical form instead of restoring stale source values; malformed preservation data still refuses export. Native export writes the seven keys explicitly, including the command's own defaults (Auto -sampling, Current Layer output). +sampling, Current Layer output). A native step without `sampleAllLayers` refuses export: on an +empty layer the command then samples the visible composite, which neither recorded value says. Steps that carry only some of the seven keys (not measured), unknown settings and malformed or repeated fields remain complete kept steps. Native layer targets, sampling/fill edits and From f858820daffa99f939cb084076fe88efe1650ca2 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 05:29:10 -0600 Subject: [PATCH 13/31] Tests: the Custom Shape tool's Make row in Path mode Main already shows Make: Selection... / Mask / Shape for every shape tool in Path mode (#13582). These tests guard it for the Custom Shape tool: greyed with no path, enabled after a drag, Shape makes a shape layer, and no Make row in Shape mode. The Make: Shape button is found among buttons only, since the bar's Shape picker shares its name. Fixes #13471 --- .../vector_ui/custom_shape_path_make_tests.rs | 81 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/options.rs | 4 + 2 files changed, 85 insertions(+) create mode 100644 crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs diff --git a/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs b/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs new file mode 100644 index 00000000000..c6a9f9f45a7 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs @@ -0,0 +1,81 @@ +//! #13471: in Path mode the Custom Shape tool's options bar shows Make: Selection… · Mask · Shape, greyed with no path; +//! with a path just drawn they are enabled and Shape turns the path into a shape layer. Shape mode has no Make row. + +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::super::test_input::harness; +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::state::Tool; +use craft::draw::ui::VectorMode; + +type H = Harness<'static, Box>; + +const MAKE: [&str; 3] = ["Selection…", "Mask", "Shape"]; + +fn custom_shape(mode: VectorMode) -> H { + let mut h = harness(Tool::CustomShape); + h.state_mut().ui.tool_options.shape_mode = mode; + h.run_steps(3); + h +} + +/// The button labelled `label`: the bar's Shape picker shares the Make button's name, so only buttons count. +fn button<'a>(h: &'a H, label: &'a str) -> Option> { + h.query_all_by_label(label).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button) +} + +/// Whether each Make button is there and enabled; `None` when it isn't shown. +fn make_buttons(h: &H) -> Vec> { + MAKE.iter().map(|label| button(h, label).map(|n| !n.accesskit_node().is_disabled())).collect() +} + +/// A drag on the canvas from `a` to `b` (document points). +fn drag(h: &mut H, a: [f64; 2], b: [f64; 2]) { + let p = testing::to_screen(h.state_mut(), a); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for i in 1..=6 { + let t = f64::from(i) / 6.0; + let q = testing::to_screen(h.state_mut(), [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); + h.event(egui::Event::PointerMoved(q)); + h.run_steps(1); + } + let q = testing::to_screen(h.state_mut(), b); + h.event(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +fn shape_layers(h: &H) -> usize { + let doc = &h.state().session.active().unwrap().doc; + doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, photocraft_doc::LayerContent::Shape(_))).count() +} + +#[test] +fn path_mode_shows_the_make_buttons_greyed_without_a_path() { + let h = custom_shape(VectorMode::Path); + assert!(h.query_by_label("Make:").is_some(), "the Make: label"); + assert_eq!(make_buttons(&h), vec![Some(false); 3], "all three greyed with no path"); +} + +#[test] +fn a_drawn_path_enables_them_and_shape_makes_a_shape_layer() { + let mut h = custom_shape(VectorMode::Path); + drag(&mut h, [40.0, 20.0], [140.0, 80.0]); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "the Custom Shape tool drew a path"); + assert_eq!(make_buttons(&h), vec![Some(true); 3], "enabled with a path"); + let before = shape_layers(&h); + button(&h, "Shape").expect("the Make: Shape button").click(); + h.run_steps(3); + assert_eq!(shape_layers(&h), before + 1, "Make: Shape made a shape layer from the path"); +} + +#[test] +fn shape_mode_has_no_make_row() { + let h = custom_shape(VectorMode::Shape); + assert_eq!(make_buttons(&h), vec![None; 3]); +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 5668bd24aca..97f388b6e59 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -528,3 +528,7 @@ mod line_arrow_concavity_field_tests; #[cfg(test)] #[path = "pen_make_mask_tests.rs"] mod pen_make_mask_tests; + +#[cfg(test)] +#[path = "custom_shape_path_make_tests.rs"] +mod custom_shape_path_make_tests; From b5c7f1f2b2c5dfc51bcc687c9b9db8af045eca8b Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:52:42 +0100 Subject: [PATCH 14/31] Content-Aware Fill action tests: build the session with crate::session() (#14254) In engine-core a bare Session::new() installs no commands, so the four tests that play steps failed with NotInstalled when nextest ran each one in its own process. They passed under cargo test only because another test in the same process had installed the commands first. --- .../src/cmd/atn_cmds/caf_action_values_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs index d22ed7878d7..5c89e4513ab 100644 --- a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -113,7 +113,7 @@ fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { /// White 8 x 8 with a red square selected for the fill. fn session() -> Session { - let mut s = Session::new(); + let mut s = crate::session(); s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); s.execute("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); @@ -188,7 +188,7 @@ fn an_empty_step_plays_with_the_remembered_settings_and_steps_never_change_them( #[test] fn remembered_settings_fill_only_what_the_step_does_not_name() { let resolve = |s: &Session, p: Value| crate::actions_cmds::playback_params(s, CMD, &p).unwrap(); - let mut s = Session::new(); + let mut s = crate::session(); assert_eq!(resolve(&s, json!({MARK: true})), json!({"output":"new"})); // Only the command's settings come over, never the overlay's. remember(&mut s, json!({"showOverlay":true,"opacity":50.0,"color":[1,2,3],"excluded":true,"sampling":"auto","output":"duplicate"})); @@ -205,7 +205,7 @@ fn remembered_settings_fill_only_what_the_step_does_not_name() { #[test] fn damaged_remembered_settings_are_skipped_without_a_panic() { let resolve = |s: &Session| crate::actions_cmds::playback_params(s, CMD, &json!({MARK: true})).unwrap(); - let mut s = Session::new(); + let mut s = crate::session(); for damaged in [json!(3), json!(null), json!([]), json!({"output":5,"scale":"yes","sampling":true,"mirror":null})] { remember(&mut s, damaged.clone()); assert_eq!(resolve(&s), json!({"output":"new"}), "{damaged}"); @@ -235,7 +235,7 @@ fn folder_batch_plays_an_empty_step_with_the_remembered_settings() { let bytes = std::fs::read(dir.path().join(out).join("in.psd")).unwrap(); photocraft_io::import("in.psd", &bytes).unwrap().document.layers.len() }; - let mut s = Session::new(); + let mut s = crate::session(); assert_eq!(layers(&mut s, "default"), 2, "nothing remembered: a new layer"); remember(&mut s, json!({"output":"current"})); assert_eq!(layers(&mut s, "remembered"), 1, "the remembered Current Layer"); From 06e8b35aeb0b7b02ab26c50cc4839cab5fa93a05 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:11:38 +0100 Subject: [PATCH 15/31] Content-Aware Fill: carry an earlier version's workspace settings to empty recorded steps (#14254) An earlier version moved the remembered Content-Aware Fill settings into the workspace's own memory and kept no copy where an empty recorded step reads them, so after upgrading the first empty step wrote to a new layer although the workspace remembered Current Layer. The startup move now gives such a profile that copy once, from the workspace's memory, with Rotation Adaptation under the step's name. A profile without that memory starts with an empty copy, so from then on only a fill that ran sets it and settings the workspace closed with but never filled are not carried forward. The copy the workspace gets from the preferences now also keeps its rotation. --- crates/ui-egui/src/dialogs.rs | 26 ++++++++- crates/ui-egui/src/dialogs/caf_ui.rs | 2 +- .../ui-egui/src/dialogs/caf_ui/lifecycle.rs | 22 +++++++ crates/ui-egui/src/dialogs/caf_ui/tests.rs | 57 ++++++++++++++++--- crates/ui-egui/src/dialogs/tests.rs | 5 +- 5 files changed, 99 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index de192f65aff..f88c9a8f14c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -677,7 +677,8 @@ fn convert_blend_mode(key: &str, value: &mut Value) { /// Moves the dialogs' last-used values out of `Preferences.dialogs` into the remembered section of `host`, once, before /// the first frame. Entries the engine reads and the don't-show-again entries stay; a second run finds nothing to move /// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too, and a shared entry -/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers. +/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers; a profile without one gets it from +/// what the framework remembers ([`carry_forward_shared`]). pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let keys: Vec = prefs.dialogs.keys().cloned().collect(); for key in keys { @@ -685,10 +686,14 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let Some(old) = prefs.dialogs.get(&key) else { continue }; let mut value = without_nulls(old.clone()); convert_blend_mode(&key, &mut value); + if key == photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS { + crate::caf_ui::recorded_to_workspace(&mut value); + } let Ok(table) = toml::Table::try_from(&value) else { continue }; let remembered = Remembered::::new(scope); if ENGINE_READ_SHARED.contains(&key.as_str()) { - if remembered.recall(host).is_none() { + // An empty entry holds no settings yet (see `carry_forward_shared`). + if !table.is_empty() && remembered.recall(host).is_none() { remembered.store(host, &table); } continue; @@ -696,6 +701,23 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { remembered.store(host, &table); prefs.dialogs.remove(&key); } + carry_forward_shared(prefs, host); +} + +/// Gives a profile without the engine's copy of a shared entry one, once (#14254). An earlier version moved the +/// Content-Aware Fill settings into the workspace's own memory and kept no copy, so that memory is carried forward: +/// it is all such a profile has, although it also holds settings the workspace closed with and never filled. With no +/// memory the copy starts empty. From then on only a fill that ran sets the copy, so settings closed without a fill +/// are never carried forward. +fn carry_forward_shared(prefs: &mut Preferences, host: &Host) { + for key in ENGINE_READ_SHARED { + if prefs.dialogs.contains_key(*key) { + continue; + } + let Some(scope) = memory_destination(key) else { continue }; + let memory = Remembered::::new(scope).recall(host).and_then(|table| serde_json::to_value(table).ok()); + prefs.dialogs.insert((*key).into(), memory.map_or_else(|| serde_json::json!({}), crate::caf_ui::recorded_from_workspace)); + } } pub mod adjust_dialog; diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index 49296ec59e7..6a76c704819 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -37,7 +37,7 @@ mod lifecycle; mod preview; pub use lifecycle::open; -pub(crate) use lifecycle::{describe, on_job_event, take}; +pub(crate) use lifecycle::{describe, on_job_event, recorded_from_workspace, recorded_to_workspace, take}; use preview::{Base, compute_preview, plan_params}; /// Longest side of the document proxy shown in the view (px). diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 737227e7b48..0488cfdadaf 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -132,6 +132,28 @@ fn report(app: &mut PhotocraftApp, e: &str) { /// The settings an empty recorded Content-Aware Fill step plays with (#14254). const RECORDED_SETTINGS: [&str; 7] = ["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; +/// The workspace's own memory names Rotation Adaptation `rotation`; an empty recorded step reads `rotationAdaptation`. +const WORKSPACE_ROTATION: &str = "rotation"; + +/// The settings an empty recorded step plays with, from what the workspace remembers (#14254). +pub(crate) fn recorded_from_workspace(memory: Value) -> Value { + let Value::Object(mut settings) = memory else { return json!({}) }; + if let Some(rotation) = settings.remove(WORKSPACE_ROTATION) { + settings.insert("rotationAdaptation".into(), rotation); + } + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Value::Object(settings) +} + +/// The settings an empty recorded step plays with, in the form the workspace remembers them. +pub(crate) fn recorded_to_workspace(settings: &mut Value) { + if let Some(settings) = settings.as_object_mut() + && let Some(rotation) = settings.remove("rotationAdaptation") + { + settings.insert(WORKSPACE_ROTATION.into(), rotation); + } +} + /// `command`'s settings that an empty recorded step plays with. fn recorded(command: &FillCommand) -> Option { let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return None }; diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 603d2b0d27f..c9b5c009af4 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -258,7 +258,7 @@ fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { fn apply_and_ok_keep_the_settings_for_an_empty_recorded_step() { let mut app = app_with_selection(); let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); - assert_eq!(saved(&app), None); + assert_eq!(saved(&app), Some(json!({})), "a new profile has no settings yet"); open(&mut app).unwrap(); ui(&mut app, json!({"output": "current", "colorAdaptation": "high", "rotation": "medium", "mirror": true})).unwrap(); ui(&mut app, json!({"apply": true})).unwrap(); @@ -337,18 +337,57 @@ fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { /// memories leaves the engine's copy in the preferences (#14254). #[test] fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { - use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; - use craft_psd::descriptor::{Descriptor, UnicodeString}; let mut app = app_with_selection(); open(&mut app).unwrap(); ui(&mut app, json!({"output": "current", "commit": true})).unwrap(); close_all(&mut app); - let prefs = app.session.prefs().clone(); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, not a new layer"); +} - // A new app over the saved preferences, moved as startup does. +/// A profile from an earlier version, which kept the Content-Aware Fill settings only in the workspace's own memory, +/// carries them forward for an empty recorded step on its first start (#14254). +#[test] +fn an_earlier_versions_workspace_settings_carry_forward_to_an_empty_recorded_step() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "rotation": "medium"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + // That version moved the engine's copy into the workspace's memory and kept none. + let mut prefs = app.session.prefs().clone(); + prefs.dialogs.remove(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS); + let mut restarted = restart(prefs); + let carried = restarted.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!((&carried["output"], &carried["rotationAdaptation"]), (&json!("current"), &json!("medium")), "{carried}"); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, as the workspace remembers"); +} + +/// Settings the workspace closed with but never filled are not carried to an empty recorded step: only a fill that ran +/// sets what it plays with (#14254). +#[test] +fn settings_closed_without_a_fill_are_not_carried_forward() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 1, "New Layer: no fill has run"); +} + +/// A new app over the saved preferences `prefs`, moved as startup does. +fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { let mut restarted = app_with_selection(); restarted.session.edit_prefs(|p| *p = prefs); restarted.framework.move_memories(&mut restarted.session); + restarted +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns how many layers it added. +fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString}; let item = AtnItem { event: AtnEvent::name("cafWorkspace"), dictionary: b"Content-Aware Fill".to_vec(), @@ -361,11 +400,11 @@ fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { ..Default::default() }; let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); - restarted.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); - let layers = restarted.session.active().unwrap().doc.layers.len(); - let result = restarted.session.execute("actions.play", json!({"action": 0})).unwrap(); + app.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + let result = app.session.execute("actions.play", json!({"action": 0})).unwrap(); assert_eq!(result["ran"], 1, "{result}"); - assert_eq!(restarted.session.active().unwrap().doc.layers.len(), layers, "Current Layer, not a new layer"); + app.session.active().unwrap().doc.layers.len() - layers } /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 7013bb90600..715f308bf9f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -148,9 +148,12 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.edit.fill").unwrap().get("mode"), Some(&toml::Value::String(photocraft_color::BlendMode::ColorBurn.key().to_string()))); let mut left: Vec<&str> = prefs.dialogs.keys().map(String::as_str).collect(); left.sort_unstable(); - let mut kept = vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF]; + // The Content-Aware Fill entry an empty recorded step reads is given to every profile, empty here (#14254). + let mut kept = + vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF, photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; kept.sort_unstable(); assert_eq!(left, kept, "only the kept entries stay in the preferences"); + assert_eq!(prefs.dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&json!({}))); // A second run finds nothing to move: a value changed since is not overwritten. Remembered::::new("photocraft.filter.gaussianBlur").store(&host, &toml::Table::new()); From 1ce53d5942999222c0c7cfb635a2b04ca657d04d Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:13:12 +0100 Subject: [PATCH 16/31] Content-Aware Fill action tests: paint the square instead of Edit > Fill (#14254) On current main Edit > Fill is registered by engine-paint, so engine-core's session no longer knows edit.fill and the four tests that build this document failed with UnknownCommand. --- .../src/cmd/atn_cmds/caf_action_values_tests.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs index 5c89e4513ab..1f4e52822bc 100644 --- a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -115,9 +115,16 @@ fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { fn session() -> Session { let mut s = crate::session(); s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); - s.execute("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); - s.execute("edit.fill", json!({"contents":"foreground"})).unwrap(); + // Painted directly: Edit › Fill is registered by another engine crate. + s.edit("paint", |doc, active| { + let surface = doc.layer_mut(active.ok_or(crate::EngineError::NoDocument)?).and_then(|l| l.surface_mut()).ok_or(crate::EngineError::NoDocument)?; + for (x, y) in [(3, 3), (4, 3), (3, 4), (4, 4)] { + surface.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + Ok(()) + }) + .unwrap(); s } From 7965a12a5b00ee9c2d84c3f450d95547a35eb1e0 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:47:32 +0100 Subject: [PATCH 17/31] Add Include ICC Profile to Layers to Files File > Export > Layers to Files gets an Include ICC Profile checkbox for every file type and a matching "iccProfile" param (#13973). Off writes no profile in PNG, JPEG, TIFF or PSD files; on embeds the document's profile (its mode's working profile when it has none, PSD included), so a CMYK document's JPEG carries its CMYK profile while its PNG, written as RGB, carries none. Without the param every file is written as before. The param sets the existing SaveOpts embed_icc field that Artboards to Files already uses. --- crates/engine-core/src/cmd/file_cmds.rs | 6 +- .../engine-core/src/cmd/file_cmds/export.rs | 19 ++- .../file_cmds/layers_to_files_icc_tests.rs | 115 ++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 2 + 4 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index 1ef2885afd2..1de73815ea9 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -434,7 +434,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"iccProfile":bool? (Include ICC Profile: false, no profile in any file; true, the document's profile, or its mode's working profile when it has none, PSD included, and none in a CMYK document's PNG; unset, as before),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, native_doc, layers_to_files ), @@ -572,3 +572,7 @@ mod aces_exr_tests { } } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "file_cmds/layers_to_files_icc_tests.rs"] +mod layers_to_files_icc_tests; diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index c1505662964..eb0483d3d55 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -57,7 +57,10 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); - let save = SaveOpts::from_params(s, p, cmd)?; + let mut save = SaveOpts::from_params(s, p, cmd)?; + // Include ICC Profile (#13973); unset, each file embeds what it did before. + let icc = super::save::tiff_bool_param(p, "iccProfile", cmd)?; + save.embed_icc = icc; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); @@ -101,6 +104,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // The prefix is optional; only the layer name needs the empty-name fallback. let prefix_part = if prefix.is_empty() { String::new() } else { part(&prefix) }; let name = format!("{prefix_part}_{:04}_{}.{format}", index, part(&l.name)); + let save = include_icc(&mut one, &format, icc, save); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); @@ -108,6 +112,19 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& Ok(report) } +/// Include ICC Profile for one layer file: off, no profile; on, the document's profile, or the one +/// its colours are taken to be in when it has none (PSD included), except that a CMYK document's +/// PNG (written as RGB) carries none, as measured. Unset changes nothing. +fn include_icc(one: &mut Document, format: &str, icc: Option, mut save: SaveOpts) -> SaveOpts { + match icc { + Some(false) => one.icc_profile = None, + Some(true) if format == "png" && one.mode == ColorMode::Cmyk => save.embed_icc = Some(false), + Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), + _ => {} + } + save +} + /// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. /// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped /// at bake time. Group adjustments need their enclosing group's compositing semantics and are diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs new file mode 100644 index 00000000000..ba68722a960 --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -0,0 +1,115 @@ +//! Layers to Files: Include ICC Profile (#13973). `iccProfile: false` writes no profile in PNG, +//! JPEG, TIFF or PSD files; `true` embeds the document's profile (a CMYK document's JPEG its CMYK +//! profile, its PNG none); unset keeps what the export wrote before. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +fn session(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 6, "mode": mode, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.8, 0.1, 0.1]})) + .unwrap(); + s +} + +/// The colour space of each written file's embedded profile (`None`: no profile), by extension. +fn profiles(s: &mut Session, format: &str, extra: Value) -> Vec<(String, Option)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let bytes = std::fs::read(path).unwrap(); + let doc = photocraft_io::import(path, &bytes).unwrap().document; + let space = doc.icc_profile.map(|icc| String::from_utf8_lossy(icc.get(16..20).unwrap()).trim().to_string()); + (format!("{:?}", doc.mode), space) + }) + .collect() +} + +const FORMATS: [&str; 4] = ["png", "jpg", "tif", "psd"]; + +/// RGB and CMYK documents at 8 and 16 bits. +const DOCS: [(&str, u32); 4] = [("rgb", 8), ("rgb", 16), ("cmyk", 8), ("cmyk", 16)]; + +fn one(s: &mut Session, format: &str, extra: Value) -> (String, Option) { + let files = profiles(s, format, extra); + assert_eq!(files.len(), 1, "{format}: one layer, one file"); + files.into_iter().next().unwrap() +} + +#[test] +fn off_writes_no_profile() { + for (mode, depth) in DOCS { + let mut s = session(mode, depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": false})).1, None, "{mode}{depth} {format}"); + } + } +} + +#[test] +fn on_embeds_the_documents_profile() { + for depth in [8, 16] { + let mut s = session("rgb", depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": true})), ("Rgb".into(), Some("RGB".into())), "rgb{depth} {format}"); + } + } + // The document's own profile, not a stand-in, when it has one. + let mut s = session("rgb", 8); + let own = crate::color_cmds::working_profile(ColorMode::Rgb).to_bytes(); + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "jpg", "iccProfile": true})).unwrap(); + let path = r["files"][0].as_str().unwrap(); + let embedded = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document.icc_profile; + assert_eq!(embedded.as_deref(), Some(&*own)); +} + +#[test] +fn a_cmyk_documents_jpeg_keeps_its_cmyk_profile_and_its_png_has_none() { + for depth in [8, 16] { + let mut s = session("cmyk", depth); + let on = json!({"iccProfile": true}); + assert_eq!(one(&mut s, "jpg", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} jpg"); + assert_eq!(one(&mut s, "tif", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} tif"); + assert_eq!(one(&mut s, "psd", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} psd"); + assert_eq!(one(&mut s, "png", on), ("Rgb".into(), None), "cmyk{depth} png"); + } +} + +#[test] +fn unset_keeps_what_the_export_wrote_before() { + // As main wrote them before the param: flat RGB files and a CMYK document's PNG carry the + // RGB working profile; PSD files and CMYK JPEG and TIFF files carry none. + let rgb = Some("RGB".to_string()); + for depth in [8, 16] { + let mut s = session("rgb", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), rgb.clone(), rgb.clone(), None], "rgb{depth}"); + let mut s = session("cmyk", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), None, None, None], "cmyk{depth}"); + // `null` is unset too. + assert_eq!(one(&mut s, "png", json!({"iccProfile": null})).1, rgb, "cmyk{depth} null"); + } +} + +#[test] +fn a_bad_value_is_an_error_and_writes_nothing() { + let mut s = session("rgb", 8); + for bad in [json!("no"), json!(0), json!([false]), json!({})] { + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "png", "iccProfile": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "{bad}: nothing written"); + } + assert_eq!(s.active().unwrap().doc.icc_profile, None, "the document is untouched"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index e34778814ae..24bc9a8a724 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -298,6 +298,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec Date: Wed, 25 Nov 2026 07:53:30 +0100 Subject: [PATCH 18/31] Keep a document's profile for its colours when Include ICC Profile is off With iccProfile false, Layers to Files cleared each layer file's document profile, and the compositor reads a CMYK document's pixels through that profile, so a CMYK document with its own profile exported to PNG with different colours. The option now only leaves the profile out of the file (SaveOpts::embed_icc), and the PSD writer (and the layered TIFF it feeds) honours embed_icc like the PNG, JPEG and TIFF encoders do. #13973 --- .../engine-core/src/cmd/file_cmds/export.rs | 5 ++- .../file_cmds/layers_to_files_icc_tests.rs | 44 +++++++++++++++++++ crates/io/src/lib.rs | 1 + crates/io/src/psd_export.rs | 4 ++ crates/io/src/psd_export/document.rs | 2 +- crates/io/src/psd_export/tests.rs | 13 ++++++ crates/io/src/tiff_layers.rs | 1 + 7 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index eb0483d3d55..4b1f5794996 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -114,10 +114,11 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& /// Include ICC Profile for one layer file: off, no profile; on, the document's profile, or the one /// its colours are taken to be in when it has none (PSD included), except that a CMYK document's -/// PNG (written as RGB) carries none, as measured. Unset changes nothing. +/// PNG (written as RGB) carries none, as measured. Unset changes nothing. Off only leaves the +/// profile out of the file (`save.embed_icc`): the document keeps it, since its colours (a CMYK +/// document's conversion to RGB) are read through it. fn include_icc(one: &mut Document, format: &str, icc: Option, mut save: SaveOpts) -> SaveOpts { match icc { - Some(false) => one.icc_profile = None, Some(true) if format == "png" && one.mode == ColorMode::Cmyk => save.embed_icc = Some(false), Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), _ => {} diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs index ba68722a960..e5512a0e173 100644 --- a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -113,3 +113,47 @@ fn a_bad_value_is_an_error_and_writes_nothing() { } assert_eq!(s.active().unwrap().doc.icc_profile, None, "the document is untouched"); } + +/// The pixels of each written file, decoded (RGBA, 0..1), and whether it carries a profile. +fn pixels(s: &mut Session, format: &str, extra: Value) -> Vec<(Vec<[f32; 4]>, bool)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let doc = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document; + let icc = doc.icc_profile.is_some(); + (photocraft_compose::flatten(&doc).px.to_vec(), icc) + }) + .collect() +} + +#[test] +fn off_keeps_a_cmyk_documents_own_profile_for_its_colours() { + // A CMYK document tagged with a profile other than the built-in coated one, whose layer + // needs compositing (50 % opacity): its colours are converted through its own profile + // whether or not the file carries it (CodeRabbit on #16653). + for depth in [8, 16] { + let mut s = session("cmyk", depth); + s.execute("edit.assignProfile", json!({"profile": "coated-fogra39"})).unwrap(); + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + let on = pixels(&mut s, "png", json!({"iccProfile": true})); + let off = pixels(&mut s, "png", json!({"iccProfile": false})); + let unset = pixels(&mut s, "png", json!({})); + assert_eq!(off[0].0, on[0].0, "cmyk{depth}: the same pixels with iccProfile false and true"); + assert_eq!(off[0].0, unset[0].0, "cmyk{depth}: the same pixels with iccProfile false and unset"); + for format in FORMATS { + assert!(pixels(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| !icc), "cmyk{depth} {format}: no profile"); + } + let layered = pixels(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| !icc), "cmyk{depth} layered tif: no profile"); + assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document keeps its profile"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b18d4782093..b8791076908 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1276,6 +1276,7 @@ fn export_stages_with_renderer( document_path: opts.document_path.clone(), read_linked_files: opts.read_linked_files, stage_on_scratch_from: Some(psd_export::STAGE_DOCUMENTS_FROM), + embed_icc: opts.encode.embed_icc, ..Default::default() }; // The preview is rendered first, while only the document is in memory: its full-size diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 5a06cf25b16..86a5fbcfd31 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -80,6 +80,9 @@ pub struct PsdExportOptions { /// pixel bytes (layers and composite) reach this and spilling is on (`None`: never). The /// save then holds the file model's structure, not a second copy of its pixels (#5333). pub stage_on_scratch_from: Option, + /// Write the document's ICC profile (resource 1039). Off leaves it out of the file only: the + /// document's colours are still read through it (a CMYK document's layers and merged image). + pub embed_icc: bool, } impl Default for PsdExportOptions { @@ -93,6 +96,7 @@ impl Default for PsdExportOptions { document_path: None, read_linked_files: true, stage_on_scratch_from: None, + embed_icc: true, } } } diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 3ac5ce1c6d8..80c2377ccf9 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -148,7 +148,7 @@ fn export_supported_document( ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), ]; - if let Some(icc) = &doc.icc_profile { + if let Some(icc) = doc.icc_profile.as_ref().filter(|_| opts.embed_icc) { resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); } if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 2284c4e86ab..19819be3f8f 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -862,3 +862,16 @@ fn a_type_layer_without_a_writable_tysh_drops_its_imported_block() { assert!(!written.blocks.iter().any(|b| b.key == *b"TySh"), "the stale imported TySh is dropped"); assert!(warnings.iter().any(|w| w.contains("no TySh data")), "{warnings:?}"); } + +/// `embed_icc: false` leaves the ICC profile resource out of the file (the document keeps it); +/// on (the default), the file carries it. +#[test] +fn embed_icc_off_writes_no_profile_resource() { + let mut doc = Document::new("icc", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + let has = |opts: &PsdExportOptions| document_to_psd_with(&doc, opts).unwrap().0.resources.iter().any(|r| r.id == ids::ICC_PROFILE); + assert!(has(&PsdExportOptions::default())); + assert!(!has(&PsdExportOptions { embed_icc: false, ..Default::default() })); + assert!(doc.icc_profile.is_some()); +} diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 0c21f3ea197..f0814956daf 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -368,6 +368,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr read_linked_files: opts.read_linked_files, // The layered TIFF reads the merged image's bytes directly: they stay in memory. stage_on_scratch_from: None, + embed_icc: opts.encode.embed_icc, }; // TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap // or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter From 6acc98ee7641b91ffa4b1e6fa80b4aa44ccdd340 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:07:22 +0100 Subject: [PATCH 19/31] Give the Layers to Files ICC tests a normal layer Layers to Files now refuses a Background-only document (#13968), so every test in layers_to_files_icc_tests.rs failed on the merge with main. The test document's Background becomes a normal layer, as in the single-layer tests (#13973). --- .../engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs index e5512a0e173..a32b976b1c4 100644 --- a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -9,6 +9,8 @@ fn session(mode: &str, depth: u32) -> Session { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 6, "mode": mode, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.8, 0.1, 0.1]})) .unwrap(); + // One normal layer: Layers to Files refuses a Background-only document (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); s } From 13a3c3acaae86a44ae43cd82833eeddab72fbe52 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:59:00 +0100 Subject: [PATCH 20/31] Leave the profile out of an Indexed PSD when Include ICC Profile is off An Indexed Color document is written over its colour table by palette_map, which adds its RGB profile (resource 1039) and returned before the embed_icc check, so Layers to Files with Include ICC Profile off still wrote the profile into an Indexed document's PSD or PSB (#13973). That path now drops the resource when embed_icc is off. Indexed PNG, BMP and GIF never carry a profile, and its JPEG and flat and layered TIFF already followed the setting; the new test covers them too. --- .../file_cmds/layers_to_files_icc_tests.rs | 22 +++++++++++++++++++ crates/io/src/psd_export/document.rs | 6 ++++- crates/io/src/psd_export/tests.rs | 20 +++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs index a32b976b1c4..19f2b9c24ef 100644 --- a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -159,3 +159,25 @@ fn off_keeps_a_cmyk_documents_own_profile_for_its_colours() { assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document keeps its profile"); } } + +/// An Indexed Color document with an RGB profile: `iccProfile: false` writes no profile in any file, +/// the PSD included, which is written over its colour table (CodeRabbit on #16653), and the +/// layered TIFF; `true` keeps it in the PSD. +#[test] +fn an_indexed_documents_files_follow_the_setting() { + let mut s = session("rgb", 8); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap(); + // The conversion flattens: a normal layer again (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.mode, ColorMode::Indexed); + assert!(doc.icc_profile.is_some(), "the document keeps its profile"); + assert!(doc.layers.iter().any(|l| !doc.is_background(l.id)), "a layer to export"); + for format in ["png", "jpg", "tif", "psd", "bmp"] { + assert!(profiles(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| icc.is_none()), "indexed {format}: no profile"); + } + let layered = profiles(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| icc.is_none()), "indexed layered tif: no profile"); + assert_eq!(one(&mut s, "psd", json!({"iccProfile": true})).1, Some("RGB".into()), "indexed psd: the profile"); +} diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 80c2377ccf9..8c2f8f6d971 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -66,7 +66,11 @@ fn document_to_psd_sized_with_patterns( if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns); } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + if let Some(mut file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + // An Indexed document's RGB profile is written there too; Include ICC Profile off leaves it out. + if !opts.embed_icc { + file.0.resources.retain(|r| r.id != ids::ICC_PROFILE); + } return Ok(file); } let fmt = doc.pixel_format(); diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 19819be3f8f..89c8b164792 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -875,3 +875,23 @@ fn embed_icc_off_writes_no_profile_resource() { assert!(!has(&PsdExportOptions { embed_icc: false, ..Default::default() })); assert!(doc.icc_profile.is_some()); } + +/// An Indexed Color document is written over its colour table (`palette_map`): `embed_icc: false` +/// leaves its RGB profile out there too, as PSD and as PSB (CodeRabbit on #16653). +#[test] +fn embed_icc_off_writes_no_profile_resource_for_an_indexed_document() { + let white = photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0); + let mut doc = Document::with_background("indexed", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8, white); + doc.mode = ColorMode::Indexed; + doc.color_table = Some(photocraft_doc::ColorTable { colors: vec![[255, 255, 255], [0, 0, 0]], transparent: None }); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + for force_psb in [false, true] { + let written = |embed_icc| document_to_psd_with(&doc, &PsdExportOptions { embed_icc, force_psb, ..Default::default() }).unwrap().0; + let on = written(true); + assert_eq!(on.header.color_mode, PsdMode::Indexed, "psb {force_psb}"); + assert!(on.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: on"); + let off = written(false); + assert_eq!((off.header.color_mode, off.header.version == Version::Psb), (PsdMode::Indexed, force_psb)); + assert!(!off.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: off"); + } +} From 9e8827aa457fbf687177e76001624cd97dfbf3f3 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:52:56 +0100 Subject: [PATCH 21/31] Actions: an empty Content-Aware Fill step after a Custom fill stops and says why (#14254) The workspace remembers Custom sampling but not its painted area (Custom reopens empty), so an empty recorded step had no area to sample and failed with the command's parameter error. It now stops before filling with a message that says the Custom area isn't remembered and how to go on, and never falls back to another sampling area. The document and the remembered settings are unchanged. --- crates/engine-core/src/cmd/actions_cmds.rs | 2 +- .../src/cmd/atn_cmds/steps_content_aware.rs | 14 ++++++-- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 34 ++++++++++++++++--- docs/atn.md | 4 ++- 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index a64ce4009a0..6ddc1951f30 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -159,7 +159,7 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { object.remove("__atnCustom"); } if id == "edit.contentAwareFill" { - crate::atn_cmds::caf_remembered(&mut p, s.prefs()); + crate::atn_cmds::caf_remembered(&mut p, s.prefs())?; } if id == "layer.setProps" && let Some(target) = p.get("_actionLayer") diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs index 73eee2cb9d0..72f63118f76 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs @@ -3,6 +3,7 @@ use super::descriptors::{desc, enm, jstr}; use super::fields::{Mapped, step}; use super::tables::lookup_back; use super::{D, Descriptor, Map, Value}; +use crate::EngineError; const CMD: &str = "edit.contentAwareFill"; const SOURCE: &str = "_atnCafDescriptor"; @@ -99,10 +100,12 @@ fn descriptor(p: &Value) -> Option { /// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and /// before any were remembered it writes to a new layer. Playing never changes what is remembered. -pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) { - let Some(object) = p.as_object_mut() else { return }; +/// Remembered Custom sampling is refused: its area is painted in the workspace, which keeps none +/// (Custom reopens empty), and the step must not sample another area instead. +pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) -> Result<(), EngineError> { + let Some(object) = p.as_object_mut() else { return Ok(()) }; if object.remove(REMEMBERED).and_then(|v| v.as_bool()) != Some(true) { - return; + return Ok(()); } let saved = prefs.dialogs.get(CAF_WORKSPACE_PREFS); for (param, flag) in PARAMS.iter().map(|param| (*param, matches!(*param, "sampleAllLayers" | "scale" | "mirror"))) { @@ -113,6 +116,11 @@ pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) { } } object.entry("output").or_insert_with(|| "new".into()); + if object.get("sampling").and_then(Value::as_str) == Some("custom") && !["area", "channel", "samplingStrokes"].iter().any(|key| object.contains_key(*key)) { + let msg = "this step plays with the remembered settings, and their Custom sampling area isn't remembered: fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again"; + return Err(EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }); + } + Ok(()) } /// Import the verified seven-field form, retaining noncanonical wire data for an unchanged save. diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index c9b5c009af4..21f108c52bc 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -376,6 +376,27 @@ fn settings_closed_without_a_fill_are_not_carried_forward() { assert_eq!(play_empty_recorded_step(&mut restarted), 1, "New Layer: no fill has run"); } +/// After a confirmed Custom fill an empty recorded step stops and says why, instead of filling from another area: the +/// workspace remembers Custom but not its painted area (Custom reopens empty), so the step has none (#14254). +#[test] +fn an_empty_recorded_step_after_a_custom_fill_stops_and_says_why() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"sampling": "custom", "output": "current"})).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + let remembered = app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!(remembered["sampling"], "custom", "the confirmed fill remembers Custom: {remembered}"); + let revision = app.session.active().unwrap().revision; + let result = play_empty_step(&mut app); + assert_eq!(result["ran"], 0, "{result}"); + let error = result["failed"]["error"].as_str().unwrap_or_default(); + assert!(error.contains("Custom sampling area isn't remembered"), "{result}"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document is unchanged"); + assert_eq!(app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&remembered), "playing remembers nothing"); +} + /// A new app over the saved preferences `prefs`, moved as startup does. fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { let mut restarted = app_with_selection(); @@ -386,6 +407,14 @@ fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { /// Plays an action of one empty recorded Content-Aware Fill step and returns how many layers it added. fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { + let layers = app.session.active().unwrap().doc.layers.len(); + let result = play_empty_step(app); + assert_eq!(result["ran"], 1, "{result}"); + app.session.active().unwrap().doc.layers.len() - layers +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns what `actions.play` answers. +fn play_empty_step(app: &mut PhotocraftApp) -> Value { use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, UnicodeString}; let item = AtnItem { @@ -401,10 +430,7 @@ fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { }; let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); app.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - let result = app.session.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(result["ran"], 1, "{result}"); - app.session.active().unwrap().doc.layers.len() - layers + app.session.execute("actions.play", json!({"action": 0})).unwrap() } /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. diff --git a/docs/atn.md b/docs/atn.md index ba6b48e302d..87a3de37014 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -430,7 +430,9 @@ step with dialogs on (#14254); the enumeration type IDs are explicit in An empty descriptor (no keys) plays with the settings the fill workspace remembers (`prefs.dialogs["edit.contentAwareFill.workspace"]`), New Layer before any are remembered; it imports as `{"_atnCafRemembered": true}`, which `playback_params` resolves, and saves back -empty. Playing a step never changes what is remembered. +empty. Playing a step never changes what is remembered. When the remembered sampling is Custom, +the step stops with a message instead of filling: the workspace doesn't remember the painted +Custom area (Custom reopens empty), and the step must not sample another area instead. Descriptor types, source identity and key order survive save while its native settings are unchanged. Editing a supported setting exports the new values in canonical form instead of From 40491cd8da5170860e22367a9029ac1d4e58c92f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:20:38 +0100 Subject: [PATCH 22/31] Actions: the Custom-area message of an empty Content-Aware Fill step is translatable (#14254) The engine keeps its English message for automation clients, now as `atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED`. When a step fails with it, the status bar shows the shell's literal `tl!` copy instead, so the recovery instructions follow the UI language and the translation coverage report lists the key. --- crates/engine-core/src/cmd/atn_cmds.rs | 2 +- .../src/cmd/atn_cmds/steps_content_aware.rs | 6 ++++-- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 4 ++++ crates/ui-egui/src/panels/actions/runner.rs | 14 +++++++++++++- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine-core/src/cmd/atn_cmds.rs b/crates/engine-core/src/cmd/atn_cmds.rs index d626f197c06..28fa834642f 100644 --- a/crates/engine-core/src/cmd/atn_cmds.rs +++ b/crates/engine-core/src/cmd/atn_cmds.rs @@ -85,8 +85,8 @@ use events::{EVENTS, event_and_descriptor, event_for}; use fields::Mapped; use files::{load, save}; pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings}; -pub use steps_content_aware::CAF_WORKSPACE_PREFS; pub(crate) use steps_content_aware::caf_remembered; +pub use steps_content_aware::{CAF_CUSTOM_AREA_NOT_REMEMBERED, CAF_WORKSPACE_PREFS}; #[cfg(test)] use steps_doc::crop_from; pub(crate) use steps_gallery::RECORDED_EVENT; diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs index 72f63118f76..958fd1961b7 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs @@ -98,6 +98,9 @@ fn descriptor(p: &Value) -> Option { ) } +/// Why an empty recorded step refuses remembered Custom sampling ([`caf_remembered`]). The shell shows it translated. +pub const CAF_CUSTOM_AREA_NOT_REMEMBERED: &str = "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again."; + /// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and /// before any were remembered it writes to a new layer. Playing never changes what is remembered. /// Remembered Custom sampling is refused: its area is painted in the workspace, which keeps none @@ -117,8 +120,7 @@ pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) - } object.entry("output").or_insert_with(|| "new".into()); if object.get("sampling").and_then(Value::as_str) == Some("custom") && !["area", "channel", "samplingStrokes"].iter().any(|key| object.contains_key(*key)) { - let msg = "this step plays with the remembered settings, and their Custom sampling area isn't remembered: fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again"; - return Err(EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }); + return Err(EngineError::BadParams { cmd: CMD.into(), msg: CAF_CUSTOM_AREA_NOT_REMEMBERED.into() }); } Ok(()) } diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 21f108c52bc..e2d2031ac38 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -393,6 +393,10 @@ fn an_empty_recorded_step_after_a_custom_fill_stops_and_says_why() { assert_eq!(result["ran"], 0, "{result}"); let error = result["failed"]["error"].as_str().unwrap_or_default(); assert!(error.contains("Custom sampling area isn't remembered"), "{result}"); + // The status bar shows the shell's translatable copy of the message, not the engine's parameter error. + crate::actions::report_play(&mut app, &result); + let status = &app.ui.status; + assert!(status.contains(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) && !status.contains("invalid parameters"), "{status}"); assert_eq!(app.session.active().unwrap().revision, revision, "the document is unchanged"); assert_eq!(app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&remembered), "playing remembers nothing"); } diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index c97cfd1d8b9..069c15c7b50 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -655,12 +655,24 @@ pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { }; let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0); let id = failed.get("id").and_then(Value::as_str).unwrap_or(""); - let error = failed.get("error").and_then(Value::as_str).unwrap_or(""); + let error = step_error(failed.get("error").and_then(Value::as_str).unwrap_or("")); let template = "Step {step} ({id}) failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("step", &(step + 1).to_string()), ("id", id), ("error", error)]); app.ui.status_error = true; } +/// A failed step's `error` in the UI language when the engine's message is one the shell spells out, otherwise as the +/// engine gave it. Automation clients keep the engine's English. +fn step_error(error: &str) -> &str { + if error.ends_with(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) { + // The engine's text, as a literal the translation coverage report collects (#14254). + return tl!( + "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again." + ); + } + error +} + /// Resume the recording a paused call suspended and journal that call, once. fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let Some(owner) = owner else { return }; From 20d5bd0ea7e8aa4c88b095612eb316784abfbf6f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:18:50 +0100 Subject: [PATCH 23/31] Pasteboard menu: Hide/Show Contextual Task Bar heads the Move tool's menu (#16757) With the Move tool, a right-click on the pasteboard now lists Hide Contextual Task Bar (Show Contextual Task Bar while the bar is off) and a separator above the colour rows. The row runs the Window item window.panel.contextualTaskBar, so it toggles the same flag and the Window item's tick follows. Other tools keep today's menu (not measured). Fixes #16757 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 31 ++++++++- .../src/task_bar_pasteboard_entry_tests.rs | 66 +++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 98d1dbf39ed..91016f918f6 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -147,7 +147,17 @@ pub fn transform_app_rows() -> [Entry; 2] { /// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice /// Preferences › Interface also offers. The ids are this menu's own: [`choose`] turns them into /// `prefs.set` (`pasteboard.`) or opens the Color Picker. -pub const PASTEBOARD_MENU: &[Row] = &[ +pub const PASTEBOARD_MENU: &[Row] = PASTEBOARD_MOVE_MENU.split_at(2).1; + +/// The Window item the Move tool's pasteboard menu toggles the contextual task bar with (#16757). +pub const PASTEBOARD_TASK_BAR: &str = "window.panel.contextualTaskBar"; + +/// The Move tool's pasteboard menu, as measured (#16757): Hide Contextual Task Bar (Show… while the +/// bar is off, [`row_label`]) and a separator above the colour rows. Other tools weren't measured and +/// keep [`PASTEBOARD_MENU`]. +pub const PASTEBOARD_MOVE_MENU: &[Row] = &[ + Some(("Hide Contextual Task Bar", PASTEBOARD_TASK_BAR)), + None, Some(("Default", "pasteboard.default")), Some(("Black", "pasteboard.black")), Some(("Dark Gray", "pasteboard.darkGray")), @@ -897,6 +907,9 @@ pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'sta if menu.tool == Tool::AddAnchorPoint { return add_anchor_row_label(app, menu, label, command); } + if command == PASTEBOARD_TASK_BAR && !app.ui.panels.context_task_bar { + return "Show Contextual Task Bar"; + } if command != "path.transform" || !matches!(menu.tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { return label; } @@ -1178,6 +1191,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { match &menu.kind { MenuKind::Crop { .. } | MenuKind::Layers { .. } | MenuKind::BrushMode { .. } => &[], MenuKind::Guide => GUIDE_MENU, + MenuKind::Pasteboard if menu.tool == Tool::Move => PASTEBOARD_MOVE_MENU, MenuKind::Pasteboard => PASTEBOARD_MENU, MenuKind::View => { if menu.tool == Tool::Hand { @@ -1410,8 +1424,13 @@ fn choose_guide(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()) } -/// A pasteboard row: set the colour, or open the Color Picker on the custom one. +/// A pasteboard row: set the colour, open the Color Picker on the custom one, or run the Window +/// item that hides or shows the contextual task bar. fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if command == PASTEBOARD_TASK_BAR { + let ctx = app.ctx().clone(); + return crate::menus::invoke(app, &ctx, command, json!({})).map(|_| ()); + } if command == PASTEBOARD_PICK { let rgb = prefs::parse_hex(&app.session.prefs().interface.canvas_custom_color).map_or([0.5; 3], |c| c.map(|v| f32::from(v) / 255.0)); crate::color_picker_ui::open_for_target(app, "pasteboard", "Color Picker (Custom Canvas Color)", rgb)?; @@ -1430,7 +1449,7 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) _ => GUIDE_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command), }; } - MenuKind::Pasteboard => return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command), + MenuKind::Pasteboard => return rows(menu).iter().flatten().any(|(_, id)| *id == command), MenuKind::View if command == "view.fillScreen" => return app.session.active().is_some(), MenuKind::View => return crate::menus::is_enabled(app, command), MenuKind::TypeEdit { .. } => { @@ -1912,6 +1931,8 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec> "Duplicate Layers…" => tl!("Duplicate Layers…"), "Delete Layers" => tl!("Delete Layers"), "Rasterize Layers" => tl!("Rasterize Layers"), + "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), + "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), key => tl!(key), }; out.push(Entry::new(command.to_string(), text.to_string()).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); @@ -1994,6 +2015,10 @@ mod cam_menu_tests; #[cfg(test)] pub(crate) mod tests; +#[cfg(test)] +#[path = "../task_bar_pasteboard_entry_tests.rs"] +mod task_bar_pasteboard_entry_tests; + #[cfg(test)] pub(crate) mod count_tests; diff --git a/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs new file mode 100644 index 00000000000..f88e7fdbbbd --- /dev/null +++ b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs @@ -0,0 +1,66 @@ +//! #16757: with the Move tool, the pasteboard's right-click menu starts with Hide Contextual Task Bar +//! (Show Contextual Task Bar while the bar is off) and a separator, and the row toggles the same flag +//! as Window › Contextual Task Bar. + +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::canvas_tool_menu::tests::{harness, right_click}; +use crate::state::Tool; + +fn app(tool: Tool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = tool; + app +} + +/// Right-clicks the pasteboard and returns the open menu's rows, a separator as `None`. +fn pasteboard_rows(h: &mut Harness<'static, Box>) -> Vec> { + let pasteboard = h.state().last_canvas_rect.min + vec2(5.0, 5.0); + right_click(h, pasteboard, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["pasteboard"], json!(true), "the pasteboard menu opens"); + let entries = inspected["canvasToolMenu"]["entries"].as_array().expect("pasteboard menu entries"); + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(str::to_owned) }).collect() +} + +#[test] +fn the_move_tools_pasteboard_menu_starts_with_the_task_bar_row() { + let mut marquee = harness(app(Tool::RectMarquee)); + let today = pasteboard_rows(&mut marquee); + assert!(!today.iter().flatten().any(|label| label.contains("Contextual Task Bar")), "other tools keep today's menu: {today:?}"); + + let mut h = harness(app(Tool::Move)); + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Hide Contextual Task Bar".to_owned())), "{rows:?}"); + assert_eq!(rows.get(1), Some(&None), "a separator under it: {rows:?}"); + assert_eq!(rows[2..], today[..], "then today's colour rows"); +} + +#[test] +fn the_task_bar_row_hides_and_shows_the_bar_as_the_window_item_does() { + let mut h = harness(app(Tool::Move)); + assert!(h.state().ui.panels.context_task_bar); + + pasteboard_rows(&mut h); + h.get_by_label("Hide Contextual Task Bar").click(); + h.run_steps(2); + assert!(!h.state().ui.panels.context_task_bar, "the row hides the bar"); + assert!(h.state().ui.canvas_tool_menu.is_none(), "and closes the menu"); + // The Window item toggles the same flag: one press turns the bar back on, and off again. + let ctx = h.ctx.clone(); + let window_item = + |h: &mut Harness<'static, Box>| crate::menus::invoke(h.state_mut(), &ctx, "window.panel.contextualTaskBar", json!({})).unwrap(); + assert_eq!(window_item(&mut h), json!(true)); + assert_eq!(window_item(&mut h), json!(false)); + + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Show Contextual Task Bar".to_owned())), "{rows:?}"); + h.get_by_label("Show Contextual Task Bar").click(); + h.run_steps(2); + assert!(h.state().ui.panels.context_task_bar, "the row shows the bar again"); +} From b59300ba2fc84ce94dccf372892771c80716bdf4 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Thu, 26 Nov 2026 14:03:01 +0000 Subject: [PATCH 24/31] Window > Arrange: match measured order and active document label (#16888) Reorder the Window > Arrange submenu entries and separators to match the measured layout (Horizontal before Vertical for 2-up and 3-up, Consolidate All to Tabs with the layout group, Float entries grouped with Cascade/Tile, and New Window after Match All). Label the final entry "New Window for " through the translation catalog with English fallback. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- crates/ui-egui/src/menu_catalog.rs | 11 +-- crates/ui-egui/src/menus.rs | 3 + .../src/menus/arrange_menu_order_tests.rs | 92 +++++++++++++++++++ crates/ui-egui/src/menus/items.rs | 6 ++ crates/ui-egui/src/menus/state.rs | 5 + 5 files changed, 111 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/menus/arrange_menu_order_tests.rs diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 4fb2750e5fe..6b7d71db4f4 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -741,27 +741,26 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["View"], "Pixel Art Preview", None, "view.pixelArtPreview"), (&["Window", "Arrange"], "Tile All Vertically", None, "window.arrange.tileAllVertically"), (&["Window", "Arrange"], "Tile All Horizontally", None, "window.arrange.tileAllHorizontally"), - (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "2-up Horizontal", None, "window.arrange.twoUpHorizontal"), - (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), + (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "3-up Horizontal", None, "window.arrange.threeUpHorizontal"), + (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), (&["Window", "Arrange"], "3-up Stacked", None, "window.arrange.threeUpStacked"), (&["Window", "Arrange"], "4-up", None, "window.arrange.fourUp"), (&["Window", "Arrange"], "6-up", None, "window.arrange.sixUp"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Consolidate All to Tabs", None, "window.arrange.consolidateAllToTabs"), + (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Cascade", None, "window.arrange.cascade"), (&["Window", "Arrange"], "Tile", None, "window.arrange.tile"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Float in Window", None, "window.arrange.floatInWindow"), (&["Window", "Arrange"], "Float All in Windows", None, "window.arrange.floatAllInWindows"), (&["Window", "Arrange"], "---", None, "---"), - (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Match Zoom", None, "window.arrange.matchZoom"), (&["Window", "Arrange"], "Match Location", None, "window.arrange.matchLocation"), (&["Window", "Arrange"], "Match Rotation", None, "window.arrange.matchRotation"), (&["Window", "Arrange"], "Match All", None, "window.arrange.matchAll"), + (&["Window", "Arrange"], "---", None, "---"), + (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), (&["Window", "Workspace"], "Essentials", None, "window.workspace.essentials"), (&["Window", "Workspace"], "Photography", None, "window.workspace.photography"), (&["Window", "Workspace"], "Painting", None, "window.workspace.painting"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9da031f57b6..2f62301eb7e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -118,6 +118,9 @@ mod open_recent_position_tests; #[cfg(test)] mod export_submenu_separator_tests; +#[cfg(test)] +mod arrange_menu_order_tests; + #[cfg(test)] mod bar_cursor_tests; diff --git a/crates/ui-egui/src/menus/arrange_menu_order_tests.rs b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs new file mode 100644 index 00000000000..51a6ebb728a --- /dev/null +++ b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs @@ -0,0 +1,92 @@ +//! Window › Arrange: measured entry order, separators, and dynamic "New Window for " label (#16888). + +use serde_json::json; + +use super::*; + +#[cfg(not(target_arch = "wasm32"))] +fn new_doc(app: &mut PhotocraftApp, name: &str) { + app.run("file.new", json!({"width": 64, "height": 64, "name": name})).unwrap(); +} + +/// The `Window › Arrange` entries returned by `ui.menu.list` as `(id, label, shortcut)`. +#[cfg(not(target_arch = "wasm32"))] +fn arrange_list(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<(String, String, Option)> { + let (req, _rx) = crate::control::ControlRequest::new("ui.menu.list", json!({})); + let reply = match crate::control::handle(app, ctx, &req) { + crate::control::Reply::Done(v) => v, + _ => panic!("ui.menu.list: expected an immediate reply"), + }; + reply["result"] + .as_array() + .expect("ui.menu.list returns an array") + .iter() + .filter(|it| it["path"] == json!(["Window", "Arrange"])) + .map(|it| { + let label = it["label"].as_str().unwrap_or_default().to_string(); + let id = if label == "---" { "---".to_string() } else { it["id"].as_str().unwrap_or_default().to_string() }; + let shortcut = it["shortcut"].as_str().map(str::to_string); + (id, label, shortcut) + }) + .collect() +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn arrange_menu_matches_measured_order_and_active_document_label() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + + // Without a document open, the final entry keeps its plain fallback label. + let empty = arrange_list(&mut app, &ctx); + assert_eq!(empty.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window"))); + + new_doc(&mut app, "W1"); + let got = arrange_list(&mut app, &ctx); + let expected: &[(&str, &str)] = &[ + ("window.arrange.tileAllVertically", "Tile All Vertically"), + ("window.arrange.tileAllHorizontally", "Tile All Horizontally"), + ("window.arrange.twoUpHorizontal", "2-up Horizontal"), + ("window.arrange.twoUpVertical", "2-up Vertical"), + ("window.arrange.threeUpHorizontal", "3-up Horizontal"), + ("window.arrange.threeUpVertical", "3-up Vertical"), + ("window.arrange.threeUpStacked", "3-up Stacked"), + ("window.arrange.fourUp", "4-up"), + ("window.arrange.sixUp", "6-up"), + ("window.arrange.consolidateAllToTabs", "Consolidate All to Tabs"), + ("---", "---"), + ("window.arrange.cascade", "Cascade"), + ("window.arrange.tile", "Tile"), + ("window.arrange.floatInWindow", "Float in Window"), + ("window.arrange.floatAllInWindows", "Float All in Windows"), + ("---", "---"), + ("window.arrange.matchZoom", "Match Zoom"), + ("window.arrange.matchLocation", "Match Location"), + ("window.arrange.matchRotation", "Match Rotation"), + ("window.arrange.matchAll", "Match All"), + ("---", "---"), + ("window.arrange.newWindowForDocument", "New Window for W1"), + ]; + let pairs: Vec<(&str, &str)> = got.iter().map(|(id, label, _)| (id.as_str(), label.as_str())).collect(); + assert_eq!(pairs, expected); + assert!(got.iter().all(|(_, _, shortcut)| shortcut.is_none()), "no Window › Arrange entry carries a shortcut: {got:?}"); + + // Activating another document updates the dynamic label while keeping the command id. + new_doc(&mut app, "W2"); + let second = arrange_list(&mut app, &ctx); + assert_eq!(second.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W2"))); + + app.session.set_active(0); + let back = arrange_list(&mut app, &ctx); + assert_eq!(back.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W1"))); +} + +#[test] +fn new_window_for_document_label_uses_translation_catalog_with_english_fallback() { + let translated = crate::i18n::fixture_lang("fr", "\tNew Window for {name}\tNouvelle fenêtre pour {name}\n"); + let missing = crate::i18n::fixture_lang("fr", ""); + + assert_eq!(translated_menu_label(translated, "window.arrange.newWindowForDocument", "New Window for W1"), "Nouvelle fenêtre pour W1"); + assert_eq!(translated_menu_label(missing, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); + assert_eq!(translated_menu_label(crate::i18n::Lang::EN, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 35685a392c7..767b0cf9207 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -258,6 +258,12 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { if let Some(item) = find(&mut rows, "layer.smartObjects.revealInFinder") { item.label = reveal_label().into(); } + // Window › Arrange › New Window names the active document (#16888). + if let Some(st) = app.session.active() + && let Some(item) = find(&mut rows, "window.arrange.newWindowForDocument") + { + item.label = format!("New Window for {}", st.doc.name); + } // File › Open Recent: a dynamic submenu of recently opened files, after Open as Smart Object… (#14053). if let Some(after) = rows.iter().position(|i| i.command.id == "file.openAsSmartObject").or_else(|| rows.iter().position(|i| i.command.id == "file.openAs")) { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index bf3cd0c253e..05acaf57555 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -235,5 +235,10 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, id: &str, label: &s { return crate::i18n::tr_id(lang, id, "Quick Export as PNG").replace("PNG", fmt); } + if id == "window.arrange.newWindowForDocument" + && let Some(name) = label.strip_prefix("New Window for ") + { + return crate::i18n::fmt(crate::i18n::tr(lang, "New Window for {name}"), &[("name", name)]); + } crate::i18n::tr_id(lang, id, label).to_string() } From d2dec04f01e1c8732b8fa099bdddd719356dcc6b Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 26 Nov 2026 18:27:10 +0000 Subject: [PATCH 25/31] Invalidate group effect maps when a child changes type --- crates/compose/src/fx_cache.rs | 2 ++ crates/compose/src/tests.rs | 23 +++++++++++++++++++++++ crates/gpu/src/fx.rs | 1 + 3 files changed, 26 insertions(+) diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 99208407c4a..e5c0b0cf13f 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -30,6 +30,8 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map:: h.finish() } layer.id.0.hash(h); + // The same display surface can blend differently before and after rasterizing a text child. + std::mem::discriminant(&layer.content).hash(h); // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the // maps are composited and `visible` only skips the lookup entirely, so neither belongs in // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 733ea78f7a3..59ca1c007c7 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4406,6 +4406,29 @@ fn effect_cache_follows_a_group_childs_blend_if() { assert!(warm.px == cold.px, "stale group effect maps after a child's Blend If changed"); } +#[test] +fn effect_cache_follows_a_group_child_being_rasterized() { + let mut doc = doc_white(32, 32); + let rect = Rect::new(4, 4, 16, 20); + let bottom = solid_layer("pale", rect, [1.0, 1.0, 1.0, 0.5]); + let mut text = solid_layer("text", rect, [0.0, 0.0, 0.0, 0.5]); + let raster = text.content.clone(); + text.content = LayerContent::Text(photocraft_doc::TextLayer { cache: text.surface().cloned(), ..Default::default() }); + let mut top = solid_layer("blend if", rect, [0.2, 0.6, 0.0, 1.0]); + top.blend_if.set(0, [FULL, range([0, 0], [100, 100])]); + let mut group = Layer::group("group", vec![bottom, text, top]); + group.effects.items = vec![Effect::DropShadow(Shadow { size: 2.0, spread: 0.0, ..shadow(3.0, 90.0) })]; + doc.layers.push(group); + let before = render(&doc, doc.bounds()); + let LayerContent::Group(group) = &mut doc.layers[1].content else { unreachable!() }; + group.children[1].content = raster; + let warm = render(&doc, doc.bounds()); + purge_effect_cache(); + let cold = render(&doc, doc.bounds()); + assert!((0..32).any(|y| (0..32).any(|x| !rect.contains(x, y) && before.get(x, y) != cold.get(x, y))), "the group's shadow changes"); + assert!(warm.px == cold.px, "rasterization must invalidate the group's shadow map"); +} + /// A document whose one-colour areas are found: shared background tiles, a painted patch over /// tile edges, a uniform mask tile, an adjustment, a group, a 16-bit layer and a hidden one. fn sparse_doc(w: u32, h: u32) -> Document { diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 2139025f94e..0c74b4df29f 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -573,6 +573,7 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( } fn walk(l: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: Pin) { l.id.0.hash(h); + std::mem::discriminant(&l.content).hash(h); (l.visible, l.clipped, l.opacity.to_bits(), l.fill_opacity.to_bits(), format!("{:?}", l.blend)).hash(h); match &l.content { LayerContent::Group(g) => { From 9f81f17b2d8452b152f4850d76964b00f46932f9 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 26 Nov 2026 18:46:07 +0000 Subject: [PATCH 26/31] Use document layer lookup in the cache regression --- crates/compose/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 59ca1c007c7..c886bcedde5 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4413,6 +4413,7 @@ fn effect_cache_follows_a_group_child_being_rasterized() { let bottom = solid_layer("pale", rect, [1.0, 1.0, 1.0, 0.5]); let mut text = solid_layer("text", rect, [0.0, 0.0, 0.0, 0.5]); let raster = text.content.clone(); + let text_id = text.id; text.content = LayerContent::Text(photocraft_doc::TextLayer { cache: text.surface().cloned(), ..Default::default() }); let mut top = solid_layer("blend if", rect, [0.2, 0.6, 0.0, 1.0]); top.blend_if.set(0, [FULL, range([0, 0], [100, 100])]); @@ -4420,8 +4421,7 @@ fn effect_cache_follows_a_group_child_being_rasterized() { group.effects.items = vec![Effect::DropShadow(Shadow { size: 2.0, spread: 0.0, ..shadow(3.0, 90.0) })]; doc.layers.push(group); let before = render(&doc, doc.bounds()); - let LayerContent::Group(group) = &mut doc.layers[1].content else { unreachable!() }; - group.children[1].content = raster; + doc.layer_mut(text_id).unwrap().content = raster; let warm = render(&doc, doc.bounds()); purge_effect_cache(); let cold = render(&doc, doc.bounds()); From 752d83c07888cd1a535b7c7c80344772401fe74a Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 22:28:42 +0100 Subject: [PATCH 27/31] test(retouch): the Healing Brush Replace stroke copies its source exactly (#12101) Red: `paint.healingBrush {"mode":"replace"}` is refused today ("unknown blend mode `replace`"). The new file pins what the ticket measures: every pixel the hard tip covers fully equals the source pixel mapped there, bit for bit, taken from the document state before the stroke; Normal's healed pixels are pinned byte for byte; an unknown mode string stays an error; and one Replace stroke is one History step named "Healing Brush". --- .../engine-paint/src/cmd/retouch_cmds/heal.rs | 4 + .../cmd/retouch_cmds/heal_replace_tests.rs | 124 ++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index 642f8cd211b..373853abcb2 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -314,3 +314,7 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { #[cfg(test)] #[path = "heal_indexed_tests.rs"] mod heal_indexed_tests; + +#[cfg(test)] +#[path = "heal_replace_tests.rs"] +mod heal_replace_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs new file mode 100644 index 00000000000..fc1558744f0 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs @@ -0,0 +1,124 @@ +//! #12101: the Healing Brush's Replace mode. `paint.healingBrush {"mode":"replace"}` copies the +//! source pixels straight onto the layer: no healing solve, Normal compositing. Every covered pixel +//! equals the source pixel the stroke maps there, bit for bit, as read from the document's state +//! before the stroke. The other modes keep their results; an unknown `mode` string stays an error, +//! and the stroke's History step keeps the name "Healing Brush". + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Size; + +use super::*; + +/// The test document: green 40,160,60 throughout with a 20 x 20 checker at 6,6 (5 px cells +/// alternating 60,60,60 / 200,200,200). The source patch and the click sit far apart, so a +/// straight copy and a heal cannot agree anywhere inside the dab. +fn document() -> Session { + let mut s = crate::session(); + s.add_document(Document::with_background("t", Size::new(48, 48), ColorMode::Rgb, SampleType::U8, Color::rgb(40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0)), None); + for cx in 0..4 { + for cy in 0..4 { + let color = if (cx + cy) % 2 == 0 { "#3c3c3c" } else { "#c8c8c8" }; + s.execute("select.rect", json!({"x": 6 + 5 * cx, "y": 6 + 5 * cy, "width": 5, "height": 5})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// One click at 30,24 with a 20 px hard round tip; the source point 16,16 is sampled under it. +fn stroke(mode: Option<&str>) -> Value { + let mut p = json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100}); + if let Some(m) = mode { + p["mode"] = json!(m); + } + p +} + +fn pixels(s: &Session) -> Vec { + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + (0..48).flat_map(|y| (0..48).flat_map(move |x| surf.pixel(x, y))).collect() +} + +/// The pixel of the Background at (`x`, `y`). +fn pixel(s: &Session, x: i32, y: i32) -> Vec { + let st = s.active().unwrap(); + st.doc.layers[0].surface().unwrap().pixel(x, y) +} + +#[test] +fn replace_paints_the_source_pixels_bit_for_bit() { + let mut s = document(); + let before = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + s.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush"), "the stroke's History name"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "the stroke is one step"); + // Every pixel the hard tip covers fully (7 px of the 10 px radius, away from the antialiased + // rim) is the source pixel mapped there, bit for bit; the samples are the pre-stroke pixels. + let green: Vec = vec![40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0, 1.0]; + let ch = pixel(&s, 0, 0).len(); + let src = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * ch; + before[at..at + ch].to_vec() + }; + let mut inside = 0; + for dy in -7..=7 { + for dx in -7..=7 { + if dx * dx + dy * dy > 49 { + continue; + } + let (x, y) = (30 + dx, 24 + dy); + assert_eq!(pixel(&s, x, y), src(x - 14, y - 8), "({x}, {y}) inside the Replace dab"); + inside += 1; + } + } + assert!(inside > 0, "the dab covers pixels"); + // Outside the tip nothing changed: the dab's edge is 10 px away, these are 13. + assert_eq!(pixel(&s, 43, 24), green, "right of the dab"); + assert_eq!(pixel(&s, 30, 37), green, "below the dab"); +} + +#[test] +fn an_unknown_mode_is_an_error_and_paints_nothing() { + let mut s = document(); + let before = (pixels(&s), s.active().unwrap().history.past_len()); + let err = s.execute("paint.healingBrush", stroke(Some("threshold"))).unwrap_err().to_string(); + assert!(err.contains("unknown blend mode `threshold`"), "{err}"); + assert_eq!((pixels(&s), s.active().unwrap().history.past_len()), (before.0.clone(), before.1), "nothing painted, no step"); +} + +#[test] +fn replace_is_the_healing_brush_command_s_alone() { + let mut s = document(); + let err = s.execute("paint.cloneStamp", json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100, "mode": "replace"})).unwrap_err().to_string(); + assert!(err.contains("unknown blend mode `replace`"), "the Clone Stamp still refuses it: {err}"); + // The live stroke parser reads the same mode: a Healing live stroke starts with Replace. + crate::cmd::retouch_cmds::clone::LiveRetouch::begin(&s, "paint.healingBrush", &stroke(Some("replace"))).unwrap(); + // And the blend parameter itself: Normal compositing for the Healing Brush, nothing else. + assert_eq!(blend_param(&json!({"mode": "replace"}), "paint.healingBrush").unwrap(), BlendMode::Normal); + assert!(blend_param(&json!({"mode": "replace"}), "paint.cloneStamp").is_err()); + assert!(blend_param(&json!({"mode": "Replace"}), "paint.healingBrush").is_err(), "the exact lowercase string only"); +} + +#[test] +fn normal_heals_the_same_pixels_as_before() { + // Pin the healed (not copied) result byte for byte: the values from main 984c304b20. If one of + // these moves, a mode the ticket leaves alone moved with it. + let mut s = document(); + s.execute("paint.healingBrush", stroke(Some("normal"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush")); + let q = |v: f32| (v * 255.0).round() as i32; + let pts = [(30, 24), (34, 26), (26, 22), (24, 24)]; + let got: Vec> = pts.iter().map(|(x, y)| pixel(&s, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + // The values main 984c304b20 gives on this document (R, G, B, A in 8-bit levels). + let pinned: Vec> = vec![vec![62, 56, 61, 255], vec![57, 63, 58, 255], vec![77, 49, 73, 255], vec![82, 53, 77, 255]]; + assert_eq!(got, pinned, "the Normal result is pinned"); + // Replace on the same document gives different pixels than Normal: the straight copy and the + // blend are visibly two different strokes. + let mut r = document(); + r.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + let replaced: Vec> = pts.iter().map(|(x, y)| pixel(&r, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + assert_ne!(got, replaced, "Replace is not Normal"); +} From de75f4764418ad0d29b6b883f79fd31dc066a57e Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 22:29:42 +0100 Subject: [PATCH 28/31] feat(retouch): paint.healingBrush accepts mode "replace" as a straight source copy (#12101) The Healing Brush's Replace row, measured in the reference application: the stroke copies the source pixels with no healing solve, composited through Normal. `blend_param` accepts the exact word "replace" for `paint.healingBrush` alone, so the live stroke parser starts too (its texture preview already draws what Replace commits); every other command keeps refusing it, and an unknown mode string stays an error. `healing_brush` reads the word from the params and paints the sampled source region as it stands: the Normal and other modes run the unchanged solve path, pinned pixel-for-pixel by the tests. --- .../src/cmd/retouch_cmds/clone.rs | 5 +++ .../engine-paint/src/cmd/retouch_cmds/heal.rs | 43 ++++++++++++------- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs index 59c39ab183e..201990dfc21 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs @@ -212,6 +212,11 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { match p.get("mode").and_then(Value::as_str) { None => Ok(BlendMode::Normal), + // The Healing Brush's Replace row (#12101) is not a blend mode: the stroke copies the + // source, which `healing_brush` reads from the params itself. Here it only opens the live + // preview, whose texture the Replace stroke draws as it stands, through Normal. Every other + // command keeps refusing the word. + Some("replace") if cmd == "paint.healingBrush" => Ok(BlendMode::Normal), Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), } } diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index 373853abcb2..db5a0e3fe72 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -58,6 +58,10 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let which = sample_layers(p, CMD)?; let source = super::clone_sampling::resolve(s, p, CMD)?; let mode = blend_param(p, CMD)?; + // The options bar's Replace row (#12101): the stroke copies the source pixels without the + // healing solve, composited through `mode` (Normal). It is the command's word, not a blend + // mode; `blend_param` already accepted it for this command alone. + let replace = p.get("mode").and_then(Value::as_str) == Some("replace"); let aligned = flag(p, "aligned", true); let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); @@ -69,27 +73,34 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let (g, cov) = pad_coverage(bounds, &cov, 2); let fmt = source.sample_format(surf); let src = clone_sample(pre, id, surf, which, &source, g, &map, wrap, CMD)?; - // The destination the texture is fitted to: the layer itself, or what the user sees when - // sampling several layers (so healing onto an empty layer matches the composite). - let dst = if wrap { - periodic::sample(pre, id, surf, which, g, CMD)? - } else if which == SampleLayers::Current { - Region::read(surf, g) - } else { - composite_region(pre, id, which, g, surf.format()) - }; - let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; // The solver can reconstruct positive alpha from the destination boundary even where // no source pixel exists. Keep source availability separate from the solved channels. let alpha = super::alpha_index(&fmt); let has_source = |pixel: &[f32]| alpha.is_none_or(|a| pixel.get(a).is_some_and(|value| *value > 0.0)); - let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); - let mut healed = heal_region(&fmt, &src, &dst, &mask); - for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { - if !has_source(sample) { - pixel.fill(0.0); + let healed = if replace { + // Replace (#12101): the sampled source as it stands, no solve against the + // destination. Pixels with no source stay transparent, as they do through the solver. + src + } else { + // The destination the texture is fitted to: the layer itself, or what the user sees when + // sampling several layers (so healing onto an empty layer matches the composite). + let dst = if wrap { + periodic::sample(pre, id, surf, which, g, CMD)? + } else if which == SampleLayers::Current { + Region::read(surf, g) + } else { + composite_region(pre, id, which, g, surf.format()) + }; + let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; + let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); + let mut healed = heal_region(&fmt, &src, &dst, &mask); + for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { + if !has_source(sample) { + pixel.fill(0.0); + } } - } + healed + }; if wrap { return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| { let part = healed.crop(r); From 5cb23ca42ad50936fd3df36f7cec18eed042f2ec Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 22:55:35 +0100 Subject: [PATCH 29/31] feat(ui): the Healing Brush Mode menus gain Replace and the reference's rules (#12101) Both measured menus, options bar dropdown and Shift+right-click, now list Normal, Replace, a rule, Multiply, Screen, Darken, Lighten, a rule, Color, Luminosity. Replace is a Healing Brush tool option, like the painting tools' Clear flags: picking it runs no command and adds no History step, and the stroke params carry mode:"replace" to the engine commit this branch adds. The seven blend modes, their keyboard letters, the step cycle and Reset Tool keep their meanings; the new option resets with the Healing Brush. --- crates/ui-egui/src/brush_mode_menu.rs | 39 ++++++- .../ui-egui/src/canvas/paint_mouse/tests.rs | 2 +- crates/ui-egui/src/healing_mode_menu_tests.rs | 110 ++++++++++++++++++ crates/ui-egui/src/input/blend_keys.rs | 8 +- crates/ui-egui/src/panels/options_bar.rs | 46 +++++--- crates/ui-egui/src/panels/options_bar/fill.rs | 22 ++++ .../ui-egui/src/panels/options_bar/paint.rs | 7 ++ crates/ui-egui/src/state/tool_options.rs | 4 + crates/ui-egui/src/tools/retouch_ui.rs | 5 + crates/ui-egui/src/tools/tool_reset.rs | 2 +- 10 files changed, 224 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/src/healing_mode_menu_tests.rs diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 4b1637a3367..8064d1ba62d 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -20,6 +20,9 @@ pub(crate) enum Item { Separator, /// The tool's blend mode. Blend(BlendMode), + /// The Healing Brush's Replace row (#12101): copy the source without healing. It is not a + /// blend mode: the stroke sends it as a mode word, and the keys and the ⇧+ / ⇧− cycle skip it. + HealingReplace, /// Painting-only: paint behind the layer's pixels (Brush, Pencil and Pattern Stamp). Behind, /// Painting-only: paint transparency (Brush, Pencil, Paint Bucket). @@ -39,6 +42,7 @@ impl Item { Item::EditBrush => "Edit Brush…", Item::Separator => return None, Item::Blend(m) => m.label(), + Item::HealingReplace => "Replace", Item::Behind => "Behind", Item::Clear => "Clear", Item::Eraser(m) => match m { @@ -98,8 +102,8 @@ fn blend_items(behind: bool, clear: bool) -> Vec { /// `tool`'s menu, top to bottom. Empty for a tool without one (its Shift+right-click keeps its /// other route). Only what the tool's options bar offers is listed: the reference application's -/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and Smudge -/// modes, the Spot Healing modes and the Healing Brush's source and Replace have no setting here. +/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and +/// Smudge modes, the Spot Healing modes and the Healing Brush's source have no setting here. pub(crate) fn items(tool: Tool) -> Vec { let with_brush = |rest: Vec| std::iter::once(Item::EditBrush).chain(std::iter::once(Item::Separator)).chain(rest).collect::>(); match tool { @@ -110,7 +114,22 @@ pub(crate) fn items(tool: Tool) -> Vec { Tool::Eraser => ["brush", "pencil", "block"].into_iter().map(Item::Eraser).collect(), Tool::Dodge | Tool::Burn => with_brush(["shadows", "midtones", "highlights"].into_iter().map(Item::Range).collect()), Tool::Sponge => with_brush(["desaturate", "saturate"].into_iter().map(Item::Sponge).collect()), - Tool::Healing => crate::blend_keys::HEALING_MODES.into_iter().map(Item::Blend).collect(), + // The measured list (#12101): Replace after Normal, rules before Multiply and before Color. + Tool::Healing => { + use BlendMode::*; + vec![ + Item::Blend(Normal), + Item::HealingReplace, + Item::Separator, + Item::Blend(Multiply), + Item::Blend(Screen), + Item::Blend(Darken), + Item::Blend(Lighten), + Item::Separator, + Item::Blend(Color), + Item::Blend(Luminosity), + ] + } Tool::Gradient => blend_items(false, false), Tool::PaintBucket => blend_items(false, true), _ => Vec::new(), @@ -151,7 +170,15 @@ pub(crate) fn current(app: &PhotocraftApp, tool: Tool) -> Option { Tool::Brush => painting(o.brush_clear), Tool::Pencil => painting(o.pencil_clear), Tool::PatternStamp => painting(false), - Tool::CloneStamp | Tool::HistoryBrush | Tool::Healing => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + Tool::CloneStamp | Tool::HistoryBrush => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + // Replace wins over the brush's blend mode: it is the row the tool option selects (#12101). + Tool::Healing => { + if o.healing_replace { + Item::HealingReplace + } else { + Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + } + } Tool::Gradient => Item::Blend(o.gradient_blend_mode), Tool::PaintBucket if o.bucket_clear => Item::Clear, Tool::PaintBucket => Item::Blend(o.bucket_blend_mode), @@ -231,6 +258,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Ok(_) => match tool { Tool::Brush => app.ui.tool_options.brush_clear = item == Item::Clear, Tool::Pencil => app.ui.tool_options.pencil_clear = item == Item::Clear, + // Any of the seven blend modes leaves Replace (#12101). + Tool::Healing => app.ui.tool_options.healing_replace = false, _ => {} }, Err(e) => app.ui.status = e, @@ -246,6 +275,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Item::Eraser(m) => app.ui.tool_options.eraser_mode = m.into(), Item::Range(r) => app.ui.tool_options.tone_range = r.into(), Item::Sponge(m) => app.ui.tool_options.sponge_mode = m.into(), + // Replace is a tool option: it runs no command and adds no History step (#12101). + Item::HealingReplace if tool == Tool::Healing => app.ui.tool_options.healing_replace = true, Item::Blend(m) if tool == Tool::Gradient => crate::blend_keys::set_gradient_mode(app, m), Item::Blend(m) if tool == Tool::PaintBucket => { app.ui.tool_options.bucket_clear = false; diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 0372fbe0812..0bcf80cbfca 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -509,7 +509,7 @@ fn shift_right_menu_lists_each_tools_own_rows_in_order() { (Tool::Sponge, edit(vec!["Desaturate", "Saturate"])), (Tool::PaintBucket, with(&["Clear"])), (Tool::MixerBrush, vec!["Edit Brush…"]), - (Tool::Healing, vec!["Normal", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"]), + (Tool::Healing, vec!["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"]), (Tool::SpotHealing, vec![]), (Tool::MagicEraser, vec![]), ] { diff --git a/crates/ui-egui/src/healing_mode_menu_tests.rs b/crates/ui-egui/src/healing_mode_menu_tests.rs new file mode 100644 index 00000000000..c92ae1c8eea --- /dev/null +++ b/crates/ui-egui/src/healing_mode_menu_tests.rs @@ -0,0 +1,110 @@ +//! #12101: the Healing Brush's Mode menus gain Replace and the reference's two separators, in the +//! measured order Normal, Replace, separator, Multiply, Screen, Darken, Lighten, separator, Color, +//! Luminosity. Picking Replace is a tool option only: it adds no History step, sends +//! `mode:"replace"` on the next stroke, and any other mode pick leaves it. The keyboard cycle +//! stays inside the seven blend modes. + +use craft::ui::patterns::blend_keys::{BlendShortcut, BlendStep}; +use photocraft_color::BlendMode; +use serde_json::json; + +use super::PaintMode; +use super::fill::mode_entries; +use crate::blend_keys::{fired, test_fired}; +use crate::brush_mode_menu::{Item, current, items, labels}; +use crate::state::Tool; +use crate::{PhotocraftApp, brush_mode_menu}; + +/// The measured row order of the canvas Shift+right-click menu, separators in place. +const MENU_ROWS: [Item; 10] = [ + Item::Blend(BlendMode::Normal), + Item::HealingReplace, + Item::Separator, + Item::Blend(BlendMode::Multiply), + Item::Blend(BlendMode::Screen), + Item::Blend(BlendMode::Darken), + Item::Blend(BlendMode::Lighten), + Item::Separator, + Item::Blend(BlendMode::Color), + Item::Blend(BlendMode::Luminosity), +]; + +/// The same list as the options bar dropdown's entry values (`None` is a rule). +const BAR_ROWS: [Option; 10] = [ + Some(PaintMode::Blend(BlendMode::Normal)), + Some(PaintMode::HealingReplace), + None, + Some(PaintMode::Blend(BlendMode::Multiply)), + Some(PaintMode::Blend(BlendMode::Screen)), + Some(PaintMode::Blend(BlendMode::Darken)), + Some(PaintMode::Blend(BlendMode::Lighten)), + None, + Some(PaintMode::Blend(BlendMode::Color)), + Some(PaintMode::Blend(BlendMode::Luminosity)), +]; + +#[test] +fn both_healing_mode_lists_show_replace_and_the_two_separators() { + assert_eq!(items(Tool::Healing), MENU_ROWS, "the Shift+right-click menu rows"); + assert_eq!(labels(Tool::Healing), ["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"], "the labels, separators left out"); + let entries = mode_entries(Tool::Healing, true, false); + let values: Vec> = entries.iter().map(|e| e.value().cloned()).collect(); + assert_eq!(values, BAR_ROWS, "the options bar dropdown"); + // Another tool's list is untouched by this: the Clone Stamp keeps the layer modes. + assert!(!mode_entries(Tool::CloneStamp, true, false).iter().any(|e| e.value() == Some(&PaintMode::HealingReplace)), "no Replace on the Clone Stamp"); + assert!(items(Tool::CloneStamp).iter().all(|i| *i != Item::HealingReplace), "no Replace row on the Clone Stamp menu"); +} + +/// A Healing Brush app with a document, a set clone source and the tool active. +fn app() -> Box { + let mut a = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + a.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + a.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut a, 8.0, 8.0); + a +} + +/// The mode the next stroke would carry in its params. +fn stroke_mode(a: &PhotocraftApp) -> String { + crate::retouch_ui::clone_params(a).expect("a source is set")["mode"].as_str().unwrap_or_default().to_owned() +} + +fn steps(a: &PhotocraftApp) -> usize { + a.session.active().unwrap().history.past_len() +} + +#[test] +fn the_canvas_menu_replace_row_switches_the_stroke_without_a_history_step() { + let mut a = app(); + let before = steps(&a); + brush_mode_menu::choose(&mut a, Item::HealingReplace); + assert!(a.ui.tool_options.healing_replace, "the row sets the tool option"); + assert_eq!(stroke_mode(&a), "replace", "the next stroke sends mode:\"replace\""); + assert_eq!(current(&a, Tool::Healing), Some(Item::HealingReplace), "the menu checks Replace"); + assert_eq!(steps(&a), before, "picking the Mode adds no History step"); + // An existing row leaves Replace and paints its blend mode. + brush_mode_menu::choose(&mut a, Item::Blend(BlendMode::Multiply)); + assert!(!a.ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert_eq!(stroke_mode(&a), "Multiply"); + assert_eq!(steps(&a), before, "picking a Mode never adds a History step"); + // Replace is not offered to the other tools' choose route: their rows and options stay. + let mut b = app(); + b.ui.tool = Tool::CloneStamp; + brush_mode_menu::choose(&mut b, Item::HealingReplace); + assert!(!b.ui.tool_options.healing_replace, "the Clone Stamp never takes Replace"); +} + +#[test] +fn the_mode_keys_keep_the_seven_modes_and_clear_replace() { + // Replace stays out of the letter keys and the ⇧+ / ⇧− cycle: the seven modes and their order. + let mut a = app(); + a.ui.tool_options.healing_replace = true; + assert!(fired(&mut a, &test_fired(BlendShortcut::Multiply.into())), "⇧⌥M is taken"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert!(!a.ui.tool_options.healing_replace, "a letter pick leaves Replace"); + let mut b = app(); + assert!(fired(&mut b, &test_fired(BlendStep::Next.into())), "⇧+ is taken"); + assert_eq!(b.session.tools.brush.mode, BlendMode::Multiply, "the cycle still runs Normal to Multiply"); + assert!(!b.ui.tool_options.healing_replace, "the cycle never picks Replace"); +} diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index 18c3f66848a..7ece1ee5d5e 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -21,7 +21,8 @@ use crate::brush_mode_menu::Item; use crate::state::Tool; use crate::{PhotocraftApp, brush_mode_menu}; -/// Photoshop's Healing Brush modes, less Replace (not implemented yet). +/// Photoshop's Healing Brush modes. Replace is the tool's own option, not a blend mode: the menus +/// add it as a row of its own (#12101), and the letters and steps below keep this list. pub const HEALING_MODES: [BlendMode; 7] = [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Darken, BlendMode::Lighten, BlendMode::Color, BlendMode::Luminosity]; @@ -129,7 +130,10 @@ fn set_tool_mode(app: &mut PhotocraftApp, mode: Option) { brush.insert("behind".into(), json!(false)); } if !brush.is_empty() { - let _ = app.run("tools.setBrush", json!({ "brush": brush })); + // Replace (#12101): a key-picked blend mode leaves it, in the same pick. + if app.run("tools.setBrush", json!({ "brush": brush })).is_ok() && app.ui.tool == Tool::Healing { + app.ui.tool_options.healing_replace = false; + } } } diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 961b2318ef7..4fc4946020c 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -262,27 +262,43 @@ fn stamp_members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { // Pattern Stamp's list has Behind, greyed on the Background. let entries = fill::mode_entries(tool, crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), threshold); if !entries.is_empty() { - let current = - if tool == Tool::PatternStamp && brush.behind { PaintMode::Behind } else { PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) }; + let current = if tool == Tool::Healing && app.ui.tool_options.healing_replace { + PaintMode::HealingReplace + } else if tool == Tool::PatternStamp && brush.behind { + PaintMode::Behind + } else { + PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + }; let picked = labelled(ui, tl!("Mode"), |ui| { let select = fill::mode_select(Bind::given(current), &entries); let select = if tool == Tool::CloneStamp { select.tooltip(tl!("Painting Mode")) } else { select }; select.show(ui) }); if let Some(mode) = picked.and_then(|shown| shown.events.value().cloned()) { - let mut after = brush.clone(); - match mode { - PaintMode::Blend(blend) => { - after.mode = blend; - if tool == Tool::PatternStamp { - after.behind = false; - } + if mode == PaintMode::HealingReplace { + // Replace (#12101): a tool option like the painting tools' Clear, with no brush + // value to write: the next stroke carries mode:"replace", and picking a Mode adds + // no History step. + app.ui.tool_options.healing_replace = true; + } else { + if tool == Tool::Healing { + // Any of the seven blend modes leaves Replace (#12101). + app.ui.tool_options.healing_replace = false; } - PaintMode::Behind => after.behind = true, - PaintMode::Clear => {} + let mut after = brush.clone(); + match mode { + PaintMode::Blend(blend) => { + after.mode = blend; + if tool == Tool::PatternStamp { + after.behind = false; + } + } + PaintMode::Behind => after.behind = true, + PaintMode::Clear | PaintMode::HealingReplace => {} + } + // A pick is one step of its own. + crate::brush_panel::commit_keyed(app, &brush, &after, None); } - // A pick is one step of its own. - crate::brush_panel::commit_keyed(app, &brush, &after, None); } } // Both stamps use whole percents. Only Clone Stamp alerts on an out-of-range commit (#12607). @@ -417,3 +433,7 @@ mod clone_stamp_fields_tests; #[cfg(test)] #[path = "art_history_bar_controls_tests.rs"] mod art_history_bar_controls_tests; + +#[cfg(test)] +#[path = "../healing_mode_menu_tests.rs"] +mod healing_mode_menu_tests; diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index 61e9ff4df51..dffe5fb1f10 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -16,6 +16,7 @@ fn label_of(mode: PaintMode) -> String { PaintMode::Blend(blend) => tl!(blend.label()).to_owned(), PaintMode::Behind => tl!("Behind").to_owned(), PaintMode::Clear => tl!("Clear").to_owned(), + PaintMode::HealingReplace => tl!("Replace").to_owned(), } } @@ -26,6 +27,25 @@ fn label_of(mode: PaintMode) -> String { pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> Vec> { static CACHE: crate::i18n::LangCache<(Tool, bool, bool), Vec>> = crate::i18n::LangCache::new(); CACHE.get_or_build((tool, behind_enabled, threshold), || { + if tool == Tool::Healing { + // The Healing Brush's measured list (#12101): Normal, Replace, a rule, Multiply, + // Screen, Darken, Lighten, a rule, Color, Luminosity. Not the blend-group rules: the + // reference starts its groups elsewhere in this short list. Replace has no letter: the + // ⇧⌥ keys and the ⇧+ / ⇧− cycle keep the seven blend modes. + let blend = |b: BlendMode| Entry::new(PaintMode::Blend(b), label_of(PaintMode::Blend(b))); + return vec![ + blend(BlendMode::Normal), + Entry::new(PaintMode::HealingReplace, label_of(PaintMode::HealingReplace)), + Entry::separator(), + blend(BlendMode::Multiply), + blend(BlendMode::Screen), + blend(BlendMode::Darken), + blend(BlendMode::Lighten), + Entry::separator(), + blend(BlendMode::Color), + blend(BlendMode::Luminosity), + ]; + } let keyed: Vec> = if tool == Tool::PatternStamp { crate::brush_mode_menu::pattern_stamp_choices() .into_iter() @@ -78,6 +98,8 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { o.bucket_blend_mode = blend; } PaintMode::Behind => {} + // Replace belongs to the Healing Brush's list, never the Paint Bucket's. + PaintMode::HealingReplace => {} } if let Some(opacity) = number_field(ui, tl!("Opacity"), o.fill_opacity, 1.0..=100.0, "%").landed() { o.fill_opacity = *opacity; diff --git a/crates/ui-egui/src/panels/options_bar/paint.rs b/crates/ui-egui/src/panels/options_bar/paint.rs index c98fecb0949..765873a3df7 100644 --- a/crates/ui-egui/src/panels/options_bar/paint.rs +++ b/crates/ui-egui/src/panels/options_bar/paint.rs @@ -28,6 +28,9 @@ pub(crate) enum PaintMode { Behind, /// Paint transparency. Clear, + /// The Healing Brush's Replace (#12101): copy the source without healing. A tool option, not a + /// brush value; only the Healing Brush's Mode list offers it. + HealingReplace, } impl PaintMode { @@ -37,6 +40,7 @@ impl PaintMode { PaintMode::Blend(m) => m.label(), PaintMode::Behind => "Behind", PaintMode::Clear => "Clear", + PaintMode::HealingReplace => "Replace", } } } @@ -209,6 +213,9 @@ fn apply_values(app: &mut PhotocraftApp, tool: Tool, brush: &mut BrushSettings, brush.mode = BlendMode::Normal; } PaintMode::Clear => brush.behind = false, + // Replace is the Healing Brush's row; a paint-bar tool's list never shows it, so + // `after.mode` is never this here. + PaintMode::HealingReplace => {} } } } diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 7c699804aed..7d469db67d0 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -93,6 +93,9 @@ pub struct ToolOptions { pub pattern_stamp_angle: f32, /// current | currentAndBelow | all pub clone_sample: String, + /// Healing Brush › Mode: Replace, which copies the source without healing (#12101). Like the + /// painting tools' Clear flags it is tool-only: the stroke params carry it, not the brush. + pub healing_replace: bool, /// Spot Healing: contentAware | createTexture | proximityMatch pub spot_type: String, /// Patch: source (repair the selection) | destination (repair where it is dragged). @@ -479,6 +482,7 @@ impl Default for ToolOptions { pattern_stamp_scale: 100.0, pattern_stamp_angle: 0.0, clone_sample: "current".into(), + healing_replace: false, spot_type: "contentAware".into(), patch_mode: "source".into(), patch_content_aware: false, diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 78538b64b58..0cf75450bff 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -48,6 +48,11 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). let sample = if clone_stamp_indexed(app) { "current" } else { o.clone_sample.as_str() }; let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); + // The Healing Brush's Replace row (#12101): the stroke copies the source; the word rides the + // params in place of the brush's blend mode. The Clone Stamp never sends it. + if app.ui.tool == Tool::Healing && o.healing_replace { + p["mode"] = json!("replace"); + } if app.ui.tool == Tool::CloneStamp { p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index f324663a30e..8f75a3c8be8 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -234,7 +234,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Zoom => reset!(zoom_scrubby, zoom_in), Tool::Hand => reset!(hand_scroll_all), Tool::SpotHealing => reset!(spot_type), - Tool::Healing => reset!(clone_aligned, clone_sample), + Tool::Healing => reset!(clone_aligned, clone_sample, healing_replace), Tool::Patch => reset!(patch_mode, patch_content_aware, patch_structure, patch_color), Tool::ContentAwareMove => reset!(cam_mode, cam_structure, cam_color, cam_transform_on_drop), Tool::RedEye => reset!(red_eye_pupil_size, red_eye_darken), From 1f486fbc1c6ed7a4e3464b20d53f8fbe8635a0c9 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 22:56:22 +0100 Subject: [PATCH 30/31] style: rustfmt on the new #12101 test files --- .../src/cmd/retouch_cmds/heal_replace_tests.rs | 10 ++++++++-- crates/ui-egui/src/healing_mode_menu_tests.rs | 6 +++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs index fc1558744f0..19b22c5a481 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs @@ -14,7 +14,10 @@ use super::*; /// straight copy and a heal cannot agree anywhere inside the dab. fn document() -> Session { let mut s = crate::session(); - s.add_document(Document::with_background("t", Size::new(48, 48), ColorMode::Rgb, SampleType::U8, Color::rgb(40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0)), None); + s.add_document( + Document::with_background("t", Size::new(48, 48), ColorMode::Rgb, SampleType::U8, Color::rgb(40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0)), + None, + ); for cx in 0..4 { for cy in 0..4 { let color = if (cx + cy) % 2 == 0 { "#3c3c3c" } else { "#c8c8c8" }; @@ -92,7 +95,10 @@ fn an_unknown_mode_is_an_error_and_paints_nothing() { #[test] fn replace_is_the_healing_brush_command_s_alone() { let mut s = document(); - let err = s.execute("paint.cloneStamp", json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100, "mode": "replace"})).unwrap_err().to_string(); + let err = s + .execute("paint.cloneStamp", json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100, "mode": "replace"})) + .unwrap_err() + .to_string(); assert!(err.contains("unknown blend mode `replace`"), "the Clone Stamp still refuses it: {err}"); // The live stroke parser reads the same mode: a Healing live stroke starts with Replace. crate::cmd::retouch_cmds::clone::LiveRetouch::begin(&s, "paint.healingBrush", &stroke(Some("replace"))).unwrap(); diff --git a/crates/ui-egui/src/healing_mode_menu_tests.rs b/crates/ui-egui/src/healing_mode_menu_tests.rs index c92ae1c8eea..7c65bd400ef 100644 --- a/crates/ui-egui/src/healing_mode_menu_tests.rs +++ b/crates/ui-egui/src/healing_mode_menu_tests.rs @@ -46,7 +46,11 @@ const BAR_ROWS: [Option; 10] = [ #[test] fn both_healing_mode_lists_show_replace_and_the_two_separators() { assert_eq!(items(Tool::Healing), MENU_ROWS, "the Shift+right-click menu rows"); - assert_eq!(labels(Tool::Healing), ["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"], "the labels, separators left out"); + assert_eq!( + labels(Tool::Healing), + ["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"], + "the labels, separators left out" + ); let entries = mode_entries(Tool::Healing, true, false); let values: Vec> = entries.iter().map(|e| e.value().cloned()).collect(); assert_eq!(values, BAR_ROWS, "the options bar dropdown"); From a438a96675f7a6b43dd8405190907ffa52396d50 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Fri, 27 Nov 2026 00:43:55 +0100 Subject: [PATCH 31/31] =?UTF-8?q?=EF=BB=BFtest(retouch,ui):=20pin=20the=20?= =?UTF-8?q?Replace=20rim,=20widen=20its=20exact=20disc,=20and=20test=20the?= =?UTF-8?q?=20dropdown=20pick=20(#12101)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round one: a hardness-50 dab pins that Replace at partial coverage composites the source through the coverage (strictly between ground and source at the rim, exact copy at the centre); the bit-exact loop widens to the full-coverage disc of the 20 px hard tip, measured at 221 pixels (pixel-centre distance under 9 of the 10 px radius); and the options bar dropdown route is now click-tested end to end: open Mode, pick Replace, the stroke would send mode:"replace" and no History step is added, pick Multiply and Replace is left. --- .../cmd/retouch_cmds/heal_replace_tests.rs | 63 ++++++++++++++++--- crates/ui-egui/src/healing_mode_menu_tests.rs | 36 +++++++++++ 2 files changed, 89 insertions(+), 10 deletions(-) diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs index 19b22c5a481..149dab07f5b 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs @@ -1,8 +1,10 @@ //! #12101: the Healing Brush's Replace mode. `paint.healingBrush {"mode":"replace"}` copies the -//! source pixels straight onto the layer: no healing solve, Normal compositing. Every covered pixel -//! equals the source pixel the stroke maps there, bit for bit, as read from the document's state -//! before the stroke. The other modes keep their results; an unknown `mode` string stays an error, -//! and the stroke's History step keeps the name "Healing Brush". +//! source pixels straight onto the layer: no healing solve, Normal compositing. Every pixel of the +//! tip's full-coverage disc equals the source pixel the stroke maps there, bit for bit, as read +//! from the document's state before the stroke (221 px for the 20 px hard tip); past that disc +//! Replace lays the same source through the antialiased rim's coverage - strictly between ground +//! and source. The other modes keep their results; an unknown `mode` string stays an error, and +//! the stroke's History step keeps the name "Healing Brush". use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::Size; @@ -58,8 +60,9 @@ fn replace_paints_the_source_pixels_bit_for_bit() { s.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush"), "the stroke's History name"); assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "the stroke is one step"); - // Every pixel the hard tip covers fully (7 px of the 10 px radius, away from the antialiased - // rim) is the source pixel mapped there, bit for bit; the samples are the pre-stroke pixels. + // Every pixel the hard tip covers fully (out to 8.48 px of its 10 px radius, away from the + // antialiased rim) is the source pixel mapped there, bit for bit; the samples are the + // pre-stroke pixels. let green: Vec = vec![40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0, 1.0]; let ch = pixel(&s, 0, 0).len(); let src = |x: i32, y: i32| { @@ -67,9 +70,13 @@ fn replace_paints_the_source_pixels_bit_for_bit() { before[at..at + ch].to_vec() }; let mut inside = 0; - for dy in -7..=7 { - for dx in -7..=7 { - if dx * dx + dy * dy > 49 { + for dy in -9i32..=9 { + for dx in -9i32..=9 { + // The exact-copy disc reaches to a pixel-centre distance under 9 px of the 10 px hard + // tip: (6, 6) has its centre at 9.19 px and already sits in the antialiased rim, where + // Replace lays the source through its coverage (the hardness-50 test below pins that). + let (ax, ay) = (f64::from(dx.abs()) + 0.5, f64::from(dy.abs()) + 0.5); + if ax * ax + ay * ay >= 81.0 { continue; } let (x, y) = (30 + dx, 24 + dy); @@ -77,12 +84,48 @@ fn replace_paints_the_source_pixels_bit_for_bit() { inside += 1; } } - assert!(inside > 0, "the dab covers pixels"); + // The exact-copy disc this engine gives for a 20 px hard tip: 221 pixels (widened from the + // first round's r = 7 disc of 149; the rim test covers what lies beyond). + assert_eq!(inside, 221, "the loop's own shape"); // Outside the tip nothing changed: the dab's edge is 10 px away, these are 13. assert_eq!(pixel(&s, 43, 24), green, "right of the dab"); assert_eq!(pixel(&s, 30, 37), green, "below the dab"); } +#[test] +fn replace_at_partial_coverage_lays_the_source_through_the_coverage() { + // The rim of Replace is coverage, not a hard copy edge: a pixel the tip covers only partly + // takes the source pixel composited over the ground by that coverage - strictly between the + // two, and neither one exactly. (The reference's rim, measured on its own document, is about + // 1 px wider than ours; the exact rim width here is not measured.) + let mut s = document(); + let before = pixels(&s); + let mut p = stroke(Some("replace")); + p["hardness"] = json!(50); + s.execute("paint.healingBrush", p).unwrap(); + let q = |v: f32| (v * 255.0).round() as i32; + let lvl = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * 4; + [before[at], before[at + 1], before[at + 2]].map(q) + }; + // The tip's centre still holds the full copy: source 6,6..26 puts a 60-cell under the centre. + let centre = pixel(&s, 30, 24); + assert_eq!(centre.iter().map(|&v| q(v)).collect::>(), vec![60, 60, 60, 255], "centre: straight copy at full coverage"); + // 8 px out on a hardness-50 tip the coverage is partial: over the pre-stroke green the 200 + // cell now lies at about 40 %, so the levels sit strictly between the ground and the source. + let rim = pixel(&s, 38, 24).iter().map(|&v| q(v)).collect::>(); + let (src, ground) = (lvl(24, 16), [40, 160, 60]); // the 200-cell source pixel this rim copies from + assert_eq!(src, [200, 200, 200], "fixture check: the rim samples a 200-cell"); + for c in 0..3 { + assert!( + rim[c] > ground[c].min(src[c]) && rim[c] < ground[c].max(src[c]), + "rim {rim:?} channel {c}: between ground {ground:?} and source {src:?}, not either" + ); + } + // And not the full copy the interior shows. + assert_ne!(rim[..3], [200, 200, 200], "the rim is not a hard copy to the tip edge"); +} + #[test] fn an_unknown_mode_is_an_error_and_paints_nothing() { let mut s = document(); diff --git a/crates/ui-egui/src/healing_mode_menu_tests.rs b/crates/ui-egui/src/healing_mode_menu_tests.rs index 7c65bd400ef..1cc29736ca5 100644 --- a/crates/ui-egui/src/healing_mode_menu_tests.rs +++ b/crates/ui-egui/src/healing_mode_menu_tests.rs @@ -99,6 +99,42 @@ fn the_canvas_menu_replace_row_switches_the_stroke_without_a_history_step() { assert!(!b.ui.tool_options.healing_replace, "the Clone Stamp never takes Replace"); } +#[test] +fn the_options_bar_dropdown_replaces_and_picking_a_blend_mode_leaves_it() { + use crate::app::framework::BuildApp as _; + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + // The options bar alone, like the other bar tests: open the Mode dropdown, click a row. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut app, 8.0, 8.0); + let mut h = Harness::builder().with_size(egui::vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_app(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Normal"), "starts at Normal"); + let before = steps(h.state()); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Replace").click(); + h.run_steps(3); + assert!(h.state().ui.tool_options.healing_replace, "the dropdown's Replace row sets the option"); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Replace"), "the dropdown reads Replace"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("replace"), "the next stroke would run in Replace"); + assert_eq!(steps(h.state()), before, "picking a Mode adds no History step"); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Multiply").click(); + h.run_steps(3); + assert!(!h.state().ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(h.state().session.tools.brush.mode, BlendMode::Multiply, "the brush takes the mode"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("Multiply")); + assert_eq!(steps(h.state()), before, "and no Mode pick ever adds a step"); +} + #[test] fn the_mode_keys_keep_the_seven_modes_and_clear_replace() { // Replace stays out of the letter keys and the ⇧+ / ⇧− cycle: the seven modes and their order.