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 001/147] 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 002/147] 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 003/147] 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 004/147] 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 6e1f1eefb8fedd49be806d9e145134607b2d4931 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 14:08:06 +0530 Subject: [PATCH 005/147] engine: name a duplicated new document Untitled-N (#14608) --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/layer_copy_cmds.rs | 7 ++- .../engine/src/cmd/layer_copy_cmds/tests.rs | 2 +- ...layer_duplicate_new_document_name_tests.rs | 50 +++++++++++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/layer_duplicate_new_document_name_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 36a1081edd..ac39b51a2c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -112,6 +112,8 @@ pub mod history_source_cmds; pub mod image_cmds; pub mod layer_copy_cmds; pub mod layer_css_cmds; +#[cfg(test)] +mod layer_duplicate_new_document_name_tests; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index f8a4f06276..e43c27cfbd 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -368,7 +368,12 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result copy". + +use serde_json::json; + +use crate::Session; + +fn doc_name(s: &Session, i: usize) -> String { + s.documents().iter().nth(i).map(|d| d.doc.name.clone()).unwrap_or_default() +} + +/// A one-layer document named `name`, with its only layer active. +fn source(name: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"name": name, "width": 40, "height": 30, "background": "white"})).unwrap(); + s +} + +#[test] +fn an_empty_name_makes_the_next_untitled_document() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + assert_eq!(doc_name(&s, 0), "oracle", "the source keeps its name"); + assert_eq!(doc_name(&s, 1), "Untitled-1"); +} + +#[test] +fn the_counter_skips_untitled_documents_already_open() { + let mut s = source("oracle"); + // An Untitled-1 is open beside the source; the copy takes the next number. + s.execute("file.new", json!({"name": "Untitled-1", "width": 8, "height": 8})).unwrap(); + let oracle = s.documents().iter().position(|d| d.doc.name == "oracle").unwrap(); + s.set_active(oracle); + s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + assert_eq!(doc_name(&s, s.active_index().unwrap()), "Untitled-2"); +} + +#[test] +fn a_typed_name_is_used_as_given() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new", "documentName": "MyNew"})).unwrap(); + assert_eq!(doc_name(&s, 1), "MyNew"); +} + +#[test] +fn an_empty_typed_name_falls_back_to_untitled() { + let mut s = source("oracle"); + s.execute("layer.duplicate", json!({"document": "new", "documentName": ""})).unwrap(); + assert_eq!(doc_name(&s, 1), "Untitled-1"); +} From 6352916c338d7516443b040845ee9e0466f4cab4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:06:13 -0800 Subject: [PATCH 006/147] 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 007/147] 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 008/147] 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 009/147] 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 010/147] 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 011/147] 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 3e768fe6e66e2bf764871402dc7a3c00945a239d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 01:36:07 -0800 Subject: [PATCH 012/147] 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 013/147] 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 014/147] 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 015/147] 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 016/147] 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 017/147] 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 018/147] 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 019/147] 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 020/147] 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 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 021/147] 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 022/147] 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 7c154afd0fc845258fdf8ce2b5a632bde9c04dee Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 04:19:07 -0600 Subject: [PATCH 023/147] Color Settings: grey the paste and missing-profile boxes when every policy is Off With the RGB, CMYK and Gray policies all Off, "Ask When Pasting" and "Missing Profiles: Ask When Opening" are shown disabled and keep their values; "Profile Mismatches: Ask When Opening" stays enabled. Any policy other than Off enables both again. Fixes #14245 --- crates/ui-egui/src/dialogs.rs | 2 + .../color_settings_policy_greying_tests.rs | 64 +++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 19 +++++- 3 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8e827d7e4d..4ee27b32e3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -701,6 +701,8 @@ pub mod channel_options_ui; pub(crate) mod color_picker_preview; pub mod color_picker_ui; pub mod color_range_ui; +#[cfg(test)] +mod color_settings_policy_greying_tests; pub mod color_table_ui; pub(crate) mod conditional_mode_change_dialog; pub mod count_group_name_ui; diff --git a/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs b/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs new file mode 100644 index 0000000000..321a6bd9e7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_settings_policy_greying_tests.rs @@ -0,0 +1,64 @@ +//! #14245: in Color Settings, with the RGB, CMYK and Gray policies all Off, "Ask When Pasting" and "Missing +//! Profiles: Ask When Opening" are greyed with their values kept, and "Profile Mismatches: Ask When Opening" stays +//! enabled; any policy other than Off enables both again. + +use craft::ui::dialog::DialogId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; + +fn open() -> (Box, DialogId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let id = crate::filter_dialog::open(&mut app, "edit.colorSettings").unwrap(); + crate::dialogs::testing::show(&mut app); + (app, id) +} + +fn set(app: &mut PhotocraftApp, id: DialogId, key: &str, value: Value) -> Result<(), String> { + let ctx = app.ctx().clone(); + let r = app.framework.dialogs.set_json_field(&ctx, id, key, value); + crate::dialogs::testing::show(app); + r +} + +fn field(app: &PhotocraftApp, id: DialogId, key: &str) -> Value { + app.framework.dialogs.open_dialogs().into_iter().find(|d| d.id == id).and_then(|d| d.fields).unwrap()[key].clone() +} + +/// Whether the row `key` takes input: a disabled row refuses a value. +fn takes_input(app: &mut PhotocraftApp, id: DialogId, key: &str) -> bool { + let before = field(app, id, key); + let flipped = json!(!before.as_bool().unwrap()); + let ok = set(app, id, key, flipped).is_ok(); + if ok { + set(app, id, key, before).unwrap(); + } + ok +} + +fn all_off(app: &mut PhotocraftApp, id: DialogId) { + for key in ["policyRgb", "policyCmyk", "policyGray"] { + set(app, id, key, json!("off")).unwrap(); + } +} + +#[test] +fn all_policies_off_grey_the_paste_and_missing_boxes() { + let (mut app, id) = open(); + let (paste, missing) = (field(&app, id, "askOnPaste"), field(&app, id, "askOnMissing")); + all_off(&mut app, id); + assert!(!takes_input(&mut app, id, "askOnPaste"), "Ask When Pasting is greyed"); + assert!(!takes_input(&mut app, id, "askOnMissing"), "Missing Profiles is greyed"); + assert!(takes_input(&mut app, id, "askOnMismatch"), "Ask When Opening stays enabled"); + assert_eq!((field(&app, id, "askOnPaste"), field(&app, id, "askOnMissing")), (paste, missing), "their values are kept"); +} + +#[test] +fn any_policy_back_on_enables_them_again() { + for (key, value) in [("policyRgb", "preserve"), ("policyCmyk", "convert"), ("policyGray", "preserve")] { + let (mut app, id) = open(); + all_off(&mut app, id); + set(&mut app, id, key, json!(value)).unwrap(); + assert!(takes_input(&mut app, id, "askOnPaste") && takes_input(&mut app, id, "askOnMissing"), "{key} {value}"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 12694ba08e..f387ce72a2 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -553,7 +553,8 @@ fn builder( let key = command.to_owned(); let canvas = app.session.active_index().map(|idx| crate::canvas::document_display::CanvasHost::primary(app, idx).canvas_id()); move |fields: &mut DialogFields| { - let mut dialog = ParamDialog::command(key.clone(), title.clone(), params.clone()) + let params = if key == "edit.colorSettings" { color_settings_greying(¶ms, fields) } else { params.clone() }; + let mut dialog = ParamDialog::command(key.clone(), title.clone(), params) .values(Bind::bound(fields)) .reset_to(reset.clone()) .layout(ParamLayout::Stacked) @@ -570,6 +571,22 @@ fn builder( } } +/// Color Settings with the RGB, CMYK and Gray policies all Off: "Ask When Pasting" and "Missing Profiles" are greyed, +/// their values kept; "Ask When Opening" stays (#14245). A row that may hold no value takes no input. +fn color_settings_greying(params: &[Param], fields: &DialogFields) -> Vec { + let all_off = ["policyRgb", "policyCmyk", "policyGray"].iter().all(|key| fields.text(key) == Some("off")); + params + .iter() + .map(|p| { + let mut p = p.clone(); + if all_off && matches!(p.key.as_str(), "askOnPaste" | "askOnMissing") { + p.enabled_when = Some((p.key.clone(), Vec::new())); + } + p + }) + .collect() +} + /// Opens `command`'s schema dialog using the current settings and editing target. The dialog's key /// is the command; Match Color captures its destination document and layer. pub fn open(app: &mut PhotocraftApp, command: &str) -> Result { From b846e831f02ee7479d73f71eb8f4f6731b7f77ad Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 21 Nov 2026 06:08:51 -0600 Subject: [PATCH 024/147] 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 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 025/147] 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 026/147] 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 027/147] 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 028/147] 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 029/147] 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