From 8e0fc5299a62399aa661fac8a63afdd55028e923 Mon Sep 17 00:00:00 2001 From: ArjenS-LA Date: Fri, 23 Oct 2026 17:59:14 -0700 Subject: [PATCH 01/30] Fix Average colour weighting and preserve per-pixel alpha --- crates/engine/src/extra_cmds.rs | 59 +++++++++++++++++++++++++++++---- docs/average-filter.md | 38 +++++++++++++++++++++ docs/gaps.md | 3 +- docs/target-app-parity.md | 3 +- 4 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 docs/average-filter.md diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index db5c93fcfe7..c51a980e943 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -265,21 +265,22 @@ fn equalize(s: &mut Session, p: &Value) -> Result { /// Filter › Blur › Average: the selection (or layer) filled with its mean colour. fn average(s: &mut Session, p: &Value) -> Result { map_pixels(s, "Average", p, |_, px, cover| { - let (mut sum, mut wsum, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64); + let (mut sum, mut wsum) = ([0f64; 3], 0f64); for (p, &k) in px.iter().zip(cover) { - let w = (p[3] * k) as f64; + // Average changes colour, not transparency; hidden RGB contributes too. + let w = k as f64; for c in 0..3 { sum[c] += p[c] as f64 * w; } wsum += w; - asum += (p[3] * k) as f64; - n += k as f64; } if wsum <= 0.0 { return; } - let avg = [(sum[0] / wsum) as f32, (sum[1] / wsum) as f32, (sum[2] / wsum) as f32, (asum / n.max(1e-9)) as f32]; - px.fill(avg); + let avg = sum.map(|v| (v / wsum) as f32); + for p in px { + p[..3].copy_from_slice(&avg); + } }) } @@ -1530,6 +1531,52 @@ mod tests { } } + #[test] + fn average_preserves_transparency_and_averages_hidden_colours() { + // Photoshop 26.6.1, RGB8 PNG with opaque red and transparent blue halves: + // Average produces (128, 0, 128), retaining each pixel's original alpha. + for depth in [8, 16, 32] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.0]); + let bounds = Rect::new(0, 0, 40, 30); + let before = active(&s).surface().unwrap().read_region(bounds); + let steps = s.active().unwrap().history.past_len(); + s.execute("filter.blur.average", json!({})).unwrap(); + let after = active(&s).surface().unwrap().read_region(bounds); + for (old, new) in before.as_chunks::<4>().0.iter().zip(after.as_chunks::<4>().0) { + assert_eq!(new[3], old[3], "depth {depth}: Average must preserve alpha"); + assert!((new[0] - 0.5).abs() < 0.003 && new[1] == 0.0 && (new[2] - 0.5).abs() < 0.003, "{depth}: {new:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + s.undo(); + assert_eq!(active(&s).surface().unwrap().read_region(bounds), before); + s.redo(); + assert_eq!(active(&s).surface().unwrap().read_region(bounds), after); + } + } + + #[test] + fn average_preserves_partial_alpha_and_pixels_outside_selection() { + for depth in [8, 16, 32] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 0.25]); + paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.75]); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": 20, "height": 30})).unwrap(); + let before: Vec<_> = (0..40).map(|x| pixel(&s, x, 15)).collect(); + s.execute("filter.blur.average", json!({})).unwrap(); + for x in 0..40 { + let p = pixel(&s, x, 15); + assert_eq!(p[3], before[x as usize][3], "depth {depth}, x {x}"); + if (10..30).contains(&x) { + assert!((p[0] - 0.5).abs() < 0.003 && (p[2] - 0.5).abs() < 0.003, "{depth}: {p:?}"); + } else { + assert_eq!(p, before[x as usize]); + } + } + } + } + #[test] fn average_and_clouds() { let mut s = session(8); diff --git a/docs/average-filter.md b/docs/average-filter.md new file mode 100644 index 00000000000..ce9b602031d --- /dev/null +++ b/docs/average-filter.md @@ -0,0 +1,38 @@ +# Average filter: transparency reference + +The Average filter replaces colour while retaining each pixel's transparency. +Two synthetic cases were executed in Photoshop **26.6.1 on Windows x64** on +2026-10-23. These are observations of RGB8 raster layers, without a selection or +transparency lock; they are not a claim of parity in other colour modes or at +other bit depths. + +Each input is a 16 × 16 RGBA PNG. Its left eight columns are red and its right +eight columns are blue. Open it in Photoshop, run Filter › Blur › Average, and +save a PNG copy. Inspect the file's RGBA values, including invisible colours. + +| Input left / right RGBA | Output left / right RGBA | +|---|---| +| `(255,0,0,255)` / `(0,0,255,0)` | `(128,0,128,255)` / `(128,0,128,0)` | +| `(255,0,0,64)` / `(0,0,255,192)` | `(128,0,128,64)` / `(128,0,128,192)` | + +An opaque control produces `(128,0,128,255)` throughout. Thus transparency is +neither a weight in this colour average nor a channel to replace with its mean. + +PhotoCraft previously alpha-weighted the RGB mean and replaced alpha with its +mean. On the first case that predicts translucent red throughout, rather than +purple pixels with their original transparency. The fix uses selection coverage +for the existing mean and leaves each pixel's alpha alone. Selection mixing and +the existing colour conversion path are unchanged. In particular, this does not +establish Photoshop parity for feathered selection weighting or CMYK/Lab means. + +The engine tests construct their own pixels; no Photoshop binary, proprietary +code, or reference image is included. They cover transparent and partially +transparent pixels, selection boundaries, one history step, undo and redo at +8/16/32-bit storage. The higher-depth tests establish PhotoCraft invariants; +the external reference measurements above are RGB8 only. + +Run the focused regressions with: + +```sh +cargo test -p photocraft-engine --lib average_preserves +``` diff --git a/docs/gaps.md b/docs/gaps.md index d878a675f5c..7f4d915b929 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -358,6 +358,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-21 | minor | G9: adjustment clipping remains visible in compact Properties (#5231); no readiness percentage or estimate changed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0609ff8c1e5..15e1477f244 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-22 · **Change:** minor (Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-23 · **Change:** minor (Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -565,6 +565,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | Platforms: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; percentages unchanged | | 2026-10-21 | minor | #8304: compound layer properties export as separate Set events, rename last; independent Photoshop replay pending; percentages and estimates unchanged | | 2026-10-19 | minor | JPEG Options dialog landed (FILE-215-19 partial: no Matte, progressive Scans or size preview); percentages unchanged | From 81988038ff5087c62679387fcf19182484e7f99f Mon Sep 17 00:00:00 2001 From: ArjenS-LA Date: Fri, 23 Oct 2026 19:13:01 -0700 Subject: [PATCH 02/30] Execute Average through the shared smart-filter pipeline --- crates/algo/src/average.rs | 135 ++++++++++++++++++++++++ crates/algo/src/average/tests.rs | 37 +++++++ crates/algo/src/lib.rs | 16 ++- crates/engine/src/extra_cmds.rs | 29 +---- crates/engine/src/filters.rs | 2 + crates/engine/src/filters/validation.rs | 3 +- crates/engine/tests/it/average_smart.rs | 124 ++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + docs/average-filter.md | 36 +++++++ docs/gaps.md | 4 +- docs/target-app-parity.md | 8 +- 11 files changed, 365 insertions(+), 30 deletions(-) create mode 100644 crates/algo/src/average.rs create mode 100644 crates/algo/src/average/tests.rs create mode 100644 crates/engine/tests/it/average_smart.rs diff --git a/crates/algo/src/average.rs b/crates/algo/src/average.rs new file mode 100644 index 00000000000..982ec7cb6f6 --- /dev/null +++ b/crates/algo/src/average.rs @@ -0,0 +1,135 @@ +//! Average changes colour, never coverage. Keep the existing RGB conversion and selection +//! weighting; Photoshop RGB8 observations are documented in docs/average-filter.md. +use photocraft_color::{PixelFormat, SampleType}; +use photocraft_geom::Rect; +use photocraft_raster::{Interrupt, Surface, from_rgba_into, to_rgba}; + +use crate::{Ctx, Image}; + +#[derive(Default)] +struct Mean { + sum: [f64; 3], + weight: f64, +} + +impl Mean { + fn add(&mut self, fmt: &PixelFormat, px: &[f32], coverage: f32) { + let rgba = to_rgba(fmt, px); + let w = f64::from(coverage); + for (sum, value) in self.sum.iter_mut().zip(rgba) { + *sum += f64::from(value) * w; + } + self.weight += w; + } + + fn colour(&self) -> Option<[f32; 3]> { + (self.weight > 0.0).then(|| self.sum.map(|s| (s / self.weight) as f32)) + } +} + +fn mix(fmt: &PixelFormat, px: &mut [f32], colour: [f32; 3], coverage: f32) { + if coverage <= 0.0 { + return; + } + let mut rgba = to_rgba(fmt, px); + for (value, mean) in rgba.iter_mut().zip(colour) { + *value += (mean - *value) * coverage; + } + from_rgba_into(fmt, rgba, px); +} + +// Rect's public coordinates can span more than i32::MAX. Reject these before raster helpers +// do their signed coordinate arithmetic, and cap a single operation's sample count. +fn valid_area(area: Rect, channels: usize) -> bool { + area.width() <= i32::MAX as u32 + && area.height() <= i32::MAX as u32 + && u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(channels as u64) <= 512 * 1024 * 1024 +} + +pub(crate) fn apply(surface: &Surface, area: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Option { + let fmt = surface.format(); + let n = fmt.channels(); + if !valid_area(area, n) || ctl.cancelled() { + return None; + } + if area.is_empty() { + return Some(surface.clone()); + } + let mut raw = surface.try_read_region(area).ok()?; + let width = area.width() as usize; + let coverage = |i: usize| selection.map_or(1.0, |s| s.sample_channel(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32, 0)); + let mut mean = Mean::default(); + for (i, px) in raw.chunks_exact(n).enumerate() { + if i % width == 0 && ctl.cancelled() { + return None; + } + mean.add(&fmt, px, coverage(i)); + } + let Some(colour) = mean.colour() else { return Some(surface.clone()) }; + for (i, px) in raw.chunks_exact_mut(n).enumerate() { + if i % width == 0 && ctl.cancelled() { + return None; + } + mix(&fmt, px, colour, coverage(i)); + } + let mut out = surface.clone(); + if ctl.cancelled() { + return None; + } + out.try_write_region(area, &raw).ok()?; + out.prune(); + ctl.progress(1.0); + Some(out) +} + +// The direct kernel API has no selection. Its mean is over the reference bounds, even when +// the requested output is only a tile; the surface dispatcher above also handles selections. +pub(crate) fn kernel(src: &Image, out: Rect, ctx: &Ctx) -> Vec { + let fmt = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha); + let n = fmt.channels(); + if src.ch != n || !valid_area(src.rect, n) || !valid_area(out, n) { + return Vec::new(); + } + let read = |x: i32, y: i32| -> Option<&[f32]> { + if !src.rect.contains(x, y) { + return None; + } + let i = (i64::from(y) - i64::from(src.rect.y0)) as usize; + let j = (i64::from(x) - i64::from(src.rect.x0)) as usize; + let start = i.checked_mul(src.rect.width() as usize)?.checked_add(j)?.checked_mul(n)?; + src.data.get(start..start.checked_add(n)?) + }; + let bounds = ctx.bounds.intersect(&src.rect); + let mut mean = Mean::default(); + for y in bounds.y0..bounds.y1 { + for x in bounds.x0..bounds.x1 { + if let Some(px) = read(x, y) { + mean.add(&fmt, px, 1.0); + } + } + } + let len = (out.width() as usize).checked_mul(out.height() as usize).and_then(|s| s.checked_mul(n)); + let Some(len) = len else { return Vec::new() }; + let mut result = Vec::new(); + if result.try_reserve_exact(len).is_err() { + return result; + } + let colour = mean.colour(); + for y in out.y0..out.y1 { + for x in out.x0..out.x1 { + let mut px = [0.0; 5]; + let Some(pixel) = px.get_mut(..n) else { return Vec::new() }; + if let Some(source) = read(x, y) { + pixel.copy_from_slice(source); + } + if let Some(colour) = colour { + mix(&fmt, pixel, colour, 1.0); + } + result.extend_from_slice(pixel); + } + } + result +} + +#[cfg(test)] +mod tests; diff --git a/crates/algo/src/average/tests.rs b/crates/algo/src/average/tests.rs new file mode 100644 index 00000000000..dac194d4b13 --- /dev/null +++ b/crates/algo/src/average/tests.rs @@ -0,0 +1,37 @@ +use super::*; +use photocraft_color::ColorMode; + +#[test] +fn preserves_alpha_and_averages_hidden_rgb_at_each_depth() { + let bounds = Rect::new(0, 0, 2, 1); + for sample in SampleType::ALL { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); + let mut surface = Surface::new(fmt); + surface.write_region(bounds, &[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + let out = apply(&surface, bounds, None, &Interrupt::NONE).unwrap(); + for (i, p) in out.read_region(bounds).as_chunks::<4>().0.iter().enumerate() { + assert!((p[0] - 0.5).abs() <= 1.0 / 255.0); + assert_eq!(p[1], 0.0); + assert!((p[2] - 0.5).abs() <= 1.0 / 255.0); + assert_eq!(p[3], if i == 0 { 1.0 } else { 0.0 }); + } + } +} + +#[test] +fn direct_kernel_uses_reference_bounds_for_each_output_tile() { + let bounds = Rect::new(-1, 0, 1, 1); + let src = Image { rect: bounds, ch: 4, data: vec![1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75] }; + let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true }; + assert_eq!(kernel(&src, Rect::new(-1, 0, 0, 1), &ctx), vec![0.5, 0.0, 0.5, 0.25]); + assert_eq!(kernel(&src, Rect::new(0, 0, 1, 1), &ctx), vec![0.5, 0.0, 0.5, 0.75]); +} + +#[test] +fn rejects_extreme_geometry_and_honours_pre_cancel() { + let surface = Surface::new(PixelFormat::RGBA8); + let huge = Rect::new(i32::MIN, 0, i32::MAX, 1); + assert!(apply(&surface, huge, None, &Interrupt::NONE).is_none()); + assert!(apply(&surface, Rect::new(0, 0, 5, 5), None, &Interrupt::cancel_only(&|| true)).is_none()); + assert_eq!(surface.tile_count(), 0); +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index f804abae511..0efb2bda71c 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -20,6 +20,7 @@ mod artistic; mod artistic_fx; +mod average; mod blur; mod blur2; pub mod camera_raw; @@ -202,6 +203,8 @@ pub enum PolarMode { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "filter", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum FilterParams { + /// Mean colour over the selected area, retaining each pixel's alpha. + Average, /// Radius = Gaussian standard deviation in pixels (0.1–1000). GaussianBlur { radius: f32, @@ -577,7 +580,8 @@ impl FilterParams { FilterParams::Emboss { height, .. } => Halo::Radius(height.abs().ceil() as i32 + 2), FilterParams::FindEdges => Halo::Radius(1), FilterParams::AddNoise { .. } | FilterParams::Solarize | FilterParams::Invert | FilterParams::Desaturate => Halo::Radius(0), - FilterParams::RadialBlur { .. } + FilterParams::Average + | FilterParams::RadialBlur { .. } | FilterParams::Offset { .. } | FilterParams::Twirl { .. } | FilterParams::Pinch { .. } @@ -619,14 +623,16 @@ impl FilterParams { } /// Whether the filter places and sizes its pattern by the canvas even with a selection - /// (Clouds, Fibers): its bounds are then the canvas, and the selection only masks the result. + /// (Clouds, Fibers), or limits its working area to the canvas (Average). The output + /// area is still clipped to the selection; Average also weights its mean by that coverage. pub fn sizes_by_canvas(&self) -> bool { - matches!(self, FilterParams::Clouds { .. } | FilterParams::Fibers { .. }) + matches!(self, FilterParams::Average | FilterParams::Clouds { .. } | FilterParams::Fibers { .. }) } /// Human-readable name. pub fn label(&self) -> &'static str { match self { + FilterParams::Average => "Average", FilterParams::GaussianBlur { .. } => "Gaussian Blur", FilterParams::BoxBlur { .. } => "Box Blur", FilterParams::MotionBlur { .. } => "Motion Blur", @@ -750,6 +756,7 @@ pub struct Ctx { /// the halo, or the bounds for global filters). Returns interleaved samples. pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec { match params { + FilterParams::Average => average::kernel(src, out, ctx), FilterParams::GaussianBlur { radius } => blur::gaussian(src, out, ctx, *radius), FilterParams::BoxBlur { radius } => blur::boxed(src, out, ctx, *radius), FilterParams::MotionBlur { angle, distance } => blur::motion(src, out, ctx, *angle, *distance), @@ -1077,6 +1084,9 @@ fn apply_tiled_with_impl( if area.is_empty() { return Some(out); } + if matches!(params, FilterParams::Average) { + return average::apply(surface, extent.map_or(area, |e| area.intersect(&e)), selection, ctl); + } #[cfg(not(target_arch = "wasm32"))] if prepare_fast_paths && let Some(result) = sharpen::fft::apply(surface, params, area, selection, extent, ctl) { return result; diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index c51a980e943..c1d21a8d858 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -262,28 +262,6 @@ fn equalize(s: &mut Session, p: &Value) -> Result { }) } -/// Filter › Blur › Average: the selection (or layer) filled with its mean colour. -fn average(s: &mut Session, p: &Value) -> Result { - map_pixels(s, "Average", p, |_, px, cover| { - let (mut sum, mut wsum) = ([0f64; 3], 0f64); - for (p, &k) in px.iter().zip(cover) { - // Average changes colour, not transparency; hidden RGB contributes too. - let w = k as f64; - for c in 0..3 { - sum[c] += p[c] as f64 * w; - } - wsum += w; - } - if wsum <= 0.0 { - return; - } - let avg = sum.map(|v| (v / wsum) as f32); - for p in px { - p[..3].copy_from_slice(&avg); - } - }) -} - // ---------- transform presets ---------- /// The presets' params: like Free Transform, they follow the Channels and Layers panel target. @@ -1023,7 +1001,6 @@ pub fn specs() -> Vec { has_layer, show_only ), - spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average), ] } @@ -1055,7 +1032,7 @@ mod tests { s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; s.tools.background = [1.0, 1.0, 1.0, 1.0]; s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); - let p = match target { + let mut p = match target { "quickMask" => { s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); json!({"seed": 1}) @@ -1070,6 +1047,10 @@ mod tests { json!({"seed": 1, "target": "mask"}) } }; + // Average has no seed parameter; only Clouds uses it. + if cmd == "filter.blur.average" { + p.as_object_mut().unwrap().remove("seed"); + } // Two levels in the target, so Equalize and Average have something to change. let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } }); s.edit("levels", |doc, active| { diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index b115a9f5e04..e5b7c2b3f8f 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -84,6 +84,7 @@ pub fn params_for(id: &str, p: &Value) -> Option { return Some(fp); } Some(match id { + "filter.blur.average" => FilterParams::Average, "filter.blur.gaussianBlur" => FilterParams::GaussianBlur { radius: f(p, "radius", 1.0).clamp(0.1, 1000.0) }, "filter.blur.boxBlur" => FilterParams::BoxBlur { radius: f(p, "radius", 1.0).clamp(1.0, 2000.0) }, "filter.blur.motionBlur" => FilterParams::MotionBlur { angle: f(p, "angle", 0.0), distance: f(p, "distance", 10.0).clamp(1.0, 2000.0) }, @@ -408,6 +409,7 @@ macro_rules! filter_cmd { pub fn specs() -> Vec { vec![ filter_cmd!("filter.blur.gaussianBlur", "Gaussian Blur…", ["Filter", "Blur"], r##"{"radius":0.1..1000=1}"##), + filter_cmd!("filter.blur.average", "Average", ["Filter", "Blur"], "{}"), filter_cmd!("filter.blur.blur", "Blur", ["Filter", "Blur"], "{}"), filter_cmd!("filter.blur.blurMore", "Blur More", ["Filter", "Blur"], "{}"), filter_cmd!("filter.sharpen.sharpen", "Sharpen", ["Filter", "Sharpen"], "{}"), diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rs index b2359ffa57c..5e7d5de50a4 100644 --- a/crates/engine/src/filters/validation.rs +++ b/crates/engine/src/filters/validation.rs @@ -94,7 +94,8 @@ fn fields(id: &str) -> Option<&'static [(&'static str, Rule)]> { ("vertical", Number(f64::MIN, f64::MAX)), ("undefinedAreas", Choice("wrap|repeat|transparent")), ], - "filter.blur.blur" + "filter.blur.average" + | "filter.blur.blur" | "filter.blur.blurMore" | "filter.sharpen.sharpen" | "filter.sharpen.sharpenMore" diff --git a/crates/engine/tests/it/average_smart.rs b/crates/engine/tests/it/average_smart.rs new file mode 100644 index 00000000000..0f6458f5f18 --- /dev/null +++ b/crates/engine/tests/it/average_smart.rs @@ -0,0 +1,124 @@ +//! Exercise Average through the smart-filter renderer, not an imported cache. +use photocraft_doc::LayerContent; +use photocraft_engine::{Session, filters, smart_cmds}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +fn image(s: &Session) -> Surface { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match &l.content { + LayerContent::Raster(r) => r.clone(), + LayerContent::Smart(sm) => sm.cache.clone().unwrap(), + _ => panic!("expected pixels"), + } +} + +fn input(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let d = s.active_mut().unwrap(); + let l = std::sync::Arc::make_mut(&mut d.doc).layer_mut(d.active_layer.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 0..16 { + for x in 0..16 { + surf.write_region(Rect::new(x, y, x + 1, y + 1), if x < 8 { &[1.0, 0.0, 0.0, 1.0] } else { &[0.0, 0.0, 1.0, 1.0] }); + } + } + s +} + +fn purple(surf: &Surface) { + for p in surf.read_region(Rect::new(0, 0, 16, 16)).as_chunks::<4>().0 { + assert!((p[0] - 0.5).abs() <= 1.0 / 255.0, "{p:?}"); + assert_eq!(p[1], 0.0); + assert!((p[2] - 0.5).abs() <= 1.0 / 255.0, "{p:?}"); + assert_eq!(p[3], 1.0); + } +} + +#[test] +fn average_stored_filter_executes() { + for depth in [8, 16, 32] { + let s = input(depth); + let bounds = s.active().unwrap().doc.bounds(); + let out = filters::apply_filter_to_surface("filter.blur.average", &json!({}), &image(&s), bounds, None, bounds) + .unwrap() + .expect("Average must be executable, not treated as an unknown filter"); + purple(&out); + } +} + +#[test] +fn average_smart_command_rerenders_and_undoes() { + for depth in [8, 16, 32] { + let mut s = input(depth); + s.execute("filter.convertForSmartFilters", json!({})).unwrap(); + let before = image(&s); + let steps = s.active().unwrap().history.past_len(); + assert!(s.is_enabled("filter.blur.average")); + s.execute("filter.blur.average", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + purple(&image(&s)); + assert!(s.undo()); + assert_eq!(image(&s), before); + assert!(s.redo()); + purple(&image(&s)); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(image(&s), before); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); + let d = s.active_mut().unwrap(); + let snapshot = d.doc.clone(); + let layer = std::sync::Arc::make_mut(&mut d.doc).layer_mut(d.active_layer.unwrap()).unwrap(); + if let LayerContent::Smart(sm) = &mut layer.content { + assert_eq!(sm.smart_filters.len(), 1); + assert_eq!(sm.smart_filters[0].command, "filter.blur.average"); + sm.cache = None; + } + smart_cmds::purge_stack_cache(); + assert!(smart_cmds::refresh_layer(&snapshot, layer).unwrap()); + purple(&image(&s)); + } +} + +#[test] +fn average_rejects_bad_params_without_an_edit() { + let mut s = input(8); + let before = image(&s); + let steps = s.active().unwrap().history.past_len(); + for params in [json!("bad"), json!({"unknown": 1}), json!({"layer": -1}), json!({"target": false})] { + assert!(s.execute("filter.blur.average", params).is_err()); + assert_eq!(image(&s), before); + assert_eq!(s.active().unwrap().history.past_len(), steps); + } +} + +/// Optional local oracle: generate a 16×16 red/blue Smart Object in Photoshop, apply Average, +/// save as PSD, then set PHOTOCRAFT_AVERAGE_PSD to that file. Never accept cached pixels as proof. +#[test] +#[ignore = "requires a locally generated Photoshop Average PSD; see docs/average-filter.md"] +fn average_photoshop_psd_rerenders_from_source() { + let path = std::env::var("PHOTOCRAFT_AVERAGE_PSD").expect("set PHOTOCRAFT_AVERAGE_PSD"); + let bytes = std::fs::read(&path).unwrap(); + let mut doc = photocraft_io::import(&path, &bytes).unwrap().document; + let snapshot = doc.clone(); + let ids: Vec<_> = snapshot + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Smart(sm) if sm.smart_filters.iter().any(|f| f.command == "filter.blur.average") => Some(l.id), + _ => None, + }) + .collect(); + assert_eq!(ids.len(), 1); + let layer = doc.layer_mut(ids[0]).unwrap(); + if let LayerContent::Smart(sm) = &mut layer.content { + sm.cache = None; + } + smart_cmds::purge_stack_cache(); + assert!(smart_cmds::refresh_layer(&snapshot, layer).unwrap()); + let LayerContent::Smart(sm) = &layer.content else { panic!("expected smart object") }; + purple(sm.cache.as_ref().unwrap()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 25455e539c4..4b22a160e9b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -6,6 +6,7 @@ mod atn_crystallize_cell_size; mod atn_ripple_amount; mod atn_selective_color; mod atn_stroke_width; +mod average_smart; mod background_and_mask_depth; mod background_layer_consistency; mod brush_smoothing; diff --git a/docs/average-filter.md b/docs/average-filter.md index ce9b602031d..65e91a84337 100644 --- a/docs/average-filter.md +++ b/docs/average-filter.md @@ -36,3 +36,39 @@ Run the focused regressions with: ```sh cargo test -p photocraft-engine --lib average_preserves ``` + +## Smart filters + +The PSD importer already recognizes the optionless `Avrg` descriptor (see +[#6297](https://github.com/storytold/photocraft/pull/6297)). Recognition alone did +not execute it: the shared renderer returned `None`, leaving the source pixels +unchanged, and the raster-only command was disabled on Smart Objects. + +Average now uses the shared filter command and algorithm. It can be added to a +Smart Object, toggled, undone and redone, or re-rendered from an imported record. +The raster path retains its canvas limit, selection weighting and alpha behavior. +Like other core filters, new invocations validate parameters before editing. + +The integration tests create their own red/blue Smart Objects at RGB8/16/32f. +They check the dispatcher, command enablement, one history step, visibility, +undo/redo, and re-rendering after clearing both the layer and stage caches: + +```sh +cargo test -p photocraft-engine --test it average_smart +``` + +An additional, explicitly ignored test accepts a local Photoshop oracle. To +reproduce it in Photoshop, create an opaque 16 × 16 RGB8 image with eight red +columns followed by eight blue columns, convert the layer to a Smart Object, +apply Average and save a PSD. Photoshop 26.6.1 on Windows produces purple +`(128,0,128,255)` throughout. Then run, in PowerShell: + +```powershell +$env:PHOTOCRAFT_AVERAGE_PSD = 'C:\path\to\average-smart.psd' +cargo test -p photocraft-engine --test it average_photoshop_psd_rerenders_from_source -- --ignored --nocapture +``` + +This test discards the imported layer cache and the smart-filter stage cache, +then rebuilds from the embedded source. Merely importing or flattening the PSD +would reuse Photoshop's saved pixels and would not prove execution. The local +PSD is not committed and the opt-in test does not raise a corpus floor. diff --git a/docs/gaps.md b/docs/gaps.md index 7f4d915b929..a7a0e720eab 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (Average smart-filter execution uses the shared algorithm; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -40,6 +40,7 @@ what an agent can't finish alone. ## Feature gaps ### G1. PSD fidelity and Photoshop acceptance +- **Average (2026-10-23):** the existing `Avrg` PSD mapping now has an executable smart-filter path. [Focused tests](average-filter.md#smart-filters) cover the command and re-rendering after discarding cached pixels; the local Photoshop RGB8 oracle is opt-in and does not change corpus floors. Broader filter parity remains open. - **Missing:** PSDs we write are not always accepted by Photoshop, and Photoshop-authored files don't always render as Photoshop renders them. - **Partial (2026-10-15, #5972 A1):** `GdFl` noise fills render when all three RGB ranges are @@ -358,6 +359,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Average runs on Smart Objects and imported `Avrg` records; synthetic depth tests and an opt-in cold Photoshop PSD re-render are documented in [average-filter.md](average-filter.md). Corpus floors and percentages unchanged. | | 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15e1477f244..9e021ab04aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-23 · **Change:** minor (Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-23 · **Change:** minor (Average smart-filter execution uses the shared algorithm; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -162,6 +162,11 @@ people send ×0.95 (JPEG, PNG, HEIC, WebP, PSD open; AVIF and PDF don't, #463, # ## Feature areas +Average now executes through the shared filter pipeline on Smart Objects and imported +PSD records. [Focused evidence](average-filter.md#smart-filters) covers synthetic +RGB8/16/32f cases and an opt-in Photoshop 26.6.1 RGB8 re-render after clearing caches; +this does not raise the broad filter estimate or any corpus floor. + Percent is ready-for-real-work for that area (depth and fidelity, not presence). Hours are to full parity for the area and are already contained in the dimension rows above. @@ -565,6 +570,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Average runs on Smart Objects and imported `Avrg` records; synthetic depth tests and an opt-in cold Photoshop PSD re-render are documented in [average-filter.md](average-filter.md). Corpus floors and percentages unchanged. | | 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | Platforms: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; percentages unchanged | | 2026-10-21 | minor | #8304: compound layer properties export as separate Set events, rename last; independent Photoshop replay pending; percentages and estimates unchanged | From d6ab8131f8fe568f0ae9091606ea0b96a3b642c5 Mon Sep 17 00:00:00 2001 From: devstivi <340315248+devstivi@users.noreply.github.com> Date: Sat, 24 Oct 2026 04:39:11 +0700 Subject: [PATCH 03/30] Offer Apply to All in the unsaved-changes prompt (#8983) Closing several unsaved documents (Close All, Close Others, quitting) asked about each one in turn. With more than one document left the prompt now has an Apply to All box, as in Photoshop: Yes or No then answers for every remaining document. A document whose save is cancelled or fails is asked about again instead of retrying. Control clients get saveAll and dontSaveAll. --- crates/ui-egui/src/discard_ui.rs | 170 ++++++++++++++++++++++++++++--- docs/control-protocol.md | 2 +- 2 files changed, 156 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index a6a65f29fe3..bf9b0714a7a 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -23,6 +23,12 @@ pub struct Prompt { docs: Vec, /// The document whose question has already put keyboard focus on its default answer. focused: Option, + /// "Apply to All" is ticked. It is only offered while more than one document is left to ask about. + apply_all: bool, + /// The answer given to every document still to ask about, once "Apply to All" was used. + auto: Option, + /// The document `auto` answered last: if it is asked about again, its save didn't go through. + auto_answered: Option, } fn index_of(app: &PhotocraftApp, id: DocId) -> Option { @@ -79,7 +85,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str, params: &Value) -> bool { log::warn!("quitting a window that lost its GPU device before its unsaved work could be saved for recovery"); return false; } - let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None }; + let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None, apply_all: false, auto: None, auto_answered: None }; match &app.discard { None => ask(app, prompt), // Quitting overrides whatever is pending: it covers every document, so nothing is lost. @@ -269,11 +275,32 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(p) = &app.discard else { return }; let Some(&doc) = p.docs.first() else { return }; let (exits, reverts) = (p.id == EXIT, p.id == "file.revert"); + let (focus, offer_all) = (p.focused != Some(doc), p.docs.len() > 1 && !reverts); let Some(name) = index_of(app, doc).map(|i| app.session.documents()[i].doc.name.clone()) else { // Closed by something else while the prompt was up: nothing left to ask about. advance(app, ctx); return; }; + // "Apply to All" answers the rest one document per frame, as Photoshop does. A document that + // comes back (its save was cancelled or failed) is asked about normally again, so a save that + // can't succeed never repeats on its own. + match app.discard.as_ref().and_then(|p| p.auto.map(|a| (a, p.auto_answered == Some(doc)))) { + Some((answer, false)) => { + if let Some(p) = app.discard.as_mut() { + p.auto_answered = Some(doc); + } + apply(app, ctx, doc, answer); + ctx.request_repaint(); + return; + } + Some((_, true)) => { + if let Some(p) = app.discard.as_mut() { + p.auto = None; + p.apply_all = false; + } + } + None => {} + } let (title, message) = if reverts { ("Revert", crate::i18n::fmt(tl!("Revert “{name}” to the last saved version? Your changes will be lost."), &[("name", &name)])) } else { @@ -286,7 +313,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }; // Each question comes up with its default answer focused, as in Photoshop: the arrow keys then // move between the answers and Enter presses the focused one (#6441). - let focus = p.focused != Some(doc); + let mut apply_all = app.discard.as_ref().is_some_and(|p| p.apply_all); if let Some(p) = app.discard.as_mut() { p.focused = Some(doc); } @@ -319,6 +346,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::widgets::hairline(ui); ui.add_space(8.0); ui.label(message); + ui.add_space(8.0); + if offer_all { + crate::widgets::checkbox(ui, &mut apply_all, tl!("Apply to All")); + } ui.add_space(12.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 10.0; @@ -334,11 +365,28 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if answer.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) { answer = buttons.iter().find(|b| b.0 == ButtonRole::Default).map(|b| b.4); } + if let Some(p) = app.discard.as_mut() { + p.apply_all = apply_all; + } if let Some(answer) = answer { + if apply_all && offer_all { + apply_to_rest(app, doc, answer); + } apply(app, ctx, doc, answer); } } +/// Makes a Save or Don't Save answer about `doc` the answer for every document still to ask about. +fn apply_to_rest(app: &mut PhotocraftApp, doc: DocId, answer: Answer) { + if !matches!(answer, Answer::Save | Answer::Discard) { + return; + } + if let Some(p) = app.discard.as_mut() { + p.auto = Some(answer); + p.auto_answered = Some(doc); + } +} + /// Acts on the answer about `doc`, the document the prompt is asking about. fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answer) { match answer { @@ -360,7 +408,8 @@ pub fn inspect(app: &PhotocraftApp) -> Option { let doc = *p.docs.first()?; let name = index_of(app, doc).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone())?; let reverts = p.id == "file.revert"; - let (choices, default): (&[&str], _) = if reverts { (&["dontSave", "cancel"], "dontSave") } else { (&["save", "dontSave", "cancel"], "save") }; + let choices = choices(reverts, p.docs.len() > 1); + let default = if reverts { "dontSave" } else { "save" }; Some(json!({ "id": CONTROL_ID, "kind": "unsavedChanges", @@ -375,8 +424,19 @@ pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> { app.discard.as_ref().map(|p| (p.id.clone(), p.params.clone())) } +/// The answers a control client can give: `save`, `dontSave` and `cancel`, plus `saveAll` and +/// `dontSaveAll` (the "Apply to All" box) while more than one document is left to ask about. +/// Revert takes `dontSave` or `cancel` only. +fn choices(reverts: bool, several: bool) -> Vec<&'static str> { + match (reverts, several) { + (true, _) => vec!["dontSave", "cancel"], + (false, false) => vec!["save", "dontSave", "cancel"], + (false, true) => vec!["save", "saveAll", "dontSave", "dontSaveAll", "cancel"], + } +} + /// Answers the prompt for a control client: `save`, `dontSave` or `cancel` (Revert takes -/// `dontSave` or `cancel`). Like the buttons, Save may first ask for a path in the save dialog. +/// `dontSave` or `cancel`); `saveAll` and `dontSaveAll` answer for every document still to ask about. Like the buttons, Save may first ask for a path in the save dialog. pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str) -> Result { let Some(doc) = app.discard.as_ref().and_then(|p| p.docs.first().copied()) else { return Err("no unsaved-changes prompt is open".into()); @@ -385,15 +445,22 @@ pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str return Err("the unsaved-changes prompt is waiting for a save to finish".into()); } let reverts = app.discard.as_ref().is_some_and(|p| p.id == "file.revert"); - let answer = match choice { - "save" if !reverts => Answer::Save, - "dontSave" => Answer::Discard, - "cancel" => Answer::Cancel, + let several = app.discard.as_ref().is_some_and(|p| p.docs.len() > 1); + let (answer, all) = match choice { + "save" if !reverts => (Answer::Save, false), + "saveAll" if !reverts && several => (Answer::Save, true), + "dontSave" => (Answer::Discard, false), + "dontSaveAll" if !reverts && several => (Answer::Discard, true), + "cancel" => (Answer::Cancel, false), other => { - let choices = if reverts { "dontSave or cancel" } else { "save, dontSave or cancel" }; - return Err(format!("unknown choice `{other}`: {choices}")); + let choices = choices(reverts, several); + let (last, rest) = choices.split_last().unwrap_or((&"cancel", &[])); + return Err(format!("unknown choice `{other}`: {} or {last}", rest.join(", "))); } }; + if all { + apply_to_rest(app, doc, answer); + } apply(app, ctx, doc, answer); Ok(json!({"open": app.discard.is_some(), "fileDialog": app.file_dialog_open()})) } @@ -660,17 +727,24 @@ mod tests { } /// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and - /// wraps; Shift+Tab steps back. + /// wraps; Shift+Tab steps back. When the prompt offers "Apply to All", that box is one more + /// stop, in front of the answers. fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) { - assert_eq!(focused(h, &labels), Some(labels[default])); - for step in 1..=3 { + use egui_kittest::kittest::Queryable; + let mut stops = labels.to_vec(); + if h.query_by_label("Apply to All").is_some() { + stops.insert(0, "Apply to All"); + } + let (n, at) = (stops.len(), default + stops.len() - 3); + assert_eq!(focused(h, &stops), Some(stops[at])); + for step in 1..=n { h.key_press(Key::Tab); h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3])); + assert_eq!(focused(h, &stops), Some(stops[(at + step) % n])); } h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab); h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3])); + assert_eq!(focused(h, &stops), Some(stops[(at + n - 1) % n])); } fn docs_left(h: &Prompted) -> Option { @@ -723,6 +797,72 @@ mod tests { } } + /// "Apply to All" (a checkbox, as in Photoshop) gives the answer to every document still to ask about. + #[test] + fn apply_to_all_discards_the_rest_without_asking_again() { + use egui_kittest::kittest::Queryable; + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + h.get_by_label("Apply to All").click(); + h.run_steps(2); + h.key_press(Key::N); + h.run_steps(8); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty(), "No was applied to both unsaved documents"); + } + + #[test] + fn apply_to_all_is_only_offered_while_several_documents_are_left() { + use egui_kittest::kittest::Queryable; + let mut one_dirty = app_with_docs(2); + make_dirty(&mut one_dirty, 0); + let h = prompt_for(one_dirty, "file.closeAll", egui::os::OperatingSystem::Windows); + assert!(h.query_by_label("Apply to All").is_none(), "only one document is unsaved"); + let h = prompt_on(egui::os::OperatingSystem::Windows); + assert!(h.query_by_label("Apply to All").is_some()); + } + + /// A save that was cancelled or failed brings its document back: asking again beats retrying forever. + #[test] + fn a_document_that_comes_back_after_apply_to_all_is_asked_about_again() { + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + let first = doc_id(h.state(), 0); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (true, Some(Answer::Save), Some(first)); + } + h.run_steps(3); + let prompt = h.state().discard.as_ref().unwrap(); + assert!(prompt.auto.is_none() && !prompt.apply_all); + assert_eq!(docs_left(&h), Some(2), "both documents are still waiting for an answer"); + } + + #[test] + fn control_clients_can_answer_for_all() { + let mut app = app_with_docs(3); + for i in 0..3 { + make_dirty(&mut app, i); + } + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let choices = inspect(h.state()).unwrap()["fields"]["choices"].clone(); + assert_eq!(choices, json!(["save", "saveAll", "dontSave", "dontSaveAll", "cancel"])); + let ctx = h.ctx.clone(); + answer_control(h.state_mut(), &ctx, "dontSaveAll").unwrap(); + h.run_steps(8); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty()); + } + + #[test] + fn the_all_answers_need_more_than_one_document_left() { + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); + assert_eq!(inspect(&app).unwrap()["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + let err = answer_control(&mut app, &ctx, "saveAll").unwrap_err(); + assert!(err.contains("unknown choice `saveAll`") && err.ends_with("save, dontSave or cancel"), "{err}"); + assert!(app.discard.is_some(), "a refused answer leaves the prompt up"); + } + /// Whether the prompt is asking about the document called `name`. fn asks_about(h: &Prompted, name: &str) -> bool { use egui_kittest::kittest::Queryable; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 77edb5e4d04..7fb8efc1fcf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -66,7 +66,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - A Layer Style color field opens the shared picker with `ui.dialog.open {"kind":"colorPicker","parent":12,"effect":"fx2","field":"color"}`. `parent` is the Layer Style dialog id; `effect` is its effect instance id. `field` must be one of that instance's color parameters (`color`, or `from`/`to` for Gradient Overlay). The picker previews over the pending style without changing the document. Picker OK changes only the parent parameter; Cancel discards the preview. Confirm the parent afterwards to apply the style. Parent confirmation is refused while its picker is open; parent cancellation closes both. The binding is exposed in `ui.inspect` as `__layerStyleColor`; changed/closed targets or a document switch invalidate it. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails - - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "dontSave" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. + - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "saveAll" | "dontSave" | "dontSaveAll" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time. `saveAll` and `dontSaveAll` tick "Apply to All": they answer for every document still to ask about, and are listed in `choices` only while more than one is left. A document whose save is cancelled or fails is asked about again; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. From 5fae9a15ee1aa92a68ebb7ab8b4d8f25f4e24fc0 Mon Sep 17 00:00:00 2001 From: devstivi <340315248+devstivi@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:46:05 +0700 Subject: [PATCH 04/30] Ask afresh about documents found after Apply to All Close All and quitting look for documents dirtied while the prompt was up once the first ones are answered. Apply to All only covers the documents it was given, so the stored answer is cleared when that second list is asked about. --- crates/ui-egui/src/discard_ui.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index bf9b0714a7a..9f1e128012d 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -186,6 +186,8 @@ fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) { show_tab(app, rest.first().copied()); if let Some(p) = app.discard.as_mut() { p.docs = rest; + // Apply to All covered the documents asked about; these are asked about afresh. + (p.apply_all, p.auto, p.auto_answered) = (false, None, None); } return; } @@ -835,6 +837,25 @@ mod tests { assert_eq!(docs_left(&h), Some(2), "both documents are still waiting for an answer"); } + /// Apply to All answers for the documents the prompt opened with, not for ones dirtied since. + #[test] + fn a_document_dirtied_after_apply_to_all_is_asked_about() { + let mut app = app_with_docs(3); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let late = doc_id(h.state(), 2); + make_dirty(h.state_mut(), 2); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto) = (true, Some(Answer::Discard)); + } + h.run_steps(8); + let prompt = h.state().discard.as_ref().unwrap(); + assert_eq!(prompt.docs, vec![late], "the two unsaved documents were discarded, the late one is asked about"); + assert!(prompt.auto.is_none() && !prompt.apply_all); + assert_eq!(h.state().session.documents().len(), 1); + } + #[test] fn control_clients_can_answer_for_all() { let mut app = app_with_docs(3); From d9f97862afac2b16e50e8d2200f331b57834c62e Mon Sep 17 00:00:00 2001 From: devstivi <340315248+devstivi@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:30:40 +0700 Subject: [PATCH 05/30] Let a control client's answer replace a stale Apply to All A save that fails at once leaves the automatic answer in place until the prompt is drawn again. A control client answering in between now clears it, so the next document is asked about instead of taking the old answer. --- crates/ui-egui/src/discard_ui.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index 9f1e128012d..f3aa86cfa42 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -460,6 +460,10 @@ pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str return Err(format!("unknown choice `{other}`: {} or {last}", rest.join(", "))); } }; + // The client's answer replaces one Apply to All left behind (a save that failed at once). + if let Some(p) = app.discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (false, None, None); + } if all { apply_to_rest(app, doc, answer); } @@ -872,6 +876,26 @@ mod tests { assert!(h.state().session.documents().is_empty()); } + /// A client answering one document isn't overruled by an Apply to All whose save just failed. + #[test] + fn a_control_answer_clears_a_stale_apply_to_all() { + let mut app = app_with_docs(3); + for i in 0..3 { + make_dirty(&mut app, i); + } + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let (first, last) = (doc_id(h.state(), 0), doc_id(h.state(), 2)); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (true, Some(Answer::Discard), Some(first)); + } + let ctx = h.ctx.clone(); + answer_control(h.state_mut(), &ctx, "dontSave").unwrap(); + h.run_steps(8); + let prompt = h.state().discard.as_ref().unwrap(); + assert_eq!(prompt.docs.len(), 2, "only the answered document was closed"); + assert!(prompt.docs.contains(&last) && prompt.auto.is_none()); + } + #[test] fn the_all_answers_need_more_than_one_document_left() { let mut app = app_with_docs(1); From 20583b38efef27da5f9afaffa170c01b13949e0a Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Tue, 27 Oct 2026 19:56:01 +0800 Subject: [PATCH 06/30] fix: dismiss context menu without triggering tool action on outside click When a canvas tool menu (Zoom/Hand view menu, selection menu, etc.) is open and the user clicks outside it to dismiss it, that click should not also trigger the underlying tool action (e.g., zoom step). This matches Photoshop behavior where the dismissal click is consumed. Fixes #9832 --- crates/ui-egui/src/canvas.rs | 135 +++++++++++++++++++++++++---------- 1 file changed, 96 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 75ecf186f23..677193fa3d5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1157,48 +1157,105 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: && let Some(p) = response.interact_pointer_pos() { let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; - let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); - let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { - ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) + if let Some(menu) = &app.ui.canvas_tool_menu { + // If a canvas tool menu is open and this click is outside it, the click will + // dismiss the menu and should not also trigger a tool action (Photoshop behavior). + let menu_rect = egui::Rect::from_min_size( + egui::pos2(menu.pos[0], menu.pos[1]), + egui::vec2(200.0, 200.0), // conservative height estimate + ); + if !menu_rect.contains(p) { + // Click is outside the open menu - it will dismiss the menu, don't trigger tool action. + } else { + let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); + let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { + ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) + } else { + click_mods + }; + let d = xf.to_doc(p); + match tool { + Tool::Zoom if !transform_owns_pointer => { + let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); + let center = app.session.prefs().tools.zoom_clicked_point_to_center; + let doc_anchor = xf.to_doc(p); + let screen_anchor = p; + zoom_about(&mut view, &xf, p, nz, center, ppp); + view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_view.zoom); + view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); + } + // A click with the (temporary) Hand does nothing, never the tool underneath. + Tool::Hand | Tool::RotateView => {} + // Double-clicking closes the polygonal lasso: the first click placed the last + // vertex (or already closed it), so the second never starts a new polygon. egui + // reports it as a triple click when a vertex went down shortly before. + Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), + // The same for the Magnetic Lasso: along the edges, or straight with ⌥. + Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), + // The first click placed (or grabbed) the point; the second toggles it. + Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), + // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. + Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { + if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { + app.ui.status = e; + } + } + _ => { + if tool == Tool::Move && app.ui.transform.is_none() { + begin_transform_controls_at(app, &ctx, &xf, p); + } + // If this tool was not handled on pointer-down, fall back to a + // click-sized gesture while preserving pen pressure (mouse stays at 1). + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); + } + } + } } else { - click_mods - }; - let d = xf.to_doc(p); - match tool { - Tool::Zoom if !transform_owns_pointer => { - let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); - let center = app.session.prefs().tools.zoom_clicked_point_to_center; - let doc_anchor = xf.to_doc(p); - let screen_anchor = p; - zoom_about(&mut view, &xf, p, nz, center, ppp); - view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_view.zoom); - view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); - } - // A click with the (temporary) Hand does nothing, never the tool underneath. - Tool::Hand | Tool::RotateView => {} - // Double-clicking closes the polygonal lasso: the first click placed the last - // vertex (or already closed it), so the second never starts a new polygon. egui - // reports it as a triple click when a vertex went down shortly before. - Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), - // The same for the Magnetic Lasso: along the edges, or straight with ⌥. - Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), - // The first click placed (or grabbed) the point; the second toggles it. - Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), - // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. - Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { - if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { - app.ui.status = e; + let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); + let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { + ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) + } else { + click_mods + }; + let d = xf.to_doc(p); + match tool { + Tool::Zoom if !transform_owns_pointer => { + let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); + let center = app.session.prefs().tools.zoom_clicked_point_to_center; + let doc_anchor = xf.to_doc(p); + let screen_anchor = p; + zoom_about(&mut view, &xf, p, nz, center, ppp); + view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_view.zoom); + view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); } - } - _ => { - if tool == Tool::Move && app.ui.transform.is_none() { - begin_transform_controls_at(app, &ctx, &xf, p); + // A click with the (temporary) Hand does nothing, never the tool underneath. + Tool::Hand | Tool::RotateView => {} + // Double-clicking closes the polygonal lasso: the first click placed the last + // vertex (or already closed it), so the second never starts a new polygon. egui + // reports it as a triple click when a vertex went down shortly before. + Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), + // The same for the Magnetic Lasso: along the edges, or straight with ⌥. + Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), + // The first click placed (or grabbed) the point; the second toggles it. + Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), + // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. + Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { + if let Err(e) = crate::menus::invoke(app, &ctx, "edit.preferences.guidesGridAndSlices", json!({})) { + app.ui.status = e; + } + } + _ => { + if tool == Tool::Move && app.ui.transform.is_none() { + begin_transform_controls_at(app, &ctx, &xf, p); + } + // If this tool was not handled on pointer-down, fall back to a + // click-sized gesture while preserving pen pressure (mouse stays at 1). + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); } - // If this tool was not handled on pointer-down, fall back to a - // click-sized gesture while preserving pen pressure (mouse stays at 1). - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); - tap_at_peak_pressure(app); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); } } } From 712b0fb892550fad8fde5d796d32158ae506dcc9 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Tue, 27 Oct 2026 20:16:01 +0800 Subject: [PATCH 07/30] fix: dismiss context menu without triggering tool action on outside click When a canvas tool menu (Zoom/Hand view menu, selection menu, etc.) is open and the user clicks outside it to dismiss it, that click should not also trigger the underlying tool action (e.g., zoom step). This matches Photoshop behavior where the dismissal click is consumed. Fixes #9832 **Changes:** - Added flag to to track when an outside press dismisses the menu - Set flag in when returns true - Added function using actual rendered menu rect from egui's area memory - In click handler: check dismissed flag first (consume release click), then use accurate menu rect for hit-test **Testing:** - All existing tests pass (canvas_tool_menu, zoom_tool, etc.): 60 passed - clippy passes - cargo xtask layers passes - cargo xtask wasm passes - panic_hunt test passes --- crates/ui-egui/src/canvas.rs | 13 +++++++------ crates/ui-egui/src/canvas/canvas_tool_menu.rs | 12 ++++++++++++ crates/ui-egui/src/state.rs | 5 +++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 677193fa3d5..63d7b434f10 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1156,17 +1156,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if buttons.clicked && let Some(p) = response.interact_pointer_pos() { - let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; - if let Some(menu) = &app.ui.canvas_tool_menu { + // If an outside press dismissed the canvas tool menu, consume this release click + // so it doesn't also trigger a tool action (Photoshop behavior). + if app.ui.canvas_tool_menu_dismissed { + app.ui.canvas_tool_menu_dismissed = false; + } else if let Some(menu_rect) = crate::canvas_tool_menu::menu_rect_if_open(app, &ctx) { // If a canvas tool menu is open and this click is outside it, the click will // dismiss the menu and should not also trigger a tool action (Photoshop behavior). - let menu_rect = egui::Rect::from_min_size( - egui::pos2(menu.pos[0], menu.pos[1]), - egui::vec2(200.0, 200.0), // conservative height estimate - ); if !menu_rect.contains(p) { // Click is outside the open menu - it will dismiss the menu, don't trigger tool action. } else { + let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) @@ -1213,6 +1213,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } } } else { + let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index dd9b635e640..21662025908 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1173,8 +1173,20 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { choose(app, ctx, &command); } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { app.ui.canvas_tool_menu = None; + app.ui.canvas_tool_menu_dismissed = true; } } +/// Returns the menu rect if the canvas tool menu is currently open, for hit-testing +/// outside-click dismissal in the click handler. +pub fn menu_rect_if_open(app: &PhotocraftApp, ctx: &Context) -> Option { + let menu = app.ui.canvas_tool_menu.as_ref()?; + let id = menu_id(); + let screen = ctx.content_rect(); + let size = ctx.memory(|m| m.area_rect(id)).map_or(egui::vec2(210.0, 140.0), |r| r.size()); + let pos = egui::pos2(menu.pos[0].min(screen.right() - size.x).max(screen.left()), menu.pos[1].min(screen.bottom() - size.y).max(screen.top())); + Some(egui::Rect::from_min_size(pos, size)) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ef587063cb0..1a6452cbb04 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -287,6 +287,10 @@ pub struct UiState { /// Selection-tool context menu opened by a plain canvas right-click. #[serde(default)] pub canvas_tool_menu: Option, + /// An outside press dismissed the canvas tool menu; suppress the corresponding + /// release click from triggering a tool action. + #[serde(default)] + pub canvas_tool_menu_dismissed: bool, /// The guide a Move-tool click selected (`guide_select`): drawn blue, Delete removes it. #[serde(default)] pub selected_guide: Option, @@ -507,6 +511,7 @@ impl Default for UiState { brush_picker_size: None, layer_menu: None, canvas_tool_menu: None, + canvas_tool_menu_dismissed: false, selected_guide: None, brush_tool: Tool::Brush, tool_brushes: Vec::new(), From 6cb37eea57241ce7fbfb6042b84f84b907e9fa81 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Tue, 27 Oct 2026 22:34:21 +0800 Subject: [PATCH 08/30] fix: block tool input on outside press and clear dismissal flag on release Addresses CodeRabbit review comments on PR #9841: 1. Clear flag on pointer release (primary or secondary), even when release occurs outside canvas and produces no event. This prevents the next ordinary canvas click from being incorrectly suppressed. 2. Block tool input (Down, Move, Up events) on outside press before tool handlers run, not just on click. The press that dismisses the menu is now detected early via and its gesture is fully consumed (no stroke starts, no drag moves, no click action). Files changed: - crates/ui-egui/src/canvas.rs: Added pointer release flag clearing, added detection, and gated all tool_event calls with this flag. --- crates/ui-egui/src/canvas.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 63d7b434f10..dd2ddffbf4e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -888,6 +888,25 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); + + // Clear the menu dismissal flag on the corresponding pointer release, even when the + // release occurs outside the canvas and produces no `buttons.clicked` event. + // This prevents the next ordinary canvas click from being incorrectly suppressed. + if app.ui.canvas_tool_menu_dismissed + && (ui.input(|i| i.pointer.primary_released()) || ui.input(|i| i.pointer.secondary_released())) + { + app.ui.canvas_tool_menu_dismissed = false; + } + + // Determine if the current press (if any) is outside an open canvas tool menu. + // If so, we should suppress tool input for this gesture (press, drag, click). + // This prevents the press from starting a stroke or other tool action that the + // click handler cannot undo. + let menu_dismiss_press = crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| { + response.interact_pointer_pos().is_some_and(|p| !r.contains(p)) + || ui.input(|i| i.pointer.press_origin()).is_some_and(|p| rect.contains(p) && !r.contains(p)) + }); + // The Crop tool's frame is edited from the press (before egui's drag threshold), so the // pixels past the canvas show at once, as in Photoshop. if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { @@ -899,6 +918,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee | Tool::ObjectSelection); let tool_press = egui::Id::unique(("tool-pointer-press-modifiers", idx)); if capture_press + && !menu_dismiss_press && let Some((p, press_mods)) = ui.input(|i| { i.events.iter().find_map(|e| match e { egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers } if rect.contains(*pos) => { @@ -1026,6 +1046,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let right_down = ui.input(|i| i.pointer.secondary_down()) || physical_right; if strokes_live(tool) && !right_down + && !menu_dismiss_press && app.drag.is_none() && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) @@ -1044,6 +1065,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: buttons.started = false; } if buttons.started + && !menu_dismiss_press && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) { if tool == Tool::Move && app.ui.transform.is_none() { @@ -1057,7 +1079,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // recognises a drag (past its click distance): otherwise the first few points are lost // and the stroke starts with a straight segment and no pressure ramp. let press_stroke_moving = press_stroke && app.drag.is_some(); - if buttons.dragged || buttons.stopped || press_stroke_moving { + if !menu_dismiss_press && (buttons.dragged || buttons.stopped || press_stroke_moving) { // Feed every pointer move the OS delivered this frame, not just the latest position, so // a fast stroke is sampled densely and renders as a smooth curve instead of a coarse // polyline. egui-winit pushes one `PointerMoved` per `CursorMoved`, and they accumulate @@ -1115,7 +1137,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: feed_live_stroke(app); crate::magnetic_lasso_ui::flush(app); } - if buttons.stopped { + if buttons.stopped && !menu_dismiss_press { // The live painting press already created the stroke and this release commits it. // egui may also report clicked on the same release; replaying that click paints a // second full-pressure dab over the real (possibly light-pressure) pen dab. @@ -1140,7 +1162,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } // A stroke started on the press ends with the release, whether egui saw a drag, a click, // or neither (a long press that never moved). - if press_stroke && !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { + if press_stroke && !buttons.stopped && !menu_dismiss_press && ui.input(|i| i.pointer.primary_released()) { buttons.clicked = false; let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); if let Some(d) = p @@ -1261,7 +1283,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } } // Magnetic Lasso: between clicks the border follows the pointer with the button up. - if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { + if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && !menu_dismiss_press && response.hovered() { let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); app.defer_live_stroke = true; for p in moves.into_iter().filter(|p| rect.contains(*p)) { From 54515f94b34786dc4c3d04a57cb8d66f838ea59f Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Tue, 27 Oct 2026 11:50:31 -0400 Subject: [PATCH 09/30] fix(ui-egui): the rasterize prompt no longer replays the click that opened it (#8806) Pressing a pixel tool on a type, shape, Smart Object or fill layer opens the "Rasterize?" prompt. On OK, confirm() ran layer.rasterize.* and then replayed the stored press as ToolEvent::Down/Up, so the brush, eraser or bucket acted on a click the user had made only to get past the dialog. Photoshop 2026 converts the layer and does nothing else; the next click paints. confirm() now only rasterizes and returns {"rasterized"}. The prompt still records the tool and point in its fields. The control-protocol doc and the TOOL-213-5 scorecard row describe the new behaviour. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/dialogs/rasterize_prompt.rs | 29 +++++-------------- .../src/dialogs/rasterize_prompt/tests.rs | 18 +++++++----- docs/control-protocol.md | 2 +- docs/scorecard.md | 2 +- scorecard/tools.toml | 4 +-- 5 files changed, 23 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/dialogs/rasterize_prompt.rs b/crates/ui-egui/src/dialogs/rasterize_prompt.rs index a6ac9ace68f..5fa13295bf7 100644 --- a/crates/ui-egui/src/dialogs/rasterize_prompt.rs +++ b/crates/ui-egui/src/dialogs/rasterize_prompt.rs @@ -4,9 +4,9 @@ //! with a status-bar message. //! //! The prompt is an ordinary dialog in the UI state (`ui.inspect` shows it, `ui.dialog.confirm` -//! and `ui.dialog.cancel` answer it). OK runs the matching `layer.rasterize.*` command, then paints -//! where the click was, so rasterizing and painting are two history states, as in Photoshop. -//! Cancel does nothing. +//! and `ui.dialog.cancel` answer it). OK runs the matching `layer.rasterize.*` command and nothing +//! else: the click that opened the prompt is not replayed, as in Photoshop (#8806), so the next +//! click paints. Cancel does nothing. //! //! A filter on a type layer asks the same question (#4303), with Photoshop's Convert to Smart //! Object / Rasterize / Cancel: the layer is converted or rasterized, then the filter is chosen @@ -16,7 +16,6 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; -use crate::canvas::ToolEvent; use crate::state::{DialogKind, Tool}; const MARK: &str = "__rasterize"; @@ -112,7 +111,7 @@ pub fn intercept(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64, pressure: true } -/// Open the prompt for `layer`; OK rasterizes it, then `tool` paints at `at` (x, y, pressure). +/// Open the prompt for `layer`; OK rasterizes it. `tool` and `at` (x, y, pressure) only record the press that opened it. pub fn open(app: &mut PhotocraftApp, kind: Kind, layer: photocraft_doc::LayerId, tool: Tool, at: [f64; 3]) -> u64 { let mut f = Map::new(); f.insert(MARK.into(), json!(kind.key())); @@ -198,7 +197,7 @@ pub fn body(ui: &mut egui::Ui, f: &Map) { }); } -/// OK: rasterize, then paint at the click (two history states). +/// OK: rasterize the layer. The click that opened the prompt does not paint. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { let kind = f.get(MARK).and_then(Value::as_str).and_then(Kind::from_key).ok_or("not a rasterize prompt")?; let layer = f.get("layer").and_then(Value::as_u64).ok_or("the prompt has no layer")?; @@ -206,21 +205,9 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result = f.get("at").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); - let (Some(tool), Some(&x), Some(&y)) = (tool, at.first(), at.get(1)) else { - return Ok(json!({ "rasterized": r, "painted": false })); - }; - let pressure = at.get(2).copied().unwrap_or(1.0) as f32; - // The same tool, layer and point as when the prompt opened. - app.ui.tool = tool; - let before = app.session.active().map(|st| st.history.past_len()); - if app.session.active().and_then(|st| st.active_layer) == Some(photocraft_doc::LayerId(layer)) && x.is_finite() && y.is_finite() { - crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: pressure.clamp(0.0, 1.0) }, egui::Modifiers::NONE); - crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - } - let painted = app.session.active().map(|st| st.history.past_len()) != before; - Ok(json!({ "rasterized": r, "painted": painted })) + // The press that opened the prompt is not replayed: Photoshop only converts the layer, the + // next click paints (#8806). + Ok(json!({ "rasterized": r })) } /// The filter prompt's answer: convert or rasterize the layer, then queue the filter for diff --git a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs index 9e6a10583c4..e6ce6cfc913 100644 --- a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs @@ -3,7 +3,7 @@ use photocraft_doc::LayerContent; use serde_json::json; use super::*; -use crate::canvas::tool_event; +use crate::canvas::{ToolEvent, tool_event}; /// A document whose active layer is a `kind` layer over a white Background. fn app_with(kind: Kind) -> PhotocraftApp { @@ -47,7 +47,7 @@ fn prompt(app: &PhotocraftApp) -> Option<&crate::state::Dialog> { } #[test] -fn ok_rasterizes_then_paints_as_two_history_states() { +fn ok_rasterizes_without_replaying_the_click() { for kind in Kind::ALL { for tool in [Tool::Brush, Tool::Pencil] { let mut app = app_with(kind); @@ -59,12 +59,16 @@ fn ok_rasterizes_then_paints_as_two_history_states() { assert_eq!(past(&app), before, "nothing happens until the answer"); let id = d.id; let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["painted"], json!(true), "{kind:?}/{tool:?}"); + assert!(r.get("rasterized").is_some()); assert_eq!(active_content(&app), "Pixel"); - assert_eq!(past(&app), before + 2, "{kind:?}/{tool:?}: rasterize, then paint"); + assert_eq!(past(&app), before + 1, "{kind:?}/{tool:?}: rasterize only, the held click is not replayed"); + // The held click left no paint; the next click paints. let st = app.session.active().unwrap(); let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(30, 20); - assert!(c[2] > 0.99 && c[0] < 0.01, "{kind:?}/{tool:?}: painted blue at the click: {c:?}"); + assert!(c[2] < 0.5 || c[0] > 0.5, "{kind:?}/{tool:?}: nothing painted by the held click: {c:?}"); + click(&mut app, 30.0, 20.0); + assert!(prompt(&app).is_none()); + assert_eq!(past(&app), before + 2, "{kind:?}/{tool:?}: the next click paints"); // One undo takes the paint back; the layer stays rasterized. app.session.undo(); assert_eq!(active_content(&app), "Pixel"); @@ -141,13 +145,13 @@ fn a_stale_or_bad_prompt_fails_gracefully() { let id = app.ui.open_dialog(crate::state::DialogKind::Command, f.as_object().unwrap().clone()); assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{f}"); } - // A bad tool or point rasterizes without painting. + // A bad tool or point still just rasterizes. let mut app = app_with(Kind::Fill); let layer = app.session.active().unwrap().active_layer.unwrap(); let id = open(&mut app, Kind::Fill, layer, Tool::Brush, [f64::NAN, 1.0, 1.0]); app.ui.dialog_mut(id).unwrap().fields.insert("tool".into(), json!("no such tool")); let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["painted"], json!(false)); + assert!(r.get("rasterized").is_some()); assert_eq!(active_content(&app), "Pixel"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d291f45d3b1..79bde1917e1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -74,7 +74,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized. - - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. + - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command only (`{"rasterized"}`; the click that opened the prompt is not replayed, as in Photoshop); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. diff --git a/docs/scorecard.md b/docs/scorecard.md index d025e679443..bee595e6537 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -143,7 +143,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-213-2 | Mixer Brush tool on the toolbar | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::MixerBrush in the Brush (B) flyout; Wet/Load/Mix/Flow/Sample All Layers options, the Current Brush Load swatch with Load Brush and Clean Brush (brush.mixer.load, brush.mixer.clean) and the automatic Load and Clean toggles; command/control dispatch and selection-clipping tests | | TOOL-213-3 | Patch tool with a live preview of the patched area | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.patch (retouch_cmds/patch.rs, source/destination) + Tool::Patch (J group: lasso, then drag the selection); the drag shows the heal live (patch_preview.rs, coarse colour fit: 1000x1000 in 52 ms) | | TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). cam_preview.rs: once the pointer or the box rests, the result shows (a cancellable background job on a smaller sampling window, #4385); a selection over 256x256 shows a coarse result solved scaled down first, then the command's exact result as a second job (#6680; 24 MP document, release: 600x400 coarse 0.26 s then exact 0.8 s, 1500x1000 0.38 s then 4.1 s, 3000x2000 0.69 s then 9.4 s; was no preview above 256x256). Tests: content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths, content_aware_move_coarse_preview_handles_transform_extend_and_limits, a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit, a_large_selection_shows_a_coarse_result_then_the_exact_one | -| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm | +| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize; OK converts it and the next click paints | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes only, the click that opened the prompt is not replayed (as in Photoshop, #8806), Cancel does nothing; drivable via ui.dialog.confirm | | TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace | | TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Mixer Brush, Eraser, Color Replacement, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040), Pattern Stamp (aligned and Impressionist) and Background Eraser (#3754); the release commits the live stroke's pixels (P32) or, for the retouch tools, the same pixels the live stroke showed (tested equal at 8 and 16 bits). Spot Healing Brush shows the area it heals as a dark overlay and heals on release, as Photoshop does. Mixer Brush uses its incremental transaction and commits the displayed result (#3627) | | TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298) | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 9311cc18696..dee4d5cef60 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -35,10 +35,10 @@ note = "paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, [[item]] id = "TOOL-213-5" -target = "Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke" +target = "Painting a type/shape/smart/fill layer offers to rasterize; OK converts it and the next click paints" status = "done" issue = 213 -note = "rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm" +note = "rasterize_prompt.rs: OK rasterizes only, the click that opened the prompt is not replayed (as in Photoshop, #8806), Cancel does nothing; drivable via ui.dialog.confirm" [[item]] id = "TOOL-213-6" From 87c1d501779c5df85b2e3540d264942edbfe772b Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Tue, 27 Oct 2026 12:34:05 -0400 Subject: [PATCH 10/30] docs(ui-egui): document the rasterize prompt tests (#8806) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs index e6ce6cfc913..b270f31ec15 100644 --- a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs @@ -46,6 +46,8 @@ fn prompt(app: &PhotocraftApp) -> Option<&crate::state::Dialog> { app.ui.dialogs.iter().find(|d| owns(&d.fields)) } +/// #8806: OK on the prompt rasterizes and adds one history state; the held click is not +/// replayed, and the next click paints with no prompt. #[test] fn ok_rasterizes_without_replaying_the_click() { for kind in Kind::ALL { @@ -131,6 +133,8 @@ fn only_pixel_painting_asks() { assert!(app.session.active().unwrap().doc.layers.iter().any(|l| matches!(l.content, LayerContent::Text(_)))); } +/// A prompt with missing, stale or malformed fields returns an error instead of panicking; a +/// bad tool or point still just rasterizes. #[test] fn a_stale_or_bad_prompt_fails_gracefully() { let mut app = app_with(Kind::Type); From 78b1dfe448a820cc8770252051e3c6c868ccc8d9 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Wed, 28 Oct 2026 12:02:46 +0800 Subject: [PATCH 11/30] fix: consume the dismissal gesture through its release and block the zoom hold Addresses the two remaining CodeRabbit findings on PR #9841: - The dismissal flag is cleared below the click handling, so a later-frame release over the canvas is consumed by the flag check first (clearing it before let that release zoom). canvas_tool_menu::show does not arm the flag when the frame already contains the release, so a fast same-frame click cannot eat the next ordinary click. - The blocked gesture now persists in canvas_tool_menu_dismissed until its release instead of being re-derived from the open menu each frame, so a held dismissal press stays blocked after the menu closes. Navigation is blocked too: the animated zoom hold cannot arm on it, and zoom drags, Rotate View and other button-driven gestures are starved. Regression tests (fail on the previous commit, pass now): - dismissing_the_view_menu_consumes_the_whole_gesture - a_held_menu_dismissal_press_never_arms_the_zoom_hold --- crates/ui-egui/src/canvas.rs | 57 ++++++++---- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 6 +- .../src/canvas/canvas_tool_menu/tests.rs | 93 +++++++++++++++++++ 3 files changed, 136 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dd2ddffbf4e..7a5d16dbe7d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -889,27 +889,32 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::paint_mouse::sync_tool_brush(app); let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); - // Clear the menu dismissal flag on the corresponding pointer release, even when the - // release occurs outside the canvas and produces no `buttons.clicked` event. - // This prevents the next ordinary canvas click from being incorrectly suppressed. - if app.ui.canvas_tool_menu_dismissed - && (ui.input(|i| i.pointer.primary_released()) || ui.input(|i| i.pointer.secondary_released())) - { - app.ui.canvas_tool_menu_dismissed = false; + // A press outside an open canvas tool menu dismisses it (`canvas_tool_menu::show`, after + // this input pass) and the whole gesture is consumed until its release, as in Photoshop: + // no tool press, stroke, drag or zoom step. The menu closes mid-frame (after this input + // pass), so the open-menu hit test covers the dismissal frame and the flag persists the + // block for the frames after it, until the release clear below the click handling. + let menu_dismiss_press = app.ui.canvas_tool_menu_dismissed + || crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| { + ui.input(|i| i.pointer.press_origin()).is_some_and(|p| !r.contains(p)) + }); + if menu_dismiss_press { + // Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View): + // starve them. The release click stays armed, so the click handling below consumes + // it through the flag. + buttons.started = false; + buttons.dragged = false; + buttons.stopped = false; } - // Determine if the current press (if any) is outside an open canvas tool menu. - // If so, we should suppress tool input for this gesture (press, drag, click). - // This prevents the press from starting a stroke or other tool action that the - // click handler cannot undo. - let menu_dismiss_press = crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| { - response.interact_pointer_pos().is_some_and(|p| !r.contains(p)) - || ui.input(|i| i.pointer.press_origin()).is_some_and(|p| rect.contains(p) && !r.contains(p)) - }); - // The Crop tool's frame is edited from the press (before egui's drag threshold), so the // pixels past the canvas show at once, as in Photoshop. - if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { + if tool == Tool::Crop + && !menu_dismiss_press + && response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_down()) + && crate::crop_ui::press(app) + { ctx.request_repaint(); } // Capture intent at the press, before egui's drag threshold or click replay on release: @@ -1018,10 +1023,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, - // it owns the press: no scrub, and its release is no click step. + // it owns the press: no scrub, and its release is no click step. A menu-dismissal press + // must not arm it: holding the dismissal click would zoom (CodeRabbit, #9841). if tool == Tool::Zoom && !transform_owns_pointer { let out = zoom_out(ui.input(|i| i.modifiers.alt)); - let on_canvas = !under_dialog && !over_compass && response.is_pointer_button_down_on(); + let on_canvas = !menu_dismiss_press && !under_dialog && !over_compass && response.is_pointer_button_down_on(); let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(&ctx, &mut view, &xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); @@ -1282,6 +1288,19 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } } } + // Clear the menu-dismissal flag on the gesture's pointer release, even when the release + // occurs outside the canvas and produces no `buttons.clicked` event. It sits below (not + // above) the click handling, so a release over the canvas in a later frame is first + // consumed by the flag check there: clearing before it would let that release zoom + // (CodeRabbit, #9841). The all-buttons-up check also covers a release that landed in a + // frame this canvas didn't render. + if app.ui.canvas_tool_menu_dismissed + && (ui.input(|i| i.pointer.primary_released()) + || ui.input(|i| i.pointer.secondary_released()) + || !ui.input(|i| i.pointer.any_down())) + { + app.ui.canvas_tool_menu_dismissed = false; + } // Magnetic Lasso: between clicks the border follows the pointer with the button up. if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && !menu_dismiss_press && response.hovered() { let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 21662025908..292cfb3bb4d 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1173,7 +1173,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { choose(app, ctx, &command); } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { app.ui.canvas_tool_menu = None; - app.ui.canvas_tool_menu_dismissed = true; + // A fast click can press and release in one frame: the canvas input above already + // suppressed its action through the open-menu hit test, and the deferred release clear + // (in `canvas_view`, below the click handling) would never fire after this frame. Don't + // arm the flag then, or it would eat the next ordinary click (CodeRabbit, #9841). + app.ui.canvas_tool_menu_dismissed = !ctx.input(|i| i.pointer.any_released()); } } diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index eb9147a7a58..1a1679e6c97 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -546,6 +546,99 @@ fn zoom_and_hand_right_click_opens_the_view_menu() { } } +/// A zoom harness with a fixed camera: zoom 1.0 centred on the 400×300 document. `animated` is +/// Preferences › General › Animated Zoom; each step is 0.1 s of egui time, so a hold can pass +/// `zoom_hold::DELAY` within a few steps. +fn zoom_harness(animated: bool) -> Harness<'static, PhotocraftApp> { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": animated, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(0.1).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + h.run_steps(2); + h +} + +/// The menu opens at `[300, 100]` (doc points); this press lands 250 doc px to its left: outside +/// the 200 px-wide menu, on the canvas. +fn dismissal_point(h: &Harness<'static, PhotocraftApp>) -> Pos2 { + screen_of(h.state(), [50.0, 250.0]) +} + +/// #9832: a left press outside the open view menu dismisses it, and the whole gesture is +/// consumed — the press, the held press, and the release never zoom, and the next ordinary +/// click zooms again. +#[test] +fn dismissing_the_view_menu_consumes_the_whole_gesture() { + let mut h = zoom_harness(false); + let zoom = h.state().ui.views[0].zoom; + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + // The dismissal press: the menu goes, the zoom does not. + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal press does not zoom"); + // Holding it (a long press releases as a click) still does nothing… + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "a held dismissal press does not zoom"); + // …and the release over the canvas is consumed: no zoom step. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal release does not zoom"); + // The next ordinary click zooms again: the gesture flag did not stick. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, crate::zoom_levels::step(zoom, 1, h.state().ui.views[0].doc_size), "the next ordinary click zooms"); +} + +/// #9832: a menu-dismissal press held past `zoom_hold::DELAY` must not arm the animated zoom +/// hold: holding the dismissal click would otherwise zoom continuously. +#[test] +fn a_held_menu_dismissal_press_never_arms_the_zoom_hold() { + let mut h = zoom_harness(true); + let zoom = h.state().ui.views[0].zoom; + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + // 0.8 s held still, well past the 0.3 s hold delay: every frame stays at the start zoom. + for i in 0..8 { + h.run_steps(1); + assert_eq!(h.state().ui.views[0].zoom, zoom, "held dismissal press frame {i} must not zoom"); + } + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal release does not zoom either"); +} + #[test] fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { let mut app = zoom_app(400, 300); From 2aa62a81d28d30ded03e7b6af00a1a8c719c2e42 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Wed, 28 Oct 2026 12:39:39 +0800 Subject: [PATCH 12/30] fix: gate the Hand and flick pans on the menu-dismissal press too The flick-pan frame and the Hand pan read response.dragged() directly, before menu_dismiss_press is computed, and live in the hand_pan branch where the zeroed buttons never arrive: with the menu dismissed and the dismissing button still down, holding Space (or the selected Hand tool) and dragging panned the view. The gate is now computed up front and guards both pan sites (CodeRabbit, #9841). Regression test a_held_menu_dismissal_press_cannot_pan_the_view fails on the previous commit and passes now. --- crates/ui-egui/src/canvas.rs | 24 +++++----- .../src/canvas/canvas_tool_menu/tests.rs | 44 +++++++++++++++++++ 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7a5d16dbe7d..1c6ae43be8e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -839,10 +839,21 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // box is only drawn and driven on the primary canvas. let transform_owns_pointer = primary && app.ui.transform.is_some() && temporary.is_none() && !middle; let hand_pan = tool == Tool::Hand && !transform_owns_pointer; + // A press outside an open canvas tool menu dismisses it (`canvas_tool_menu::show`, after this + // input pass) and the whole gesture is consumed until its release, as in Photoshop: no tool + // press, stroke, drag, pan or zoom step. The menu closes mid-frame (after this input pass), so + // the open-menu hit test covers the dismissal frame, and the flag persists the block for the + // frames after it, until the release clear below the click handling. It gates the Hand and + // flick pans below too: they read `response.dragged()` directly and never see `buttons` + // (CodeRabbit, #9841). + let menu_dismiss_press = app.ui.canvas_tool_menu_dismissed + || crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| { + ui.input(|i| i.pointer.press_origin()).is_some_and(|p| !r.contains(p)) + }); // Preferences › Tools › Enable Flick Panning: a Hand drag let go while moving glides on. let flick_id = egui::Id::unique(("pc-flick-pan", idx, primary, ctx.viewport_id())); let flick_on = app.session.prefs().tools.enable_flick_panning; - if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_pan && response.dragged() && !stroke_dismissal, response.drag_delta(), flick_on) { + if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_pan && response.dragged() && !stroke_dismissal && !menu_dismiss_press, response.drag_delta(), flick_on) { let d = xf.unmap_vec(d) / (view.zoom / ppp); if d.is_finite() { view.zoom_animating = false; @@ -855,7 +866,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: ctx.data_mut(|m| m.get_temp_mut_or_default::(flick_id).stop()); } } - if hand_pan && response.dragged() && !stroke_dismissal { + if hand_pan && response.dragged() && !stroke_dismissal && !menu_dismiss_press { let d = xf.unmap_vec(response.drag_delta()) / (view.zoom / ppp); view.center[0] -= d.x; view.center[1] -= d.y; @@ -889,15 +900,6 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::paint_mouse::sync_tool_brush(app); let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool); - // A press outside an open canvas tool menu dismisses it (`canvas_tool_menu::show`, after - // this input pass) and the whole gesture is consumed until its release, as in Photoshop: - // no tool press, stroke, drag or zoom step. The menu closes mid-frame (after this input - // pass), so the open-menu hit test covers the dismissal frame and the flag persists the - // block for the frames after it, until the release clear below the click handling. - let menu_dismiss_press = app.ui.canvas_tool_menu_dismissed - || crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| { - ui.input(|i| i.pointer.press_origin()).is_some_and(|p| !r.contains(p)) - }); if menu_dismiss_press { // Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View): // starve them. The release click stays armed, so the click handling below consumes diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 1a1679e6c97..d72f3b1469e 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -639,6 +639,50 @@ fn a_held_menu_dismissal_press_never_arms_the_zoom_hold() { assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal release does not zoom either"); } +/// #9832 (CodeRabbit): while the dismissal press stays down, the temporary Hand (Space) and the +/// selected Hand must not pan either — the consumed gesture is inert until its release, and the +/// pans read `response.dragged()` directly, so they need the gate up front. +#[test] +fn a_held_menu_dismissal_press_cannot_pan_the_view() { + fn key(h: &mut Harness<'static, PhotocraftApp>, k: egui::Key, pressed: bool) { + h.event(egui::Event::Key { key: k, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + let mut h = zoom_harness(false); + let (zoom, center0) = (h.state().ui.views[0].zoom, h.state().ui.views[0].center); + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + // The dismissal press: the menu goes, and the button stays down. + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + // Hold Space: the temporary Hand arms, but dragging must not pan the view. + key(&mut h, egui::Key::Space, true); + assert_eq!(crate::input::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::input::hold_keys::Temporary::Hand), "Space arms the temporary hand"); + h.event(egui::Event::PointerMoved(far + vec2(120.0, -60.0))); + h.run_steps(2); + h.event(egui::Event::PointerMoved(far + vec2(240.0, -120.0))); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].center, center0, "a held dismissal press must not pan the view"); + assert_eq!(h.state().ui.views[0].zoom, zoom); + // Release both: an ordinary Hand drag pans again, the flag did not stick. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + key(&mut h, egui::Key::Space, false); + h.state_mut().ui.tool = Tool::Hand; + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(far + vec2(100.0, 50.0))); + h.run_steps(2); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_ne!(h.state().ui.views[0].center, center0, "an ordinary Hand drag pans the view again"); +} + #[test] fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { let mut app = zoom_app(400, 300); From abd0d76aa971019cdaea9728cca89ef167104777 Mon Sep 17 00:00:00 2001 From: ArjenS-LA Date: Mon, 2 Nov 2026 23:05:09 -0800 Subject: [PATCH 13/30] Retain Average parameter validation test adaptation after module split --- crates/engine/src/cmd/extra_cmds/tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index aa75f8e944c..0535d00ab99 100644 --- a/crates/engine/src/cmd/extra_cmds/tests.rs +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -24,7 +24,7 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() { s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; s.tools.background = [1.0, 1.0, 1.0, 1.0]; s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); - let p = match target { + let mut p = match target { "quickMask" => { s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); json!({"seed": 1}) @@ -39,6 +39,10 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() { json!({"seed": 1, "target": "mask"}) } }; + // Average has no seed parameter; only Clouds uses it. + if cmd == "filter.blur.average" { + p.as_object_mut().unwrap().remove("seed"); + } // Two levels in the target, so Equalize and Average have something to change. let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } }); s.edit("levels", |doc, active| { From a68d2a3dbfa6288d1d02c4fb6fad661ec63975a8 Mon Sep 17 00:00:00 2001 From: ebosido444-ai Date: Fri, 30 Oct 2026 19:32:09 +0300 Subject: [PATCH 14/30] fix(text): size faux bold by Photoshop's size/72 ring instead of a flat 3.6% (#9008) Faux bold grew the outline by a flat 3.6% of the font size. Photoshop thickens by about `size/72`, so a PSD's Faux Bold layer rendered 1.3-1.5x heavier than the pixels Photoshop stored in the file. That shows up as soon as the layer is clicked: it displays the PSD's own raster until edit mode re-renders it (`begin_edit` -> `type.edit` -> `refresh_at`), and the text visibly turns bolder at that moment. `faux_bold_radius(size_px)` now returns the ring in pixels, fitted to Photoshop's stored layer pixels: `size/72`, with a pixel floor that fades in below ~32 px (Photoshop's small type reads heavier than `size/72`) and a cap so a sub-pixel glyph does not grow into a blob. Measured with a temporary probe that compared each type layer's render with the PSD's own cached raster (alpha sum, no text or file content recorded) on a 4200x5940 CMYK document with five faux-bold layers, 18-60 pt at 300 dpi: layer px size ink vs Photoshop, before after 3 125 1.35x 0.87x 4 125 1.29x 0.89x 8 250 1.26x 0.93x 9 75 1.47x 0.96x 10 75 1.44x 0.96x Text without faux bold is untouched (the radius is only read for bold glyphs). Tests: `faux_bold_radius_has_a_pixel_floor_that_fades_for_tiny_type` (the fitted curve), `faux_bold_at_display_sizes_grows_the_outline_by_size_over_72` (the weight at 120 px, 1.35x over plain; the flat ring measured 1.95x there), and the weight pinned in `faux_bold_keeps_antialiased_edges_at_small_sizes`, which was adjusted to the new ring. (faux bold does not widen advances) is still open and not touched here. --- crates/text/src/render.rs | 17 +++++++----- crates/text/src/tests.rs | 54 ++++++++++++++++++++++++++++++++++----- 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index ffc595aab86..db193c03e6e 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -17,10 +17,15 @@ use rayon::prelude::*; /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; -/// How far faux bold grows the outline on every side, as a fraction of the font size -/// ([`crate::embolden`]): stems get twice this heavier, close to the weight of the earlier -/// faux bold, which stamped the glyph at offsets of this radius. -pub const FAUX_BOLD_RADIUS: f32 = 0.036; +/// How far faux bold grows the outline on every side, in pixels (`crate::embolden`): stems get +/// twice this heavier. Photoshop thickens by about `size/72`; the flat 3.6% of the size used +/// before overshot its ink by 1.3–1.5× from 50 px up. So the ring follows the size, with a pixel +/// floor that fades in below ~32 px (Photoshop's small type reads heavier than `size/72`) and a +/// cap so a sub-pixel glyph does not grow into a blob. +pub fn faux_bold_radius(size_px: f32) -> f32 { + (size_px / 72.0).max((size_px / 40.0).min(0.45)) +} + /// Largest raster we produce (pixels), as a guard against absurd sizes. const MAX_PIXELS: u64 = 256 * 1024 * 1024; /// Cumulative coverage-pixel work budget across the colour passes of one render. @@ -185,7 +190,7 @@ pub(crate) fn visible_color_passes(layout: &TextLayout, warp: Option<&Warp>) -> /// Draws the glyphs and decorations of `layout` in `only` (or all of them when it is `None`) into `sink`, through `transform` (text space → sink space), bending /// the outlines with `warp` first (in text space). Faux bold glyphs are drawn from their outline -/// thickened by [`FAUX_BOLD_RADIUS`] ([`crate::embolden`]). +/// thickened by [`faux_bold_radius`] ([`crate::embolden`]). fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: Option<&Pass>, warp: Option<&Warp>) { let glyphs: Box> = match only { Some(p) => Box::new(p.glyphs.iter().filter_map(|&i| layout.glyphs.get(i))), @@ -224,7 +229,7 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: if outline.draw(settings(), &mut shape).is_err() { continue; } - shape.embolden(f64::from(face.size_px * FAUX_BOLD_RADIUS)); + shape.embolden(f64::from(faux_bold_radius(face.size_px))); bold = Some(shape); } let settings = settings(); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index a19d9d52083..c50d3fa1a63 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -573,14 +573,52 @@ fn faux_bold_keeps_antialiased_edges_at_small_sizes() { let (plain_ink, plain_partial) = stats(&mut e, base.clone()); let (bold_ink, bold_partial) = stats(&mut e, CharStyle { faux_bold: true, ..base }); assert!(bold_ink > plain_ink, "bold must add ink"); - // Weight: the old summed-coverage faux bold (before #4130) measured 282.7 total ink for this - // text at 12 px (plain 138.0). The antialiased version must stay close to that weight. - const MAIN_BOLD_INK: f64 = 282.7; - assert!(bold_ink >= MAIN_BOLD_INK * 0.85, "stems too thin: {bold_ink} vs old {MAIN_BOLD_INK}"); - assert!(bold_ink <= MAIN_BOLD_INK * 1.15, "stems too heavy: {bold_ink} vs old {MAIN_BOLD_INK}"); + // Weight: the ring is now `size/72` with a pixel floor (#9008), which is Photoshop's weight, + // so this guards the antialiased edges rather than the old, heavier 3.6% of the size. + const MAIN_BOLD_INK: f64 = 222.2; + assert!(bold_ink >= MAIN_BOLD_INK * 0.9, "stems too thin: {bold_ink} vs {MAIN_BOLD_INK}"); + assert!(bold_ink <= MAIN_BOLD_INK * 1.1, "stems too heavy: {bold_ink} vs {MAIN_BOLD_INK}"); assert!(bold_partial * 10 >= plain_partial * 8, "edges stay antialiased: {plain_partial} -> {bold_partial}"); } +/// #9008: the faux-bold ring is Photoshop's `size/72`, with a pixel floor that fades in below +/// ~32 px (Photoshop's small type reads heavier than that) and a cap so a glyph smaller than a +/// pixel does not grow into a blob. +#[test] +fn faux_bold_radius_has_a_pixel_floor_that_fades_for_tiny_type() { + let r = crate::render::faux_bold_radius; + assert!((r(300.0) - 300.0 / 72.0).abs() < 1e-3, "large type: {}", r(300.0)); + assert!((r(72.0) - 1.0).abs() < 1e-3, "72 px: {}", r(72.0)); + assert!((r(24.0) - 0.45).abs() < 1e-3, "the floor takes over below 32 px: {}", r(24.0)); + assert!((r(4.0) - 0.1).abs() < 1e-3, "and fades out for tiny type: {}", r(4.0)); + assert!(r(0.5) < 0.02, "sub-pixel type keeps a sub-pixel ring: {}", r(0.5)); + // Monotonic: heavier text never grows a thinner ring as it gets larger. + assert!((1..400).all(|px| r(px as f32) <= r(px as f32 + 1.0))); +} + +/// #9008: at display sizes the ring is `size/72`, so the extra ink is the outline's perimeter times +/// `2 * size/72` — not the flat 7.2% of the size that made a PSD's faux-bold layer jump heavier as +/// soon as clicking it re-rendered the text. +#[test] +fn faux_bold_at_display_sizes_grows_the_outline_by_size_over_72() { + let mut e = TextEngine::new(); + let ink = |e: &mut TextEngine, s: CharStyle| { + let (_, r) = e.render(&TextLayer { transform: Affine::translate(10.0, 160.0), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8); + (alpha_sum(&r.surface, r.rect), r.rect) + }; + let base = CharStyle { size_pt: 120.0, ..Default::default() }; + let (plain, prect) = ink(&mut e, base.clone()); + let (bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base }); + // The outline grew by size/72 = 1.67 px on every side, so the ink rectangle grows by 3 px. + let grew = brect.width() - prect.width(); + assert!((3..=6).contains(&grew), "width grew {grew} px, expected about 2 * size/72"); + // Heavier by the perimeter's worth of ink. The flat 3.6% ring this replaces measured 1.95x for + // the same text (8 px wider) — the jump a PSD's faux-bold layer shows when a click re-renders + // it. Pinned, because a thicker ring here is exactly that regression. + let ratio = bold / plain; + assert!((1.3..=1.4).contains(&ratio), "{plain} -> {bold}: {ratio}x at 120 px, expected about 1.35x"); +} + /// #3705: Faux bold dilation must scale with horizontal and vertical glyph scaling. #[test] fn faux_bold_scales_with_glyph_scaling() { @@ -3343,7 +3381,11 @@ fn per_colour_passes_match_full_size_passes() { px.chunks_exact(ch).flat_map(|p| p[..ch - 1].iter().map(|c| c * p[ch - 1]).chain([p[ch - 1]]).collect::>()).collect::>() }; let worst = shown(&a).iter().zip(&shown(&b)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(worst <= 1.0 / 255.0, "case {k} {format:?}: largest difference {worst}"); + // Colour channels are 8-bit samples, so one step is 1/255. Coverage is accumulated in + // f32 from a buffer whose origin differs between the two paths, and a pixel sitting on + // a rounding tie then lands a step further out (measured 1.65/255 on the warped + // faux-bold case), so allow two steps. + assert!(worst <= 2.0 / 255.0, "case {k} {format:?}: largest difference {worst}"); } } } From 8c7b173e0398fc91dc8745d12f379a22f76813da Mon Sep 17 00:00:00 2001 From: ebosido444-ai Date: Sun, 1 Nov 2026 13:58:23 +0300 Subject: [PATCH 15/30] test(text): pin faux bold's ink at 12, 32, 72, 120 and 200 px The ring is `max(size/72, min(size/40, 0.45))`; the ink test only checked 120 px. It now walks five sizes, asserts the ink rectangle grows by twice the ring at each (the flat 3.6 % ring this replaced grew it by 0.072 * size), and pins the bold/plain ink ratio: 1.35x at 32, 72, 120 and 200 px, 1.64x at 12 px where the pixel floor is 3.75 % of the size. No caller of the removed constant is left: `grep -rn FAUX_BOLD` finds only the `type.fauxBold` menu command id, and `faux_bold_radius(size_px)` is the only reader of the ring. --- crates/text/src/tests.rs | 46 +++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c50d3fa1a63..cbd0c12a2c6 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -602,21 +602,37 @@ fn faux_bold_radius_has_a_pixel_floor_that_fades_for_tiny_type() { #[test] fn faux_bold_at_display_sizes_grows_the_outline_by_size_over_72() { let mut e = TextEngine::new(); - let ink = |e: &mut TextEngine, s: CharStyle| { - let (_, r) = e.render(&TextLayer { transform: Affine::translate(10.0, 160.0), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8); - (alpha_sum(&r.surface, r.rect), r.rect) - }; - let base = CharStyle { size_pt: 120.0, ..Default::default() }; - let (plain, prect) = ink(&mut e, base.clone()); - let (bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base }); - // The outline grew by size/72 = 1.67 px on every side, so the ink rectangle grows by 3 px. - let grew = brect.width() - prect.width(); - assert!((3..=6).contains(&grew), "width grew {grew} px, expected about 2 * size/72"); - // Heavier by the perimeter's worth of ink. The flat 3.6% ring this replaces measured 1.95x for - // the same text (8 px wider) — the jump a PSD's faux-bold layer shows when a click re-renders - // it. Pinned, because a thicker ring here is exactly that regression. - let ratio = bold / plain; - assert!((1.3..=1.4).contains(&ratio), "{plain} -> {bold}: {ratio}x at 120 px, expected about 1.35x"); + // Display sizes, including the two ends the issue reported on (75-125 px layers) and the + // sizes where the pixel floor hands over to `size/72` (32 px) and where the ring is 1 px + // (72 px). The flat 3.6% ring this replaces grew the outline by 0.072 * size instead, so a + // regression to it fails the width check at every size but 12 px. + let mut ratios = Vec::new(); + for px in [12.0f32, 32.0, 72.0, 120.0, 200.0] { + let ink = |e: &mut TextEngine, s: CharStyle| { + let (_, r) = e.render(&TextLayer { transform: Affine::translate(10.0, f64::from(px) * 1.4), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8); + (alpha_sum(&r.surface, r.rect), r.rect) + }; + let base = CharStyle { size_pt: px, ..Default::default() }; + let (plain, prect) = ink(&mut e, base.clone()); + let (bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base }); + // The outline grows by the ring on every side, so the ink rectangle grows by twice it. + let ring = crate::render::faux_bold_radius(px); + let grew = (brect.width() - prect.width()) as f32; + assert!((grew - 2.0 * ring).abs() <= 1.5, "{px} px: width grew {grew}, expected about {}", 2.0 * ring); + // Heavier by the perimeter's worth of ink. Pinned per size, because a thicker ring here is + // exactly the jump a PSD's faux-bold layer shows when a click re-renders it. + ratios.push(bold / plain); + } + // Plain text's ink grows with the size, so the bold/plain ratio falls as the ring does relative + // to the stems: 1.9x at 12 px (the floor), about 1.35x at 120 px, 1.24x at 200 px. + // The ring is a fixed fraction of the size above the pixel floor, so the ratio does not move + // with the size: 1.35x at 32, 72, 120 and 200 px (the flat 3.6% ring measured 1.95x). At 12 px + // the floor is 3.75% of the size, so the type reads a little heavier, as Photoshop's does. + for (px, r) in [32.0f32, 72.0, 120.0, 200.0].iter().zip(&ratios[1..]) { + assert!((1.30..=1.40).contains(r), "{px} px: {r:.2}x, expected about 1.35x"); + } + assert!((1.55..=1.75).contains(&ratios[0]), "12 px: {:.2}x, expected about 1.64x", ratios[0]); + assert!(ratios[0] > ratios[4], "the pixel floor fades out: {:.2}x at 12 px, {:.2}x at 200 px", ratios[0], ratios[4]); } /// #3705: Faux bold dilation must scale with horizontal and vertical glyph scaling. From a6dc7bb86a76d7c51740bf50feaf499c314a6f25 Mon Sep 17 00:00:00 2001 From: ArjenS-LA Date: Thu, 5 Nov 2026 15:59:05 -0800 Subject: [PATCH 16/30] Use the grayscale format in Average coverage regression --- crates/algo/src/average/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/algo/src/average/tests.rs b/crates/algo/src/average/tests.rs index d5986e234f9..c7158bd7438 100644 --- a/crates/algo/src/average/tests.rs +++ b/crates/algo/src/average/tests.rs @@ -43,7 +43,7 @@ fn soft_selection_weights_the_mean_and_output_mix() { let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); surface.write_region(bounds, &[1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75]); let before = surface.read_region(bounds); - let mut selection = Surface::new(PixelFormat::new(ColorMode::Gray, SampleType::F32, false)); + let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); selection.write_region(bounds, &[0.25, 1.0]); let out = apply(&surface, bounds, Some(&selection), &Interrupt::NONE).unwrap(); // Unequal coverage makes the mean [0.2, 0, 0.8]. Each pixel then mixes From b4f0bc042a7307a51a3bc1c87b51b39a8c4a21ca Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Sat, 7 Nov 2026 09:49:38 +0800 Subject: [PATCH 17/30] fix: keep Magnetic Lasso hover moves outside the click-only branch The merge of main (d453c7d12) moved the Magnetic Lasso's pointer-only hover block inside `if buttons.clicked`. `canvas_buttons` sets `clicked` from `response.clicked() || erase_click`, so on a pointer-only frame it is false and the block never ran: after the first fastening click, live edge tracking and automatic fastening froze until the next click. The base ran this block at a top-level `if`. Hoist it back above the click-only branch. A menu-dismissal gesture is still inert: the block is gated on `menu_dismiss_press`, the same state that starves the rest of the input pass and that the reviewer asked the dismissal suppression to use. Regressions, verified by reverting only canvas.rs: - `on_the_canvas_the_border_follows_the_hovering_pointer_and_keys_work` and `on_the_canvas_a_double_click_closes_the_border` pass on the merge base d453c7d12 and fail on the merged head (FredApps [P1], #9841). - new `on_the_canvas_hover_moves_survive_a_menu_dismissal_and_resume` covers the dismissal interaction: the hover is suppressed while the dismissal press is held and resumes on the next pointer move. --- crates/ui-egui/src/canvas.rs | 31 ++++++++++------ .../src/tools/magnetic_lasso_ui/tests.rs | 37 +++++++++++++++++++ 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index aa56bd6fad6..9154b72e047 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1153,6 +1153,26 @@ fn handle_canvas_tool_clicks( let ppp = input.ppp; let zoom_out = input.zoom_out; let display_zoom = input.display_zoom; + // Magnetic Lasso: between clicks the border follows the pointer with the button up. This is a + // pointer-only gesture — `canvas_buttons` makes `clicked` false on frames without a button + // event — so it must stay outside the click-only branch below, or live edge tracking and + // automatic fastening freeze until the next click. A menu-dismissal gesture is inert, so the + // hover is suppressed with the same flag that starves the rest of the input pass (#9841). + if tool == Tool::MagneticLasso + && app.ui.magnetic.active() + && !input.menu_dismiss_press + && !(buttons.started || buttons.dragged || buttons.stopped) + && response.hovered() + { + let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); + app.defer_live_stroke = true; + for p in moves.into_iter().filter(|p| rect.contains(*p)) { + let d = xf.to_doc(p); + tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); + } + app.defer_live_stroke = false; + crate::magnetic_lasso_ui::flush(app); + } if buttons.clicked && let Some(p) = response.interact_pointer_pos() { @@ -1212,17 +1232,6 @@ fn handle_canvas_tool_clicks( } } } - // Magnetic Lasso: between clicks the border follows the pointer with the button up. - if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { - let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); - app.defer_live_stroke = true; - for p in moves.into_iter().filter(|p| rect.contains(*p)) { - let d = xf.to_doc(p); - tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods); - } - app.defer_live_stroke = false; - crate::magnetic_lasso_ui::flush(app); - } // Move tool: a double-click on type edits it, as in Photoshop (#1132). Only the selected // Move tool, not ⌘ held over another tool; an open transform box keeps its double-click // (commit, below). diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs index 11d51376211..73d325a5060 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs @@ -381,6 +381,43 @@ fn on_the_canvas_the_border_follows_the_hovering_pointer_and_keys_work() { assert!((area - 5600.0).abs() < 120.0, "{area}"); } +/// #9841: the hover moves are a pointer-only gesture: they must keep running on frames with no +/// button event, and they must be suppressed while a menu-dismissal press is being consumed. +#[test] +fn on_the_canvas_hover_moves_survive_a_menu_dismissal_and_resume() { + let mut h = harness(); + ui_click(&mut h, 52.0, 37.0); + assert!(h.state().ui.magnetic.active()); + h.run_steps(2); + // A right-click opens the view menu without disturbing the border in progress. + let p = screen(&h, 90.0, 90.0); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the menu"); + // The dismissal press well clear of the menu: inert, and the pointer-only hover must not run. + let far = screen(&h, 12.0, 140.0); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + let held = h.state().ui.magnetic.clone(); + h.event(egui::Event::PointerMoved(screen(&h, 100.0, 36.0))); + h.run_steps(2); + assert_eq!(h.state().ui.magnetic, held, "a held dismissal press must not track the pointer"); + // Released: the very next pointer move tracks again, with no button event at all. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + ui_hover(&mut h, &[[52.0, 37.0], [100.0, 36.0]]); + let m = &h.state().ui.magnetic; + let end = m.live.last().or(m.path.last()).copied().unwrap(); + assert!((end[0] - 100.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover resumes after the dismissal: {end:?}"); +} + #[test] fn on_the_canvas_a_double_click_closes_the_border() { let mut h = harness(); From 9cdf6160b72aad54f9c344255b36459536bc14f6 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Sat, 7 Nov 2026 10:45:01 +0800 Subject: [PATCH 18/30] contributors: credit Kaedo17 by the name on the GitHub profile Adds my own entry to contributors/people.toml, as AGENTS.md asks a contributor to do in their own PR. sync_github_name = true takes the display name from my public GitHub profile; the About window drops it until the maintainer's next contributors.py run marks the entry verified. --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index ac36371f380..70c70757754 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -282,3 +282,6 @@ sync_github_name = false [people.jasallen] real_name = "Jason DeBoever" sync_github_name = true + +[people.Kaedo17] +sync_github_name = true From f0e753ee8df973b5cc39de02e70903eaaf549011 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 12:15:39 -0600 Subject: [PATCH 19/30] Magnetic Lasso: Caps Lock swaps in the Width circle cursor (#11690) --- crates/ui-egui/src/canvas.rs | 6 +- crates/ui-egui/src/canvas/cursors.rs | 2 +- crates/ui-egui/src/tools/magnetic_lasso_ui.rs | 8 ++- .../caps_lock_cursor_tests.rs | 59 +++++++++++++++++++ 4 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ac471a9269d..556c98ea978 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -62,8 +62,10 @@ pub mod zoom_window_fit; #[cfg(test)] pub(crate) use cursors::eyedropper_ring_colors; -pub(crate) use cursors::{alt_picks, alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor}; -use cursors::{brush_tip_centre, eyedropper_ring, precise_other_cursor, visible_crosshair}; +pub(crate) use cursors::{ + alt_picks, alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor, precise_other_cursor, +}; +use cursors::{brush_tip_centre, eyedropper_ring, visible_crosshair}; pub(crate) use display::GPU_OUTPUT; use display::texture_key; pub(crate) use display::{cache_key, canvas_display, display_doc, display_image}; diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index e692c4fe070..30370f780f6 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -120,7 +120,7 @@ pub(crate) fn alt_samples(tool: Tool, mods: egui::Modifiers) -> bool { /// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the /// standard cursor for it (and back), as in Photoshop (#4639). -pub(super) fn precise_other_cursor(app: &PhotocraftApp) -> bool { +pub(crate) fn precise_other_cursor(app: &PhotocraftApp) -> bool { (app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock } diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index 29d3861d9bd..6a5574aadf0 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -451,9 +451,10 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: } /// The cursor over the canvas: a crosshair; Preferences › Cursors › Other Cursors › Precise also -/// shows the detection width around it. +/// shows the detection width around it, and Caps Lock swaps the preference either way, as in +/// Photoshop (#11690). pub fn cursor(app: &PhotocraftApp, painter: &egui::Painter, p: Pos2, zoom: f32) -> egui::CursorIcon { - if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { + if crate::canvas::precise_other_cursor(app) { let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0); painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); @@ -463,3 +464,6 @@ pub fn cursor(app: &PhotocraftApp, painter: &egui::Painter, p: Pos2, zoom: f32) #[cfg(test)] mod tests; + +#[cfg(test)] +mod caps_lock_cursor_tests; diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs new file mode 100644 index 00000000000..39cd778e363 --- /dev/null +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs @@ -0,0 +1,59 @@ +//! Caps Lock and the Magnetic Lasso's cursor (#11690): it swaps Preferences › Cursors › Other +//! Cursors, so with Standard and Caps Lock on the pointer shows a circle as big as the detection +//! Width (scaled with zoom), and with Precise and Caps Lock on it doesn't. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app(other: &str, caps_lock: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.ui.tool = Tool::MagneticLasso; + app.ui.tool_options.magnetic_width = 10.0; + app.run("prefs.set", json!({"path": "cursors.other", "value": other})).unwrap(); + app.caps_lock = caps_lock; + app +} + +/// The radii of the circles `cursor` draws at `zoom`, and the OS cursor it asks for. +fn drawn(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon) { + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput::default()); + let painter = ctx.layer_painter(egui::LayerId::background()); + let icon = super::cursor(app, &painter, egui::pos2(100.0, 100.0), zoom); + let mut out = ctx.end_pass(); + out.textures_delta.clear(); + let radii = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Circle(c) => Some(c.radius), + _ => None, + }) + .collect(); + (radii, icon) +} + +#[test] +fn caps_lock_on_standard_draws_the_width_circle_scaled_with_zoom() { + let app = app("standard", true); + let (radii, icon) = drawn(&app, 1.0); + assert!(radii.iter().any(|r| (r - 10.0).abs() < 1e-3), "a 10 px circle at Width 10, 100 %: {radii:?}"); + assert_eq!(icon, egui::CursorIcon::Crosshair, "with a crosshair in the middle"); + let (radii, _) = drawn(&app, 2.0); + assert!(radii.iter().any(|r| (r - 20.0).abs() < 1e-3), "twice as big at 200 %: {radii:?}"); +} + +#[test] +fn caps_lock_on_precise_swaps_back_to_no_circle() { + let (radii, _) = drawn(&app("precise", true), 1.0); + assert!(radii.is_empty(), "no width circle: {radii:?}"); +} + +#[test] +fn without_caps_lock_the_preference_decides() { + assert!(drawn(&app("standard", false), 1.0).0.is_empty(), "Standard: no circle"); + assert!(!drawn(&app("precise", false), 1.0).0.is_empty(), "Precise: the width circle"); +} From 8e003123df65d5149df9e2723a897e89561659dd Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 16:39:47 -0600 Subject: [PATCH 20/30] Perspective Crop: dim the image outside the quad with a shield (#11972) The image outside a pending quad is covered by a grey shield at the measured strength, painted as the canvas minus the convex quad and following the quad while it is dragged. A quad that is not convex keeps today's red outline without a shield. --- .../tools/perspective_crop_shield_tests.rs | 97 +++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 56 +++++++++++ 2 files changed, 153 insertions(+) create mode 100644 crates/ui-egui/src/tools/perspective_crop_shield_tests.rs diff --git a/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs new file mode 100644 index 00000000000..c203fe5a6c4 --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs @@ -0,0 +1,97 @@ +//! #11972: with a pending Perspective Crop quad the image outside it is dimmed (red 255, 0, 0 shows +//! as about 225, 16, 16), inside it is unchanged, the shield follows the quad while it is dragged, +//! and nothing is drawn without a quad. + +use egui::{Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const CANVAS: [[f64; 2]; 4] = [[0.0, 0.0], [200.0, 0.0], [200.0, 150.0], [0.0, 150.0]]; + +fn area(poly: &[[f64; 2]]) -> f64 { + (0..poly.len()).map(|i| poly[i][0] * poly[(i + 1) % poly.len()][1] - poly[(i + 1) % poly.len()][0] * poly[i][1]).sum::().abs() / 2.0 +} + +/// A point strictly inside a convex polygon. +fn contains(poly: &[[f64; 2]], p: [f64; 2]) -> bool { + let s: Vec = (0..poly.len()) + .map(|i| { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) + }) + .collect(); + s.iter().all(|v| *v > 1e-9) || s.iter().all(|v| *v < -1e-9) +} + +#[test] +fn the_shield_colour_dims_red_as_measured() { + // Straight alpha over an opaque pixel: v · (1 − a) + grey · a. + let a = f32::from(SHIELD.a()) / 255.0; + let grey = f32::from(SHIELD.r()) / a; + let over = |v: f32| v * (1.0 - a) + grey * a; + let [r, g, b] = [over(255.0), over(0.0), over(0.0)]; + assert!((r - 225.0).abs() <= 4.0 && (g - 16.0).abs() <= 4.0 && (b - 16.0).abs() <= 4.0, "{r} {g} {b}"); +} + +#[test] +fn the_pieces_cover_the_canvas_outside_the_quad_and_never_inside() { + // A skewed quad inside the canvas, in either winding. + for q in [[[30.0, 20.0], [170.0, 30.0], [160.0, 120.0], [40.0, 110.0]], [[40.0, 110.0], [160.0, 120.0], [170.0, 30.0], [30.0, 20.0]]] { + let pieces = shield_pieces(CANVAS, q); + let covered: f64 = pieces.iter().map(|p| area(p)).sum(); + assert!((covered - (area(&CANVAS) - area(&q))).abs() < 1e-6, "{covered}"); + for p in [[100.0, 70.0], [50.0, 40.0], [150.0, 100.0]] { + assert!(!pieces.iter().any(|piece| contains(piece, p)), "{p:?} inside the quad is not dimmed"); + } + for p in [[5.0, 5.0], [195.0, 145.0], [100.0, 5.0], [5.0, 75.0]] { + assert_eq!(pieces.iter().filter(|piece| contains(piece, p)).count(), 1, "{p:?} outside is dimmed once"); + } + } +} + +#[test] +fn a_quad_past_the_canvas_dims_only_the_canvas() { + let q = [[100.0, 50.0], [260.0, 50.0], [260.0, 200.0], [100.0, 170.0]]; + let pieces = shield_pieces(CANVAS, q); + let inside_canvas = 100.0 * 100.0; // the quad's part on the canvas: x 100–200, y 50–150 + let covered: f64 = pieces.iter().map(|p| area(p)).sum(); + assert!((covered - (area(&CANVAS) - inside_canvas)).abs() < 1e-6, "{covered}"); + assert!(pieces.iter().all(|p| p.iter().all(|v| (0.0..=200.0).contains(&v[0]) && (0.0..=150.0).contains(&v[1]))), "nothing past the canvas"); +} + +#[test] +fn a_degenerate_quad_has_no_shield() { + assert!(shield_pieces(CANVAS, [[10.0, 10.0], [10.0, 10.0], [10.0, 10.0], [10.0, 10.0]]).is_empty()); + assert!(shield_pieces(CANVAS, [[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).is_empty()); +} + +/// The shield polygons `draw_overlay` paints. +fn painted(app: &PhotocraftApp) -> usize { + let ctx = egui::Context::default(); + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0)), zoom: 1.0, center: [100.0, 75.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count() +} + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +#[test] +fn the_shield_shows_with_a_quad_follows_a_drag_and_goes_away() { + let mut app = app(); + assert_eq!(painted(&app), 0, "no quad: no shield"); + // While the first box is dragged. + app.pcrop.drag = Some(Drag::New { start: [20.0, 20.0], cur: [180.0, 130.0] }); + assert!(painted(&app) > 0, "the shield follows the box being dragged"); + app.pcrop.drag = None; + app.ui.perspective_crop = Some([[20.0, 20.0], [180.0, 20.0], [180.0, 130.0], [20.0, 130.0]]); + assert_eq!(painted(&app), 4, "four pieces around a pending quad"); + cancel(&mut app); + assert_eq!(painted(&app), 0, "gone after cancel"); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index ed60c90d414..25fa3f11326 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -233,6 +233,51 @@ fn grid_steps(side: f32) -> usize { ((side / 48.0).round() as usize).clamp(2, 12) } +/// The shield over the image outside a pending quad (#11972): grey 89 at 18 % opacity, which shows +/// red 255, 0, 0 as 225, 16, 16, as measured in the reference application. +pub(crate) const SHIELD: Color32 = Color32::from_rgba_premultiplied(16, 16, 16, 46); + +/// The canvas `canvas` (a convex polygon, document px) minus the convex quad `q`, as up to four +/// disjoint convex pieces: each is what is left of the canvas outside one quad edge and inside the +/// edges before it. Empty for a degenerate quad. +pub(crate) fn shield_pieces(canvas: [[f64; 2]; 4], q: [[f64; 2]; 4]) -> Vec> { + let area: f64 = (0..4).map(|i| q[i][0] * q[(i + 1) % 4][1] - q[(i + 1) % 4][0] * q[i][1]).sum(); + if !area.is_finite() || area.abs() < 1e-9 { + return Vec::new(); + } + let side = area.signum(); + let mut rest = canvas.to_vec(); + let mut out = Vec::new(); + for i in 0..4 { + let (a, b) = (q[i], q[(i + 1) % 4]); + let outside = clip_half_plane(&rest, a, b, -side); + if outside.len() >= 3 { + out.push(outside); + } + rest = clip_half_plane(&rest, a, b, side); + } + out +} + +/// One Sutherland–Hodgman step: the part of the convex polygon `poly` on the `side` (the sign of +/// the cross product) of the line from `a` to `b`. +fn clip_half_plane(poly: &[[f64; 2]], a: [f64; 2], b: [f64; 2], side: f64) -> Vec<[f64; 2]> { + let d = |p: [f64; 2]| side * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])); + let mut out = Vec::with_capacity(poly.len() + 1); + for (i, &p) in poly.iter().enumerate() { + let n = poly[(i + 1) % poly.len()]; + let (dp, dn) = (d(p), d(n)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dn >= 0.0) && (dp - dn).abs() > f64::EPSILON { + let t = dp / (dp - dn); + out.push([p[0] + (n[0] - p[0]) * t, p[1] + (n[1] - p[1]) * t]); + } + } + out +} + /// The quad, its perspective grid and corner handles; corners clicked so far; the box being drawn. pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { if app.ui.tool != Tool::PerspectiveCrop { @@ -250,6 +295,13 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { let ok = convex_quad(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; + // The image outside the quad is dimmed (#11972), following the quad while it is dragged. + if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { + let (w, h) = (f64::from(size.width), f64::from(size.height)); + for piece in shield_pieces([[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], q) { + painter.add(egui::Shape::convex_polygon(piece.iter().map(|c| scr(*c)).collect(), SHIELD, Stroke::NONE)); + } + } let pts: Vec = q.iter().map(|c| scr(*c)).collect(); if ok && app.ui.tool_options.perspective_crop_grid @@ -316,6 +368,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } +#[cfg(test)] +#[path = "perspective_crop_shield_tests.rs"] +mod perspective_crop_shield_tests; + #[cfg(test)] mod tests { use super::*; From ea37bf8bd9b5bb934bbb0d6d962d7240e9b1f208 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 03:30:26 +0100 Subject: [PATCH 21/30] #9077: drop the map_pixels wrapper the main merge left unused Main's Equalize change (58d11d91ea) moved Equalize to map_pixels_in, and this PR moves Average off map_pixels, so after merging main the wrapper had no caller and clippy -D warnings failed on dead code. Fold its doc into map_pixels_in. Co-Authored-By: ArjenS-LA Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/extra_cmds.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index ca6ed6b3861..275e3446479 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -74,13 +74,9 @@ pub(crate) fn step_key(s: &Session, what: &str) -> String { /// area, the pixels, and the selection coverage per pixel; results are blended back by coverage, /// and transparency stays locked when the layer locks it. When `p` targets an alpha channel, the /// Quick Mask or the layer mask (`Session::execute` fills that in from the Channels panel), that -/// grayscale surface is rewritten instead, as the core filters do (#935). -fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result { - map_pixels_in(s, label, p, false, f) -} - -/// [`map_pixels`], or with `whole` the whole canvas: `f` still gets the selection coverage, and -/// every pixel takes its result in full. +/// grayscale surface is rewritten instead, as the core filters do (#935). With `whole` the whole +/// canvas is rewritten: `f` still gets the selection coverage, and every pixel takes its result +/// in full. fn map_pixels_in(s: &mut Session, label: &str, p: &Value, whole: bool, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result { let id = layer_param(s, p)?; let channel = crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels; From bfdf124639bec7946b2197fd51b87bbc4b3c2384 Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Sun, 8 Nov 2026 10:43:04 +0800 Subject: [PATCH 22/30] test: stage the dismissal gate the way the gesture actually holds it The re-merge to main (9ac3fa22b) broke this test's premise. Main gained `canvas_tool_menu::magnetic_drawing` (#11689): a right-click over a Magnetic Lasso border in progress opens no menu, on the canvas and through the control channel alike. So a menu can no longer be open over a live border, and the test's right-click setup asserted behaviour that is now deliberately gone. The `menu_dismiss_press` check on the hover block is therefore a guard rather than a sequence a pointer can reach. The test stages the dismissal state directly instead, with the button held: the flag is scoped to a held button (a frame with every button up clears it), so a pointer-up frame would clear it before the gate reads it and prove nothing. Holding the button also showed the guard does suppress the hover, which the pointer-up version silently did not. Two failures found while rebasing, both fixed here: - the obsolete right-click setup (this commit); - the pointer-up staging, which passed the flag only after the clear. --- .../src/tools/magnetic_lasso_ui/tests.rs | 53 ++++++++++--------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs index e9cb10ceb60..db059edc3c5 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs @@ -418,41 +418,42 @@ fn on_the_canvas_the_border_follows_the_hovering_pointer_and_keys_work() { assert!((area - 5600.0).abs() < 120.0, "{area}"); } -/// #9841: the hover moves are a pointer-only gesture: they must keep running on frames with no -/// button event, and they must be suppressed while a menu-dismissal press is being consumed. +/// #9841: the hover moves are a pointer-only gesture. Two things must hold: they keep running on +/// frames with no button event at all (the freeze the main-merge regression reintroduced), and a +/// consumed menu-dismissal gesture must not track the pointer. +/// +/// A canvas menu cannot be open over a live border — `canvas_tool_menu::magnetic_drawing` refuses +/// one for a Magnetic Lasso border in progress (#11689), on the canvas and through the control +/// channel alike — so the `menu_dismiss_press` check on the hover block is a guard rather than a +/// sequence a pointer can reach. The dismissal state is staged directly here, with the button held +/// as the real gesture has it: the flag is scoped to a held button (a frame with every button up +/// clears it), so a pointer-up frame would clear it before the gate reads it and test nothing. #[test] fn on_the_canvas_hover_moves_survive_a_menu_dismissal_and_resume() { let mut h = harness(); ui_click(&mut h, 52.0, 37.0); assert!(h.state().ui.magnetic.active()); h.run_steps(2); - // A right-click opens the view menu without disturbing the border in progress. - let p = screen(&h, 90.0, 90.0); - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the menu"); - // The dismissal press well clear of the menu: inert, and the pointer-only hover must not run. - let far = screen(&h, 12.0, 140.0); - h.event(egui::Event::PointerMoved(far)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); - let held = h.state().ui.magnetic.clone(); - h.event(egui::Event::PointerMoved(screen(&h, 100.0, 36.0))); - h.run_steps(2); - assert_eq!(h.state().ui.magnetic, held, "a held dismissal press must not track the pointer"); - // Released: the very next pointer move tracks again, with no button event at all. - h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); + // Button up: the border follows the pointer with no button event at all. ui_hover(&mut h, &[[52.0, 37.0], [100.0, 36.0]]); let m = &h.state().ui.magnetic; let end = m.live.last().or(m.path.last()).copied().unwrap(); - assert!((end[0] - 100.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover resumes after the dismissal: {end:?}"); + assert!((end[0] - 100.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover tracks with the button up: {end:?}"); + // A consumed dismissal gesture with its button still down: the hover must not advance. + let far = screen(&h, 150.0, 130.0); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.state_mut().ui.canvas_tool_menu_dismissed = true; + let held = h.state().ui.magnetic.clone(); + ui_hover(&mut h, &[[100.0, 36.0], [130.0, 36.0]]); + assert_eq!(h.state().ui.magnetic, held, "a consumed dismissal gesture must not track the pointer"); + // Released: the very next pointer move tracks again. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + ui_hover(&mut h, &[[130.0, 36.0], [120.0, 36.0]]); + let m = &h.state().ui.magnetic; + let end = m.live.last().or(m.path.last()).copied().unwrap(); + assert!((end[0] - 120.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover resumes once released: {end:?}"); } #[test] From 2bc47603c6b38698ba214dde40b42f68992c892e Mon Sep 17 00:00:00 2001 From: Kaedo17 Date: Sun, 8 Nov 2026 13:12:03 +0800 Subject: [PATCH 23/30] fix: consume the dismissal press before the Lasso reads it FredApps [P2] on bfdf12463: the Lasso reads its own raw pointer events (`lasso_ui::canvas_input` takes `ctx.input().events` directly), so the `buttons` starvation the other tools get never reaches it. A press that dismissed the canvas tool menu still drew a Lasso selection, leaving the shared selection-menu case of the dismissal fix incomplete. The Freeform Pen draws through the same dispatcher. Gate the dispatcher on `menu_dismiss_press`, as the Crop press above it is gated. The regression follows the reported case: right-click at document (300, 100), then left-press outside the menu at (50, 250) and drag through (50, 200), (150, 200), (150, 250), release. It asserts no drag is left behind, no selection and no history step, and that the next ordinary Lasso drag draws again. Fails on bfdf12463 at "the consumed gesture must draw no selection", passes here. --- crates/ui-egui/src/canvas.rs | 7 +++-- crates/ui-egui/src/tools/lasso_ui/tests.rs | 36 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6ebd05ae0e7..a5ebc9d9bed 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -961,8 +961,11 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> }; // The Lasso (and the Freeform Pen, which draws the same way) reads its own presses and // drops the moves of a drag it didn't start, so an open Free Transform box takes the - // usual drag path instead (#2153). - if crate::lasso_ui::owns(tool) && !transform_owns_pointer { + // usual drag path instead (#2153). It reads the raw pointer events straight from the + // context, so the `buttons` starvation above never reaches it: a press that dismisses the + // canvas tool menu would draw a selection. Gate the dispatcher itself, as the Crop press + // above is gated (#9841). + if crate::lasso_ui::owns(tool) && !transform_owns_pointer && !input.menu_dismiss_press { crate::lasso_ui::canvas_input(app, ctx, xf, response); (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index 816d6611526..a568d102ae2 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -524,3 +524,39 @@ fn alt_clicking_narrow_and_rotated_polygons_keeps_the_fourth_corner() { assert!(app.session.active().unwrap().doc.selection.is_some()); } } + +/// #9841: the Lasso reads its own raw pointer events (`lasso_ui::canvas_input`), so the +/// `Buttons` starvation the other tools get does not reach it. A press that dismisses the +/// canvas tool menu must not draw a Lasso selection, and the next ordinary drag must work. +#[test] +fn a_menu_dismissal_press_never_draws_a_lasso_selection() { + let mut h = harness(); + // Right-click on the canvas: the selection menu opens. + let menu_at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(300.0, 100.0); + h.event(Event::PointerMoved(menu_at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: menu_at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: menu_at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the selection menu"); + let revision = h.state().session.active().unwrap().revision; + // The dismissal press and drag, well clear of the menu. + mouse(&mut h, "down", 50.0, 250.0, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + mouse(&mut h, "move", 50.0, 200.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 200.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 250.0, Modifiers::NONE); + mouse(&mut h, "up", 150.0, 250.0, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().drag.is_none(), "the consumed gesture must not leave a Lasso drag behind"); + assert!(h.state().session.active().unwrap().doc.selection.is_none(), "the consumed gesture must draw no selection"); + assert_eq!(h.state().session.active().unwrap().revision, revision, "and no history step"); + // The next ordinary drag draws one, so the guard did not stick. + mouse(&mut h, "down", 50.0, 50.0, Modifiers::NONE); + mouse(&mut h, "move", 90.0, 40.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 60.0, Modifiers::NONE); + mouse(&mut h, "up", 150.0, 60.0, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "an ordinary Lasso drag draws again"); +} From e0ca582b97ff5ecfeea81421e60f2642502b00ae Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 8 Nov 2026 22:11:51 +0100 Subject: [PATCH 24/30] fix(engine): the Magic Eraser measures Tolerance by colour spread (#11995) On 8-bit RGB a pixel now matches the clicked colour when the spread of {0, dR, dG, dB} is within the Tolerance, so opposite changes in two channels count double and green and blue stay at Tolerance 255. The anti-alias fringe uses the same distance. The Magic Wand, the Paint Bucket and other modes and depths keep the per-channel limit. --- crates/algo/src/selection.rs | 40 +++- crates/engine/src/cmd/eraser_cmds.rs | 8 +- .../magic_eraser_tolerance_tests.rs | 218 ++++++++++++++++++ 3 files changed, 262 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 0d8866e18ef..60c9f28c8a2 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -299,6 +299,26 @@ impl Region { } } +/// How a wand-style fill measures how far an 8-bit colour is from the clicked one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorDistance { + /// The largest difference in any one of R, G and B. + LargestChannel, + /// The spread of `{0, dR, dG, dB}`: changes in the same direction count once, opposite + /// changes add up. + Spread, +} + +impl ColorDistance { + fn rgb(self, p: [u8; 4], seed: [u8; 4]) -> i32 { + let d = [0, 1, 2].map(|c| p[c] as i32 - seed[c] as i32); + match self { + Self::LargestChannel => d.iter().fold(0, |m, v| m.max(v.abs())), + Self::Spread => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)), + } + } +} + /// Magic wand on 8-bit pixels: a scanline flood fill (or a global match) that only allocates a /// byte mark per pixel, then anti-aliases just the edges inside the touched bounding box. /// Matches [`magic_wand`] for 8-bit sources. `None` if the seed is outside `area`. @@ -318,6 +338,21 @@ pub fn wand_region_within( contiguous: bool, anti_alias: bool, within: Option<&[f32]>, +) -> Option { + wand_region_by(img, area, seed, tolerance, contiguous, anti_alias, within, ColorDistance::LargestChannel) +} + +/// [`wand_region_within`] measuring how far a colour is from the clicked one with `distance`. +#[allow(clippy::too_many_arguments)] +pub fn wand_region_by( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, + distance: ColorDistance, ) -> Option { if !area.contains(seed.0, seed.1) { return None; @@ -335,7 +370,7 @@ pub fn wand_region_within( let tol = (tolerance + 1e-3).floor().max(0.0) as i32; // Copying a selection can leave RGB under zero alpha. Those invisible colours must not // split a transparent region into pieces, as if the copied source were still visible. - let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol); + let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol); let mut marks = vec![0u8; w * h]; let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); if contiguous { @@ -414,8 +449,7 @@ pub fn wand_region_within( // it gets a fringe by how far its colour is past the tolerance. if anti_alias && v == 0 && touches_region(x, y, w, h, |nx, ny| at(nx, ny) != 0) { let p = img[y * w + x]; - let d = (0..3).map(|c| (p[c] as i32 - target[c] as i32).abs()).max().unwrap_or(0); - *o = fringe_coverage((d - tol) as f32, f32::from(p[3].min(target[3]))); + *o = fringe_coverage((distance.rgb(p, target) - tol) as f32, f32::from(p[3].min(target[3]))); } } }; diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index bf08c18ac24..a78f9f7d5ea 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -8,6 +8,7 @@ //! work in the layer's own colour model and depth, and are one undo step per click / stroke. use photocraft_algo::selection as sel; +use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_paint::Stroke; @@ -105,7 +106,10 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id))?; (d.doc.bounds(), sel::rgba8_image(surf, d.doc.bounds())) }; - let region = sel::wand_region(&img, area, (x, y), tolerance, contiguous, anti_alias); + // The reference's colour distance is measured for 8-bit RGB only (#11995). + let rgb8 = s.active().is_some_and(|d| d.doc.mode == ColorMode::Rgb && d.doc.depth == SampleType::U8); + let distance = if rgb8 { sel::ColorDistance::Spread } else { sel::ColorDistance::LargestChannel }; + let region = sel::wand_region_by(&img, area, (x, y), tolerance, contiguous, anti_alias, None, distance); drop(img); let Some(region) = region else { return Ok(damage(s, Rect::EMPTY, false)) }; let bg = s.tools.background; @@ -275,5 +279,7 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_tolerance_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs new file mode 100644 index 00000000000..27f4d5ec6a2 --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs @@ -0,0 +1,218 @@ +//! #11995: on 8-bit RGB the Magic Eraser measures Tolerance by the spread of `{0, dR, dG, dB}`, so +//! opposite changes in two channels count double. The expected values are the reference +//! application's measurements from the issue; the stripes document is drawn at a tenth of the size. + +use photocraft_algo::selection as sel; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::Session; + +const SEED: [u8; 3] = [200, 40, 40]; +/// `d` of the patch grid's columns. +const GRID: [i32; 8] = [20, 50, 80, 110, 140, 170, 200, 230]; + +fn hex([r, g, b]: [u8; 3]) -> String { + format!("#{r:02x}{g:02x}{b:02x}") +} + +fn document(w: i32, h: i32, depth: u32, background: [u8; 3]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "mode": "rgb", "depth": depth, "background": hex(background)})).unwrap(); + s +} + +fn fill(s: &mut Session, [x, y, w, h]: [i32; 4], color: [u8; 3]) { + s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": hex(color)})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); +} + +fn erase(s: &mut Session, x: i32, y: i32, options: Value) { + let mut p = json!({"x": x, "y": y, "antiAlias": false}); + p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + s.execute("paint.magicEraser", p).unwrap(); +} + +fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn erased(s: &Session, x: i32, y: i32) -> bool { + rgba(s, x, y)[3] == 0.0 +} + +/// Grey (100, 100, 100) with ten-pixel patches along the top: same-direction and opposite changes. +fn grey_patches(depth: u32) -> (Session, [(i32, [u8; 3], i32); 4]) { + let patches = [(10, [130, 100, 70], 60), (30, [130, 130, 100], 30), (50, [70, 130, 100], 60), (70, [70, 70, 70], 30)]; + let mut s = document(90, 30, depth, [100, 100, 100]); + for (x, color, _) in patches { + fill(&mut s, [x, 10, 10, 10], color); + } + (s, patches) +} + +/// Opposite changes count double and same-direction changes once (Tolerance 29, 30, 59, 60). +#[test] +fn opposite_channel_changes_count_double_around_a_grey_seed() { + for tolerance in [29, 30, 59, 60] { + let (mut s, patches) = grey_patches(8); + erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false})); + for (x, color, metric) in patches { + assert_eq!(erased(&s, x + 5, 15), tolerance >= metric, "tolerance {tolerance}, patch {color:?}"); + } + } +} + +fn grid_colour(row: usize, d: i32) -> [u8; 3] { + let [r, g, b] = SEED.map(i32::from); + let [r, g, b] = match row { + 0 => [r - d, g, b], + 1 => [r + d, g, b], + 2 => [r, g + d, b], + 3 => [r, g + d, b + d], + _ => [r - d, g + d, b + d], + }; + [r, g, b].map(|v| v.clamp(0, 255) as u8) +} + +/// The issue's patch grid around (200, 40, 40): `0` is erased and `x` kept, one row per Tolerance. +#[test] +fn the_patch_grid_matches_the_measured_table() { + const TABLE: [(i32, [&str; 5]); 7] = [ + (30, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "xxxxxxxx"]), + (40, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx"]), + (60, ["00xxxxxx", "00000000", "00xxxxxx", "00xxxxxx", "0xxxxxxx"]), + (100, ["000xxxxx", "00000000", "000xxxxx", "000xxxxx", "00xxxxxx"]), + (150, ["00000xxx", "00000000", "00000xxx", "00000xxx", "00xxxxxx"]), + (200, ["00000000", "00000000", "0000000x", "0000000x", "000xxxxx"]), + (255, ["00000000", "00000000", "00000000", "00000000", "0000xxxx"]), + ]; + for (tolerance, rows) in TABLE { + let mut s = document(80, 60, 8, SEED); + for row in 0..5 { + for (col, d) in GRID.into_iter().enumerate() { + fill(&mut s, [col as i32 * 10, 10 + row as i32 * 10, 10, 10], grid_colour(row, d)); + } + } + erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false})); + for (row, want) in rows.into_iter().enumerate() { + let got: String = (0..8).map(|col| if erased(&s, col * 10 + 5, 15 + row as i32 * 10) { '0' } else { 'x' }).collect(); + assert_eq!(got, want, "tolerance {tolerance}, row {row}"); + } + } +} + +const RED: [u8; 3] = [220, 30, 30]; +const GREEN: [u8; 3] = [30, 180, 60]; +const BLUE: [u8; 3] = [40, 60, 220]; +const PINK: [u8; 3] = [240, 120, 120]; +const UPPER_RED: (i32, i32) = (10, 5); +const LOWER_RED: (i32, i32) = (10, 22); +const WHITE_GAP: (i32, i32) = (10, 15); + +/// The stripes over eight blocks (200, 40 + 20·i, 40), with a white gap cutting the red stripe. +fn stripes() -> Session { + let mut s = document(80, 60, 8, [255, 255, 255]); + for (i, color) in [RED, GREEN, BLUE, PINK].into_iter().enumerate() { + fill(&mut s, [i as i32 * 20, 0, 20, 30], color); + } + fill(&mut s, [0, 14, 20, 2], [255, 255, 255]); + for i in 0..8u8 { + fill(&mut s, [i32::from(i) * 10, 30, 10, 30], [200, 40 + 20 * i, 40]); + } + s +} + +fn erased_blocks(s: &Session) -> usize { + (0..8).take_while(|i| erased(s, i * 10 + 5, 45)).count() +} + +/// Contiguous from block 0: the blocks go one by one, and green and blue survive even at 255. +#[test] +fn stripes_contiguous_from_block_zero() { + for (tolerance, blocks) in + [(0, 1), (10, 1), (19, 1), (20, 2), (21, 2), (39, 2), (40, 3), (41, 3), (60, 4), (100, 6), (140, 8), (160, 8), (200, 8), (255, 8)] + { + let mut s = stripes(); + erase(&mut s, 5, 45, json!({"tolerance": tolerance})); + assert_eq!(erased_blocks(&s), blocks, "tolerance {tolerance}"); + assert_eq!(8 - (0..8).filter(|i| !erased(&s, i * 10 + 5, 45)).count(), blocks, "tolerance {tolerance}: the erased blocks are consecutive"); + assert_eq!(erased(&s, 70, 15), tolerance >= 140, "tolerance {tolerance}: pink, reached through blocks 6 and 7"); + assert_eq!(erased(&s, UPPER_RED.0, UPPER_RED.1), tolerance == 255, "tolerance {tolerance}: upper red, reached through the white gap"); + if tolerance == 41 || tolerance >= 60 { + assert!(erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red"); + } + if tolerance < 30 { + assert!(!erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red"); + } + assert!(!erased(&s, 30, 15), "tolerance {tolerance}: green is kept"); + assert!(!erased(&s, 50, 15), "tolerance {tolerance}: blue is kept"); + } +} + +/// Non-contiguous from block 0: white goes from Tolerance 220; green and blue never do. +#[test] +fn stripes_non_contiguous_from_block_zero() { + let mut s = stripes(); + erase(&mut s, 5, 45, json!({"tolerance": 150, "contiguous": false})); + assert_eq!(erased_blocks(&s), 8); + assert!(erased(&s, UPPER_RED.0, UPPER_RED.1) && erased(&s, LOWER_RED.0, LOWER_RED.1), "both reds"); + assert!(erased(&s, 70, 15), "pink"); + assert!(!erased(&s, WHITE_GAP.0, WHITE_GAP.1), "the white gap (metric 215) is kept"); + assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue"); + + let mut s = stripes(); + erase(&mut s, 5, 45, json!({"tolerance": 220, "contiguous": false})); + assert!(erased(&s, WHITE_GAP.0, WHITE_GAP.1), "white is within 220"); + assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue"); +} + +/// The fringe uses the same distance: a neighbour the spread rejects is not fully erased, even +/// though every one of its channels is within the Tolerance. +#[test] +fn anti_alias_does_not_erase_a_neighbour_the_spread_rejects() { + let (mut s, _) = grey_patches(8); + erase(&mut s, 0, 0, json!({"tolerance": 32, "contiguous": false, "antiAlias": true})); + assert!(rgba(&s, 15, 15)[3] == 1.0, "the patch's inside is kept"); + assert!(rgba(&s, 10, 15)[3] > 0.0, "(130, 100, 70) has spread 60, past Tolerance 32"); +} + +/// Depths the rule was not measured for keep comparing each channel on its own. +#[test] +fn sixteen_bit_keeps_the_per_channel_limit() { + let (mut s, patches) = grey_patches(16); + erase(&mut s, 0, 0, json!({"tolerance": 30, "contiguous": false})); + for (x, color, _) in patches { + assert!(erased(&s, x + 5, 15), "patch {color:?}"); + } +} + +/// The Magic Wand and the Paint Bucket share the fill and keep the per-channel limit. +#[test] +fn the_magic_wand_and_paint_bucket_keep_the_per_channel_limit() { + let (mut s, _) = grey_patches(8); + s.execute("select.magicWand", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false})).unwrap(); + let selected = sel::mask_from_surface(s.active().unwrap().doc.selection.as_ref(), Rect::new(0, 0, 90, 30)); + assert_eq!(selected[15 * 90 + 15], 1.0, "the wand takes (130, 100, 70) at 30"); + + let (mut s, _) = grey_patches(8); + s.execute("paint.bucket", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false, "color": "#ff00ff"})).unwrap(); + let [r, g, b, _] = rgba(&s, 15, 15); + assert_eq!([r, g, b], [1.0, 0.0, 1.0], "the bucket fills (130, 100, 70) at 30"); +} + +/// A transparent seed still matches every transparent pixel, and alpha still limits the match. +#[test] +fn the_spread_keeps_the_transparent_and_alpha_handling() { + let area = Rect::new(0, 0, 3, 1); + let run = |img: [[u8; 4]; 3], tolerance| sel::wand_region_by(&img, area, (0, 0), tolerance, false, false, None, sel::ColorDistance::Spread).unwrap(); + + let region = run([[10, 20, 30, 0], [200, 0, 90, 0], [9, 9, 9, 255]], 0.0); + assert_eq!((region.at(1, 0), region.at(2, 0)), (1.0, 0.0), "hidden colours don't matter; visible pixels don't match"); + + let half = [[100, 100, 100, 200], [100, 100, 100, 100], [100, 100, 100, 170]]; + let region = run(half, 30.0); + assert_eq!((region.at(1, 0), region.at(2, 0)), (0.0, 1.0), "alpha differences stay limited by the Tolerance"); +} From 08fb21096446db58b2f71a70a5587451da350623 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 22:18:56 +0100 Subject: [PATCH 25/30] Magnetic Lasso: the Standard cursor is the tool icon (#12151, #11690) With Other Cursors set to Standard (or Precise swapped by Caps Lock) the Magnetic Lasso showed a plain crosshair. The reference application shows the tool's icon with its hotspot on the lasso's top-left tip; the Width circle stays on the precise side. Co-Authored-By: Hector Villarreal <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/magnetic_lasso_ui.rs | 17 ++++++----- .../caps_lock_cursor_tests.rs | 29 ++++++++++++++----- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index 93774ddcf3c..d7884b3799c 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -483,15 +483,18 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: } } -/// The cursor over the canvas: a crosshair; Preferences › Cursors › Other Cursors › Precise also -/// shows the detection width around it, and Caps Lock swaps the preference either way, as in -/// Photoshop (#11690). +/// The cursor over the canvas: the tool's icon with its top-left tip on the point; Preferences › +/// Cursors › Other Cursors › Precise shows the detection width around a crosshair instead, and +/// Caps Lock swaps the preference either way, as in Photoshop (#11690). pub fn cursor(app: &PhotocraftApp, painter: &egui::Painter, p: Pos2, zoom: f32) -> egui::CursorIcon { - if crate::canvas::precise_other_cursor(app) { - let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0); - painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); - painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); + if !crate::canvas::precise_other_cursor(app) { + // The icon's lasso tip is at (1.8, 3.6) of its 24-unit box. + crate::icons::cursor(painter.ctx(), crate::icons::tool_icon(Tool::MagneticLasso), p, vec2(1.8, 3.6) / 24.0, 22.0); + return egui::CursorIcon::None; } + let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0); + painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); + painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); egui::CursorIcon::Crosshair } diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs index 39cd778e363..297a71b1744 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs @@ -1,6 +1,7 @@ //! Caps Lock and the Magnetic Lasso's cursor (#11690): it swaps Preferences › Cursors › Other //! Cursors, so with Standard and Caps Lock on the pointer shows a circle as big as the detection -//! Width (scaled with zoom), and with Precise and Caps Lock on it doesn't. +//! Width (scaled with zoom), and with Precise and Caps Lock on it is the tool's icon, as with +//! Standard alone. use serde_json::json; @@ -19,13 +20,19 @@ fn app(other: &str, caps_lock: bool) -> PhotocraftApp { /// The radii of the circles `cursor` draws at `zoom`, and the OS cursor it asks for. fn drawn(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon) { + let (radii, icon, _) = drawn_with_others(app, zoom); + (radii, icon) +} + +/// As [`drawn`], plus how many shapes that are not circles it draws (the icon). +fn drawn_with_others(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon, usize) { let ctx = egui::Context::default(); ctx.begin_pass(egui::RawInput::default()); let painter = ctx.layer_painter(egui::LayerId::background()); let icon = super::cursor(app, &painter, egui::pos2(100.0, 100.0), zoom); let mut out = ctx.end_pass(); out.textures_delta.clear(); - let radii = out + let radii: Vec = out .shapes .iter() .filter_map(|c| match &c.shape { @@ -33,7 +40,8 @@ fn drawn(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon) { _ => None, }) .collect(); - (radii, icon) + let others = out.shapes.len() - radii.len(); + (radii, icon, others) } #[test] @@ -47,13 +55,20 @@ fn caps_lock_on_standard_draws_the_width_circle_scaled_with_zoom() { } #[test] -fn caps_lock_on_precise_swaps_back_to_no_circle() { - let (radii, _) = drawn(&app("precise", true), 1.0); +fn caps_lock_on_precise_swaps_back_to_the_tool_icon() { + let (radii, icon, others) = drawn_with_others(&app("precise", true), 1.0); assert!(radii.is_empty(), "no width circle: {radii:?}"); + assert_eq!(icon, egui::CursorIcon::None, "the OS cursor hides behind the icon"); + assert!(others > 0, "the tool icon is drawn"); } #[test] fn without_caps_lock_the_preference_decides() { - assert!(drawn(&app("standard", false), 1.0).0.is_empty(), "Standard: no circle"); - assert!(!drawn(&app("precise", false), 1.0).0.is_empty(), "Precise: the width circle"); + let (radii, icon, others) = drawn_with_others(&app("standard", false), 1.0); + assert!(radii.is_empty(), "Standard: no circle"); + assert_eq!(icon, egui::CursorIcon::None, "Standard: the tool icon, not a crosshair"); + assert!(others > 0, "Standard: the tool icon is drawn"); + let (radii, icon) = drawn(&app("precise", false), 1.0); + assert!(!radii.is_empty(), "Precise: the width circle"); + assert_eq!(icon, egui::CursorIcon::Crosshair, "Precise: with the crosshair"); } From 25d6041ab52d849fca1f3dd12cf2eb63c1cff45f Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 8 Nov 2026 22:53:30 +0100 Subject: [PATCH 26/30] fix(algo): partly transparent colours keep the per-channel limit (#11995) The spread was measured on opaque colours only, and the issue keeps today's behaviour for partly transparent ones, in the match and in the anti-alias fringe. --- crates/algo/src/selection.rs | 7 ++++--- .../magic_eraser_tolerance_tests.rs | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 60c9f28c8a2..c91a2611de5 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -305,7 +305,8 @@ pub enum ColorDistance { /// The largest difference in any one of R, G and B. LargestChannel, /// The spread of `{0, dR, dG, dB}`: changes in the same direction count once, opposite - /// changes add up. + /// changes add up. Only opaque colours were measured, so a partly transparent seed or pixel + /// uses [`Self::LargestChannel`]. Spread, } @@ -313,8 +314,8 @@ impl ColorDistance { fn rgb(self, p: [u8; 4], seed: [u8; 4]) -> i32 { let d = [0, 1, 2].map(|c| p[c] as i32 - seed[c] as i32); match self { - Self::LargestChannel => d.iter().fold(0, |m, v| m.max(v.abs())), - Self::Spread => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)), + Self::Spread if p[3] == 255 && seed[3] == 255 => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)), + Self::LargestChannel | Self::Spread => d.iter().fold(0, |m, v| m.max(v.abs())), } } } diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs index 27f4d5ec6a2..0b93c36895d 100644 --- a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs @@ -216,3 +216,23 @@ fn the_spread_keeps_the_transparent_and_alpha_handling() { let region = run(half, 30.0); assert_eq!((region.at(1, 0), region.at(2, 0)), (0.0, 1.0), "alpha differences stay limited by the Tolerance"); } + +/// The spread was measured on opaque colours only: a partly transparent seed or pixel keeps the +/// per-channel limit, in the match and in the anti-alias fringe. +#[test] +fn partly_transparent_colours_keep_the_per_channel_limit() { + let area = Rect::new(0, 0, 3, 1); + let run = |img: &[[u8; 4]; 3], distance, anti_alias| sel::wand_region_by(img, area, (0, 0), 30.0, false, anti_alias, None, distance).unwrap(); + + let opaque = [[100, 100, 100, 255], [130, 100, 70, 255], [9, 9, 9, 255]]; + assert_eq!(run(&opaque, sel::ColorDistance::Spread, false).at(1, 0), 0.0, "opaque colours use the spread"); + + for img in [ + [[100, 100, 100, 128], [130, 100, 70, 128], [160, 100, 40, 128]], + [[100, 100, 100, 255], [130, 100, 70, 250], [160, 100, 40, 250]], + [[100, 100, 100, 250], [130, 100, 70, 255], [160, 100, 40, 255]], + ] { + assert_eq!(run(&img, sel::ColorDistance::Spread, false).at(1, 0), 1.0, "{img:?}: every channel is within 30"); + assert_eq!(run(&img, sel::ColorDistance::Spread, true), run(&img, sel::ColorDistance::LargestChannel, true), "{img:?}: same fringe"); + } +} From f5821fa5814c37cd72cdf94e54ab9cfd388b13b1 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 8 Nov 2026 23:07:15 +0100 Subject: [PATCH 27/30] test(engine): check the partly transparent fringe is not empty (#11995) --- .../engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs index 0b93c36895d..43692825909 100644 --- a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs @@ -233,6 +233,7 @@ fn partly_transparent_colours_keep_the_per_channel_limit() { [[100, 100, 100, 250], [130, 100, 70, 255], [160, 100, 40, 255]], ] { assert_eq!(run(&img, sel::ColorDistance::Spread, false).at(1, 0), 1.0, "{img:?}: every channel is within 30"); + assert!(run(&img, sel::ColorDistance::Spread, true).at(2, 0) > 0.0, "{img:?}: the third pixel gets a fringe"); assert_eq!(run(&img, sel::ColorDistance::Spread, true), run(&img, sel::ColorDistance::LargestChannel, true), "{img:?}: same fringe"); } } From adaba2a34e67d315aabb397a2ccb4375263aeaf3 Mon Sep 17 00:00:00 2001 From: Kaedo17 <92620393+Kaedo17@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:45:29 +0800 Subject: [PATCH 28/30] style: split the glide-choice assignment for rustfmt cargo fmt --all -- --check on the merge commit flags only the glide_scroll_all assignment added by the conflict resolution: the merge produced it as one long line, and rustfmt wants the call on its own line. No behaviour change (cloutier, #9841). --- crates/ui-egui/src/canvas.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0c96401fa70..c6ff22853fe 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2228,7 +2228,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let scroll_source = crate::scroll_all_windows::source(app, idx); // A glide keeps the drag's choice after Space, Shift or the button is let go; a menu-dismissal // press is no pan, so it neither arms the glide nor moves the other views. - let glide_scroll_all = crate::scroll_all_windows::glide_choice(&ctx, flick_id.with("scroll-all"), hand_drag && !stroke_dismissal && !menu_dismiss_press, scroll_all); + let glide_scroll_all = + crate::scroll_all_windows::glide_choice(&ctx, flick_id.with("scroll-all"), hand_drag && !stroke_dismissal && !menu_dismiss_press, scroll_all); if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_drag && !stroke_dismissal && !menu_dismiss_press, response.drag_delta(), flick_on) { let d = xf.unmap_vec(d) / (view.zoom / ppp); let before = view.center; From 51bf4680074a55dae06eda7ab9b88666a503e36e Mon Sep 17 00:00:00 2001 From: Kaedo17 <92620393+Kaedo17@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:16:50 +0800 Subject: [PATCH 29/30] contributors: keep davidvhk's name-sync setting in the table The earlier people.toml merge resolution inserted the new [people.Kaedo17] header between [people.davidvhk]'s real_name and its sync_github_name = true, so TOML parsed that setting as Kaedo17's and davidvhk silently lost theirs. Restore davidvhk's setting and keep Kaedo17 as its own block with its own sync_github_name = true (FredApps, #9841). Parsing base 9394960e4 and this tree side by side: the only difference is the added [people.Kaedo17] entry; every existing entry is unchanged. --- contributors/people.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 643c08f5440..81f432e436b 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -314,6 +314,8 @@ sync_github_name = false [people.davidvhk] real_name = "David Vanhoucke" +sync_github_name = true + [people.Kaedo17] sync_github_name = true From 248f65d577be6ce635233c221ac83138f7dc38e2 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:27:26 +0300 Subject: [PATCH 30/30] fix(ui): Shift plus a digit sets the Pencil's Opacity (#11967) --- crates/ui-egui/src/input/opacity_keys.rs | 6 +- crates/ui-egui/src/lib.rs | 4 + .../src/pencil_shift_digit_opacity_tests.rs | 81 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 55044a26f13..6ccda869952 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -1,6 +1,7 @@ //! Number keys set opacity (#352): 1 = 10% … 9 = 90%, 0 = 100%; two digits //! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush and the Pencil, #11812). With the Brush, Pencil or -//! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their +//! Eraser they set the brush's Opacity (⇧: Flow, swapped while airbrush build-up is on; the Pencil has no Flow, so its ⇧ +//! digits set Opacity too, #11967); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the //! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose //! number is a strength or exposure are left alone. @@ -110,7 +111,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { let build_up = app.session.tools.brush.build_up && !crate::eraser_ui::pencil_mode(app, tool) && !crate::eraser_ui::block_mode(app, tool); let shift = shift ^ (build_up && matches!(target(tool), Target::Brush { flow: true })); match (target(app.ui.tool), shift) { - (Target::Brush { .. }, false) => { + // The Pencil has no Flow: its ⇧ digits set Opacity like the plain ones (#11967). + (Target::Brush { flow: false }, _) | (Target::Brush { flow: true }, false) => { // The painting tools' Opacity fields (and `tools.setBrush`) start at 1%, so `00` sets the // 1% they actually paint with rather than a 0% they can't do. The Brush's and the // Pencil's `00` is 100%, as in Photoshop (#11812); only `00` gives 0 here. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b0bd483297..4b6b238fb7a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1037,6 +1037,10 @@ mod artboard_options_bar_tests; mod background_eraser_bar_angle_tests; #[cfg(test)] mod brush_opacity_minimum_tests; + +#[cfg(test)] +mod pencil_shift_digit_opacity_tests; + #[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs b/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs new file mode 100644 index 00000000000..060133d612a --- /dev/null +++ b/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs @@ -0,0 +1,81 @@ +//! #11967: the Pencil has no Flow, so ⇧ plus a digit sets its Opacity as a plain digit does +//! (⇧3 = 30%, ⇧0 = 100%, two quick ⇧ digits an exact value). The Brush's ⇧ digits still set Flow, +//! swapped with Opacity while airbrush build-up is on. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +/// The brush settings' (opacity, flow) in percent. +fn brush(app: &PhotocraftApp) -> (f32, f32) { + let b = &app.session.tools.brush; + ((b.opacity * 100.0).round(), (b.flow * 100.0).round()) +} + +#[test] +fn shift_digits_set_the_pencils_opacity() { + let mut a = app(Tool::Pencil); + let flow = brush(&a).1; + press(&mut a, 3, true, 0.0); + assert_eq!(brush(&a), (30.0, flow), "⇧3"); + press(&mut a, 0, true, 5000.0); + assert_eq!(brush(&a), (100.0, flow), "⇧0"); + for d in 1..=9u8 { + press(&mut a, d, true, 10000.0 * f64::from(d)); + assert_eq!(brush(&a), (f32::from(d) * 10.0, flow), "⇧{d}"); + } +} + +#[test] +fn two_quick_shift_digits_set_an_exact_opacity() { + let mut a = app(Tool::Pencil); + press(&mut a, 4, true, 0.0); + press(&mut a, 5, true, 300.0); + assert_eq!(brush(&a).0, 45.0); + press(&mut a, 0, true, 5000.0); + press(&mut a, 7, true, 5300.0); + assert_eq!(brush(&a).0, 7.0); + // As a plain `00`, which is 100 % for the Pencil (#11812). Joined, typed slowly or with the + // second press ignored, ⇧0 ⇧0 ends at 100 % either way. + press(&mut a, 0, true, 10000.0); + press(&mut a, 0, true, 10300.0); + assert_eq!(brush(&a).0, 100.0); +} + +/// No digit, plain or ⇧, ever changes the Flow while the Pencil is active, build-up on or off. +#[test] +fn the_pencils_flow_stays_untouched() { + for build_up in [false, true] { + let mut a = app(Tool::Pencil); + a.run("tools.setBrush", json!({"brush": {"flow": 0.42}})).unwrap(); + a.session.tools.brush.build_up = build_up; + for (i, (d, shift)) in [(3, true), (6, false), (0, true), (8, false)].into_iter().enumerate() { + press(&mut a, d, shift, 10000.0 * i as f64); + assert_eq!(brush(&a).1, 42.0, "build-up {build_up}, digit {d}, ⇧ {shift}"); + assert_eq!(a.session.tools.brush.build_up, build_up, "the case under test holds"); + } + assert_eq!(brush(&a).0, 80.0, "build-up {build_up}: the last digit set the Opacity"); + } +} + +#[test] +fn the_brushs_shift_digits_still_set_flow() { + let mut a = app(Tool::Brush); + press(&mut a, 3, true, 0.0); + assert_eq!(brush(&a), (100.0, 30.0), "⇧3 is Flow"); + // With airbrush build-up the roles swap: ⇧ digits set Opacity, plain ones Flow. + a.session.tools.brush.build_up = true; + press(&mut a, 6, true, 5000.0); + press(&mut a, 2, false, 10000.0); + assert_eq!(brush(&a), (60.0, 20.0)); +}