diff --git a/contributors/people.toml b/contributors/people.toml index 5995994db31..81f432e436b 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -316,6 +316,9 @@ sync_github_name = false real_name = "David Vanhoucke" sync_github_name = true +[people.Kaedo17] +sync_github_name = true + [people.rmsff] real_name = "Serikov Roman" sync_github_name = false 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..c7158bd7438 --- /dev/null +++ b/crates/algo/src/average/tests.rs @@ -0,0 +1,59 @@ +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); +} + +#[test] +fn soft_selection_weights_the_mean_and_output_mix() { + let bounds = Rect::new(0, 0, 2, 1); + for sample in SampleType::ALL { + 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::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 + // toward it using its own coverage, independently of its original alpha. + for (i, expected) in [[0.8, 0.0, 0.2], [0.2, 0.0, 0.8]].iter().enumerate() { + let pixel = out.pixel(i as i32, 0); + for (actual, expected) in pixel.iter().zip(expected) { + assert!((actual - expected).abs() <= 1.0 / 255.0, "{sample:?}: {pixel:?}"); + } + assert_eq!(pixel[3], before[i * 4 + 3]); + } + } +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index ad72954a22d..d1c797b228c 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -21,6 +21,7 @@ pub mod art_history; mod artistic; mod artistic_fx; +mod average; mod blur; mod blur2; pub mod camera_raw; @@ -208,6 +209,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, @@ -592,7 +595,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 { .. } @@ -634,14 +638,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", @@ -766,6 +772,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), @@ -1141,6 +1148,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/algo/src/selection.rs b/crates/algo/src/selection.rs index 0d8866e18ef..c91a2611de5 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -299,6 +299,27 @@ 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. Only opaque colours were measured, so a partly transparent seed or pixel + /// uses [`Self::LargestChannel`]. + 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::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())), + } + } +} + /// 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 +339,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 +371,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 +450,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 b2a36fdd187..8e2b16b41eb 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -9,6 +9,7 @@ //! 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; @@ -106,7 +107,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; @@ -283,6 +287,8 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_tolerance_tests; #[cfg(test)] mod tests; #[cfg(test)] 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..43692825909 --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs @@ -0,0 +1,239 @@ +//! #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"); +} + +/// 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!(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"); + } +} diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index da5bc746b4a..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; @@ -275,27 +271,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, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64); - for (p, &k) in px.iter().zip(cover) { - let w = (p[3] * 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); - }) -} - // ---------- transform presets ---------- /// The presets' params: like Free Transform, they follow the Channels and Layers panel target. @@ -1119,7 +1094,6 @@ pub fn specs() -> Vec { has_layer, show_only ), - spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average), ] } diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 3543a012b44..ba0140504e4 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| { @@ -65,6 +69,18 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() { let case = format!("{cmd} on {target} at {depth}"); assert_eq!(layer1, layer0, "{case}: the layer is untouched"); assert_ne!(target1, target0, "{case}: the target changed"); + if cmd == "filter.blur.average" { + // The equal-sized halves contribute equally, using their stored sample values. + let mean = (f64::from(target0[0]) + f64::from(target0[20])) / 2.0; + let tolerance = match depth { + 8 => 1.0 / 255.0, + 16 => 1.0 / 65535.0, + _ => 1e-6, + }; + for value in &target1 { + assert!((f64::from(*value) - mean).abs() <= tolerance, "{case}: {value}, expected {mean}"); + } + } assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}"); s.undo(); assert_eq!(read(&s).1, target0, "{case}: undo restores the target"); @@ -556,6 +572,52 @@ fn clouds_in_a_selection_are_the_canvas_clouds() { } } +#[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": 15, "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..25).contains(&x) { + assert!((p[0] - 2.0 / 3.0).abs() < 0.003 && (p[2] - 1.0 / 3.0).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/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index d2fcd10064e..7c9e28a64d4 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) }, @@ -471,6 +472,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 da816353d56..c658dd01ac9 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 b53745ab2e9..33e9e9e7cf7 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -28,6 +28,7 @@ mod atn_stroke_width; mod atn_type_path; mod atn_v12; mod atn_video_frames; +mod average_smart; mod background_and_mask_depth; mod background_layer_consistency; mod brush_smoothing; 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..cbd0c12a2c6 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -573,14 +573,68 @@ 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(); + // 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. #[test] fn faux_bold_scales_with_glyph_scaling() { @@ -3343,7 +3397,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}"); } } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6ba31d2ac75..7744d7f7c55 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -63,8 +63,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, preview_locator_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, preview_locator_cursor, visible_crosshair}; pub(crate) use display::GPU_OUTPUT; use display::texture_key; pub(crate) use display::{cache_key, canvas_display, display_doc, display_image}; @@ -883,6 +885,7 @@ struct CanvasToolInput<'a> { hand_pan: bool, ppp: f32, under_dialog: bool, + menu_dismiss_press: bool, zoom_out: &'a dyn Fn(bool) -> bool, display_zoom: f32, } @@ -902,9 +905,22 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool); + if input.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; + } // 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 + && !input.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: @@ -913,6 +929,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: tool.is_type() || 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 + && !input.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) => Some((*pos, *modifiers)), @@ -932,6 +949,17 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: handle_canvas_tool_navigation(app, ui, view, input, &mut buttons); handle_canvas_tool_stroke(app, ui, input, mods, capture_press, tool_press, &mut buttons); handle_canvas_tool_clicks(app, ui, view, input, mods, tool_press, &buttons); + // 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; + } } fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_>, mods: egui::Modifiers, buttons: &mut crate::paint_mouse::Buttons) { @@ -958,8 +986,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); } @@ -1047,10 +1078,11 @@ fn handle_canvas_tool_navigation( (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 = !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); + let on_canvas = !input.menu_dismiss_press && !input.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, 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); @@ -1092,6 +1124,7 @@ fn handle_canvas_tool_stroke( let right_down = ui.input(|i| i.pointer.secondary_down()) || physical_right; if strokes_live(tool) && !right_down + && !input.menu_dismiss_press && app.drag.is_none() && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) @@ -1111,6 +1144,7 @@ fn handle_canvas_tool_stroke( buttons.started = false; } if buttons.started + && !input.menu_dismiss_press && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) { // A press the controls refused (the Background among the layers) goes nowhere else (#11101). @@ -1125,7 +1159,7 @@ fn handle_canvas_tool_stroke( // 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 !input.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 @@ -1183,7 +1217,7 @@ fn handle_canvas_tool_stroke( feed_live_stroke(app); crate::magnetic_lasso_ui::flush(app); } - if buttons.stopped { + if buttons.stopped && !input.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. @@ -1208,7 +1242,7 @@ fn handle_canvas_tool_stroke( } // 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 && !input.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 @@ -1241,66 +1275,17 @@ fn handle_canvas_tool_clicks( let ppp = input.ppp; let zoom_out = input.zoom_out; let display_zoom = input.display_zoom; - if buttons.clicked - && let Some(p) = response.interact_pointer_pos() + // 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 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) - } 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(view, xf, p, nz, center, ppp); - view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_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; - } - } - // A click the transform controls refused (the Background among the layers) goes - // nowhere else (#11101). - _ if tool == Tool::Move && app.ui.transform.is_none() && begin_transform_controls_at(app, ctx, xf, p) == ControlsPress::Refused => {} - _ => { - // 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); - } - } - } - // A Frame drag uses a temporary Free Transform for its image/both target. That owns - // the release, so the generic tool-click gate can be false even for a double click. - if tool == Tool::Frame - && response.contains_pointer() - && ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) - && let Some(p) = response.interact_pointer_pos().or_else(|| ctx.pointer_hover_pos()) - { - crate::frame_tool::double_click(app, xf.to_doc(p)); - } - // 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)) { @@ -1310,17 +1295,87 @@ fn handle_canvas_tool_clicks( 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). - if tool == Tool::Move - && app.ui.tool == Tool::Move - && app.ui.transform.is_none() - && response.double_clicked() + if buttons.clicked && let Some(p) = response.interact_pointer_pos() { - let d = xf.to_doc(p); - crate::type_tool::edit_at(app, d[0], d[1]); + // If an outside press dismissed the canvas tool menu, consume this release click + // so it doesn't also trigger a tool action (Photoshop behavior). A click outside a + // still-open menu dismisses it and is consumed the same way (CodeRabbit, #9841). + 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) + && !menu_rect.contains(p) + { + // The click is outside the open menu: it dismisses the menu, no 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) + } 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(view, xf, p, nz, center, ppp); + view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_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; + } + } + // A click the transform controls refused (the Background among the layers) goes + // nowhere else (#11101). + _ if tool == Tool::Move && app.ui.transform.is_none() && begin_transform_controls_at(app, ctx, xf, p) == ControlsPress::Refused => {} + _ => { + // 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); + } + } + } + // 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). + if tool == Tool::Move + && app.ui.tool == Tool::Move + && app.ui.transform.is_none() + && response.double_clicked() + && let Some(p) = response.interact_pointer_pos() + { + let d = xf.to_doc(p); + crate::type_tool::edit_at(app, d[0], d[1]); + } + } + + // A Frame drag uses a temporary Free Transform for its image/both target. That owns + // the release, so the generic tool-click gate can be false even for a double click. + if tool == Tool::Frame + && response.contains_pointer() + && ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) + && let Some(p) = response.interact_pointer_pos().or_else(|| ctx.pointer_hover_pos()) + { + crate::frame_tool::double_click(app, xf.to_doc(p)); } // A double-click commits an open Free Transform only on the box (handles included); outside // it does nothing (#11100). @@ -2138,6 +2193,15 @@ 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))); // The Hand pans with a drag of any button, but the selected Hand's right button is its view // menu, as in Photoshop: a drag with that button alone is a right-click that moved, which // opens the menu instead, until it strays past a right-click's reach and pans after all @@ -2164,9 +2228,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // other shown views follow this one. let scroll_all = hand_pan && crate::scroll_all_windows::active(app, crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).shift); 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. - let glide_scroll_all = crate::scroll_all_windows::glide_choice(&ctx, flick_id.with("scroll-all"), hand_drag && !stroke_dismissal, scroll_all); - if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_drag && !stroke_dismissal, response.drag_delta(), flick_on) { + // 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); + 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; if d.is_finite() { @@ -2184,7 +2250,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } // A scroll or zoom while the right button is held moves the image under its press: no click. crate::paint_mouse::track_right_press_view(&response, &view, flip); - if hand_drag && !stroke_dismissal { + if hand_drag && !stroke_dismissal && !menu_dismiss_press { let d = xf.unmap_vec(response.drag_delta()) / (view.zoom / ppp); let before = view.center; view.center[0] -= d.x; @@ -2209,6 +2275,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: hand_pan, ppp, under_dialog, + menu_dismiss_press, zoom_out: &zoom_out, display_zoom: display_view.zoom, }; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 6e8b5b2d6c2..30a627846cb 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1312,9 +1312,25 @@ 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; + // 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()); } } +/// 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/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 41c5c72f9d0..920767cb446 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -550,6 +550,143 @@ 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"); +} + +/// #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_view_centre() { let mut app = zoom_app(400, 300); diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index dc037f5d01a..44de2ec9501 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -121,7 +121,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/dialogs/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs index b08fb22247c..9871bf08653 100644 --- a/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/crates/ui-egui/src/dialogs/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. @@ -180,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; } @@ -269,11 +277,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 +315,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 +348,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 +367,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 +410,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 +426,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 +447,26 @@ 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(", "))); } }; + // 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); + } apply(app, ctx, doc, answer); Ok(json!({"open": app.discard.is_some(), "fileDialog": app.file_dialog_open()})) } diff --git a/crates/ui-egui/src/dialogs/discard_ui/tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests.rs index 45558cf306f..5978a3f42a0 100644 --- a/crates/ui-egui/src/dialogs/discard_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/discard_ui/tests.rs @@ -238,17 +238,24 @@ fn drawn_order<'a>(h: &Prompted, labels: [&'a str; 3]) -> Vec<&'a str> { } /// 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 { @@ -301,6 +308,111 @@ fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() { } } +/// "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"); +} + +/// 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); + 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()); +} + +/// 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); + 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/crates/ui-egui/src/dialogs/rasterize_prompt.rs b/crates/ui-egui/src/dialogs/rasterize_prompt.rs index fc9018516df..423ced45ebe 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"; @@ -115,7 +114,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())); @@ -201,7 +200,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")?; @@ -209,21 +208,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..b270f31ec15 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 { @@ -46,8 +46,10 @@ 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_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 +61,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"); @@ -127,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); @@ -141,13 +149,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/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)); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5b793318190..9d07bf8fce2 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -342,6 +342,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, @@ -595,6 +599,7 @@ impl Default for UiState { color_hud: None, layer_menu: None, canvas_tool_menu: None, + canvas_tool_menu_dismissed: false, selected_guide: None, brush_tool: Tool::Brush, tool_brushes: Vec::new(), 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"); +} diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index f669f61368c..d7884b3799c 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -483,16 +483,23 @@ 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. +/// 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 app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - 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 } #[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..297a71b1744 --- /dev/null +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs @@ -0,0 +1,74 @@ +//! 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 is the tool's icon, as with +//! Standard alone. + +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 (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: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Circle(c) => Some(c.radius), + _ => None, + }) + .collect(); + let others = out.shapes.len() - radii.len(); + (radii, icon, others) +} + +#[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_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() { + 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"); +} 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 b5e41a5e1b7..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,6 +418,44 @@ 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. 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); + // 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 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] fn on_the_canvas_a_double_click_closes_the_border() { let mut h = harness(); 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 9875916d724..a64683558e0 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 @@ -324,6 +376,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { #[path = "perspective_crop_bar_buttons_tests.rs"] mod perspective_crop_bar_buttons_tests; +#[cfg(test)] +#[path = "perspective_crop_shield_tests.rs"] +mod perspective_crop_shield_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/docs/average-filter.md b/docs/average-filter.md new file mode 100644 index 00000000000..65e91a84337 --- /dev/null +++ b/docs/average-filter.md @@ -0,0 +1,74 @@ +# 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 +``` + +## 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/control-protocol.md b/docs/control-protocol.md index 7ebf31bbe90..ad8d63ab6de 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -73,7 +73,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `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. @@ -83,7 +83,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - 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"]`). - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. - 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 keep the view centre with the non-temporary Zoom tool and Zoom Clicked Point to Center off; other cases retain their pressed-point behaviour; `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. For a painting tool's Shift+right-click, see the Mode menu exception below. 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/gaps.md b/docs/gaps.md index 7a038cf6cf1..65ef3715f22 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-11-07 · **Change:** minor (G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; 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; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; 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; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **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 @@ -41,6 +41,7 @@ what an agent can't finish alone. ### G1. PSD fidelity and Photoshop acceptance - **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`). Malformed descriptors stay verbatim. Other unsupported gallery effects remain opaque on import or produce an export warning. +- **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 @@ -513,6 +514,8 @@ what an agent can't finish alone. | 2026-10-23 | minor | G10: Amiga IFF write landed (24-plane ILBM, Save As `.iff`) and 24-plane ILBMs open | | 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | G11: document offsets use opening order despite tab reordering; lifecycle and `.atn` playback regressions; behavioral source evidence, no new live Photoshop reproduction | +| 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-19 | minor | G5: Free Transform of several selected layers (#6501): one box moves them all; no estimate changed | | 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/scorecard.md b/docs/scorecard.md index 09b5e7b77dc..ffd56334c9d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -165,7 +165,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/docs/target-app-parity.md b/docs/target-app-parity.md index a90defabed0..6eb431f3d4b 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-11-08 · **Change:** trivial (languages are measured with `cargo xtask i18n-report` over the craft-i18n catalogs; previously minor: RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; 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; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** trivial (languages are measured with `cargo xtask i18n-report` over the craft-i18n catalogs; previously minor: Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; 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; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; 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. @@ -607,6 +612,8 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | +| 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-22 | minor | Print: Japanese paper sizes (はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切) in the Print dialog, `file.print` and the PDF page, by their customary names; no percentage changed | | 2026-10-21 | minor | #8304: compound layer properties export as separate Set events, rename last; independent Photoshop replay pending; percentages and estimates unchanged | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 90f63a0f412..376f05418a4 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"