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 001/124] 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 18663f2cff..505cedfa8f 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 7928bf442c..8eac700621 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 0000000000..0cc6b35c2b --- /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 002/124] 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 505cedfa8f..2dfd4772cb 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 0cc6b35c2b..cd81809036 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 4c586aba1f4464950df116cc8f9e3173bbbd5a6e Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:10:45 +0100 Subject: [PATCH 003/124] fix(paint): History Brush restores transparency instead of painting over (#14701) In Normal mode the History Brush composited the source state over the current pixels, so a transparent area in the source could not clear what was painted or moved there since, and a moved subject stayed visible as a second image. It now mixes the source into the pixels at the brush weight (premultiplied, alpha included), in the commit and in the live stroke. Other modes and locked transparency composite as before. --- crates/engine/src/cmd/retouch_cmds.rs | 2 +- crates/engine/src/cmd/retouch_cmds/clone.rs | 6 +- crates/engine/src/cmd/retouch_cmds/heal.rs | 8 +- .../history_brush_transparency_tests.rs | 107 ++++++++++++++++++ crates/paint/src/retouch.rs | 38 ++++++- 5 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 6c891b8449..3af08d9c98 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -16,7 +16,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, restore_coverage}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index ada043ade4..6eb13ef6a9 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -4,7 +4,7 @@ use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, - reject_huge_stroke, run_stroke, to_rgba, + reject_huge_stroke, restore_coverage, run_stroke, to_rgba, }; /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, @@ -512,10 +512,14 @@ impl LiveRetouch { // The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it. let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. }); let clone = matches!(self.paint, LivePaint::Clone { .. }); + let history = matches!(self.paint, LivePaint::History(_)); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; surf.write_region(r, &self.pre_surf.read_region(r)); let damage = if clone { apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) + } else if history { + // As the commit paints it (`heal::history_brush`): the source state replaces the pixels. + restore_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) } else { pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind) }; diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index 9388258ef7..97955cac24 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -3,7 +3,7 @@ use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, - coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, restore_coverage, run_stroke, string, }; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). @@ -172,7 +172,7 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + Ok(restore_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; let mut r = json!({ "damage": damage_json(dmg) }); if from_live { @@ -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 = "history_brush_transparency_tests.rs"] +mod history_brush_transparency_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs b/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs new file mode 100644 index 0000000000..7f57a168b2 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs @@ -0,0 +1,107 @@ +//! #14701: the History Brush in Normal mode restores the source state's pixels, transparency +//! included, instead of laying them over what is there now. Painting a moved subject's new place +//! from the state before the move clears it again (no "ghost" double image), at the stroke's +//! opacity, and the live stroke shows what the commit paints. Other modes still composite. + +use serde_json::json; + +use super::*; + +const W: i32 = 48; +const H: i32 = 16; +const RED: [f32; 4] = [0.8, 0.1, 0.1, 1.0]; + +/// A `depth` RGB document with a layer over the Background holding a red subject on its left +/// half (History row 2), then the subject moved to the right half (row 3, the current state). +fn moved(depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": "rgb"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for left in [true, false] { + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (b.y0..b.y1) + .flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))) + .flat_map(|(x, _)| photocraft_raster::from_rgba(&fmt, if (x < W / 2) == left { RED } else { [0.0; 4] })) + .collect(); + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + } + s +} + +/// A stroke across the whole layer from History row 2 (the subject still on the left). +fn stroke(extra: Value) -> Value { + let mut p = json!({"points": [[0, 8], [W, 8]], "size": 40, "hardness": 100, "state": 2}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p +} + +fn layer_rgba(doc: &Document, s: &Session, x: i32, y: i32) -> [f32; 4] { + doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tol) +} + +#[test] +fn history_brush_restores_transparency_from_the_source_state() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: the subject comes back on the left: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the moved subject is cleared, no ghost: {right:?}"); + } +} + +#[test] +fn history_brush_restores_transparency_at_the_stroke_opacity() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({"opacity": 50}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!((left[3] - 0.5).abs() < 0.01 && close([left[0], left[1], left[2], 1.0], RED, 0.01), "depth {depth}: half the subject back: {left:?}"); + assert!((right[3] - 0.5).abs() < 0.01 && close([right[0], right[1], right[2], 1.0], RED, 0.01), "depth {depth}: half cleared: {right:?}"); + } +} + +#[test] +fn live_history_brush_shows_the_restored_transparency() { + for depth in [8u64, 32] { + let s = moved(depth); + let live = super::super::LiveRetouch::begin(&s, "paint.historyBrush", &stroke(json!({}))).unwrap(); + let (left, right) = (layer_rgba(&live.doc, &s, 8, 8), layer_rgba(&live.doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the live stroke clears the moved subject: {right:?}"); + } +} + +#[test] +fn other_modes_and_locked_transparency_keep_compositing() { + // Multiply of a transparent source changes nothing: the moved subject stays. + let mut s = moved(8); + s.execute("paint.historyBrush", stroke(json!({"mode": "multiply"}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + // Locked transparency keeps the layer's alpha: nothing to clear, nothing to restore. + let mut s = moved(8); + s.edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + assert!(layer_rgba(&doc, &s, 8, 8)[3] < 0.01); +} diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 9ab36bf2de..2fa370367d 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -202,6 +202,39 @@ pub fn apply_coverage( lock_transparency: bool, paint: &Region, blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, false) +} + +/// [`apply_coverage`] for the History Brush (#14701): in Normal mode the paint image *replaces* +/// the pixels at the per-pixel weight (a premultiplied mix, alpha included), so a transparent +/// source pixel clears what is there instead of leaving it under the restored pixels. Other +/// modes, locked transparency and targets without alpha composite as [`apply_coverage`] does. +#[allow(clippy::too_many_arguments)] +pub fn restore_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, true) +} + +#[allow(clippy::too_many_arguments)] +fn composite_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, + replace: bool, ) -> Rect { if rect.is_empty() { return Rect::EMPTY; @@ -237,7 +270,10 @@ pub fn apply_coverage( } let src = paint.px(x, y); if blend == BlendMode::Normal { - over_native(&fmt, px, src, k, lock_transparency); + match a { + Some(a) if replace && !lock_transparency => mix_premultiplied(px, src, a, k), + _ => over_native(&fmt, px, src, k, lock_transparency), + } } else { // A transparent source cannot paint. Skip it before an RGB round trip changes // untouched native CMYK/Lab values; Normal handles zero weight in over_native. From 1680566dbc84c11a63a58b8c2fd35a9f73e17dc4 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:19:22 +0100 Subject: [PATCH 004/124] Refuse Group from Layers when the Background is selected (#14709) layer.new.groupFromLayers gets its own enabled check and run wrapper: it is disabled while the Background is among the selected layers, and refuses an explicit {"layer": }, leaving the document, selection and history unchanged. layer.groupLayers keeps grouping the Background (not measured). --- crates/engine/src/cmd/layer_multi_cmds.rs | 7 +- .../group_from_layers_background_tests.rs | 112 ++++++++++++++++++ .../src/cmd/layer_multi_cmds/structure.rs | 26 ++++ .../engine/src/cmd/layer_multi_cmds/tests.rs | 3 +- 4 files changed, 145 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs index 62a1bac9ec..d52743df32 100644 --- a/crates/engine/src/cmd/layer_multi_cmds.rs +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -159,8 +159,8 @@ pub fn specs() -> Vec { &["Layer", "New"], None, r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, - has_layer, - group_layers + structure::can_group_from_layers, + structure::group_from_layers ), spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), spec!( @@ -184,3 +184,6 @@ mod layers_panel_parity_tests; #[cfg(test)] mod tile_damage_tests; + +#[cfg(test)] +mod group_from_layers_background_tests; diff --git a/crates/engine/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs new file mode 100644 index 0000000000..8c7a5c7a1c --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/group_from_layers_background_tests.rs @@ -0,0 +1,112 @@ +//! Group from Layers is refused while the Background is among the selected layers (#14709), as +//! the menu rows already grey it. Layer > Group Layers keeps grouping it (not measured). + +use super::*; + +/// A 32 x 32 document with a white Background and the pixel layers Red, Green and Blue above it. +fn session() -> (Session, LayerId, [LayerId; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.layers[0].id; + assert!(s.active().unwrap().doc.is_background(bg)); + let ids = ["Red", "Green", "Blue"].map(|name| LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap())); + (s, bg, ids) +} + +fn select(s: &mut Session, ids: &[LayerId], active: LayerId) { + set_selection(s, ids.to_vec(), Some(active), Some(active)).unwrap(); +} + +/// Everything a refused command must leave alone: the layer tree, the selection and the history. +fn snapshot(s: &Session) -> (Vec, Vec, Option, Vec) { + let d = s.active().unwrap(); + (d.doc.layers.clone(), d.selected_layers(), d.active_layer, d.history.entries()) +} + +fn enabled(s: &Session) -> std::result::Result<(), String> { + (crate::commands::find("layer.new.groupFromLayers").unwrap().enabled)(s) +} + +fn refused(s: &mut Session, params: Value) { + let before = snapshot(s); + assert!(s.execute("layer.new.groupFromLayers", params.clone()).is_err(), "{params} must be refused"); + assert!(snapshot(s) == before, "{params} changed the document"); + assert!(s.active().unwrap().doc.background().is_some(), "the Background is still there"); +} + +#[test] +fn the_background_alone_is_refused() { + let (mut s, bg, _) = session(); + select(&mut s, &[bg], bg); + assert!(enabled(&s).is_err(), "disabled with the Background selected"); + refused(&mut s, json!({})); + refused(&mut s, json!({"name": "Set", "color": "red", "mode": "normal", "opacity": 50})); +} + +#[test] +fn the_background_with_other_layers_is_refused() { + let (mut s, bg, [red, green, _]) = session(); + for active in [red, bg] { + select(&mut s, &[bg, red], active); + assert!(enabled(&s).is_err(), "disabled with the Background and Red selected"); + refused(&mut s, json!({})); + } + select(&mut s, &[bg, red, green], green); + refused(&mut s, json!({})); +} + +#[test] +fn an_explicit_background_layer_is_refused() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[red, blue], red); + refused(&mut s, json!({"layer": bg.0})); + select(&mut s, &[bg], bg); + refused(&mut s, json!({"layer": bg.0})); +} + +#[test] +fn a_background_only_document_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(enabled(&s).is_err()); + refused(&mut s, json!({})); +} + +fn children(s: &Session, group: LayerId) -> Vec { + s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +#[test] +fn layers_without_the_background_still_group() { + let (mut s, bg, [red, green, blue]) = session(); + select(&mut s, &[blue], blue); + assert!(enabled(&s).is_ok()); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![blue]); + + select(&mut s, &[red, green], green); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red, green]); + assert!(s.active().unwrap().doc.is_background(bg), "the Background stays"); +} + +#[test] +fn an_explicit_layer_other_than_the_background_still_groups() { + let (mut s, bg, [red, _, blue]) = session(); + select(&mut s, &[blue], blue); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"layer": red.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![red]); + assert!(s.active().unwrap().doc.is_background(bg)); +} + +/// Layer > Group Layers with the Background selected is not measured: it keeps today's result. +#[test] +fn group_layers_keeps_grouping_the_background() { + let (mut s, bg, [red, ..]) = session(); + select(&mut s, &[bg, red], red); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(children(&s, g), vec![bg, red]); +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 16cc828c81..32419a4438 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -111,6 +111,32 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { Ok(()) } +/// Group from Layers is greyed while the Background is among the selected layers, as in the +/// menus (#14709). +pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> { + super::has_layer(s)?; + let d = s.active().ok_or("no document open")?; + if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) { + return Err("the Background layer can't go into a group".into()); + } + Ok(()) +} + +/// Group from Layers: [`group_layers`], refused with the Background among the layers it would +/// move, also when the `layer` param names it (#14709). Group Layers (⌘G) is not measured and +/// keeps grouping it. +pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result { + let ids = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + if ids.iter().any(|id| doc.is_background(*id)) { + return Err(EngineError::Other("the Background layer can't go into a group".into())); + } + group_layers(s, p) +} + /// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves /// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is /// preserved. The New Group dialog's colour, mode and opacity are set in the same history step. diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index 5dbf78f158..642a2a6bfa 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -1014,7 +1014,8 @@ fn a_locked_group_keeps_a_grouped_background_locked() { let mut s = session(8); let bg = doc(&s).layers[0].id; s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + // Group from Layers refuses the Background (#14709); Group Layers still groups it. + let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); s.execute("layer.select", json!({"layer": bg.0})).unwrap(); for (cmd, p) in [ From d003380fee1b8348444bf5725f4753d14e19de09 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:40:31 +0100 Subject: [PATCH 005/124] fix(paint): premultiplied mix keeps the source exactly at full weight mix_premultiplied computed d + (s - d) * k, which for large 32-bit values rounds the source away at k = 1 (destination 67108864, source 1 gave 0). It now weights both sides directly, so the destination drops out at full weight. Algebraically the same; only the rounding changes. Review feedback on #14814. --- crates/paint/src/retouch.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 2fa370367d..0f6f05f540 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -407,7 +407,9 @@ pub fn mix_premultiplied(dst: &mut [f32], src: &[f32], a: usize, k: f32) { if c == a { continue; } - *d = if oa > 1e-6 { (*d * da + (*s * sa - *d * da) * k) / oa } else { *d + (*s - *d) * k }; + // Weighted, not `d + (s - d) * k`: at k = 1 the destination drops out exactly, even for + // large 32-bit values where the difference would round away the source. + *d = if oa > 1e-6 { (*d * da * (1.0 - k) + *s * sa * k) / oa } else { *d * (1.0 - k) + *s * k }; } if let Some(d) = dst.get_mut(a) { *d = oa; @@ -1028,6 +1030,13 @@ mod tests { assert_eq!(d, [0.5, 0.5]); } + #[test] + fn premultiplied_mix_at_full_weight_keeps_the_source_exactly() { + let mut d = [67_108_864.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0]); + } + #[test] fn footprint_stays_inside_the_tips_reach() { let radius = 10.5f32; From 7cb7d48c6a0253e5c81ba4d63363ed6da0988b78 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:08:00 +0100 Subject: [PATCH 006/124] fix(paint): premultiplied mix weights alpha separately and keeps colour at tiny alpha Alpha is now da*(1-k) + sa*k, so a tiny source alpha next to an opaque destination survives a full-weight mix instead of rounding to 0. The premultiplied colour mix is used for every positive result alpha; the straight fallback only runs when the result is fully transparent. --- crates/paint/src/retouch.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 0f6f05f540..3735864912 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -402,14 +402,14 @@ pub fn mix_back(target: &mut Surface, orig: &Region, work: &Region, rect: Rect, #[inline] pub fn mix_premultiplied(dst: &mut [f32], src: &[f32], a: usize, k: f32) { let (Some(&da), Some(&sa)) = (dst.get(a), src.get(a)) else { return }; - let oa = da + (sa - da) * k; + // Weighted, not `d + (s - d) * k`: at k = 1 the destination drops out exactly, even for + // large 32-bit values (or a tiny alpha next to 1) where the difference would round away the source. + let oa = da * (1.0 - k) + sa * k; for (c, (d, s)) in dst.iter_mut().zip(src).enumerate() { if c == a { continue; } - // Weighted, not `d + (s - d) * k`: at k = 1 the destination drops out exactly, even for - // large 32-bit values where the difference would round away the source. - *d = if oa > 1e-6 { (*d * da * (1.0 - k) + *s * sa * k) / oa } else { *d * (1.0 - k) + *s * k }; + *d = if oa > 0.0 { (*d * da * (1.0 - k) + *s * sa * k) / oa } else { *d * (1.0 - k) + *s * k }; } if let Some(d) = dst.get_mut(a) { *d = oa; @@ -1037,6 +1037,21 @@ mod tests { assert_eq!(d, [1.0, 0.0, 0.0, 1.0]); } + #[test] + fn premultiplied_mix_keeps_colour_at_tiny_alpha() { + // Half of a barely-there 32-bit red over transparent black is still that red, not half of it. + let mut d = [0.0, 0.0, 0.0, 0.0]; + mix_premultiplied(&mut d, &[1.0e6, 0.0, 0.0, 5.0e-7], 3, 0.5); + assert_eq!(d, [1.0e6, 0.0, 0.0, 2.5e-7]); + } + + #[test] + fn premultiplied_mix_at_full_weight_keeps_a_tiny_source_alpha() { + let mut d = [0.0, 0.0, 0.0, 1.0]; + mix_premultiplied(&mut d, &[1.0, 0.0, 0.0, 1.0e-8], 3, 1.0); + assert_eq!(d, [1.0, 0.0, 0.0, 1.0e-8]); + } + #[test] fn footprint_stays_inside_the_tips_reach() { let radius = 10.5f32; 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 007/124] 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 c854dfa631..6f8b66c2c3 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 feb8a1a3dd..1e47e84180 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 0000000000..28c019e11f --- /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 3e30609ea2..2d11728a8c 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 c5d6aaa46b..9eefe6b455 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 f81ab2e864..13c3fc04f7 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 4370e3375e..2d8cf8f49b 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 6352916c338d7516443b040845ee9e0466f4cab4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:06:13 -0800 Subject: [PATCH 008/124] Show unreadable-file failures in modal alerts --- crates/ui-egui/src/file_open.rs | 26 ++- .../src/file_open/unreadable_alert_tests.rs | 154 ++++++++++++++++++ 2 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/file_open/unreadable_alert_tests.rs diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 1ae2be2003..e577c2d451 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -327,7 +327,7 @@ impl PhotocraftApp { // prompt that is answered later all place the file at its place in the set. match self.open_path_placed(abs, None, Some(order)) { Ok(_) => opened += 1, - Err(e) => self.open_failed(&display_name(abs), &e), + Err(e) => self.open_failed(abs, &e), } } crate::jobs_ui::end_batch(self); @@ -361,12 +361,23 @@ impl PhotocraftApp { true } - /// Show "Couldn't open : " as an error (status bar + notice). - pub fn open_failed(&mut self, name: &str, err: &str) { - self.failed({ + /// Report one failed open in an OK alert, naming its source file once. Pass the source path + /// when available so its exact prefix can be removed from filesystem read errors too. + pub fn open_failed(&mut self, source: &str, err: &str) { + let name = display_name(source); + let source_prefix = format!("{source}: "); + let name_prefix = format!("{name}: "); + let reason = err.strip_prefix(&source_prefix).or_else(|| err.strip_prefix(&name_prefix)).unwrap_or(err); + let msg = if reason == "codec: unrecognized image format" { + crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) + } else { let template = "Couldn't open {name}: {error}"; - crate::i18n::fmt(tl!(template), &[("name", name), ("error", err)]) - }); + crate::i18n::fmt(tl!(template), &[("name", &name), ("error", reason)]) + }; + log::warn!("{msg}"); + self.ui.status = msg.clone(); + self.ui.status_error = true; + self.ui.open_dialog(crate::state::DialogKind::Error, serde_json::json!({"message": msg}).as_object().cloned().unwrap_or_default()); } /// Show "Couldn't place : " as an error (status bar + notice). @@ -712,3 +723,6 @@ fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool { mod dialog_order_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod unreadable_alert_tests; diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs new file mode 100644 index 0000000000..2268c819a1 --- /dev/null +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -0,0 +1,154 @@ +//! #14059: unreadable File > Open inputs use one modal alert per file, while callers that +//! request an error result still receive it. + +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::file_dialog::{self, FileDialogAnswer}; +use crate::state::DialogKind; +use crate::{Services, menus}; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn app_with(answer: Option) -> PhotocraftApp { + let services = Services { file_dialog: Some(file_dialog::fake(vec![answer]).0), ..Default::default() }; + PhotocraftApp::new(photocraft_engine::Session::new(), services) +} + +fn pick(app: &mut PhotocraftApp) { + menus::invoke(app, &egui::Context::default(), "file.open", json!({})).unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); +} + +fn messages(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).map(|d| d.fields["message"].as_str().unwrap()).collect() +} + +fn expected(name: &str) -> String { + format!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file.") +} + +fn png() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "valid.png", &Default::default()).unwrap().bytes +} + +#[test] +fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { + for (name, bytes) in [("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect())] { + let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); + pick(&mut app); + assert_eq!(messages(&app), [expected(name)]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); + assert!(app.ui.status_error); + assert_eq!(app.ui.status, expected(name)); + assert_eq!(app.ui.status.matches(name).count(), 1); + } +} + +#[test] +fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { + let mut app = app_with(None); + app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + assert!(h.query_by_label(&expected("notes.txt")).is_some()); + assert!(h.query_by_label("Cancel").is_none()); + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert!(h.state().session.documents().is_empty()); +} + +#[test] +fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { + let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); + for err in [format!("{source}: file not found"), "missing.png: permission denied".into(), "the directory is missing.png: keep this reason".into()] { + let mut app = app_with(None); + app.open_failed(&source, &err); + let reason = if err.starts_with(&source) { + "file not found" + } else if err.starts_with("missing.png: ") { + "permission denied" + } else { + &err + }; + assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); + assert!(app.ui.notices.is_empty()); + } +} + +#[test] +fn several_failed_files_each_get_one_alert_and_valid_files_still_open() { + let files = vec![("a.txt".into(), b"text".to_vec()), ("b.png".into(), png()), ("c.png".into(), b"text".to_vec()), ("d.png".into(), png())]; + let mut app = app_with(Some(FileDialogAnswer::ContentsMany(files))); + pick(&mut app); + assert_eq!(messages(&app), [expected("a.txt"), expected("c.png")]); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["b.png", "d.png"]); + assert!(app.ui.notices.iter().all(|n| !n.error)); + let first = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, first).unwrap(); + assert_eq!(messages(&app), [expected("c.png")]); + let second = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, second).unwrap(); + assert!(messages(&app).is_empty()); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn background_open_failures_are_reported_once_when_the_jobs_finish() { + let mut app = app_with(None); + app.background_jobs = true; + app.open_bytes("first.txt", b"text").unwrap(); + app.open_bytes("second.png", b"text").unwrap(); + app.open_bytes("valid.png", &png()).unwrap(); + let ctx = egui::Context::default(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open jobs did not finish"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let mut actual = messages(&app).into_iter().map(str::to_owned).collect::>(); + actual.sort(); + let mut wanted = vec![expected("first.txt"), expected("second.png")]; + wanted.sort(); + assert_eq!(actual, wanted); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["valid.png"]); + crate::jobs_ui::tick(&mut app, &ctx); + assert_eq!(messages(&app).len(), 2, "a consumed failure event cannot show twice"); + assert!(app.ui.notices.iter().all(|n| !n.error)); +} + +#[test] +fn cancelling_file_open_does_not_show_an_error() { + let mut app = app_with(None); + pick(&mut app); + assert!(!app.file_dialog_open()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); + assert!(!app.ui.status_error); +} + +#[test] +fn automation_and_control_open_still_return_the_original_error() { + let mut app = app_with(None); + app.services.import = Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })); + let err = app.open_automation_bytes("notes.txt", b"text").unwrap_err(); + assert_eq!(err, "notes.txt: codec: unrecognized image format"); + assert!(app.ui.dialogs.is_empty()); + app.services.automation_read = Some(Box::new(|_| Ok(crate::AutomationReadResult { name: "notes.txt".into(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": "notes.txt"})); + let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], err); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); +} From 29350152b816d6f910f8a823b36a7918188a4a86 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:38:50 -0800 Subject: [PATCH 009/124] Add Smudge pressure-for-size control --- .../src/smudge_bar_pressure_size_tests.rs | 161 ++++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 11 +- crates/ui-egui/src/tools/retouch_ui.rs | 10 ++ 3 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/smudge_bar_pressure_size_tests.rs diff --git a/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs new file mode 100644 index 0000000000..425b64c4e6 --- /dev/null +++ b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs @@ -0,0 +1,161 @@ +//! Smudge Pressure for Size (#12961): the bar toggle binds the same brush used by paint.smudge. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::BrushSettings; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const PRESSURE: &str = "Always use pressure for size"; +const TOOLTIP: &str = "Always use Pressure for Size. When off, Brush Preset controls pressure"; + +fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = Harness::builder() + .with_size(vec2(1600.0, 400.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium)) + .build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +fn toggle(h: &mut Harness<'static, PhotocraftApp>) { + h.get_by_label(PRESSURE).click(); + h.run_steps(3); +} + +fn brush_commands(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count() +} + +#[test] +fn pressure_is_off_by_default_and_follows_finger_painting_with_the_exact_tooltip() { + let h = bar(Tool::Smudge); + let pressure = h.get_by_label(PRESSURE); + assert!(h.get_by_label("Finger Painting").rect().right() <= pressure.rect().left()); + assert_eq!(pressure.accesskit_node().description().as_deref(), Some(TOOLTIP)); + assert!(!h.state().session.tools.brush.pressure_size); +} + +#[test] +fn the_toggle_updates_the_brush_settings_value_with_one_command_per_click() { + let mut h = bar(Tool::Smudge); + let n = brush_commands(&h); + toggle(&mut h); + assert!(h.state().session.tools.brush.pressure_size); + assert_eq!(h.state_mut().run("brush.get", json!({})).unwrap()["pressureSize"], json!(true)); + assert_eq!(brush_commands(&h), n + 1); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": true})); + toggle(&mut h); + assert!(!h.state().session.tools.brush.pressure_size); + assert_eq!(brush_commands(&h), n + 2); + assert_eq!(h.state().session.journal.last().unwrap().1["brush"], json!({"pressureSize": false})); +} + +#[test] +fn reset_tool_turns_pressure_off_and_other_tools_keep_their_own_setting() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + h.run_steps(2); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(!h.state().session.tools.brush.pressure_size, "Smudge starts with its own default"); + toggle(&mut h); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "the Brush setting is retained"); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "Smudge remembers its value"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(2); + assert!(!h.state().session.tools.brush.pressure_size); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "resetting Smudge does not reset the Brush"); +} + +/// Read the actual shared generator's dabs for a pen tap, rather than duplicating its formula. +fn radii(brush: &BrushSettings, pressure: f32) -> Vec { + let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + generator.push(&[photocraft_paint::StrokePoint::new(28.0, 40.0, pressure)], &mut dabs, &mut dual); + generator.finish(&mut dabs, &mut dual); + assert!(!dabs.is_empty()); + dabs.into_iter().map(|dab| dab.radius).collect() +} + +#[test] +fn the_ui_toggle_changes_generated_dab_size_with_pressure_and_off_restores_the_baseline() { + let mut h = bar(Tool::Smudge); + let original = h.state().session.tools.brush.clone(); + let off_low = radii(&original, 0.25); + let off_full = radii(&original, 1.0); + assert_eq!(off_low, off_full); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + assert_eq!(radii(&on, 1.0), off_full); + let low = radii(&on, 0.25); + assert!(low.iter().all(|r| (*r - original.size * 0.25 * 0.5).abs() < 1e-6)); + toggle(&mut h); + assert_eq!(radii(&h.state().session.tools.brush, 0.25), off_low); + assert_eq!(h.state().session.tools.brush.shape_dynamics, original.shape_dynamics, "the toggle does not rewrite preset dynamics"); +} + +/// A red/white edge and a real paint.smudge command, with the UI-selected brush and real point +/// pressures. All comparisons use complete resulting pixels, with no visual threshold. +fn smudged(brush: &BrushSettings, pressure: f32) -> (Vec, Vec) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80, "depth": 32, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 80})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Smudge; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": brush})).unwrap(); + app.ui.tool_options.strength = 100.0; + let read = |app: &PhotocraftApp| { + let state = app.session.active().unwrap(); + state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap().read_region(state.doc.bounds()) + }; + let before = read(&app); + let (command, mut params) = super::dab_params(&app, Tool::Smudge).unwrap(); + assert_eq!(command, "paint.smudge"); + params["points"] = json!([[28.0, 40.0, pressure], [42.0, 40.0, pressure], [58.0, 40.0, pressure]]); + app.run(command, params).unwrap(); + (before, read(&app)) +} + +#[test] +fn actual_smudge_pixels_follow_pressure_on_and_keep_the_existing_result_off() { + let mut h = bar(Tool::Smudge); + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0, "spacing": 0.25, "smoothing": {"enabled": false}}})).unwrap(); + h.run_steps(2); + let off = h.state().session.tools.brush.clone(); + let (before, off_low) = smudged(&off, 0.25); + let (_, off_full) = smudged(&off, 1.0); + assert_ne!(off_full, before, "the edge fixture must actually smudge"); + assert_eq!(off_low, off_full, "off keeps today's pressure-independent size"); + toggle(&mut h); + let on = h.state().session.tools.brush.clone(); + let (_, on_low) = smudged(&on, 0.25); + let (_, on_full) = smudged(&on, 1.0); + assert_ne!(on_low, on_full, "the actual command receives pen pressure and the selected brush"); + assert_ne!(on_low, off_low); + assert_eq!(on_full, off_full, "full pressure keeps the full-size result"); + toggle(&mut h); + assert_eq!(smudged(&h.state().session.tools.brush, 0.25).1, off_low); +} + +#[test] +fn the_smudge_change_does_not_add_pressure_controls_to_blur_or_sharpen() { + for tool in [Tool::Blur, Tool::Sharpen] { + assert!(bar(tool).query_by_label(PRESSURE).is_none(), "{tool:?}"); + } +} diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 3a88440a52..27079950b5 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -189,6 +189,13 @@ fn angle_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) -> b /// How far the Angle field lets a typed number through before [`angle_field`] clamps it. const ANGLE_TYPED_MAX: f32 = 1.0e6; +/// The options-bar pressure-for-size toggle, bound to the active tool's brush. +pub(crate) fn pressure_size_button(ui: &mut egui::Ui, on: bool) -> egui::Response { + let name = tl!("Always use pressure for size"); + icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), on, name, false) + .on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")) +} + /// Options bar for the Magic Eraser and Background Eraser. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { let o = &mut app.ui.tool_options; @@ -242,9 +249,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } widgets::checkbox(ui, &mut app.ui.tool_options.bg_protect_fg, tl!("Protect Foreground Color")) .on_hover_text(tl!("Do not erase the foreground swatch color")); - let name = tl!("Always use pressure for size"); - let pressure = icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false); - if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { + if pressure_size_button(ui, brush.pressure_size).clicked() { brush.pressure_size = !brush.pressure_size; } crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 0f03e84658..04a48444ae 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1113,6 +1113,12 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } if tool == Tool::Smudge { crate::widgets::checkbox(ui, &mut o.finger_painting, tl!("Finger Painting")); + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + if crate::eraser_ui::pressure_size_button(ui, brush.pressure_size).clicked() { + brush.pressure_size = !brush.pressure_size; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); } if out_of_range { crate::eraser_ui::open_range_alert(app); @@ -1310,3 +1316,7 @@ mod remove_options_bar_labels_tests; #[cfg(test)] #[path = "../burn_exposure_field_tests.rs"] mod burn_exposure_field_tests; + +#[cfg(test)] +#[path = "../smudge_bar_pressure_size_tests.rs"] +mod smudge_bar_pressure_size_tests; From 065abdffc68f6736301f33cb11637f7f2771b4ac Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:38:50 -0800 Subject: [PATCH 010/124] Configure real imports and fonts in unreadable-alert tests --- .../src/file_open/unreadable_alert_tests.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 2268c819a1..8251221539 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -10,7 +10,13 @@ use egui_kittest::kittest::Queryable; use serde_json::json; fn app_with(answer: Option) -> PhotocraftApp { - let services = Services { file_dialog: Some(file_dialog::fake(vec![answer]).0), ..Default::default() }; + let services = Services { + file_dialog: Some(file_dialog::fake(vec![answer]).0), + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })), + ..Default::default() + }; PhotocraftApp::new(photocraft_engine::Session::new(), services) } @@ -52,8 +58,10 @@ fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_docume fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { let mut app = app_with(None); app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 600.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); h.run_steps(3); assert!(h.query_by_label(&expected("notes.txt")).is_some()); assert!(h.query_by_label("Cancel").is_none()); From 13049cf36a76cf5207f347208f68c490e514a07d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 15:40:21 -0800 Subject: [PATCH 011/124] Keep Smudge pressure control logic within the options bar complexity limit --- crates/ui-egui/src/tools/retouch_ui.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 04a48444ae..022403c310 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1112,13 +1112,16 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::checkbox(ui, &mut o.protect_detail, tl!("Protect Detail")); } if tool == Tool::Smudge { - crate::widgets::checkbox(ui, &mut o.finger_painting, tl!("Finger Painting")); - let before = app.session.tools.brush.clone(); - let mut brush = before.clone(); - if crate::eraser_ui::pressure_size_button(ui, brush.pressure_size).clicked() { - brush.pressure_size = !brush.pressure_size; + fn pressure_size_control(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + if crate::eraser_ui::pressure_size_button(ui, brush.pressure_size).clicked() { + brush.pressure_size = !brush.pressure_size; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); } - crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); + crate::widgets::checkbox(ui, &mut o.finger_painting, tl!("Finger Painting")); + pressure_size_control(app, ui); } if out_of_range { crate::eraser_ui::open_range_alert(app); From c10e7f277db16b3a41006969f2c39248beae931c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 18:22:05 -0800 Subject: [PATCH 012/124] Update Open failure tests for modal unreadable-file alerts --- crates/ui-egui/src/file_open/tests.rs | 37 +++++++++++++++++++-------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 6f015aad0b..26f71e3652 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -170,7 +170,7 @@ fn the_web_opens_every_selected_file() { // Each good file is its own tab; the broken one is reported without stopping the rest. let names: Vec<_> = app.session.documents().iter().map(|st| st.doc.name.as_str()).collect(); assert_eq!(names, ["one.png", "two.jpg"]); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("broken.png")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|message| message.contains("broken.png")), "{:?}", app.ui.dialogs); } /// #5749: the web shell reads dropped files itself, so it asks where they landed: image files @@ -401,7 +401,7 @@ fn open_failures_are_errors_and_leave_no_document() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.status_error); assert!(app.ui.status.starts_with("Couldn't open broken.psd"), "{}", app.ui.status); - assert!(app.ui.notices.last().is_some_and(|n| n.error)); + assert_eq!(open_error_messages(&app).len(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -414,8 +414,11 @@ fn a_picked_file_that_cannot_be_read_is_reported_like_any_open_failure() { answer(&mut app); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - let notice = app.ui.notices.last().unwrap(); - assert!(notice.error && notice.title.starts_with("Couldn't open big.psb: "), "{}", notice.title); + let messages = open_error_messages(&app); + assert_eq!(messages.len(), 1); + assert!(messages[0].starts_with("Couldn't open big.psb: "), "{}", messages[0]); + let alert = app.ui.dialogs.last().unwrap().id; + crate::dialogs::confirm(&mut app, alert).unwrap(); // Commands that read a picked file (scripts, notes, Place) fail with the file's name. app.ui.status_error = false; app.pick_file_bytes(|_, _, _| Err("read".into())).unwrap(); @@ -436,7 +439,8 @@ fn open_paths_reports_each_failure_without_panicking() { assert_eq!(n, 0); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.len(), notices::MAX_NOTICES); + assert_eq!(open_error_messages(&app).len(), 4, "every failing path has its own alert"); + assert!(app.ui.notices.is_empty()); // Bad control params error instead of panicking. let ctx = egui::Context::default(); assert!(menus::invoke(&mut app, &ctx, "file.open", json!({ "path": "" })).is_err()); @@ -545,7 +549,7 @@ fn dropped_files_open_with_path_and_recent() { assert_eq!(app.session.documents()[1].path, None); assert_eq!(app.ui.recent_files, vec![abs_s]); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.iter().filter(|n| n.error).count(), 2); + assert_eq!(open_error_messages(&app).len(), 2); let _ = std::fs::remove_dir_all(&dir); } @@ -1860,6 +1864,10 @@ fn error_titles(app: &PhotocraftApp) -> Vec { app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect() } +fn open_error_messages(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).map(|d| d.fields["message"].as_str().unwrap().to_owned()).collect() +} + /// The Home screen (no document open) is where a first drop lands: every file opens as its own /// document, in drop order, whatever the type, and nothing is placed. #[test] @@ -1882,6 +1890,7 @@ fn files_dropped_with_no_document_open_all_open() { assert_eq!(doc_names(&app), names); assert!(app.drop_places.is_empty()); assert!(error_titles(&app).is_empty(), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).is_empty(), "{:?}", app.ui.dialogs); let _ = std::fs::remove_dir_all(&dir); } @@ -1899,7 +1908,7 @@ fn a_dropped_folder_is_refused_with_a_clear_message() { let (mut app, _) = app_with(Vec::new()); app.open_dropped(&ctx, vec![dropped(folder.clone(), Err("read from the path".into())), dropped(file, Err("read from the path".into()))], None); assert_eq!(doc_names(&app), ["ok.psd"]); - let errors = error_titles(&app); + let errors = open_error_messages(&app); assert_eq!(errors.len(), 1, "{errors:?}"); assert!(errors[0].starts_with("Couldn't open Holiday photos: ") && errors[0].contains("folder"), "{errors:?}"); // On the canvas: not queued for placing, and the layers stay as they were. @@ -1927,7 +1936,7 @@ fn a_dropped_file_that_is_not_an_image_reports_why() { app.open_dropped(&ctx, vec![dropped(file.clone(), Err("read from the path".into()))], None); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open notes.txt: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open notes.txt: ")), "{:?}", app.ui.dialogs); let mut app = app_with_canvas(); let layers = layer_count(&app); app.open_dropped(&ctx, vec![dropped(file, Err("read from the path".into()))], Some(egui::pos2(300.0, 300.0))); @@ -1962,7 +1971,7 @@ fn several_files_dropped_on_the_canvas_are_queued_in_order() { }) .collect(); assert_eq!(queued, ["one.png", "two.jpg"]); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.dialogs); } #[test] @@ -1997,7 +2006,10 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert!( + open_error_messages(&app).iter().any(|message| message == "Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."), + "the unreadable file is reported" + ); let _ = std::fs::remove_dir_all(&dir); } @@ -2019,7 +2031,10 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert!( + open_error_messages(&app).iter().any(|message| message == "Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."), + "the unreadable file is reported" + ); let _ = std::fs::remove_dir_all(&dir); } From 16d9a0dc13f94959e54fb809b22622301cda06b4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 19:57:55 -0800 Subject: [PATCH 013/124] Preserve read sources in unreadable-file alerts --- crates/ui-egui/src/app/files.rs | 7 +- .../ui-egui/src/canvas/scroll_all_windows.rs | 2 +- crates/ui-egui/src/dialogs/open_prompt.rs | 18 +- crates/ui-egui/src/file_dialog.rs | 2 +- crates/ui-egui/src/file_open.rs | 14 +- crates/ui-egui/src/file_open/tests.rs | 13 +- .../src/file_open/unreadable_alert_tests.rs | 230 ++++++++++++++++-- crates/ui-egui/src/home_recent_ui.rs | 2 +- crates/ui-egui/src/jobs_ui.rs | 20 +- crates/ui-egui/src/jobs_ui/tests.rs | 2 +- crates/ui-egui/src/psd_open_tests.rs | 7 +- 11 files changed, 274 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1fa6b5ec16..dbeb45ceb0 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -82,7 +82,6 @@ impl PhotocraftApp { if let Some(r) = preset_files_ui::open(self, name, bytes) { return r.map(|()| Vec::new()); } - let name = &self.open_name(name); // Decoded on a worker: a tab with progress appears now, the document when it's ready // (warnings are shown then). if self.background_jobs { @@ -117,6 +116,12 @@ impl PhotocraftApp { let (doc, warnings) = import(name, bytes, &opts)?; (doc, warnings, false) }; + // Decode under the source name; only a successfully opened template becomes untitled. + let opened_name = self.open_name(name); + if opened_name != name { + doc.name = opened_name.clone(); + } + let name = &opened_name; // Preferences › Raw Defaults › Resolution, as the engine's open applies it. photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // Edit › Color Settings policies apply on open; Ask When Opening holds the file back diff --git a/crates/ui-egui/src/canvas/scroll_all_windows.rs b/crates/ui-egui/src/canvas/scroll_all_windows.rs index 34d15b4897..b27519f50e 100644 --- a/crates/ui-egui/src/canvas/scroll_all_windows.rs +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -272,7 +272,7 @@ mod tests { app.ui.chrome.home = Some(app.session.documents().len()); } else { let job = photocraft_engine::jobs::JobId(9); - app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, slot: None, order: None }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, error_source: None, slot: None, order: None }); app.jobs.focus = Some(job); } diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 4c7c49618f..e48418505d 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -466,13 +466,27 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { if accept { if let Some(job) = r.get("job").and_then(Value::as_u64) { - app.jobs.opens.push(crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(job), name: name.clone(), path, slot, order }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(job), + name: name.clone(), + path, + error_source: None, + slot, + order, + }); app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); app.ui.chrome.home = None; app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); app.ui.status_error = false; } else if let Some(result) = r.get("result") { - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order }; + let tab = crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(0), + name: name.clone(), + path: path.clone(), + error_source: None, + slot, + order, + }; if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { app.ui.status = e; app.ui.status_error = true; diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index aabff48324..a7829f735c 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -312,7 +312,7 @@ impl PhotocraftApp { for (seq, path) in paths.iter().enumerate() { let order = crate::jobs_ui::OpenOrder { batch, seq }; if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) { - app.open_failed(&crate::file_open::display_name(path), &e); + app.open_failed(path, &e); } } crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index e577c2d451..7ed8f34a17 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -367,7 +367,14 @@ impl PhotocraftApp { let name = display_name(source); let source_prefix = format!("{source}: "); let name_prefix = format!("{name}: "); - let reason = err.strip_prefix(&source_prefix).or_else(|| err.strip_prefix(&name_prefix)).unwrap_or(err); + // The native background importer wraps its path-prefixed read error in the file name. + let wrapped_source_prefix = format!("{name}: {source}: "); + let reason = (source != name) + .then(|| err.strip_prefix(&wrapped_source_prefix)) + .flatten() + .or_else(|| err.strip_prefix(&source_prefix)) + .or_else(|| err.strip_prefix(&name_prefix)) + .unwrap_or(err); let msg = if reason == "codec: unrecognized image format" { crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) } else { @@ -429,7 +436,10 @@ impl PhotocraftApp { match self.open_dropped_file(&f, &name, slot) { Ok(true) => slot = slot.map(|s| s + 1), Ok(false) => {} - Err(e) => self.open_failed(&name, &e), + Err(e) => { + let source = if f.path().is_absolute() { f.path().to_string_lossy().into_owned() } else { name.clone() }; + self.open_failed(&source, &e); + } } } } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 26f71e3652..9cb1c6b28f 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1552,7 +1552,14 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let (mut app, _) = app_with(Vec::new()); app.open_bytes("existing.psd", b"x").unwrap(); let batch = jobs_ui::begin_batch(&mut app); - let tab = |seq: usize| OpenTab { job: JobId(100 + seq as u64), name: format!("f{seq}.psd"), path: None, slot: None, order: Some(OpenOrder { batch, seq }) }; + let tab = |seq: usize| OpenTab { + job: JobId(100 + seq as u64), + name: format!("f{seq}.psd"), + path: None, + error_source: None, + slot: None, + order: Some(OpenOrder { batch, seq }), + }; app.jobs.opens.extend((0..4).map(tab)); // f1 opened at once (a preset file, say, or background jobs off for it). app.jobs.opens.remove(1); @@ -1574,11 +1581,11 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { assert_eq!(app.ui.views.len(), 5, "views follow their documents"); assert!(app.jobs.batches.is_empty(), "forgotten once every member opened"); // A tab with a slot (dropped on the tabs) keeps it; one from a forgotten set goes to the end. - let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, slot: Some(0), order: None }; + let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, error_source: None, slot: Some(0), order: None }; let index = app.session.add_document(Document::new("dropped.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index, "docId": id.0})).unwrap(); - let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; + let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, error_source: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; let index = app.session.add_document(Document::new("late.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index, "docId": id.0})).unwrap(); diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 8251221539..561c8eba5c 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -41,17 +41,46 @@ fn png() -> Vec { #[test] fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { - for (name, bytes) in [("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect())] { + for (name, bytes) in [ + ("notes.txt", b"ordinary text".to_vec()), + ("broken.png", b"ordinary text".to_vec()), + ("zz-bad.png", (1..=17).collect()), + ("unknown.psdt", b"ordinary text".to_vec()), + ] { let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); pick(&mut app); - assert_eq!(messages(&app), [expected(name)]); + let wanted = + if name == "unknown.psdt" { format!("Couldn't open {name}: PSD: invalid signature [111, 114, 100, 105], expected 8BPS") } else { expected(name) }; + assert_eq!(messages(&app), [wanted.as_str()]); assert!(app.session.documents().is_empty()); assert!(app.ui.recent_files.is_empty()); assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); assert!(app.ui.status_error); - assert_eq!(app.ui.status, expected(name)); + assert_eq!(app.ui.status, wanted); assert_eq!(app.ui.status.matches(name).count(), 1); } + // Interactive foreground errors now retain the source name instead of a generated Untitled-N. + let mut interactive = app_with(None); + assert_eq!( + interactive.open_bytes("unknown.psdt", b"ordinary text").unwrap_err(), + "unknown.psdt: PSD: invalid signature [111, 114, 100, 105], expected 8BPS" + ); + assert!(interactive.ui.dialogs.is_empty(), "the caller owns presentation of a returned error"); + + #[cfg(not(target_arch = "wasm32"))] + { + let mut app = app_with(Some(FileDialogAnswer::Contents("unknown.psdt".into(), b"ordinary text".to_vec()))); + app.background_jobs = true; + pick(&mut app); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("unknown.psdt")); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, "unknown.psdt", "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); + } } #[test] @@ -74,16 +103,15 @@ fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { #[test] fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); - for err in [format!("{source}: file not found"), "missing.png: permission denied".into(), "the directory is missing.png: keep this reason".into()] { + for (err, reason) in [ + (format!("{source}: file not found"), "file not found"), + ("missing.png: permission denied".into(), "permission denied"), + (format!("missing.png: {source}: file not found"), "file not found"), + ("missing.png: elsewhere/missing.png: keep this reason".into(), "elsewhere/missing.png: keep this reason"), + ("the directory is missing.png: keep this reason".into(), "the directory is missing.png: keep this reason"), + ] { let mut app = app_with(None); app.open_failed(&source, &err); - let reason = if err.starts_with(&source) { - "file not found" - } else if err.starts_with("missing.png: ") { - "permission denied" - } else { - &err - }; assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); assert!(app.ui.notices.is_empty()); } @@ -144,19 +172,173 @@ fn cancelling_file_open_does_not_show_an_error() { #[test] fn automation_and_control_open_still_return_the_original_error() { - let mut app = app_with(None); - app.services.import = Some(Box::new(|name, bytes, opts| { - photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) - })); - let err = app.open_automation_bytes("notes.txt", b"text").unwrap_err(); - assert_eq!(err, "notes.txt: codec: unrecognized image format"); - assert!(app.ui.dialogs.is_empty()); - app.services.automation_read = Some(Box::new(|_| Ok(crate::AutomationReadResult { name: "notes.txt".into(), bytes: b"text".to_vec(), save_path: None }))); - let (request, _rx) = ControlRequest::new("app.open", json!({"path": "notes.txt"})); - let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; - assert_eq!(reply["ok"], false); - assert_eq!(reply["error"], err); + // app.open reserves the template's untitled name before its separate automation decode. + for (name, expected_error, expected_control_error) in [ + ("notes.txt", "notes.txt: codec: unrecognized image format", "notes.txt: codec: unrecognized image format"), + ("unknown.psdt", "unknown.psdt: PSD: invalid signature [116, 101, 120, 116], expected 8BPS", "Untitled-1: codec: unrecognized image format"), + ] { + let mut app = app_with(None); + let err = app.open_automation_bytes(name, b"text").unwrap_err(); + assert_eq!(err, expected_error); + assert!(app.ui.dialogs.is_empty()); + let read_name = name.to_string(); + app.services.automation_read = + Some(Box::new(move |_| Ok(crate::AutomationReadResult { name: read_name.clone(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": name})); + let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], expected_control_error); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); + } +} + +/// This path must remain absent: both the foreground and worker open really fail to read it. +#[cfg(not(target_arch = "wasm32"))] +fn missing_source(tag: &str, name: &str) -> (std::path::PathBuf, String, String) { + let path = std::env::temp_dir().join(format!("photocraft-unreadable-{tag}-{}", std::process::id())).join(name); + assert!(!path.exists()); + let reason = photocraft_format::read_file(&path).unwrap_err().to_string(); + let source = path.to_string_lossy().into_owned(); + (path, source, reason) +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +struct UnreadableNativeDrop(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl egui::DroppedFile for UnreadableNativeDrop { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + panic!("a native absolute-path drop must read from disk") + } +} + +/// Apply actual worker events and check the unmodified error sent to a waiting control client. +#[cfg(not(target_arch = "wasm32"))] +fn finish_read_failure(app: &mut PhotocraftApp, source: &str, reason: &str, worker_error: &str) { + let job = app.jobs.opens.first().map(|tab| tab.job); + let reply = job.map(|job| { + let (tx, rx) = std::sync::mpsc::channel(); + app.jobs.waiters.push((job, tx)); + rx + }); + let ctx = egui::Context::default(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open job did not finish"); + crate::jobs_ui::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if let Some(reply) = reply { + assert_eq!(reply.try_recv().unwrap(), json!({"ok": false, "error": worker_error})); + } + let name = display_name(source); + let wanted = if reason == "codec: unrecognized image format" { expected(&name) } else { format!("Couldn't open {name}: {reason}") }; + assert_eq!(messages(app), [wanted]); + assert_eq!(app.ui.status, messages(app)[0]); + assert_eq!(app.ui.status.matches(name.as_str()).count(), 1); assert!(app.session.documents().is_empty()); - assert!(app.ui.dialogs.is_empty()); assert!(app.ui.notices.is_empty()); + crate::jobs_ui::tick(app, &ctx); + assert_eq!(messages(app).len(), 1, "the finished event is consumed once"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_drop_read_failures_name_the_source_once_in_foreground_and_background() { + for name in ["missing.psd", "missing.psdt"] { + let (path, source, reason) = missing_source("drop", name); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + app.open_dropped(&egui::Context::default(), vec![std::sync::Arc::new(UnreadableNativeDrop(path.clone()))], None); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_name = app.jobs.opens.first().map(|tab| tab.name.as_str()).unwrap_or(name); + if background { + assert_eq!(worker_name, if name == "missing.psdt" { "Untitled-1" } else { name }); + } + let worker_error = format!("{worker_name}: {source}: {reason}"); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } + } + + // The public path-plus-bytes API retains the source while the actual template worker is untitled. + let (_, source, _) = missing_source("template-codec", "unknown.psdt"); + let mut app = app_with(None); + app.background_jobs = true; + app.open_file(&source, b"ordinary text").unwrap(); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert_eq!(tab.path.as_deref(), Some(source.as_str())); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, &source, "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path() { + let (_, source, reason) = missing_source("recent", "missing.psd"); + for grid in [false, true] { + let mut app = app_with(None); + app.background_jobs = false; + app.ui.chrome.home_recent_grid = grid; + app.push_recent(&source); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 760.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state( + |ui, app: &mut PhotocraftApp| { + let recent = app.ui.recent_files.clone(); + crate::home_recent_ui::show_home_recent(app, ui, &recent, 600.0); + }, + app, + ); + h.run_steps(3); + h.get_by_label("missing.psd").click(); + h.run_steps(3); + finish_read_failure(h.state_mut(), &source, &reason, "no worker in this foreground control"); + assert_eq!(h.state().ui.recent_files.as_slice(), std::slice::from_ref(&source)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn os_open_read_failures_keep_the_existing_full_source_route() { + let (_, source, reason) = missing_source("os", "missing.psd"); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let mut events = vec![OsEvent::Open(vec![source.clone()])]; + app.services.os_events = Some(Box::new(move || std::mem::take(&mut events))); + app.drain_os_events(&egui::Context::default()); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_error = format!("{}: {source}: {reason}", display_name(&source)); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_recent_path() { + let (_, source, reason) = missing_source("smart-object", "missing.psd"); + for background in [false, true] { + let mut app = app_with(Some(FileDialogAnswer::Paths(vec![source.clone()]))); + app.background_jobs = background; + app.open_dialog_as_smart_object().unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + assert!(app.jobs.opens.iter().all(|tab| tab.path.is_none()), "a Smart Object remains untitled"); + assert!(app.jobs.opens.iter().all(|tab| tab.error_source.as_deref() == Some(source.as_str()))); + finish_read_failure(&mut app, &source, &reason, &format!("{source}: {reason}")); + assert!(app.ui.recent_files.is_empty()); + } } diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index e8f25a1e72..24cffe4a6e 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -877,7 +877,7 @@ pub(crate) fn show_home_recent(app: &mut PhotocraftApp, ui: &mut Ui, recent: &[S match action { RecentAction::Open(path) => { if let Err(e) = open_recent_gate(app, &path).and_then(|()| app.open_path(&path)) { - app.open_failed(&crate::file_open::display_name(&path), &e); + app.open_failed(&path, &e); } } RecentAction::Remove(path) => { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index d636067b3b..b3b2cb486e 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -42,6 +42,8 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, + /// Actual read source when it differs from the save/recent path (an untitled Smart Object). + pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, /// Its place in a set of files opened together, when it is one of several (see [`OpenOrder`]). @@ -281,13 +283,15 @@ pub fn start_open( slot: Option, order: Option, ) -> Result<(), String> { - let name = &app.open_name(name); + let source_name = name; + let name = &app.open_name(source_name); + let error_source = (path.is_none() && name.as_str() != source_name).then(|| source_name.to_string()); match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), Started::Job(job) => { - track_open(app, OpenTab { job, name: name.to_string(), path, slot, order }); + track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) } } @@ -318,7 +322,7 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or match started { Started::Done(v) => finish_open(app, &name, None, &v, None, order), Started::Job(job) => { - track_open(app, OpenTab { job, name, path: None, slot: None, order }); + track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) } } @@ -640,13 +644,19 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) { let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return }; let tab = app.jobs.opens.remove(i); + let source = tab.error_source.as_deref().or(tab.path.as_deref()).unwrap_or(&tab.name); match e.outcome { JobOutcome::Done(v) => { if let Err(err) = finish_open_tab(app, &tab, &v) { - app.open_failed(&tab.name, &err); + app.open_failed(source, &err); } } - JobOutcome::Failed(err) => app.open_failed(&tab.name, &err), + JobOutcome::Failed(err) => { + // A template's worker name is Untitled-N, while its alert names the read source. + let reason = + if tab.name != crate::file_open::display_name(source) { err.strip_prefix(&format!("{}: ", tab.name)).unwrap_or(&err) } else { &err }; + app.open_failed(source, reason); + } JobOutcome::Cancelled => { app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &tab.name)]); app.ui.status_error = false; diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 8cc19bdcf8..b7193b12db 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -343,7 +343,7 @@ fn the_opening_card_keeps_a_long_name_and_cancel_inside() { let long = "a7rv-test_2024_02_17_shot_30_3705_with_an_even_longer_suffix_that_never_ends.psb"; for name in ["short.psd", long] { h.state_mut().jobs.opens.clear(); - h.state_mut().jobs.opens.push(crate::jobs_ui::OpenTab { job, name: name.to_string(), path: None, slot: None, order: None }); + h.state_mut().jobs.opens.push(crate::jobs_ui::OpenTab { job, name: name.to_string(), path: None, error_source: None, slot: None, order: None }); h.state_mut().jobs.focus = Some(job); h.run_steps(4); let r = crate::jobs_ui::open_card_rects(&h.ctx).expect("the opening card was drawn"); diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 61ad40a919..287db29b58 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -718,6 +718,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { job: photocraft_engine::jobs::JobId(1), name: "unknown.psd".into(), path: Some("/pics/unknown.psd".into()), + error_source: None, slot: None, order: None, }; @@ -742,7 +743,8 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { // A measured capacity shows the number and drops the uncertainty warning. let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -768,7 +770,8 @@ fn memory_prompt_warns_when_little_memory_would_be_left() { let mut app = app(); let available = 3 * gb + gb / 2; let id = store_preflight(&mut app, "tight.psd", 3 * gb, Some(available)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, 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 014/124] 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 28c019e11f..c44459c1ca 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 050b476ced..c53b00be57 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 3e768fe6e66e2bf764871402dc7a3c00945a239d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 01:36:07 -0800 Subject: [PATCH 015/124] Preserve unreadable alert behavior for templates and approved opens --- crates/ui-egui/src/dialogs/open_prompt.rs | 9 ++- crates/ui-egui/src/file_open.rs | 25 ++++++- .../src/file_open/unreadable_alert_tests.rs | 36 +++++++++- crates/ui-egui/src/psd_open_tests.rs | 66 +++++++++++++++++++ 4 files changed, 131 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index e48418505d..1b770f99ce 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -502,8 +502,13 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { - app.ui.status = err.clone(); - app.ui.status_error = true; + let source = path.as_deref().unwrap_or(&name); + // A template may have reserved an Untitled name; presentation names its read source, + // while the returned error keeps the approval command's original wrapper. + let prefix = format!("{name}: "); + let error = err.strip_prefix(&prefix).unwrap_or(&err); + let reason = if name != crate::file_open::display_name(source) { error.strip_prefix(&prefix).unwrap_or(error) } else { error }; + app.open_failed(source, reason); crate::jobs_ui::end_batch(app); advance(app); crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 7ed8f34a17..c888251e1b 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -205,6 +205,29 @@ pub fn display_name(path: &str) -> String { std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string()) } +// Named PSD/PSB/templates deliberately keep the PSD parser's errors for direct callers. Only +// its missing file-header signature means unrecognized content; damaged internal signatures +// (8BIM, etc.) and a recognized 8BPS file's other parse errors must retain their reasons. +fn unrecognized_open_reason(reason: &str) -> bool { + if reason == "codec: unrecognized image format" { + return true; + } + let Some(signature) = reason.strip_prefix("PSD: invalid signature [").and_then(|s| s.strip_suffix("], expected 8BPS")) else { + return false; + }; + let mut values = signature.split(", "); + let mut found = [0u8; 4]; + for byte in &mut found { + let Some(text) = values.next() else { return false }; + let Ok(value) = text.parse::() else { return false }; + if text != value.to_string() { + return false; + } + *byte = value; + } + values.next().is_none() && &found != b"8BPS" +} + impl PhotocraftApp { /// Open `bytes` read from the file at `path`: the document is named after the file, keeps /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import @@ -375,7 +398,7 @@ impl PhotocraftApp { .or_else(|| err.strip_prefix(&source_prefix)) .or_else(|| err.strip_prefix(&name_prefix)) .unwrap_or(err); - let msg = if reason == "codec: unrecognized image format" { + let msg = if unrecognized_open_reason(reason) { crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) } else { let template = "Couldn't open {name}: {error}"; diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 561c8eba5c..a46004fec0 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -45,12 +45,13 @@ fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_docume ("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect()), + ("unknown.psd", b"ordinary text".to_vec()), + ("unknown.psb", b"ordinary text".to_vec()), ("unknown.psdt", b"ordinary text".to_vec()), ] { let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); pick(&mut app); - let wanted = - if name == "unknown.psdt" { format!("Couldn't open {name}: PSD: invalid signature [111, 114, 100, 105], expected 8BPS") } else { expected(name) }; + let wanted = expected(name); assert_eq!(messages(&app), [wanted.as_str()]); assert!(app.session.documents().is_empty()); assert!(app.ui.recent_files.is_empty()); @@ -342,3 +343,34 @@ fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_rece assert!(app.ui.recent_files.is_empty()); } } + +#[test] +fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { + // The file signature is recognized: a bad version is a PSD error, not a codec miss. + let bytes = b"8BPS\0\0".to_vec(); + let mut app = app_with(Some(FileDialogAnswer::Contents("corrupt.psdt".into(), bytes.clone()))); + pick(&mut app); + assert_eq!(messages(&app), ["Couldn't open corrupt.psdt: PSD: unsupported file version 0"]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty()); + let mut direct = app_with(None); + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "corrupt.psdt: PSD: unsupported file version 0"); + assert!(direct.ui.dialogs.is_empty()); + + // A damaged internal block or an unrelated/malformed diagnostic retains its reason. + for reason in [ + "PSD: invalid signature [0, 0, 0, 0], expected 8BIM (layer blend mode)", + "PSD: invalid signature [56, 66, 80, 83], expected 8BPS", + "PSD: invalid signature [0, 0, 0], expected 8BPS", + "PSD: invalid signature [256, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [+1, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [00, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [0, 0, 0, 0], expected 8BPS; keep this detail", + "embedded PSD: invalid signature [0, 0, 0, 0], expected 8BPS", + ] { + let mut app = app_with(None); + app.open_failed("corrupt.psdt", reason); + assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); + } +} diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 287db29b58..eb64397069 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1010,3 +1010,69 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti } let _ = std::fs::remove_dir_all(&dir); } + +/// A real inline decode after consent fails on a tiny recognized PSD header. Its raw control +/// reply is unchanged, its one alert names the source, and the next prompt retains its batch. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, b"8BPS\0\0").unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(b"8BPS\0\0".to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, name: name.into(), source, fingerprint, + required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, + }).unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = app.ui.dialogs[0].id; + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original error reply"); + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { assert!(!app.ui.status.contains(name)); } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = app.ui.dialogs.iter().find(|d| crate::open_prompt::owns_memory(&d.fields)).unwrap().id; + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.ui.dialogs.len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id}))["ok"], true); + assert_eq!(app.ui.dialogs.len(), 1); + assert_eq!(app.ui.dialogs[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + } +} From 9db3e586d9a1dae1ffd18ceb7c66d050c4051d98 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 01:58:18 -0800 Subject: [PATCH 016/124] Format template and memory approval alert regressions --- crates/ui-egui/src/psd_open_tests.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index eb64397069..1861659c33 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1029,10 +1029,20 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), ); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let first = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, name: name.into(), source, fingerprint, - required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, - }).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); let batch = crate::jobs_ui::begin_batch(&mut app); let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; @@ -1051,7 +1061,9 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e let error_id = errors[0].id; assert_eq!(app.ui.status, wanted); assert_eq!(app.ui.status.matches(source_name).count(), 1); - if name != source_name { assert!(!app.ui.status.contains(name)); } + if name != source_name { + assert!(!app.ui.status.contains(name)); + } assert!(app.ui.status_error); assert!(app.ui.notices.is_empty()); assert!(app.session.documents().is_empty()); From 85e5ec2b9862b27a1352cf6065b236f6a21e9d6f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 02:11:15 -0800 Subject: [PATCH 017/124] Correct PSD alert test oracle and approved-open header fixture --- .../src/file_open/unreadable_alert_tests.rs | 3 ++- crates/ui-egui/src/psd_open_tests.rs | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index a46004fec0..4cbfe98561 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -355,7 +355,8 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.notices.is_empty()); let mut direct = app_with(None); - assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "corrupt.psdt: PSD: unsupported file version 0"); + // The typed PSD path returns its raw IO error without adding a source-name prefix. + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "PSD: unsupported file version 0"); assert!(direct.ui.dialogs.is_empty()); // A damaged internal block or an unrelated/malformed diagnostic retains its reason. diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 1861659c33..fe3af29274 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1016,16 +1016,28 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti #[cfg(not(target_arch = "wasm32"))] #[test] fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + // File-backed decoding reads the complete 26-byte header before parsing it. Give both + // routes that same header so the unsupported version, rather than EOF, is the failure. + let header = [ + b'8', b'B', b'P', b'S', + 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { let mut app = app(); let temp = tempfile::tempdir().unwrap(); let path = file_name.map(|file| { let path = temp.path().join(file); - std::fs::write(&path, b"8BPS\0\0").unwrap(); + std::fs::write(&path, header).unwrap(); path.to_string_lossy().into_owned() }); let source = path.as_ref().map_or_else( - || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(b"8BPS\0\0".to_vec())), + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), ); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); From edc838a573989966c254652bbda5f2d355cee9f0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 02:15:01 -0800 Subject: [PATCH 018/124] Format the complete PSD approval fixture --- crates/ui-egui/src/psd_open_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index fe3af29274..03aa0c6734 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1019,8 +1019,7 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e // File-backed decoding reads the complete 26-byte header before parsing it. Give both // routes that same header so the unsupported version, rather than EOF, is the failure. let header = [ - b'8', b'B', b'P', b'S', - 0, 0, // unsupported version + b'8', b'B', b'P', b'S', 0, 0, // unsupported version 0, 0, 0, 0, 0, 0, // reserved 0, 3, // channels 0, 0, 0, 1, // height From d8c1efec890f71bc4b0347a76d31a98c6ae44f72 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:14:18 -0800 Subject: [PATCH 019/124] Preserve byte-template source through memory approval Carry read-source metadata through high-memory prompts and approval completions while retaining worker names, save paths, and raw error replies. Add real byte-template preflight approval/cancel controls and inline/background approval decoder failure regressions. Native validation remains Root-owned and unrun for this commit. --- crates/ui-egui/src/dialogs/open_prompt.rs | 12 +- .../src/file_open/unreadable_alert_tests.rs | 147 ++++++++++++++++++ crates/ui-egui/src/jobs_ui.rs | 11 +- crates/ui-egui/src/psd_open_tests.rs | 22 +-- 4 files changed, 173 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 1b770f99ce..3d0dcb2a38 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -64,6 +64,8 @@ pub struct MemoryPrompt { pub id: u64, pub name: String, pub path: Option, + /// Original read source when an untitled open has no save/recent path. + pub error_source: Option, pub slot: Option, pub order: Option, pub estimated: u64, @@ -370,6 +372,7 @@ pub fn arrive_memory( id: u64, name: String, path: Option, + error_source: Option, slot: Option, order: Option, estimated: u64, @@ -377,7 +380,7 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, error_source, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } @@ -457,6 +460,7 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result Result Result Result { - let source = path.as_deref().unwrap_or(&name); + let source = path.as_deref().or(error_source.as_deref()).unwrap_or(&name); // A template may have reserved an Untitled name; presentation names its read source, // while the returned error keeps the approval command's original wrapper. let prefix = format!("{name}: "); diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 4cbfe98561..a5c38e4485 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -375,3 +375,150 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); } } + + +#[cfg(not(target_arch = "wasm32"))] +fn template_psd_for_memory_prompt() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4, "height": 3, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "small.psd", &Default::default()).unwrap().bytes +} + +#[cfg(not(target_arch = "wasm32"))] +fn memory_dialog_reply(app: &mut PhotocraftApp, dialog: u64, accept: bool) -> serde_json::Value { + let method = if accept { "ui.dialog.confirm" } else { "ui.dialog.cancel" }; + let (request, _rx) = ControlRequest::new(method, json!({"dialog": dialog})); + let Outcome::Done(reply) = handle(app, &egui::Context::default(), &request) else { panic!("memory prompt reply is immediate") }; + reply +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_successful_template_jobs(app: &mut PhotocraftApp) { + let jobs: Vec<_> = app.jobs.opens.iter().map(|tab| tab.job).collect(); + for job in jobs { + app.session.wait_job(job).unwrap(); + } + crate::jobs_ui::tick(app, &egui::Context::default()); +} + +/// A real picked byte template reaches preflight through both immediate and worker completion. +/// Its original source is metadata only: approval still opens Untitled-1 without a save path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_prompt_keeps_the_source_through_real_open_approve_and_cancel() { + if cfg!(target_pointer_width = "32") { + return; // The scoped 3 GiB estimate charge exceeds the 32-bit product cap. + } + let gb = 1u64 << 30; + let psd = template_psd_for_memory_prompt(); + let memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + for background in [false, true] { + for accept in [false, true] { + let mut app = app_with(Some(FileDialogAnswer::Contents("card.psdt".into(), psd.clone()))); + app.background_jobs = background; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(memory, || { + pick(&mut app); + assert_eq!(app.jobs.opens.len(), usize::from(background)); + if background { + finish_successful_template_jobs(&mut app); + } + assert!(app.session.documents().is_empty()); + assert_eq!(app.held_memory_prompts.len(), 1, "use the real high-memory preflight"); + let prompt = &app.held_memory_prompts[0]; + assert_eq!(prompt.name, "Untitled-1"); + assert!(prompt.path.is_none()); + assert_eq!(prompt.error_source.as_deref(), Some("card.psdt")); + assert!(prompt.estimated > 3 * gb); + let preflight = prompt.id; + let dialog = app.ui.dialogs[0].id; + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let reply = memory_dialog_reply(&mut app, dialog, accept); + assert_eq!(reply["ok"], true, "{reply}"); + if background && accept { + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_successful_template_jobs(&mut app); + } + assert_eq!(app.session.documents().len(), usize::from(accept)); + if accept { + let opened = &app.session.documents()[0]; + assert_eq!(opened.doc.name, "Untitled-1"); + assert!(opened.path.is_none(), "error source is never a save destination"); + } + assert!(app.ui.recent_files.is_empty(), "byte input does not acquire a Recent path"); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert!(app.session.take_pending_preflight(preflight).is_none()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(!app.ui.status_error); + }); + }); + } + } +} + +/// A stored byte preflight with a valid identity but invalid PSD version drives the real +/// approval decoder, so both the immediate error and the later worker failure keep raw replies. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_replies() { + let header = vec![ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let preflight = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, name: "Untitled-1".into(), source, fingerprint, + required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, + }).unwrap(); + crate::open_prompt::arrive_memory( + &mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false, + ); + let dialog = app.ui.dialogs[0].id; + let reply = memory_dialog_reply(&mut app, dialog, true); + let reason = "PSD: unsupported file version 0"; + if background { + assert_eq!(reply["ok"], true, "the actual approval starts a worker: {reply}"); + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_read_failure(&mut app, "card.psdt", reason, &format!("Untitled-1: {reason}")); + } else { + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], format!("Untitled-1: Untitled-1: {reason}"), "preserve the approval's original wrapper"); + assert_eq!(messages(&app), [format!("Couldn't open card.psdt: {reason}")]); + } + assert_eq!(app.ui.status, format!("Couldn't open card.psdt: {reason}")); + assert_eq!(app.ui.status.matches("card.psdt").count(), 1); + assert!(!app.ui.status.contains("Untitled-1")); + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(app.session.take_pending_preflight(preflight).is_none()); + let alert = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, alert).unwrap(); + assert!(app.ui.dialogs.is_empty(), "the one error alert closes normally"); + } +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index b3b2cb486e..abdc53ae7c 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -42,7 +42,7 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, - /// Actual read source when it differs from the save/recent path (an untitled Smart Object). + /// Actual read source when it differs from the save/recent path (an untitled Smart Object or byte-backed template). pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, @@ -289,7 +289,7 @@ pub fn start_open( match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. - Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), + Started::Done(v) => finish_open(app, name, path.as_deref(), error_source.as_deref(), &v, slot, order), Started::Job(job) => { track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) @@ -320,7 +320,7 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?) }; match started { - Started::Done(v) => finish_open(app, &name, None, &v, None, order), + Started::Done(v) => finish_open(app, &name, None, Some(path), &v, None, order), Started::Job(job) => { track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) @@ -376,7 +376,7 @@ pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option, order: Opti /// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory /// preflight keeps both in its prompt. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { - let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order); + let r = finish_open(app, &tab.name, tab.path.as_deref(), tab.error_source.as_deref(), v, tab.slot, tab.order); end_batch(app); r } @@ -708,7 +708,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, error_source: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); @@ -719,6 +719,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu preflight_id, name.to_string(), path.map(str::to_string), + error_source.map(str::to_string), slot, order, estimated, diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 03aa0c6734..2e7ce2058a 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -218,7 +218,7 @@ fn memory_confirmation_dialog_and_cancel_lifecycle() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); assert_eq!(app.ui.dialogs.len(), 1); assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); let dlg_id = app.ui.dialogs[0].id; @@ -365,6 +365,7 @@ fn memory_confirmation_refuses_when_source_changed_inline() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -417,6 +418,7 @@ fn memory_confirmation_refuses_when_source_changed_async() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -466,7 +468,7 @@ fn memory_decline_advances_queue_and_cleans_batch() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, None, Some(order), 1000, Some(4000), false, false); assert_eq!(app.ui.dialogs.len(), 1); let dlg_id = app.ui.dialogs[0].id; @@ -515,8 +517,8 @@ fn batch_single_file_cancel_preserves_other_held_memory_orders() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, None, Some(order0), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, None, Some(order1), 1000, Some(4000), false, false); // Cancel first file: let dlg0 = app.ui.dialogs[0].id; @@ -553,7 +555,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); crate::open_prompt::arrive( &mut app, @@ -620,7 +622,7 @@ fn mixed_prompts_follow_arrival_order_fifo() { confirm_damage: true, }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); // First prompt shown must be damage (since it arrived first)! assert_eq!(app.ui.dialogs.len(), 1); @@ -792,7 +794,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { let gb = 1u64 << 30; let mut app = app(); let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 1); assert_eq!(app.ui.dialogs.len(), 1); assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); @@ -801,7 +803,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { // The template exception: a repeat open still creates another Untitled. let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 2); assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt"); assert_eq!(app.held_memory_prompts.len(), 2); @@ -1058,8 +1060,8 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e let batch = crate::jobs_ui::begin_batch(&mut app); let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; - crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, Some(first_order), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, Some(second_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); let dialog = app.ui.dialogs[0].id; let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog})); assert_eq!(reply["ok"], false); From eb76800acbad9f9f664bd259db355771a7f2a054 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:23:52 -0800 Subject: [PATCH 020/124] Format byte-template memory prompt source retention --- crates/ui-egui/src/dialogs/open_prompt.rs | 13 ++++++++++- .../src/file_open/unreadable_alert_tests.rs | 23 ++++++++++++------- crates/ui-egui/src/jobs_ui.rs | 10 +++++++- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 3d0dcb2a38..2d81b58729 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -380,7 +380,18 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, error_source, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { + id, + name, + path, + error_source, + slot, + order, + estimated, + available, + capacity_unknown, + uncertain_capacity_warning, + }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index a5c38e4485..a9729a9f96 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -376,7 +376,6 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { } } - #[cfg(not(target_arch = "wasm32"))] fn template_psd_for_memory_prompt() -> Vec { let mut s = photocraft_engine::Session::new(); @@ -482,13 +481,21 @@ fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_re app.background_jobs = background; let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let preflight = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, name: "Untitled-1".into(), source, fingerprint, - required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, - }).unwrap(); - crate::open_prompt::arrive_memory( - &mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false, - ); + let preflight = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); let dialog = app.ui.dialogs[0].id; let reply = memory_dialog_reply(&mut app, dialog, true); let reason = "PSD: unsupported file version 0"; diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index abdc53ae7c..bf07b69a89 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -708,7 +708,15 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, error_source: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open( + app: &mut PhotocraftApp, + name: &str, + path: Option<&str>, + error_source: Option<&str>, + v: &Value, + slot: Option, + order: Option, +) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); From 94219e012266e009e58ec1e0a0f140866ade8134 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:29:47 -0800 Subject: [PATCH 021/124] Update open completion fixtures for optional source metadata --- crates/ui-egui/src/jobs_ui/tests.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index b7193b12db..27fa1fe304 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1127,7 +1127,7 @@ fn background_open_warns_about_missing_fonts() { // What the open job leaves behind: the decoded document in the session, then its result. let (index, _) = app.session.open_document(doc, None); let id = app.session.documents()[index].doc.id; - super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); + super::finish_open(&mut app, "poster.psd", None, None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()]; assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices); } @@ -1209,7 +1209,7 @@ fn open_identity_survives_tab_reordering() { let old_index = result["document"].as_u64().unwrap() as usize; app.session.move_document(old_index, 0).unwrap(); assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, None, None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png")); @@ -1224,7 +1224,7 @@ fn open_identity_survives_an_earlier_tab_closing() { let (result, imported) = identified_result(&app, result); app.session.close(1).unwrap(); app.session.set_active(0); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, Some(0), None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document"); @@ -1246,13 +1246,13 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); result["docId"] = json!(imported.0); assert!( - super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(), + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, None, None).is_err(), "a closed identity must not fall back to the old tab index" ); control.assert_untouched(&app); @@ -1273,9 +1273,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { let (second, second_id) = identified_result(&app, second); // All engine applies have finished. Handling the first ordinary result removes its tab, // shifting the second result before its UI callback runs. - super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap(); - super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap(); - super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap(); + super::finish_open(&mut app, "profile.png", Some("profile.png"), None, &prompt, None, None).unwrap(); + super::finish_open(&mut app, "first.png", Some("first.png"), None, &first, None, None).unwrap(); + super::finish_open(&mut app, "second.png", Some("second.png"), None, &second, None, None).unwrap(); assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::>(), ["profile.png", "first.png", "second.png"]); assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::>(), [first_id, second_id]); assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt"); From ee4cfc0a087da1cc9346ce95772ffa743b547747 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:33:44 -0800 Subject: [PATCH 022/124] Format open fixture source argument calls --- crates/ui-egui/src/jobs_ui/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 27fa1fe304..6d33028859 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1246,7 +1246,10 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!( + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), + "invalid identity was accepted: {result}" + ); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); From 811eddf4ef74655b0aa1aa78abc214f1be3e4842 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 10:32:12 -0800 Subject: [PATCH 023/124] test: apply bounded CI formatting repair for PR15372 --- crates/ui-egui/src/smudge_bar_pressure_size_tests.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs index 0bf4464b1e..a6b9dddede 100644 --- a/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs +++ b/crates/ui-egui/src/smudge_bar_pressure_size_tests.rs @@ -16,10 +16,8 @@ fn bar(tool: Tool) -> Harness<'static, Box> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); app.ui.tool = tool; - let mut h = Harness::builder() - .with_size(vec2(1600.0, 400.0)) - .with_context(app.ctx().clone()) - .build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + let mut h = + Harness::builder().with_size(vec2(1600.0, 400.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); h.run_steps(4); h } 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 024/124] 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 1b4bb5f9d4..9380424ebd 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 9527bc2453..aec8cd6b52 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 5915e4f2cd..9897c42179 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 025/124] 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 9897c42179..9d7bc0c26b 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 026/124] 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 ab2b7d2a09..49296ec59e 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 aec8cd6b52..737227e7b4 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 9d7bc0c26b..fef671fa6b 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 a92adf7fe8..a4d211db0d 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 027/124] 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 57a836fc1e..951fa032c7 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 3d638c8a4e..b246b3713e 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 1b93cd8ac6..b7ba3da110 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 0000000000..0e4277b884 --- /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 791a102c59..99208407c4 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 4f265a3202..5a19067a7b 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 a3a2311201..24fe70102f 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 d796288eeb..fcc3b51be7 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 615677d840..a02b81b611 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 9f4d44ac43..bc72e6a35c 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 e12030fe52..b4b0a7570a 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 028/124] 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 0e4277b884..4f58458169 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 029/124] 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 b246b3713e..f7f82fce13 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 030/124] 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 4b7963e120..86e6da4c8c 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 fef671fa6b..9a16352b45 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 6d9c82f67e..cf9cd9ba28 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 031/124] 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 2d11728a8c..73eee2cb9d 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 aec3f8a8f1..3e8ce71595 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 e20de57d9b..2d16f026b1 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 98b08b013a96d508c725bc7f35b6387ff3ad448e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:36:43 +0100 Subject: [PATCH 032/124] Artboard from Group: an empty group goes right of the topmost board (#14558) A group without bounds (empty, or holding only an adjustment layer) used to become a board over the whole canvas, on top of any existing board. Once the document has artboards, it now gets the topmost artboard's size, placed GAP (100 px) right of it at the same top, and the canvas grows to show it. Without artboards it still covers the canvas, and a group with content keeps its own bounds. The slot is computed in i64; with no room right of a board at the far right edge the command fails and leaves the document unchanged (#931). --- crates/engine/src/cmd/artboard_cmds.rs | 24 ++++- .../from_group_empty_placement_tests.rs | 95 +++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 9a12568cd3..30dd8cfaa5 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -369,9 +369,19 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } + let topmost = doc.artboards().last().map(|b| b.2.rect); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; // A hidden group keeps today's measure (not measured in the reference). - let rect = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }.unwrap_or(canvas); + let bounds = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }; + // A group without bounds covers the canvas, or once there are boards, takes the slot + // right of the topmost one (#14558). + let rect = match (bounds, topmost) { + (Some(r), _) => r, + (None, None) => canvas, + (None, Some(board)) => { + right_of(board).ok_or_else(|| bad(cmd, format!("no room for an artboard right of the topmost one (its right edge is x = {})", board.x1)))? + } + }; set_artboard(l, Artboard { rect, background, preset }); // As in the reference application, the new artboard is Normal at 100 % whatever the group had. l.blend = photocraft_color::BlendMode::Normal; @@ -385,6 +395,14 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// A board the size of `board`, [`GAP`] right of it at the same top; `None` past the 32-bit range +/// (computed in i64, #931). +fn right_of(board: Rect) -> Option { + let x0 = i32::try_from(i64::from(board.x1) + i64::from(GAP)).ok()?; + let x1 = i32::try_from(i64::from(x0) + i64::from(board.width())).ok()?; + Some(Rect::new(x0, board.y0, x1, board.y1)) +} + /// [`layer_multi_cmds::layer_bounds`](crate::layer_multi_cmds::layer_bounds) of what shows: a /// group unions only its visible children, so hidden layers (and a hidden group's children) don't /// size the board Artboard from Group makes (#14553). @@ -1054,6 +1072,10 @@ mod from_layers_history_name_tests; #[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"] mod from_group_hidden_bounds_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_group_empty_placement_tests.rs"] +mod from_group_empty_placement_tests; + #[cfg(test)] #[path = "artboard_cmds/overlapping_areas_tests.rs"] mod overlapping_areas_tests; diff --git a/crates/engine/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs b/crates/engine/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs new file mode 100644 index 0000000000..d25a24fa6b --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/from_group_empty_placement_tests.rs @@ -0,0 +1,95 @@ +//! Artboard from Group on a group without bounds (#14558): the canvas when the document has no +//! artboard yet, else a board of the topmost artboard's size, `GAP` right of it at the same top. + +use super::*; +use photocraft_geom::Rect; + +/// 800 x 600 with the white Background, the artboards `boards` (`[x, y, w, h]`, bottom to top) +/// and an empty top-level group "Empty" above them. Returns the session and Empty's id. +fn session_with(boards: &[[i32; 4]]) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + for b in boards { + s.execute("layer.new.artboard", json!({"rect": b})).unwrap(); + } + let id = s.edit("Empty", |doc, active| Ok(*active.insert(doc.insert_above(None, Layer::group("Empty", vec![]))))).unwrap(); + (s, id) +} + +/// [`session_with`] with no board, or with "Artboard 1" at 100,100 to 600,450. +fn session(board: bool) -> (Session, LayerId) { + session_with(if board { &[[100, 100, 500, 350]] } else { &[] }) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn from_group(s: &mut Session, id: LayerId) -> Result { + s.execute("layer.new.artboardFromGroup", json!({"layer": id.0})) +} + +fn board_rect(s: &Session, id: LayerId) -> Rect { + doc(s).layer(id).unwrap().artboard().unwrap().rect +} + +#[test] +fn an_empty_group_goes_right_of_the_topmost_board() { + let (mut s, id) = session(true); + let r = from_group(&mut s, id).unwrap(); + assert_eq!(r["rect"], json!([700, 100, 500, 350])); + assert_eq!(board_rect(&s, id), Rect::new(700, 100, 1200, 450)); + assert!(doc(&s).bounds().contains_rect(&Rect::new(700, 100, 1200, 450)), "the canvas grew to show it: {:?}", doc(&s).bounds()); +} + +#[test] +fn without_artboards_an_empty_group_covers_the_canvas() { + let (mut s, id) = session(false); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(0, 0, 800, 600)); + assert_eq!(doc(&s).bounds(), Rect::new(0, 0, 800, 600)); +} + +/// A group with content keeps its own bounds when boards exist. +#[test] +fn a_group_with_content_keeps_its_bounds_beside_boards() { + let (mut s, id) = session(true); + s.edit("Red", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(650, 50, 750, 150), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(650, 50, 750, 150)); +} + +/// With several boards (not measured) the slot follows the topmost board in the Layers panel, +/// not the rightmost one. +#[test] +fn the_slot_follows_the_topmost_board_not_the_rightmost() { + // The topmost board is a small one left of the 100,100 to 600,450 board. + let (mut s, id) = session_with(&[[100, 100, 500, 350], [0, 480, 60, 40]]); + from_group(&mut s, id).unwrap(); + assert_eq!(board_rect(&s, id), Rect::new(60 + GAP, 480, 120 + GAP, 520)); +} + +/// #931: a topmost board at the far right edge leaves no room right of it; the command says so +/// and changes nothing, instead of wrapping. +#[test] +fn no_room_right_of_a_far_right_board_is_an_error() { + let (mut s, id) = session(false); + s.edit("Far", |doc, _| { + let mut g = Layer::group("Far", vec![]); + set_artboard(&mut g, Artboard::new(Rect::new(i32::MAX - 600, 0, i32::MAX - 50, 300))); + doc.insert_above(None, g); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = from_group(&mut s, id).unwrap_err().to_string(); + assert!(e.contains("no room"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "the document changed"); +} From f9fda28c3f7965d6798b4e609ab91bb32edc2add Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 03:05:41 -0600 Subject: [PATCH 033/124] Duplicate Layer: propose the layer's own name for another or a new document Choosing another open document or New in Duplicate Layer now rewrites As to the layer's plain name, and choosing the source document gives " copy" back. The copy keeps that name also beside a layer of the same name; a Background goes to another document as a normal layer named "Background" and to New as a Background. An empty As takes the destination's default. Dragging layers between documents keeps its names. The existing dialog tests that expected "Ink copy" in another or a new document now expect "Ink". Fixes #14604 --- crates/ui-egui/src/dialogs.rs | 2 + .../dialogs/duplicate_layer_indexed_tests.rs | 2 +- ...plicate_layer_other_document_name_tests.rs | 158 ++++++++++++++++++ .../ui-egui/src/dialogs/duplicate_layer_ui.rs | 36 +++- 4 files changed, 190 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8e827d7e4d..96a4d9a0f1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -710,6 +710,8 @@ pub mod delete_layer_prompt; pub mod discard_ui; pub mod disk_change_prompt; pub mod distort_ui; +#[cfg(test)] +mod duplicate_layer_other_document_name_tests; pub mod duplicate_layer_ui; pub mod equalize_ui; pub mod export_dialog; diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs index 96958d5d6a..e1df6960ad 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs @@ -87,7 +87,7 @@ fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { crate::dialogs::testing::show(&mut app); } let names: Vec<_> = app.session.documents()[2].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(names.contains(&"Ink copy".to_string()), "Card receives the copy: {names:?}"); + assert!(names.contains(&"Ink".to_string()), "Card receives the copy: {names:?}"); assert_eq!(app.session.documents()[1].doc.layer_count(), palette_layers, "the Indexed document is untouched"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); } diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs new file mode 100644 index 0000000000..da3ffc9c89 --- /dev/null +++ b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs @@ -0,0 +1,158 @@ +//! #14604: Duplicate Layer proposes the layer's own name for another document or New, and " copy" for the +//! source document; the copy keeps that name also beside a layer of the same name. A Background goes to another +//! document as a normal layer named "Background" and to New as a Background. A typed name is used as typed; an empty +//! As takes the destination's default. Dragging between documents keeps its names. + +use craft::ui::dialog::DialogId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{set, top}; + +/// "source" (active: Background, then "Top") and "target" (Background, then a layer also named "Top"). +fn app() -> Box { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "source"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("file.new", json!({"width": 20, "height": 20, "name": "target"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.set_active(0); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn open(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "layer.duplicate", json!({})).unwrap(); + crate::dialogs::testing::show(app); + top(app) +} + +/// Chooses the Document entry `value` and shows the dialog once. +fn choose(app: &mut PhotocraftApp, dialog: DialogId, value: Value) { + set(app, dialog, "document", value).unwrap(); + crate::dialogs::testing::show(app); +} + +fn proposed(app: &PhotocraftApp, dialog: DialogId) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|d| d.id == dialog).and_then(|d| d.fields).unwrap()["name"].clone() +} + +fn doc_key(app: &PhotocraftApp, i: usize) -> Value { + json!(app.session.documents()[i].doc.id.0.to_string()) +} + +fn ok(app: &mut PhotocraftApp, dialog: DialogId) { + let ctx = app.ctx().clone(); + crate::dialogs::confirm(app, &ctx, dialog).unwrap(); + for _ in 0..2 { + crate::dialogs::testing::show(app); + } +} + +fn names(app: &PhotocraftApp, i: usize) -> Vec { + app.session.documents()[i].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() +} + +fn count(app: &PhotocraftApp, i: usize, name: &str) -> usize { + names(app, i).iter().filter(|n| *n == name).count() +} + +#[test] +fn the_document_choice_rewrites_the_proposed_name() { + let mut app = app(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Top copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Top"), "another document: the plain name"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Top"), "New: the plain name"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Top copy"), "the source again: the copy name"); +} + +#[test] +fn the_plain_name_lands_beside_a_layer_of_the_same_name_and_in_a_new_document() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "{:?}", names(&app, 1)); + assert_eq!(count(&app, 1, "Top copy"), 0); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = app.session.documents().len() - 1; + assert_eq!(names(&app, new), vec!["Top".to_string()]); +} + +#[test] +fn a_background_arrives_as_background_in_another_document_and_in_new() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + ok(&mut app, dialog); + let target = &app.session.documents()[1].doc; + let copy = target.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.name == "Background").find(|l| !target.is_background(l.id)); + assert!(copy.is_some(), "a normal layer named Background: {:?}", names(&app, 1)); + app.session.set_active(0); + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + choose(&mut app, dialog, json!("new")); + ok(&mut app, dialog); + let new = &app.session.documents().last().unwrap().doc; + assert!(new.background().is_some_and(|l| l.name == "Background"), "{:?}", names(&app, app.session.documents().len() - 1)); +} + +#[test] +fn a_typed_name_is_used_and_an_empty_one_takes_the_default() { + let mut app = app(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target.clone()); + set(&mut app, dialog, "name", json!("Typed copy")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Typed copy"), 1); + app.session.set_active(0); + let dialog = open(&mut app); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Top"), 2, "empty As into another document: the plain name"); + app.session.set_active(0); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 0, "Top copy"), 1, "empty As in the source: the copy name"); +} + +#[test] +fn dragging_between_documents_keeps_its_names() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + let before = names(&app, 1).len(); + app.run("layer.copyToDocument", json!({"source": 0, "document": 1, "layers": [bg.0]})).unwrap(); + let after = names(&app, 1); + assert_eq!(after.len(), before + 1); + assert!(!after.iter().any(|n| n == "Background copy")); + assert_eq!(after.iter().filter(|n| *n == "Background").count(), 1, "a dragged Background is renamed as today: {after:?}"); +} + +#[test] +fn an_empty_name_for_a_background_into_another_document_is_background() { + let mut app = app(); + let bg = app.session.active().unwrap().doc.background().unwrap().id; + app.session.select_layer(bg).unwrap(); + let dialog = open(&mut app); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + set(&mut app, dialog, "name", json!("")).unwrap(); + ok(&mut app, dialog); + assert_eq!(count(&app, 1, "Background"), 2, "the target's own Background and the copy: {:?}", names(&app, 1)); +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index 59e6ace51c..63018d3c14 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -3,7 +3,7 @@ //! the New Layer button still duplicate at once. use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; -use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -62,7 +62,19 @@ pub fn open(app: &mut PhotocraftApp) -> Result { }; let mut options: Vec<(String, Label)> = destinations(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); options.push(("new".to_string(), Label::from(tl!("New")))); + // Another document or New proposes the layer's own name; the source document, " copy" again (#14604). + let names = name.clone().map(|copy| (copy, layer.name.clone())); + let shown_for = std::sync::Mutex::new(source.to_string()); Ok(params::open_param(app, KEY, DialogFields::new(), captured, move |fields: &mut DialogFields| { + if let Some((copy, plain)) = &names { + let chosen = fields.text("document").map(str::to_owned); + let mut shown = shown_for.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(chosen) = chosen.filter(|chosen| *chosen != *shown) { + let proposed = if chosen == source.to_string() { copy } else { plain }; + fields.set("name", FieldValue::Text(proposed.clone())); + *shown = chosen; + } + } let mut rows = Vec::new(); if let Some(name) = &name { rows.push(Param::new("name", tl!("As:"), ParamKind::text(name.clone()))); @@ -109,10 +121,20 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe fn duplicate(app: &mut PhotocraftApp, fields: &DialogFields) -> Result { let index = app.session.active_index().ok_or("The document is closed")?; let mut params = serde_json::Map::new(); - if let Some(name) = fields.text("name") { - params.insert("name".into(), json!(name)); + let destination = destination(app, fields)?; + match fields.text("name") { + Some(name) if !name.is_empty() => { + params.insert("name".into(), json!(name)); + } + // An empty As: another document or New takes the layer's own name, as the dialog proposes for them (#14604). + Some(_) if !matches!(destination, Destination::Document(d) if d == index) => { + if let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) { + params.insert("name".into(), json!(layer.name)); + } + } + _ => {} } - match destination(app, fields)? { + match destination { Destination::New => { if let Some(doc_name) = fields.text("documentName").filter(|n| !n.is_empty()) { params.insert("documentName".into(), json!(doc_name)); @@ -192,7 +214,7 @@ mod tests { set(&mut app, dialog, "document", pick).unwrap(); confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(app.session.documents()[0].doc.layer_count(), 2); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -207,7 +229,7 @@ mod tests { assert_eq!(app.session.active_index(), Some(1)); assert_eq!(app.session.documents()[1].doc.name, "Card"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); - assert!(names(&app, 1).contains(&"Ink copy".to_string())); + assert!(names(&app, 1).contains(&"Ink".to_string())); } #[test] @@ -258,7 +280,7 @@ mod tests { let docs = app.session.documents(); let spare = docs.iter().position(|d| d.doc.name == "Spare").unwrap(); let spare_names: Vec<_> = docs[spare].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); - assert!(spare_names.contains(&"Ink copy".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); + assert!(spare_names.contains(&"Ink".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); if let Some(card) = docs.iter().position(|d| d.doc.name == "Card") { assert_eq!(docs[card].doc.layer_count(), 1, "{change}: Card is untouched"); } From b846e831f02ee7479d73f71eb8f4f6731b7f77ad Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 06:08:51 -0600 Subject: [PATCH 034/124] Duplicate Layer: groups keep their naming; a typed As: name survives destination changes (CodeRabbit on #16090) Groups stay out of the new proposal policy (dialog and duplicate); the proposal only replaces an untouched As: value. Tests: a_typed_name_survives_a_change_of_destination, a_groups_proposal_does_not_change_with_the_destination. --- ...plicate_layer_other_document_name_tests.rs | 30 +++++++++++++++++++ .../ui-egui/src/dialogs/duplicate_layer_ui.rs | 15 ++++++++-- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs index da3ffc9c89..72e14c7437 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_other_document_name_tests.rs @@ -156,3 +156,33 @@ fn an_empty_name_for_a_background_into_another_document_is_background() { ok(&mut app, dialog); assert_eq!(count(&app, 1, "Background"), 2, "the target's own Background and the copy: {:?}", names(&app, 1)); } + +/// A name the user typed survives a change of destination; only an untouched proposal is rewritten (CodeRabbit on #16090). +#[test] +fn a_typed_name_survives_a_change_of_destination() { + let mut app = app(); + let dialog = open(&mut app); + set(&mut app, dialog, "name", json!("Shadow")).unwrap(); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "New"); + let source = doc_key(&app, 0); + choose(&mut app, dialog, source); + assert_eq!(proposed(&app, dialog), json!("Shadow"), "the source again"); +} + +/// A group is outside the new proposal policy: its " copy" stays whatever the destination (CodeRabbit on #16090). +#[test] +fn a_groups_proposal_does_not_change_with_the_destination() { + let mut app = app(); + app.run("layer.new.group", json!({"name": "Folder"})).unwrap(); + let dialog = open(&mut app); + assert_eq!(proposed(&app, dialog), json!("Folder copy")); + let target = doc_key(&app, 1); + choose(&mut app, dialog, target); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "another document"); + choose(&mut app, dialog, json!("new")); + assert_eq!(proposed(&app, dialog), json!("Folder copy"), "New"); +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index 63018d3c14..559ddbf263 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -63,15 +63,23 @@ pub fn open(app: &mut PhotocraftApp) -> Result { let mut options: Vec<(String, Label)> = destinations(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); options.push(("new".to_string(), Label::from(tl!("New")))); // Another document or New proposes the layer's own name; the source document, " copy" again (#14604). - let names = name.clone().map(|copy| (copy, layer.name.clone())); + // A group's naming is not measured and stays as it was (CodeRabbit on #16090). + let names = name.clone().filter(|_| !layer.is_group()).map(|copy| (copy, layer.name.clone())); let shown_for = std::sync::Mutex::new(source.to_string()); + // The proposal the As: field currently holds: only an untouched one is replaced when the destination changes. + let proposal = std::sync::Mutex::new(name.clone().unwrap_or_default()); Ok(params::open_param(app, KEY, DialogFields::new(), captured, move |fields: &mut DialogFields| { if let Some((copy, plain)) = &names { let chosen = fields.text("document").map(str::to_owned); let mut shown = shown_for.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(chosen) = chosen.filter(|chosen| *chosen != *shown) { let proposed = if chosen == source.to_string() { copy } else { plain }; - fields.set("name", FieldValue::Text(proposed.clone())); + let mut last = proposal.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // A name the user typed is theirs: keep it across destination changes (CodeRabbit on #16090). + if fields.text("name").is_none_or(|now| now.is_empty() || now == *last) { + fields.set("name", FieldValue::Text(proposed.clone())); + *last = proposed.clone(); + } *shown = chosen; } } @@ -127,8 +135,9 @@ fn duplicate(app: &mut PhotocraftApp, fields: &DialogFields) -> Result { - if let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) { + if let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).filter(|l| !l.is_group()) { params.insert("name".into(), json!(layer.name)); } } From f858820daffa99f939cb084076fe88efe1650ca2 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 05:29:10 -0600 Subject: [PATCH 035/124] 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 0000000000..c6a9f9f45a --- /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 5668bd24ac..97f388b6e5 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 c018f0a9fed83aeb504e92c90554182101bed03e Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:01:22 +0100 Subject: [PATCH 036/124] Make a Red Eye press outside the selection silent A Red Eye press that starts outside the selection already changed no pixels and added no History state, but the command returned the miss error "no red-eye pixels near the click", which the app showed in the status bar as an error. Photoshop does nothing and shows nothing. The press point is now checked before the edit and returns Ok with pixels 0 and outsideSelection true, so the status bar stays empty; a real miss inside the selection keeps its result. Fixes #13096. --- crates/engine/src/cmd/redeye_cmds.rs | 18 ++++---- .../src/cmd/redeye_history_state_tests.rs | 8 +++- .../src/cmd/redeye_outside_selection_tests.rs | 41 ++++++++++++++++++- crates/ui-egui/src/tools/retouch_ui/tests.rs | 35 ++++++++++++++++ 4 files changed, 92 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/redeye_cmds.rs b/crates/engine/src/cmd/redeye_cmds.rs index 305b094846..15ebb9b16b 100644 --- a/crates/engine/src/cmd/redeye_cmds.rs +++ b/crates/engine/src/cmd/redeye_cmds.rs @@ -249,18 +249,22 @@ fn red_eye(s: &mut Session, p: &Value) -> Result { let pupil = pupil_raw.clamp(1.0, 100.0); let darken = darken.clamp(0.0, 100.0); let id = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|d| d.active_layer) }; + // The press point decides (#12576): a press outside the selection does nothing, not clipped, and + // like Photoshop it is silent (#13096): no pixels, no state, no message. Feathered (partly + // selected) and off-canvas presses were not measured and keep today's behaviour: any value above + // 0 counts as inside, and off-canvas presses are not checked. + if let (Some(&first), Some(d)) = (pts.first(), s.active()) + && d.doc.bounds().contains(first.0, first.1) + && d.doc.selection.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) + { + return Ok(json!({ "damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true })); + } let (damage, total) = s.edit("Red Eye Removal Tool", |doc, active| { let canvas = doc.bounds(); let sel = doc.selection.clone(); let layer = id.or(*active); let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?; let Some(&first) = pts.first() else { return Err(EngineError::Other(MISS.into())) }; - // The press point decides (#12576): a press outside the selection is refused like a miss, - // not clipped. Feathered (partly selected) and off-canvas presses were not measured and keep - // today's behaviour: any value above 0 counts as inside, and off-canvas presses are not checked. - if canvas.contains(first.0, first.1) && sel.as_ref().is_some_and(|m| m.sample_channel(first.0, first.1, 0) <= 0.0) { - return Err(EngineError::Other(MISS.into())); - } // The Background always locks transparency, so only a click on a clear pixel counts. let on_locked_clear = lock && surf.rgba(first.0, first.1)[3] <= 1.0e-5; let mut total = 0u32; @@ -286,7 +290,7 @@ pub fn specs() -> Vec { label: "Red Eye", menu: &[], shortcut: None, - params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n}"#, + params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n, "outsideSelection":true?}"#, enabled, run: red_eye, journal: true, diff --git a/crates/engine/src/cmd/redeye_history_state_tests.rs b/crates/engine/src/cmd/redeye_history_state_tests.rs index 20fb8c7a6b..73bc74b55e 100644 --- a/crates/engine/src/cmd/redeye_history_state_tests.rs +++ b/crates/engine/src/cmd/redeye_history_state_tests.rs @@ -127,7 +127,13 @@ fn refused_clicks_add_no_state() { refused(&mut s, params, case); } s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); - refused(&mut s, json!({"x": 8, "y": 8}), "a click outside the selection"); + // #13096: a click outside the selection does nothing silently: an Ok with no state. + let (n, _) = last(&s); + let before = pixels(&s); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap(); + assert_eq!((r["pixels"].as_u64(), r["outsideSelection"].as_bool()), (Some(0), Some(true)), "{r}"); + assert_eq!(last(&s).0, n, "a click outside the selection: no state"); + assert!(pixels(&s) == before, "a click outside the selection"); unchanged_state(&mut s, json!({"x": 44, "y": 44}), "a click inside the selection"); s.execute("select.deselect", json!({})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); diff --git a/crates/engine/src/cmd/redeye_outside_selection_tests.rs b/crates/engine/src/cmd/redeye_outside_selection_tests.rs index 8bc173e223..9c1ffce326 100644 --- a/crates/engine/src/cmd/redeye_outside_selection_tests.rs +++ b/crates/engine/src/cmd/redeye_outside_selection_tests.rs @@ -1,5 +1,6 @@ //! #12576: a Red Eye press outside the selection does nothing and adds no History state; a press //! inside it is clipped to the selection as before, and with no selection nothing changes. +//! #13096: the outside press is silent, an `Ok` that says so, not the miss error. use serde_json::{Value, json}; @@ -23,7 +24,7 @@ fn eyes() -> Session { /// The left half of eye B: x 450–499. fn select_left_half_of_eye_b(s: &mut Session) { - s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 1000})).unwrap(); } /// History length, and the Background's pixels as one value per channel. @@ -53,10 +54,46 @@ fn a_press_outside_the_selection_changes_nothing_and_adds_no_state() { let (states, cols, r) = press(&mut s, params.clone()); assert_eq!(cols, None, "{params}: pixels changed"); assert_eq!(states, 0, "{params}: a history state was added"); - assert_eq!(r, Err(MISS.to_string()), "{params}"); + let r = r.unwrap_or_else(|e| panic!("{params}: an outside press is not an error: {e}")); + assert_eq!(r, json!({"damage": [0, 0, 0, 0], "pixels": 0, "outsideSelection": true}), "{params}"); } } +#[test] +fn an_outside_press_is_silent_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": "rgb", "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": "#d22828"})).unwrap(); + s.execute("select.rect", json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap_or_else(|e| panic!("{depth} bit: {e}")); + assert_eq!(r["pixels"], 0, "{depth} bit"); + assert_eq!(r["outsideSelection"], true, "{depth} bit"); + assert_eq!(s.active().unwrap().history.past_len(), n, "{depth} bit: no state"); + } +} + +#[test] +fn a_miss_inside_the_selection_keeps_its_result() { + // On a dark blue patch inside the selection: the tool runs and leaves one unchanged state, as before. + let mut s = eyes(); + s.execute("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 100})).unwrap(); + s.execute("edit.fill", json!({"color": "#283c78"})).unwrap(); + select_left_half_of_eye_b(&mut s); + let (states, cols, r) = press(&mut s, json!({"x": 475, "y": 40, "pupilSize": 1})); + let r = r.unwrap(); + assert_eq!((r["pixels"].as_u64(), r.get("outsideSelection")), (Some(0), None), "{r}"); + assert_eq!((states, cols), (1, None)); + // On a clear pixel under Lock transparent pixels inside the selection: still the miss error. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let n = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 475, "y": 40, "pupilSize": 1})).map_err(|e| e.to_string()); + assert_eq!(r, Err(MISS.to_string())); + assert_eq!(s.active().unwrap().history.past_len(), n); +} + #[test] fn a_press_inside_the_selection_is_clipped_and_adds_one_state() { // A batch whose first point is inside runs, and x 499.5 is still on the last selected column. diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index 62ecc823d2..c2ee4e7a2b 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -834,3 +834,38 @@ fn an_empty_clone_source_slot_refuses_to_paint() { assert!(app.ui.clone_source.is_some(), "the old ⌥-click point is still remembered"); assert!(crate::retouch_ui::clone_params(&app).is_none()); } + +/// #13096: a Red Eye press outside the selection does nothing and says nothing, as in Photoshop: +/// no status message, no error, no History state and no pixel change. +#[test] +fn a_red_eye_press_outside_the_selection_is_silent() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "mode": "rgb", "depth": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#c08a68"})).unwrap(); + for cx in [200, 500] { + for (r, color) in [(40, "#ffffff"), (30, "#d22828")] { + app.run("select.rect", json!({"x": cx - r, "y": 200 - r, "width": 2 * r, "height": 2 * r, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + } + } + // The left half of eye B: x 450–499. A press at x 500.0 lands on pixel 499, so press at 500.5. + app.run("select.rect", json!({"x": 450, "y": 0, "width": 50, "height": 600})).unwrap(); + app.ui.tool = Tool::RedEye; + app.ui.status.clear(); + app.ui.status_error = false; + let snapshot = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + (st.history.past_len(), active(app).surface().unwrap().read_region(st.doc.bounds())) + }; + let (states, pixels) = snapshot(&app); + gesture(&mut app, &[[500.5, 200.5]]); + assert_eq!(app.ui.status, "", "no status message"); + assert!(!app.ui.status_error); + let (after_states, after_pixels) = snapshot(&app); + assert_eq!(after_states, states, "no History state"); + assert!(after_pixels == pixels, "no pixel change"); + // A press inside the selection still corrects the left half. + gesture(&mut app, &[[490.5, 200.5]]); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(snapshot(&app).0, states + 1); +} From 1342fb73b075c9ba847c57b8a14c83c28c9810a9 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:34:31 +0100 Subject: [PATCH 037/124] Start a new Gradient Overlay at grey 215 to white, Smooth A new Gradient Overlay (the dialog page, its Reset to Default and layer.layerStyle.gradientOverlay without colours or stops) now starts at the reference application's factory gradient: grey 215 to white with the Smooth method at Smoothness 100 %, instead of black to white with straight stops. effect_defaults carries the stop list the page reads plus the method, and the factory effect is built from those defaults so it records the Smooth source. Commands that name their own colours or stops keep the straight stops they made before, and an overlay without a recorded method still opens as Custom so an unchanged OK keeps its baked curve. Fixes #14900. --- crates/engine/src/layer_style.rs | 22 ++- .../src/layer_style/gradient_overlay.rs | 13 +- .../gradient_overlay_defaults_tests.rs | 142 ++++++++++++++++++ crates/ui-egui/src/dialogs/layer_style.rs | 5 + 4 files changed, 175 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/layer_style/gradient_overlay_defaults_tests.rs diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 37317609d5..e323c42380 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -162,7 +162,9 @@ pub fn effect_defaults(kind: &str) -> Value { "stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "color": "#000000"}), "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}), "gradientOverlay" => { - json!({"blend": "Normal", "opacity": 100, "from": "#000000", "to": "#ffffff", "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "custom"}) + // The reference application's "Gray, White" with the Smooth method (#14900). The page + // edits the stop list; From/To name the same ends for callers that read them. + json!({"blend": "Normal", "opacity": 100, "from": "#d7d7d7", "to": "#ffffff", "stops": [[0, "#d7d7d7"], [1, "#ffffff"]], "reverse": false, "style": "linear", "angle": 90, "scale": 100, "method": "smooth", "smoothness": 100}) } "patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}), "bevelEmboss" => { @@ -551,6 +553,12 @@ pub fn contour_to_shc_all(list: &[&Contour]) -> Result> { craft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}"))) } +/// A Gradient Overlay with `Gradient::default()` (black to white, straight stops) and no recorded +/// method: what a command that names its own colours or stops starts from. +fn blank_gradient_overlay() -> Effect { + Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } +} + /// An effect of `kind` with its factory settings (before params are applied). fn fresh_effect(kind: &str) -> Option { let shadow = |inner: bool| Shadow { @@ -596,7 +604,10 @@ fn fresh_effect(kind: &str) -> Option { }), "colorOverlay" => Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 0.0, 0.0) }, "gradientOverlay" => { - Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false, interpolation: None } + // The factory values carry the recorded Smooth method, so build them like the page does. + let mut fx = blank_gradient_overlay(); + overlay_effect(&mut fx, &effect_defaults(kind)); + fx } "patternOverlay" => Effect::PatternOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), @@ -972,7 +983,10 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) { /// spread, range in percent; sizes in px; angles in degrees). pub fn effect_from_params(kind: &str, p: &Value) -> Option { crate::commands::check_f32_values("layer.layerStyle", p).ok()?; - let mut fx = fresh_effect(kind)?; + // A Gradient Overlay given its own colours or stops keeps today's straight stops unless the + // params pick a method; only the factory one (#14900) starts from the Smooth grey to white. + let mut fx = + if kind == "gradientOverlay" && ["from", "to", "stops"].iter().any(|k| p.get(k).is_some()) { blank_gradient_overlay() } else { fresh_effect(kind)? }; overlay_effect(&mut fx, p); Some(fx) } @@ -1284,6 +1298,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { Ok(Value::Null) } +#[cfg(test)] +mod gradient_overlay_defaults_tests; #[cfg(test)] mod outer_glow_defaults_tests; diff --git a/crates/engine/src/layer_style/gradient_overlay.rs b/crates/engine/src/layer_style/gradient_overlay.rs index 217f6fd70c..aa1a0ca88d 100644 --- a/crates/engine/src/layer_style/gradient_overlay.rs +++ b/crates/engine/src/layer_style/gradient_overlay.rs @@ -248,13 +248,18 @@ mod tests { } #[test] - fn reset_to_factory_defaults_removes_the_recorded_method() { + fn reset_to_factory_defaults_restores_the_factory_gradient_and_method() { let mut gradient = Gradient::default(); let mut source = None; - overlay(&mut gradient, &mut source, &json!({"method": "smooth", "from": "#ff0000"})); + overlay(&mut gradient, &mut source, &json!({"method": "classic", "from": "#ff0000"})); overlay(&mut gradient, &mut source, &super::super::effect_defaults("gradientOverlay")); - assert!(source.is_none()); - assert_eq!(gradient, Gradient::default()); + let Some(Effect::GradientOverlay { gradient: factory, interpolation: factory_source, .. }) = + super::super::effect_from_params("gradientOverlay", &json!({})) + else { + panic!("no factory overlay") + }; + assert_eq!(source, factory_source, "#14900: the factory overlay records Smooth grey 215 to white"); + assert_eq!(gradient, factory); } } diff --git a/crates/engine/src/layer_style/gradient_overlay_defaults_tests.rs b/crates/engine/src/layer_style/gradient_overlay_defaults_tests.rs new file mode 100644 index 0000000000..88992c4037 --- /dev/null +++ b/crates/engine/src/layer_style/gradient_overlay_defaults_tests.rs @@ -0,0 +1,142 @@ +//! #14900: the Gradient Overlay page's factory values (Normal, 100 %, grey 215 to white, Method +//! Smooth, Smoothness 100 %, Linear, Angle 90, Scale 100) and the rule that an overlay already +//! stored keeps its own gradient and method. The measured column of the factory overlay sits +//! within 2 levels of the reference application's on the white test document. + +use super::*; +use crate::Session; +use photocraft_doc::GradientStyle; +use photocraft_doc::effects::GradientInterpolation; +use serde_json::json; + +const GREY_215: f32 = 215.0 / 255.0; + +/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel +/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224. +fn test_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 100, "y": 75, "width": 200, "height": 150})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff8000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one effect the active layer carries. +fn only_effect(s: &Session) -> Effect { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [fx] => fx.clone(), + other => panic!("not one effect: {other:?}"), + } +} + +fn close(a: &Color, rgb: [f32; 3]) -> bool { + a.to_rgb().iter().zip(rgb).all(|(x, y)| (x - y).abs() < 1e-3) +} + +/// #14900: Layer > Layer Style > Gradient Overlay... seeds a new instance from `effect_defaults` +/// (the page reads its stop list, so the stops carry the colours as well as From/To). +#[test] +fn a_new_gradient_overlay_starts_at_the_factory_values() { + let d = effect_defaults("gradientOverlay"); + assert_eq!(d["blend"], json!("Normal"), "blend"); + assert_eq!(d["opacity"], json!(100), "opacity"); + assert_eq!(d["stops"], json!([[0, "#d7d7d7"], [1, "#ffffff"]]), "stops"); + assert_eq!((d["from"].as_str(), d["to"].as_str()), (Some("#d7d7d7"), Some("#ffffff")), "from / to"); + assert_eq!(d["method"], json!("smooth"), "method"); + assert_eq!(d["smoothness"], json!(100), "smoothness"); + assert_eq!(d["reverse"], json!(false), "reverse"); + assert_eq!(d["style"], json!("linear"), "style"); + assert_eq!(d["angle"], json!(90), "angle"); + assert_eq!(d["scale"], json!(100), "scale"); +} + +/// #14900: `layer.layerStyle.gradientOverlay` without colours or stops makes the factory overlay: +/// grey 215 to white with the Smooth method recorded, the rest at the page's values. +#[test] +fn a_gradient_overlay_command_without_colours_makes_the_factory_effect() { + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let Effect::GradientOverlay { common, gradient, dither, interpolation } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!((common.blend, common.opacity), (BlendMode::Normal, 1.0)); + assert!(!dither, "dither"); + let Some(GradientInterpolation { method, smoothness, stops }) = interpolation else { panic!("no recorded method") }; + assert_eq!((method.as_str(), smoothness), ("smooth", 100.0)); + assert_eq!(stops.len(), 2, "source stops {stops:?}"); + assert!(stops[0].0 == 0.0 && close(&stops[0].1, [GREY_215; 3]), "first stop {:?}", stops[0]); + assert!(stops[1].0 == 1.0 && close(&stops[1].1, [1.0; 3]), "last stop {:?}", stops[1]); + assert!(close(&gradient.stops.first().unwrap().1, [GREY_215; 3]) && close(&gradient.stops.last().unwrap().1, [1.0; 3]), "baked ends"); + assert!(gradient.stops.len() > 2, "the Smooth curve is baked, not straight: {:?}", gradient.stops); + assert_eq!((gradient.style, gradient.angle, gradient.scale, gradient.reverse, gradient.align), (GradientStyle::Linear, 90.0, 1.0, false, true)); + // The dialog's OK on the factory values (its stop list, no From/To) builds the same effect. + let mut dialog = effect_defaults("gradientOverlay"); + dialog.as_object_mut().unwrap().retain(|k, _| k != "from" && k != "to"); + assert_eq!(effect_from_params("gradientOverlay", &json!({})), effect_from_params("gradientOverlay", &dialog)); +} + +/// #14900 measured: OK on the factory values over the white test document. Red channel at +/// x 200 down the rectangle; the reference application gives +/// `255 255 251 246 240 235 235 230 224 219 215 215`, each within 2 levels. Outside stays white. +#[test] +fn the_factory_gradient_overlay_paints_the_measured_column() { + let mut s = test_document(); + s.execute("layer.layerStyle.gradientOverlay", json!({})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let level = |x: usize, y: usize, c: usize| (px[y * 400 + x][c] * 255.0).round() as i32; + let want = [(75, 255), (76, 255), (94, 251), (112, 246), (131, 240), (149, 235), (150, 235), (168, 230), (187, 224), (205, 219), (223, 215), (224, 215)]; + let got: Vec = want.iter().map(|&(y, _)| level(200, y, 0)).collect(); + for (&(y, w), g) in want.iter().zip(&got) { + assert!((g - w).abs() <= 2, "red at (200, {y}): {g}, the reference gives {w}; column {got:?}"); + } + for (x, y) in [(200, 74), (200, 225), (99, 150), (300, 150)] { + assert_eq!([0, 1, 2].map(|c| level(x, y, c)), [255; 3], "outside the layer at ({x}, {y})"); + } +} + +/// #14900: Reset to Default reads the factory values through `layer.layerStyle.defaultFor` until a +/// Make Default stores other ones; the saved values keep winning. +#[test] +fn reset_to_default_restores_the_gradient_overlay_factory_values() { + let mut s = session(); + let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(d["user"], json!(false)); + assert_eq!(d["params"], effect_defaults("gradientOverlay")); + assert_eq!((d["params"]["method"].as_str(), d["params"]["stops"][0][1].as_str()), (Some("smooth"), Some("#d7d7d7"))); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "gradientOverlay", "params": {"opacity": 40, "method": "linear"}})).unwrap(); + let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "gradientOverlay"})).unwrap(); + assert_eq!(saved["user"], json!(true)); + assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["method"].as_str()), (Some(40.0), Some("linear")), "a saved default still wins"); +} + +/// #14900: an overlay the document already carries (a PSD or `.pcraft` one, edited in the dialog) +/// keeps its gradient and method through `layer.layerStyle.replace`, and a command that names its +/// colours still gets those colours. +#[test] +fn a_stored_gradient_overlay_keeps_its_own_gradient_and_method() { + let mut s = session(); + let stored = Effect::GradientOverlay { + common: FxCommon::new(BlendMode::Multiply, 0.5), + gradient: Gradient { stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], angle: 30.0, ..Gradient::default() }, + dither: true, + interpolation: None, + }; + let snapshot = serde_json::to_value(&stored).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "params": {}, "fx": snapshot}]})).unwrap(); + assert_eq!(only_effect(&s), stored, "an edited effect list left the overlay alone"); + + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff"})).unwrap(); + let Effect::GradientOverlay { gradient, interpolation, .. } = only_effect(&s) else { panic!("not a gradient overlay") }; + assert_eq!(interpolation, None, "named colours keep today's straight stops"); + assert_eq!(gradient.stops, vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))]); +} diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 4a5aa47dd8..38f89c021c 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -193,6 +193,11 @@ fn values_of(e: &Effect, light: f32) -> Value { if let Some(source) = interpolation { set(&mut v, "method", json!(source.method)); set(&mut v, "smoothness", json!(source.smoothness)); + } else { + // No recorded method (a baked PSD curve): the factory Smooth (#14900) must not + // rebuild it on an unchanged OK, so the page shows its stops as they are. + set(&mut v, "method", json!("custom")); + drop_keys(&mut v, &["smoothness"]); } let (stops, opacity) = gradient_field::stops_to_json(&gradient_field::stops_of_doc(stops, &g.opacity_stops)); set(&mut v, gradient_field::KEY, stops); From 750a67a96dc8db204f6be338ecfc2fe44e61437b Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:25:44 +0100 Subject: [PATCH 038/124] Paint Bucket: whole-number Opacity and Tolerance with alerts, tooltips, no Fill label The Paint Bucket's Opacity and Tolerance now take whole numbers (1..100 % and 0..255); a value typed past either range becomes the closest one with the reference application's alert, and a typed fraction rounds without one. The seven controls carry the reference tooltips and the Source dropdown no longer has a "Fill" label. The Magic Wand and Magic Eraser keep their behaviour. Fixes #12533. --- crates/ui-egui/src/lib.rs | 2 + .../src/paint_bucket_options_fields_tests.rs | 162 ++++++++++++++++++ crates/ui-egui/src/panels/options_bar/fill.rs | 38 ++-- 3 files changed, 189 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/paint_bucket_options_fields_tests.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1b338620f..288fa6d0df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -733,6 +733,8 @@ mod eyedropper_context_menu_tests; #[cfg(test)] mod menu_automate_groups_tests; #[cfg(test)] +mod paint_bucket_options_fields_tests; +#[cfg(test)] mod patch_shift_constrain_tests; #[cfg(test)] mod paths_scroll_tests; diff --git a/crates/ui-egui/src/paint_bucket_options_fields_tests.rs b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs new file mode 100644 index 0000000000..d4957fb53a --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs @@ -0,0 +1,162 @@ +//! #12533: the Paint Bucket's Tolerance takes whole numbers 0..255 and Opacity whole percents +//! 1..100; a value typed past either range becomes the closest one with the reference's "Closest +//! value inserted" alert, and a typed fraction rounds without one. The seven controls carry the +//! reference's tooltips, and the Source dropdown has no "Fill" label. The Magic Wand and the Magic +//! Eraser share Tolerance and keep their own behaviour. + +use std::cell::Cell; + +use craft::ui::runtime::env::Env; +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +const TOLERANCE_ALERT: &str = "An integer between 0 and 255 is required. Closest value inserted."; +const OPACITY_ALERT: &str = "An integer between 1% and 100% is required. Closest value inserted."; + +thread_local! { + /// The decimal mark the bar's fields read, from the env they are drawn in: the system region's + /// unless the host sets one, so a typed fraction must use it to be read as one. + static MARK: Cell = const { Cell::new('.') }; +} + +/// The options bar with `tool` active, and the dialog host its alerts open on. +fn bar(tool: Tool) -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + app.ui.tool_options.tolerance = 32.0; + app.ui.tool_options.fill_opacity = 37.0; + crate::theme::install_fonts(app.ctx()); + crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro()); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut Box| { + MARK.set(Env::of(ui).format().separators().0); + crate::panels::options_bar(app, ui); + crate::dialogs::run(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// `text` with `.` replaced by the fields' decimal mark. +fn localized(text: &str) -> String { + text.replace('.', &MARK.get().to_string()) +} + +/// The number field named `label`, with or without its caption's colon. +fn field<'a>(h: &'a H, label: &str) -> Option> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label)) +} + +/// Types `text` (with `.` as the decimal mark) into the field named `label` and commits it with Enter. +fn type_into(h: &mut H, label: &str, text: &str) { + let text = localized(text); + field(h, label).unwrap_or_else(|| panic!("the {label} field")).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text)); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +/// The messages of the open framework alerts. +fn alerts(h: &H) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +/// The description (tooltip) of the control labelled `label`: not its caption's text node. +fn tip(h: &H, label: &str) -> Option { + let named = move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() != Role::Label && n.label().is_some_and(|l| l.trim_end_matches(':') == label); + let node = h.query_all(egui_kittest::kittest::by().predicate(named)).next()?; + node.accesskit_node().description().map(|d| d.to_string()) +} + +#[test] +fn tolerance_past_0_255_takes_the_closest_value_and_alerts() { + for (typed, want) in [("300", 255.0), ("256", 255.0), ("-5", 0.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn tolerance_is_a_whole_number() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("255", 255.0), ("0", 0.0), ("abc", 32.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + if !typed.contains('.') { + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } + } +} + +#[test] +fn opacity_past_1_100_takes_the_closest_value_and_alerts() { + for (typed, want) in [("150", 100.0), ("0", 1.0), ("-3", 1.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert_eq!(alerts(&h), vec![OPACITY_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn opacity_in_range_rounds_to_a_whole_percent_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("100", 100.0), ("1", 1.0), ("abc", 37.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + +#[test] +fn the_seven_controls_have_the_reference_tooltips() { + let h = bar(Tool::PaintBucket); + for (control, want) in [ + ("Source", "Set source for fill area"), + ("Mode", "Fill Mode"), + ("Opacity", "Set opacity for fill"), + ("Tolerance", "Range of colors to fill"), + ("Anti-alias", "Smoothes edge transition"), + ("Contiguous", "Fill only contiguous pixels"), + ("All Layers", "Fill composite image"), + ] { + assert_eq!(tip(&h, control).as_deref(), Some(want), "{control}"); + } +} + +#[test] +fn the_source_dropdown_has_no_fill_label() { + let h = bar(Tool::PaintBucket); + assert!(h.query_by_label("Fill").is_none() && h.query_by_label("Fill:").is_none(), "a Fill label is shown"); + assert!(h.query_all_by_role(Role::ComboBox).any(|n| n.accesskit_node().label().as_deref() == Some("Source")), "the Source dropdown is shown"); +} + +/// The Magic Wand and the Magic Eraser share Tolerance and keep today's behaviour: a value past +/// 0..255 is clamped without an alert. +#[test] +fn magic_wand_and_magic_eraser_tolerance_are_unchanged() { + for tool in [Tool::MagicWand, Tool::MagicEraser] { + for (typed, want) in [("300", 255.0), ("-5", 0.0), ("128", 128.0)] { + let mut h = bar(tool); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{tool:?} {typed}"); + assert!(alerts(&h).is_empty(), "{tool:?} {typed}: no alert, got {:?}", alerts(&h)); + } + } +} diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index 61e9ff4df5..ecc14de237 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -1,14 +1,16 @@ //! The Paint Bucket's members of the options bar, and the Mode list of the Paint Bucket and the stamp tools. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; use craft::ui::pickers::Select; use photocraft_doc::BlendMode; +use super::labelled; use super::paint::PaintMode; -use super::{check, labelled, number_field}; use crate::PhotocraftApp; use crate::state::Tool; +use crate::tools::option_cells::number; /// The text of a Mode entry. fn label_of(mode: PaintMode) -> String { @@ -60,7 +62,13 @@ pub(crate) fn mode_select<'a>(mode: Bind<'a, PaintMode>, entries: &'a [Entry o.bucket_clear = true, PaintMode::Blend(blend) => { @@ -79,13 +88,16 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } PaintMode::Behind => {} } - if let Some(opacity) = number_field(ui, tl!("Opacity"), o.fill_opacity, 1.0..=100.0, "%").landed() { - o.fill_opacity = *opacity; + let opacity = number(tl!("Opacity"), &mut o.fill_opacity, 1.0..=100.0).whole().unit("%").tooltip(tl!("Set opacity for fill")).show(ui).out_of_range; + let tolerance = number(tl!("Tolerance"), &mut o.tolerance, 0.0..=255.0).whole().tooltip(tl!("Range of colors to fill")).show(ui).out_of_range; + Checkbox::new(Bind::bound(&mut o.anti_alias)).label(tl!("Anti-alias").to_owned()).tooltip(tl!("Smoothes edge transition").to_owned()).show(ui); + Checkbox::new(Bind::bound(&mut o.contiguous)).label(tl!("Contiguous").to_owned()).tooltip(tl!("Fill only contiguous pixels").to_owned()).show(ui); + Checkbox::new(Bind::bound(&mut o.sample_all.paint_bucket)).label(tl!("All Layers").to_owned()).tooltip(tl!("Fill composite image").to_owned()).show(ui); + if opacity.is_some() { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_OPACITY_ALERT)); + } else if let Some(alert) = tolerance { + // The framework words a whole-number field without a unit as the reference does: + // "An integer between 0 and 255 is required. Closest value inserted." + crate::tools::option_cells::range_alert(app, ui, &alert); } - if let Some(tolerance) = number_field(ui, tl!("Tolerance"), o.tolerance, 0.0..=255.0, "").landed() { - o.tolerance = *tolerance; - } - check(ui, tl!("Anti-alias"), &mut o.anti_alias); - check(ui, tl!("Contiguous"), &mut o.contiguous); - check(ui, tl!("All Layers"), &mut o.sample_all.paint_bucket); } From 800701d7ba689c7445058d33c39b9bbc21f4b83b Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:51:21 +0100 Subject: [PATCH 039/124] Give Auto-Align Layers the reference dialog layout Edit > Auto-Align Layers opened the generic command form (a Projection dropdown, Geometric Correction, Interpolation and Registration) with Alt turning Cancel into Reset. It now shows a Projection group of six radios with pictures (3 x 2), a Lens Correction group (Vignette Removal, shown disabled until the engine takes it, and Geometric Distortion; Collage and Reposition grey and clear both), the selected projection's description and the camera-metadata and vignette warnings. Alt keeps Cancel, Interpolation and Registration stay engine params with their defaults, and the dialog reopens with the projection and ticks of the last run, including a scripted one (read from the session journal). The rows live in the new dialogs/auto_align_ui.rs; filter_dialog.rs only gains three hooks. Fixes #14196. --- crates/ui-egui/src/dialogs.rs | 3 + .../src/dialogs/auto_align_dialog_tests.rs | 276 +++++++++++++++++ crates/ui-egui/src/dialogs/auto_align_ui.rs | 285 ++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 11 +- 4 files changed, 573 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs create mode 100644 crates/ui-egui/src/dialogs/auto_align_ui.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e3cca6c221..2770e24d02 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -687,6 +687,9 @@ pub mod adjust_preview; pub mod alerts; #[cfg(test)] mod arbitrary_ruler_prefill_tests; +#[cfg(test)] +mod auto_align_dialog_tests; +pub(crate) mod auto_align_ui; pub(crate) mod bitmap_dialog; pub mod blend_options; pub mod blur_pins; diff --git a/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs new file mode 100644 index 0000000000..a39c7a1a21 --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_dialog_tests.rs @@ -0,0 +1,276 @@ +//! #14196: Edit › Auto-Align Layers opens the reference application's dialog: a Projection group of six radios over +//! three columns (Auto, Perspective, Collage / Cylindrical, Spherical, Reposition) with Auto selected on a fresh +//! start, a Lens Correction group (Vignette Removal, Geometric Distortion, both off; Collage and Reposition grey and +//! clear them), the selected projection's description line and the warnings under them, OK and Cancel. No +//! Interpolation or Registration rows, Alt keeps Cancel a Cancel, and the last run's projection (also a scripted +//! one) is what the dialog reopens with. + +use craft::ui::dialog::DialogId; +use egui::accesskit::{Role, Toggled}; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{fields, set, top}; + +const COMMAND: &str = "edit.autoAlignLayers"; +/// The radios in reading order: the first row, then the second. +const RADIOS: [&str; 6] = ["Auto", "Perspective", "Collage", "Cylindrical", "Spherical", "Reposition"]; + +type H = Harness<'static, Box>; + +/// The deterministic texture of the engine's Auto-Align tests, written into layer `id` at offset (dx, dy). +fn paint_texture(app: &mut PhotocraftApp, id: LayerId, dx: i32, dy: i32) { + app.session + .edit("tex", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 99u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / (1u64 << 31) as f64 + }; + surf.fill_rect(photocraft_geom::Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); + for _ in 0..120 { + let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); + let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); + let v = rnd() as f32; + surf.fill_rect(photocraft_geom::Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); +} + +/// A 300x240 document with two textured layers, the second offset, both selected: Auto-Align can run on it. +fn two_layers(app: &mut PhotocraftApp) { + app.run("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, dx, dy) in [("A", 20, 20), ("B", 31, 13)] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + paint_texture(app, id, dx, dy); + ids.push(id); + } + app.run("layer.select", json!({"layer": ids[0].0})).unwrap(); + app.run("layer.select", json!({"layer": ids[1].0, "mode": "add"})).unwrap(); +} + +/// The whole app with the two-layer document, before the dialog opens. +fn harness() -> H { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + two_layers(&mut app); + app + }); + h.run_steps(3); + h +} + +/// Opens the dialog through the menu and draws a few frames. +fn open(h: &mut H) -> DialogId { + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + let id = top(h.state()); + h.run_steps(4); + id +} + +fn dialog() -> (H, DialogId) { + let mut h = harness(); + let id = open(&mut h); + (h, id) +} + +fn radio(h: &H, label: &str) -> egui::Rect { + h.get_by_role_and_label(Role::RadioButton, label).rect() +} + +fn checked(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn disabled(h: &H, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().is_disabled() +} + +fn sent(h: &H, id: DialogId) -> Value { + crate::filter_dialog::command_params(COMMAND, fields(h.state(), id)) +} + +fn shows(h: &H, text: &str) -> bool { + h.query_all_by_label(text).next().is_some() +} + +#[test] +fn six_projection_radios_stand_three_by_two_with_auto_selected() { + let (h, _) = dialog(); + let rects: Vec = RADIOS.iter().map(|label| radio(&h, label)).collect(); + for row in [&rects[0..3], &rects[3..6]] { + for r in &row[1..] { + assert!((r.center().y - row[0].center().y).abs() < 4.0, "one row: {row:?}"); + } + assert!(row[0].right() < row[1].left() && row[1].right() < row[2].left(), "left to right: {row:?}"); + } + assert!(rects[3].top() > rects[0].bottom(), "Cylindrical, Spherical and Reposition stand under the first row"); + for col in 0..3 { + assert!((rects[col].left() - rects[col + 3].left()).abs() < 4.0, "column {col} lines up"); + } + assert!(checked(&h, Role::RadioButton, "Auto"), "a fresh dialog selects Auto"); + for label in &RADIOS[1..] { + assert!(!checked(&h, Role::RadioButton, label), "{label} starts clear"); + } +} + +#[test] +fn the_description_line_follows_the_selected_radio() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Determine the best projection automatically.")); + for (label, line) in [ + ("Perspective", "Only allow perspective image transform."), + ("Collage", "Allow image rotation, scale and translation."), + ("Cylindrical", "Only allow cylindrical image transform."), + ("Spherical", "Only allow spherical image transform."), + ("Reposition", "Only allow image translation."), + ] { + h.get_by_role_and_label(Role::RadioButton, label).click(); + h.run_steps(3); + assert!(shows(&h, line), "{label}: {line}"); + assert!(!shows(&h, "Determine the best projection automatically."), "{label}: one description line"); + assert_eq!(sent(&h, id)["projection"], json!(label.to_lowercase())); + } +} + +#[test] +fn lens_correction_has_two_clear_boxes_that_collage_and_reposition_grey_and_clear() { + let (mut h, id) = dialog(); + assert!(shows(&h, "Projection") && shows(&h, "Lens Correction"), "the two groups are named"); + for label in ["Vignette Removal", "Geometric Distortion"] { + assert!(!checked(&h, Role::CheckBox, label), "{label} starts off"); + } + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(3); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion")); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(true), "Geometric Distortion drives geometricCorrection"); + for picked in ["Collage", "Reposition"] { + h.get_by_role_and_label(Role::RadioButton, picked).click(); + h.run_steps(3); + assert!(disabled(&h, Role::CheckBox, "Geometric Distortion") && disabled(&h, Role::CheckBox, "Vignette Removal"), "{picked} greys both"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "{picked} clears it"); + assert_eq!(sent(&h, id)["geometricCorrection"], json!(false)); + } + h.get_by_role_and_label(Role::RadioButton, "Auto").click(); + h.run_steps(3); + assert!(!disabled(&h, Role::CheckBox, "Geometric Distortion"), "Auto enables it again"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "still cleared"); +} + +#[test] +fn no_interpolation_or_registration_rows_and_the_command_keeps_them() { + let (h, id) = dialog(); + assert!(h.query_by_label("Interpolation").is_none(), "no Interpolation row"); + assert!(h.query_by_label("Registration").is_none(), "no Registration row"); + let params = sent(&h, id); + assert!(params.get("interpolation").is_none() && params.get("registration").is_none(), "the command's defaults apply: {params}"); + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + let keys: Vec = craft::ui::patterns::form_dialogs::Param::parse_list(spec.params).into_iter().map(|p| p.key).collect(); + assert!(keys.iter().any(|k| k == "interpolation") && keys.iter().any(|k| k == "registration"), "{keys:?}"); +} + +#[test] +fn the_metadata_warning_shows_for_layers_without_camera_metadata() { + let (h, _) = dialog(); + assert!( + shows( + &h, + "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion." + ), + "the document has no EXIF" + ); + assert!( + !shows( + &h, + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings." + ), + "Vignette Removal is off" + ); +} + +/// The text block's lines: the description, the metadata warning, then the vignette warning while it is ticked. +#[test] +fn the_text_block_lists_the_warnings_in_order() { + use super::auto_align_ui::{METADATA_WARNING, VIGNETTE_WARNING, lines}; + assert_eq!(lines("reposition", false, true), vec!["Only allow image translation."]); + assert_eq!(lines("auto", false, false), vec!["Determine the best projection automatically.", METADATA_WARNING]); + assert_eq!(lines("auto", true, false), vec!["Determine the best projection automatically.", METADATA_WARNING, VIGNETTE_WARNING]); + assert_eq!(lines("spherical", true, true), vec!["Only allow spherical image transform.", VIGNETTE_WARNING]); +} + +#[test] +fn alt_keeps_cancel_and_escape_cancels() { + let (mut h, _) = dialog(); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(h.query_by_label("Reset").is_none(), "Alt does not turn Cancel into Reset"); + h.get_by_role_and_label(Role::Button, "Cancel"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.query_by_label("Only allow image translation.").is_none() && !shows(&h, "Lens Correction"), "Escape closes the dialog"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before, "Escape leaves the history alone"); +} + +#[test] +fn ok_runs_and_the_dialog_reopens_with_the_projection_and_ticks_it_ran_with() { + let (mut h, id) = dialog(); + h.get_by_role_and_label(Role::RadioButton, "Perspective").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + let before = h.state().session.active().unwrap().history.past_len(); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before + 1, "OK runs Auto-Align"); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Perspective"), "reopens with Perspective"); + assert!(checked(&h, Role::CheckBox, "Geometric Distortion"), "and the tick confirmed with OK"); + assert_eq!(sent(&h, id)["projection"], json!("perspective")); +} + +#[test] +fn a_scripted_run_decides_the_projection_the_dialog_reopens_with() { + let mut h = harness(); + // An OK with Geometric Distortion ticked first, so the script's run has something to replace. + let id = open(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Geometric Distortion").click(); + h.run_steps(2); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + h.state_mut().run(COMMAND, json!({"projection": "reposition"})).unwrap(); + h.run_steps(2); + let id = open(&mut h); + assert!(checked(&h, Role::RadioButton, "Reposition"), "the scripted projection"); + assert!(!checked(&h, Role::CheckBox, "Geometric Distortion"), "a run without the lens keys leaves the box clear"); + assert!(shows(&h, "Only allow image translation.")); + assert_eq!(sent(&h, id)["projection"], json!("reposition")); +} + +#[test] +fn an_agent_sets_the_projection_by_its_id_and_a_bad_one_is_refused() { + let (mut h, id) = dialog(); + set(h.state_mut(), id, "projection", json!("cylindrical")).unwrap(); + h.run_steps(3); + assert!(checked(&h, Role::RadioButton, "Cylindrical")); + assert_eq!(sent(&h, id)["projection"], json!("cylindrical")); + // An unknown id never reaches the command: the row keeps a projection it knows. + let _ = set(h.state_mut(), id, "projection", json!("sideways")); + h.run_steps(3); + let projection = sent(&h, id)["projection"].as_str().unwrap().to_owned(); + assert!(RADIOS.iter().any(|r| r.to_lowercase() == projection), "{projection}"); +} diff --git a/crates/ui-egui/src/dialogs/auto_align_ui.rs b/crates/ui-egui/src/dialogs/auto_align_ui.rs new file mode 100644 index 0000000000..b05bcb127c --- /dev/null +++ b/crates/ui-egui/src/dialogs/auto_align_ui.rs @@ -0,0 +1,285 @@ +//! Edit › Auto-Align Layers: the reference application's dialog (#14196). A Projection group of six radios with a +//! small picture under each (3 x 2), a Lens Correction group with Vignette Removal and Geometric Distortion, and a +//! text block at the foot: the selected projection's description and the warnings. OK and Cancel; Alt does not turn +//! Cancel into Reset. +//! +//! It stays the command's schema dialog (`filter_dialog::open`), so Enter / Escape, `ui.dialog.*`, action step +//! dialogs and the no-match alert work as for every other command dialog; only its rows and buttons differ. The +//! command keeps its `interpolation` and `registration` params for scripts: the dialog has no rows for them, so the +//! command's own defaults apply. +//! +//! Memory: the projection lives in a hidden radio row ([`LAST`]) the framework remembers on OK beside the two boxes. +//! A run that did not come from this dialog (a script, the control channel, an action step) lands in the session's +//! journal; opening the dialog copies the last journaled run into those remembered values, so it reopens with the +//! projection (and the lens keys) that run used. + +use craft::behavior::ColumnWidth; +use craft::ui::choice::{Radio, RadioGroup}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Grid, Stack}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; +use egui::{Color32, Pos2, Rect, Shape, Stroke, pos2, vec2}; +use serde_json::{Map, Value}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const COMMAND: &str = "edit.autoAlignLayers"; +/// The projection the command runs with. The custom row writes it; an agent's `ui.dialog.set` may too. +pub const PROJECTION: &str = "projection"; +/// The hidden radio row that keeps the projection the framework remembers (a custom row's value is not remembered). +pub const LAST: &str = "__projection"; +/// The Geometric Distortion box: the command's `geometricCorrection`. +pub const GEOMETRIC: &str = "geometricCorrection"; +/// The Vignette Removal box: the command's `vignetteRemoval`, once the engine takes it (#14197). +pub const VIGNETTE: &str = "vignetteRemoval"; + +/// The projections in the reference application's order, row by row over three columns: id, label and the +/// description line it shows while selected. +pub const PROJECTIONS: [(&str, &str, &str); 6] = [ + ("auto", "Auto", "Determine the best projection automatically."), + ("perspective", "Perspective", "Only allow perspective image transform."), + ("collage", "Collage", "Allow image rotation, scale and translation."), + ("cylindrical", "Cylindrical", "Only allow cylindrical image transform."), + ("spherical", "Spherical", "Only allow spherical image transform."), + ("reposition", "Reposition", "Only allow image translation."), +]; +/// The projections that grey and clear both Lens Correction boxes. +const NO_LENS: [&str; 2] = ["collage", "reposition"]; +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +/// The picture under each radio, in points. +const PICTURE: egui::Vec2 = vec2(64.0, 40.0); + +/// The text under the boxes when the layers carry no camera metadata. +pub const METADATA_WARNING: &str = "Warning: Could not detect camera metadata. Use the \"File > Scripts > Load Images into Stack...\" script to preserve metadata for Vignette Removal and/or Geometric Distortion."; +/// The text under the boxes while Vignette Removal is ticked. +pub const VIGNETTE_WARNING: &str = + "Warning: For better Vignette Removal results, shoot with the same camera, lens, aperture, resolution, orientation, focal length and focus settings."; + +/// `id` when it names one of the six projections. +fn known(id: &str) -> Option<&'static str> { + PROJECTIONS.iter().map(|(p, _, _)| *p).find(|p| *p == id) +} + +/// Whether the projection `id` lets the Lens Correction boxes take input. +pub fn lens_allowed(id: &str) -> bool { + !NO_LENS.contains(&id) +} + +/// Whether the engine's command takes `vignetteRemoval` yet (#14197); until then the box is shown disabled. +pub fn vignette_supported() -> bool { + photocraft_engine::commands::find(COMMAND).is_some_and(|c| Param::parse_list(c.params).iter().any(|p| p.key == VIGNETTE)) +} + +/// The projection the dialog's values hold: the row's own value (text, or the JSON string `ui.dialog.set` writes), +/// else the remembered one, else Auto. +pub fn projection(fields: &DialogFields) -> &'static str { + let own = match fields.get(PROJECTION) { + Some(FieldValue::Text(id)) => known(id), + Some(FieldValue::Json(Value::String(id))) => known(id), + _ => None, + }; + own.or_else(|| fields.text(LAST).and_then(known)).unwrap_or("auto") +} + +/// The save key the schema dialog remembers this command's values under. +fn remembered_key() -> SaveKey { + SaveKey::named(super::params::memory_scope(COMMAND)) +} + +/// Whether the active document carries camera metadata (a camera make or model in its EXIF). +fn has_camera_metadata(app: &PhotocraftApp) -> bool { + app.session.active().and_then(|st| st.doc.metadata.exif.as_ref()).is_some_and(|exif| { + let info = photocraft_algo::exif::read(exif); + info.make.is_some_and(|m| !m.trim().is_empty()) || info.model.is_some_and(|m| !m.trim().is_empty()) + }) +} + +/// Copies the session's last journaled run of the command into the values the dialog remembers, so a run from a +/// script, the control channel or an action step decides what the dialog reopens with, as one confirmed with OK +/// does. Keys the run left out are their defaults: a scripted run without the lens keys leaves both boxes clear. +pub(crate) fn adopt_last_run(app: &PhotocraftApp) { + let Some((_, params)) = app.session.journal.iter().rev().find(|(id, _)| id == COMMAND) else { return }; + let ctx = app.ctx(); + let key = remembered_key(); + let mut saved = saved_value::>(ctx, &key).unwrap_or_default(); + let id = params.get(PROJECTION).and_then(Value::as_str).and_then(known).unwrap_or("auto"); + let lens = lens_allowed(id); + let flag = |k: &str| lens && params.get(k).and_then(Value::as_bool).unwrap_or(false); + saved.set(LAST, FieldValue::Text(id.to_owned())); + saved.set(GEOMETRIC, FieldValue::Bool(flag(GEOMETRIC))); + saved.set(VIGNETTE, FieldValue::Bool(flag(VIGNETTE))); + set_saved_value(ctx, &key, Some(saved)); +} + +/// The dialog's rows, in place of the schema's: the Projection group, the Lens Correction group and the text block. +/// Opening also adopts the last journaled run ([`adopt_last_run`]). +pub(crate) fn params(app: &PhotocraftApp) -> Vec { + adopt_last_run(app); + let metadata = has_camera_metadata(app); + let lens: Vec = PROJECTIONS.iter().map(|(id, _, _)| *id).filter(|id| lens_allowed(id)).map(str::to_owned).collect(); + let vignette_on: Vec = if vignette_supported() { lens.clone() } else { Vec::new() }; + let options = PROJECTIONS.iter().map(|(id, label, _)| ((*id).to_owned(), Label::from(crate::i18n::t(label).to_string()))).collect(); + vec![ + Param::section(tl!("Projection")), + // The remembered projection: never shown, never sent (keys under `__` are not command params). + Param::new(LAST, tl!("Projection"), ParamKind::radio(options, Some("auto".into()))).visible_when("__hidden", true), + Param::custom(PROJECTION, tl!("Projection"), |ui, fields, _| projection_row(ui, fields)).full_width(), + Param::section(tl!("Lens Correction")), + Param::new(VIGNETTE, tl!("Vignette Removal"), ParamKind::bool(false)).enabled_when_in(LAST, vignette_on), + Param::new(GEOMETRIC, tl!("Geometric Distortion"), ParamKind::bool(false)).enabled_when_in(LAST, lens), + Param::custom("__notes", Label::Empty, move |ui, fields, _| notes(ui, fields, metadata)).full_width(), + ] +} + +/// The command params of the dialog's values: the projection the row shows (the remembered one when the row never +/// drew), no lens correction under Collage or Reposition, and no `vignetteRemoval` until the engine takes it. +pub(crate) fn command_params(map: &mut Map, fields: &DialogFields) { + let id = projection(fields); + map.insert(PROJECTION.into(), Value::String(id.to_owned())); + if !lens_allowed(id) { + map.insert(GEOMETRIC.into(), Value::Bool(false)); + map.insert(VIGNETTE.into(), Value::Bool(false)); + } + if !vignette_supported() { + map.remove(VIGNETTE); + } +} + +/// Keeps the values in step with the projection: both keys hold it as text, and Collage or Reposition clears the +/// Lens Correction boxes (switching back leaves them clear). +fn settle(fields: &mut DialogFields, id: &str) { + if fields.get(PROJECTION) != Some(&FieldValue::Text(id.to_owned())) { + fields.set(PROJECTION, FieldValue::Text(id.to_owned())); + } + if fields.text(LAST) != Some(id) { + fields.set(LAST, FieldValue::Text(id.to_owned())); + } + if !lens_allowed(id) { + for key in [GEOMETRIC, VIGNETTE] { + if fields.bool(key) != Some(false) { + fields.set(key, FieldValue::Bool(false)); + } + } + } +} + +/// The six radios over three columns, each with its picture under it. A press on a picture selects nothing. +fn projection_row(ui: &mut egui::Ui, fields: &mut DialogFields) -> egui::Response { + let current = projection(fields); + settle(fields, current); + let group = RadioGroup::new(tl!("Projection").to_owned(), Bind::given(current.to_owned())).show(ui, |ui, _| { + Grid::new(COLUMNS).show(ui, |ui, _| { + for (id, label, _) in PROJECTIONS { + Stack::new().show(ui, |ui, _| { + Radio::new(id.to_owned()).label(crate::i18n::t(label).to_string()).show(ui); + picture(ui, id); + }); + } + }); + }); + if let Some(picked) = group.output.value().and_then(|id| known(id)) { + settle(fields, picked); + } + group.output.response.clone() +} + +/// The lines of the text block at the foot, in English: the projection `id`'s description, the metadata warning when +/// the layers carry no camera `metadata`, then the vignette warning while `vignette` is ticked. +pub fn lines(id: &str, vignette: bool, metadata: bool) -> Vec<&'static str> { + let mut out: Vec<&'static str> = PROJECTIONS.iter().filter(|(p, _, _)| *p == id).map(|(_, _, d)| *d).collect(); + if !metadata { + out.push(METADATA_WARNING); + } + if vignette { + out.push(VIGNETTE_WARNING); + } + out +} + +/// The text block at the foot ([`lines`]): the description, then the warnings, dimmer. +fn notes(ui: &mut egui::Ui, fields: &mut DialogFields, metadata: bool) -> egui::Response { + let shown = lines(projection(fields), fields.bool(VIGNETTE) == Some(true), metadata); + Stack::new() + .show(ui, |ui, _| { + for (k, line) in shown.iter().enumerate() { + let text = Text::new(crate::i18n::t(line).to_string()); + if k == 0 { + text.show(ui) + } else { + text.shade(Shade::Muted).show(ui) + }; + } + }) + .output +} + +/// The small line drawing under a projection's radio (look only; it takes no press). +fn picture(ui: &mut egui::Ui, id: &str) { + let (rect, _) = ui.allocate_exact_size(PICTURE, egui::Sense::hover()); + let t = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, t.radius_sm, t.field); + let ink = Stroke::new(1.0, t.icon); + let fill = t.accent_soft; + let c = rect.center(); + let image = Rect::from_center_size(c, vec2(22.0, 15.0)); + let poly = |points: Vec| Shape::convex_polygon(points, fill, ink); + match id { + "auto" => { + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for (corner, out) in [ + (image.left_top(), vec2(-6.0, -5.0)), + (image.right_top(), vec2(6.0, -5.0)), + (image.left_bottom(), vec2(-6.0, 5.0)), + (image.right_bottom(), vec2(6.0, 5.0)), + ] { + painter.arrow(corner, out, ink); + } + } + "perspective" => { + painter.add(poly(vec![pos2(c.x - 26.0, c.y - 6.0), pos2(c.x - 12.0, c.y - 10.0), pos2(c.x - 12.0, c.y + 10.0), pos2(c.x - 26.0, c.y + 6.0)])); + painter.rect(Rect::from_center_size(c, vec2(22.0, 20.0)), 0.0, fill, ink, egui::StrokeKind::Inside); + painter.add(poly(vec![pos2(c.x + 12.0, c.y - 10.0), pos2(c.x + 26.0, c.y - 6.0), pos2(c.x + 26.0, c.y + 6.0), pos2(c.x + 12.0, c.y + 10.0)])); + } + "collage" => { + let turn = egui::emath::Rot2::from_angle(-0.3); + let corners = [vec2(-11.0, -7.5), vec2(11.0, -7.5), vec2(11.0, 7.5), vec2(-11.0, 7.5)]; + painter.add(poly(corners.iter().map(|v| c + turn * *v).collect())); + let (a, b) = (pos2(c.x + 10.0, c.y + 14.0), pos2(c.x + 24.0, c.y + 4.0)); + painter.arrow(a, b - a, ink); + painter.arrow(b, a - b, ink); + } + "cylindrical" => { + let mut top: Vec = + (0..=8).map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y - 10.0 + 4.0 * (s - 0.5).powi(2) * 4.0 - 4.0)).collect(); + let bottom: Vec = + (0..=8).rev().map(|k| k as f32 / 8.0).map(|s| pos2(c.x - 18.0 + 36.0 * s, c.y + 10.0 - 4.0 * (s - 0.5).powi(2) * 4.0 + 4.0)).collect(); + top.extend(bottom); + painter.add(Shape::closed_line(top.clone(), ink)); + painter.add(Shape::line(vec![pos2(c.x, c.y - 14.0), pos2(c.x, c.y + 14.0)], Stroke::new(1.0, t.text_faint))); + } + "spherical" => { + // An image whose corners are pulled in: each side bows inward. + let (l, r, tp, b) = (c.x - 16.0, c.x + 16.0, c.y - 12.0, c.y + 12.0); + let side = |from: Pos2, to: Pos2, bow: egui::Vec2| -> Vec { + (0..8).map(|k| k as f32 / 8.0).map(|s| from + (to - from) * s - bow * (1.0 - (2.0 * s - 1.0).powi(2))).collect() + }; + let mut outline = side(pos2(l, tp), pos2(r, tp), vec2(0.0, -4.0)); + outline.extend(side(pos2(r, tp), pos2(r, b), vec2(4.0, 0.0))); + outline.extend(side(pos2(r, b), pos2(l, b), vec2(0.0, 4.0))); + outline.extend(side(pos2(l, b), pos2(l, tp), vec2(-4.0, 0.0))); + painter.add(Shape::closed_line(outline, ink)); + } + _ => { + // Reposition: the image with blocks around it. + painter.rect(image, 0.0, fill, ink, egui::StrokeKind::Inside); + for offset in [vec2(-20.0, -9.0), vec2(20.0, -9.0), vec2(-20.0, 9.0), vec2(20.0, 9.0)] { + painter.rect(Rect::from_center_size(c + offset, vec2(10.0, 8.0)), 0.0, Color32::TRANSPARENT, ink, egui::StrokeKind::Inside); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index f52a73e5de..64ecccddf3 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -364,6 +364,10 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if command == super::rotate_canvas_ui::COMMAND { list = super::rotate_canvas_ui::params(); } + // Auto-Align Layers: the Projection and Lens Correction groups and the text block (#14196). + if command == super::auto_align_ui::COMMAND { + list = super::auto_align_ui::params(app); + } rows::custom_rows(app, command, &mut list); if command == "edit.colorSettings" { // The monitor line under the rows: the cell holds the text each frame refreshes, which the build closure cannot read from the app. @@ -561,8 +565,8 @@ fn builder( .reset_to(reset.clone()) .layout(ParamLayout::Stacked) .previews(preview) - // Alt keeps Rotate Canvas's Cancel a Cancel, as in the reference application (#14462). - .alt_resets(key != super::rotate_canvas_ui::COMMAND) + // Alt keeps Rotate Canvas's and Auto-Align's Cancel a Cancel, as in the reference application (#14462, #14196). + .alt_resets(key != super::rotate_canvas_ui::COMMAND && key != super::auto_align_ui::COMMAND) .alert_title(tl!("PhotoCraft")); if let Some(canvas) = canvas { dialog = dialog.canvas(canvas); @@ -708,6 +712,9 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value { if command == super::rotate_canvas_ui::COMMAND { super::rotate_canvas_ui::command_params(&mut map); } + if command == super::auto_align_ui::COMMAND { + super::auto_align_ui::command_params(&mut map, fields); + } params_of(&map) } From bf4fca7232a8c95cba73fc17e0f360cafa131a7b Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:28:17 +0100 Subject: [PATCH 040/124] Paint Bucket: alert when a typed Tolerance fraction is rounded The reference application rounds a fractional Tolerance (12.7 becomes 13) and shows "An integer between 0 and 255 is required. Closest value inserted." (#12533). The Tolerance cell now commits the typed fraction, rounds it to the closest whole number and opens that alert. Opacity keeps rounding a typed fraction without an alert. --- .../src/paint_bucket_options_fields_tests.rs | 23 +++++++++- crates/ui-egui/src/panels/options_bar/fill.rs | 13 ++++-- crates/ui-egui/src/tools/option_cells.rs | 43 ++++++++++++++++--- 3 files changed, 70 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/paint_bucket_options_fields_tests.rs b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs index d4957fb53a..4d0d34e3e9 100644 --- a/crates/ui-egui/src/paint_bucket_options_fields_tests.rs +++ b/crates/ui-egui/src/paint_bucket_options_fields_tests.rs @@ -1,6 +1,7 @@ //! #12533: the Paint Bucket's Tolerance takes whole numbers 0..255 and Opacity whole percents //! 1..100; a value typed past either range becomes the closest one with the reference's "Closest -//! value inserted" alert, and a typed fraction rounds without one. The seven controls carry the +//! value inserted" alert. A typed fraction rounds to the closest whole number: in Tolerance with +//! the same alert, in Opacity without one. The seven controls carry the //! reference's tooltips, and the Source dropdown has no "Fill" label. The Magic Wand and the Magic //! Eraser share Tolerance and keep their own behaviour. @@ -104,6 +105,26 @@ fn tolerance_is_a_whole_number() { } } +#[test] +fn a_fractional_tolerance_takes_the_closest_value_and_alerts() { + for (typed, want) in [("12.7", 13.0), ("12.4", 12.0), ("0.4", 0.0), ("254.6", 255.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn a_fractional_opacity_rounds_without_an_alert() { + for (typed, want) in [("50.5", 51.0), ("50.4", 50.0), ("1.4", 1.0), ("99.6", 100.0)] { + let mut h = bar(Tool::PaintBucket); + type_into(&mut h, "Opacity", typed); + assert_eq!(h.state().ui.tool_options.fill_opacity, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed}: no alert, got {:?}", alerts(&h)); + } +} + #[test] fn opacity_past_1_100_takes_the_closest_value_and_alerts() { for (typed, want) in [("150", 100.0), ("0", 1.0), ("-3", 1.0)] { diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index ecc14de237..69d1f2b5fc 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -66,9 +66,14 @@ pub(crate) fn mode_select<'a>(mode: Bind<'a, PaintMode>, entries: &'a [Entry {} } let opacity = number(tl!("Opacity"), &mut o.fill_opacity, 1.0..=100.0).whole().unit("%").tooltip(tl!("Set opacity for fill")).show(ui).out_of_range; - let tolerance = number(tl!("Tolerance"), &mut o.tolerance, 0.0..=255.0).whole().tooltip(tl!("Range of colors to fill")).show(ui).out_of_range; + let tolerance = number(tl!("Tolerance"), &mut o.tolerance, 0.0..=255.0).whole_alerting_fractions().tooltip(tl!("Range of colors to fill")).show(ui); Checkbox::new(Bind::bound(&mut o.anti_alias)).label(tl!("Anti-alias").to_owned()).tooltip(tl!("Smoothes edge transition").to_owned()).show(ui); Checkbox::new(Bind::bound(&mut o.contiguous)).label(tl!("Contiguous").to_owned()).tooltip(tl!("Fill only contiguous pixels").to_owned()).show(ui); Checkbox::new(Bind::bound(&mut o.sample_all.paint_bucket)).label(tl!("All Layers").to_owned()).tooltip(tl!("Fill composite image").to_owned()).show(ui); if opacity.is_some() { let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_OPACITY_ALERT)); - } else if let Some(alert) = tolerance { + } else if let Some(alert) = tolerance.out_of_range { // The framework words a whole-number field without a unit as the reference does: // "An integer between 0 and 255 is required. Closest value inserted." crate::tools::option_cells::range_alert(app, ui, &alert); + } else if tolerance.rounded { + let _ = crate::dialogs::alerts::alert(app, tl!(PAINT_BUCKET_TOLERANCE_ALERT)); } } diff --git a/crates/ui-egui/src/tools/option_cells.rs b/crates/ui-egui/src/tools/option_cells.rs index 159203d9c7..e76a56c288 100644 --- a/crates/ui-egui/src/tools/option_cells.rs +++ b/crates/ui-egui/src/tools/option_cells.rs @@ -22,6 +22,7 @@ pub(crate) struct NumberCell<'a> { range: RangeInclusive, unit: Option