diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6b028524c1..c0cef67a5e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -17,6 +17,7 @@ next to them. | `assets/icons/{arrow-left-right,circle-dashed,ellipsis,file-plus,folder-plus,grid-2x2,house,link-2,message-square,panel-left,pipette,rectangle-horizontal,rectangle-vertical,redo-2,square-dashed,square-dashed-mouse-pointer,triangle-alert,type,x}.svg` | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{link-2,type,x}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 | +| `assets/icons/gradient-tool.svg` | Gradient tool glyph with a horizontal opacity ramp | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/type-vertical.svg` | Vertical Type tool glyph: Lucide `type`'s T, drawn narrower to make room for a downward arrow of our own at its left | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from `icons/type.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -27,6 +28,7 @@ next to them. | `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) | | `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 | | `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code | +| `crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs` | Built-in Black & White tonal and filter mixes | PhotoCraft contributors (@Bobderto) | Original weights chosen to produce the named tonal and color-filter effects, from [PhotoCraft `2b1afe637`](https://github.com/storytold/photocraft/commit/2b1afe637cabe3eba622c8edd3e92b279aa8dfe4) | MIT OR Apache-2.0 | | `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) | | `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, (its colour schemes are LGPL-2.0-or-later) | Original work | | `crates/ui-egui/src/theme.rs` (Soft Dark and Soft Light themes) | Original colour values and radii for two low-contrast themes on PhotoCraft's Studio layout; no third-party palette, file or code is used | PhotoCraft contributors | Original | Original work | diff --git a/Cargo.lock b/Cargo.lock index 271ff15964..467b509d34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7103,6 +7103,7 @@ version = "0.23.1" dependencies = [ "base64 0.23.1", "chrono", + "core-graphics", "craft", "craft-file-formats", "craft-i18n", @@ -7141,6 +7142,7 @@ dependencies = [ "toml", "web-time", "winsafe", + "x11rb", ] [[package]] diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 045c31def3..12817dcb2d 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -101,8 +101,8 @@ fn recovery_dir() -> Option { } /// Write `bytes` crash-safely (temp file beside the target, fsync, rename, directory fsync; see -/// [`photocraft_format::atomic`]). Every document write (Save, Save As, Export, Save for Web) and -/// the preferences go through here, so a failed or interrupted save never destroys the old file. +/// [`photocraft_format::atomic`]). Save, Save As, overwriting exports and preferences use this so +/// a failed or interrupted write never destroys the old file. fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string()) } @@ -602,6 +602,7 @@ pub fn native(automation: Option, wa file_panels: Some(file_panels), settings: Some(settings_store()), write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))), + write_new: Some(Box::new(|path, bytes| photocraft_format::write_noreplace(Path::new(path), bytes).map_err(|e| format!("{path}: {e}")))), file_stamp: Some(Box::new(|path: &str| { // Follows a symlink, as Save writes through it to the file it points at. let meta = std::fs::metadata(path).ok()?; diff --git a/assets/icons/gradient-tool.svg b/assets/icons/gradient-tool.svg new file mode 100644 index 0000000000..94516fd712 --- /dev/null +++ b/assets/icons/gradient-tool.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs index 9a15d55b25..e851db8188 100644 --- a/crates/algo/src/artistic_fx.rs +++ b/crates/algo/src/artistic_fx.rs @@ -1168,7 +1168,8 @@ fn apply_sketch(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool { let mut l = win.lum(); blur1(&mut l, w, h, 0.3 + g("smoothness") * 0.3); for i in 0..win.c.len() { - win.c[i] = mix(bg, fg, smoothstep(bal + 0.02, bal - 0.02, l[i])); + // Smooth the shapes without introducing colors between the ink and paper. + win.c[i] = if l[i] < bal { fg } else { bg }; } } F::TornEdges => { diff --git a/crates/algo/src/gradient_hard_mix_rounded_source_tests.rs b/crates/algo/src/gradient_hard_mix_rounded_source_tests.rs new file mode 100644 index 0000000000..b36237d42e --- /dev/null +++ b/crates/algo/src/gradient_hard_mix_rounded_source_tests.rs @@ -0,0 +1,61 @@ +use photocraft_color::{PixelFormat, blend, dither_noise}; +use photocraft_raster::Surface; + +use super::{BlendMode, FillMode, GradientShape, Rect, paint_gradient, sample_stops, tool_gradient_t}; + +const WIDTH: i32 = 2560; +const STOPS: [(f32, [f32; 4]); 2] = [(0.0, [0.0, 0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 1.0, 1.0])]; + +fn row(format: PixelFormat, base: u8, mode: BlendMode, dither: bool) -> Surface { + let mut surface = Surface::new(format); + let area = Rect::new(0, 0, WIDTH, 1); + let gray = f32::from(base) / 255.0; + surface.fill_rect(area, &[gray, gray, gray, 1.0]); + paint_gradient(&mut surface, area, (0.0, 0.0), (WIDTH as f32, 0.0), GradientShape::Linear, &STOPS, false, 1.0, FillMode::Blend(mode), dither, None, false); + surface +} + +#[test] +fn gradient_hard_mix_switches_at_the_normal_ramp_byte_boundary() { + let normal = row(PixelFormat::RGBA8, 0, BlendMode::Normal, false); + for (base, first_white) in [(128, 127), (100, 156)] { + let hard_mix = row(PixelFormat::RGBA8, base, BlendMode::HardMix, false); + let mut saw = [0usize; 2]; + for x in 0..WIDTH { + let normal_level = (normal.pixel(x, 0)[0] * 255.0).round() as u8; + let white = normal_level >= first_white; + assert_eq!(hard_mix.pixel(x, 0)[0], f32::from(u8::from(white)), "base {base}, x={x}, normal {normal_level}"); + if normal_level == first_white - 1 || normal_level == first_white { + saw[usize::from(white)] += 1; + } + } + assert!(saw.into_iter().all(|pixels| pixels > 1), "both tested colour runs have more than one pixel"); + } +} + +#[test] +fn dithering_deep_rgb_and_other_modes_keep_the_existing_float_composite() { + for (format, mode, dither) in [ + (PixelFormat::RGBA8, BlendMode::HardMix, true), + (PixelFormat::RGBA16, BlendMode::HardMix, false), + (PixelFormat::RGBA32F, BlendMode::HardMix, false), + (PixelFormat::RGBA8, BlendMode::Multiply, false), + ] { + let actual = row(format, 100, mode, dither); + let mut expected = Surface::new(format); + expected.write_pixel(0, 0, &[100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 1.0]); + let base = expected.rgba(0, 0); + for x in 0..WIDTH { + let t = tool_gradient_t(GradientShape::Linear, (0.0, 0.0), (WIDTH as f32, 0.0), x as f32 - 0.5, -0.5); + let mut color = sample_stops(&STOPS, t); + if dither { + let noise = (dither_noise(x, 0) - 0.5) / 255.0; + for channel in &mut color[..3] { + *channel = (*channel + noise).clamp(0.0, 1.0); + } + } + expected.write_pixel(x, 0, &blend::composite(mode, base, color, 1.0)); + assert_eq!(actual.pixel(x, 0), expected.pixel(x, 0), "{format:?} {mode:?}, dither={dither}, x={x}"); + } + } +} diff --git a/crates/algo/src/gradient_hard_mix_tie_tests.rs b/crates/algo/src/gradient_hard_mix_tie_tests.rs new file mode 100644 index 0000000000..b17295c854 --- /dev/null +++ b/crates/algo/src/gradient_hard_mix_tie_tests.rs @@ -0,0 +1,73 @@ +use std::cmp::Ordering; + +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +use super::{BlendMode, FillMode, GradientShape, Rect, paint_gradient}; + +#[test] +fn gradient_hard_mix_matches_all_u8_pairs_and_uses_each_rgb_channel() { + let mut surface = Surface::new(PixelFormat::RGBA8); + for base in 0..256 { + let gray = base as f32 / 255.0; + surface.fill_rect(Rect::new(0, base, 256, base + 1), &[gray, gray, gray, 1.0]); + } + let blue = 200.0 / 255.0; + paint_gradient( + &mut surface, + Rect::new(0, 0, 256, 256), + (-0.5, 0.0), + (254.5, 0.0), + GradientShape::Linear, + &[(0.0, [0.0, 1.0, blue, 1.0]), (1.0, [1.0, 0.0, blue, 1.0])], + false, + 1.0, + FillMode::Blend(BlendMode::HardMix), + false, + None, + false, + ); + for base in 0..256 { + for source in 0..256 { + let expected = [source, 255 - source, 200].map(|channel| match (base + channel).cmp(&255) { + Ordering::Less => 0.0, + Ordering::Greater => 1.0, + Ordering::Equal => f32::from(u8::from(channel < 128)), + }); + let actual = surface.pixel(source, base); + assert_eq!(actual[..3], expected, "base {base}, red source {source}"); + assert_eq!(actual[3], 1.0); + } + } +} + +#[test] +fn gradient_hard_mix_preserves_source_over_and_locked_alpha() { + for locked in [false, true] { + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.write_pixel(1, 0, &[127.0 / 255.0, 127.0 / 255.0, 127.0 / 255.0, 128.0 / 255.0]); + let color = [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]; + paint_gradient( + &mut surface, + Rect::new(0, 0, 2, 1), + (0.0, 0.0), + (1.0, 0.0), + GradientShape::Linear, + &[(0.0, color), (1.0, color)], + false, + 0.5, + FillMode::Blend(BlendMode::HardMix), + false, + None, + locked, + ); + let byte = |x, channel: usize| (surface.pixel(x, 0)[channel] * 255.0).round() as u8; + if locked { + assert_eq!(byte(0, 3), 0); + assert_eq!((byte(1, 0), byte(1, 3)), (64, 128)); + } else { + assert_eq!((byte(0, 0), byte(0, 3)), (128, 128)); + assert_eq!((byte(1, 0), byte(1, 3)), (85, 192)); + } + } +} diff --git a/crates/algo/src/noise.rs b/crates/algo/src/noise.rs index aa6f56673c..62cccc7b05 100644 --- a/crates/algo/src/noise.rs +++ b/crates/algo/src/noise.rs @@ -32,18 +32,24 @@ pub(crate) fn add(src: &Image, out: Rect, ctx: &Ctx, amount: f32, dist: Distribu continue; } let (x, y) = (out.x0 + (i % w) as i32, out.y0 + (i / w) as i32); - for (c, pv) in px.iter_mut().enumerate().take(cc) { - let ch = if mono { 0 } else { c as u32 }; - let v = match dist { - Distribution::Uniform => (hash01(x, y, ch, seed) - 0.5) * 2.0 * a, - Distribution::Gaussian => { - let u1 = hash01(x, y, ch * 2 + 101, seed).max(1e-7); - let u2 = hash01(x, y, ch * 2 + 102, seed); - (-2.0 * u1.ln()).sqrt() * (std::f32::consts::TAU * u2).cos() * a * 0.5 - } - }; - // Integer storage clamps on write; float surfaces keep the value. - *pv += v; + let value = |ch| match dist { + Distribution::Uniform => (hash01(x, y, ch, seed) - 0.5) * 2.0 * a, + Distribution::Gaussian => { + let u1 = hash01(x, y, ch * 2 + 101, seed).max(1e-7); + let u2 = hash01(x, y, ch * 2 + 102, seed); + (-2.0 * u1.ln()).sqrt() * (std::f32::consts::TAU * u2).cos() * a * 0.5 + } + }; + // Integer storage clamps on write; float surfaces keep the value. + if mono { + let v = value(0); + for pv in px.iter_mut().take(cc) { + *pv += v; + } + } else { + for (c, pv) in px.iter_mut().enumerate().take(cc) { + *pv += value(c as u32); + } } } res diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 39e4770117..31bfc386da 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -78,6 +78,7 @@ fn composite_area( mode: FillMode, coverage: impl Fn(i32, i32) -> f32 + Sync, color: impl Fn(i32, i32) -> [f32; 4] + Sync, + blend_pixel: impl Fn(BlendMode, [f32; 4], [f32; 4], f32, bool) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, @@ -123,8 +124,7 @@ fn composite_area( continue; } let o = match mode { - FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), + FillMode::Blend(m) => blend_pixel(m, d, color(x, y), k, lock_transparency), // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], @@ -157,6 +157,10 @@ fn composite_area( } } +fn composite_blend(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], coverage: f32, lock_transparency: bool) -> [f32; 4] { + if lock_transparency { blend::composite_atop(mode, backdrop, source, coverage) } else { blend::composite(mode, backdrop, source, coverage) } +} + /// [`FillMode::Behind`] for one pixel: `src` laid under `d` at coverage `k`, with the Brush's /// Behind formula (`photocraft_paint`'s render): the fill's share is `src α × k × (1 − d α)`. fn behind(d: [f32; 4], src: [f32; 4], k: f32) -> [f32; 4] { @@ -194,6 +198,10 @@ pub fn paint_gradient( let smooth_16 = fmt.sample == photocraft_color::SampleType::U16 && matches!(fmt.mode, photocraft_color::ColorMode::Rgb | photocraft_color::ColorMode::Grayscale); let dither = dither && !smooth_16; + let hard_mix_rgb8 = mode == FillMode::Blend(BlendMode::HardMix) + && fmt.mode == photocraft_color::ColorMode::Rgb + && fmt.sample == photocraft_color::SampleType::U8 + && !dither; composite_area( s, area, @@ -212,12 +220,35 @@ pub fn paint_gradient( } c }, + |mode, backdrop, source, coverage, locked| { + if hard_mix_rgb8 { + composite_hard_mix_gradient(backdrop, source, coverage, locked) + } else { + composite_blend(mode, backdrop, source, coverage, locked) + } + }, lock_transparency, None, None, ); } +fn composite_hard_mix_gradient(backdrop: [f32; 4], mut source: [f32; 4], coverage: f32, locked: bool) -> [f32; 4] { + // Round the comparison exactly as a Normal RGB8 gradient would store it. Equal sums + // take white for a dark source and black for a light source. + let quantize = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u16; + let blend_weight = if locked { 1.0 } else { backdrop[3] }; + for (color, base) in source[..3].iter_mut().zip(&backdrop[..3]) { + let s = quantize(*color); + let sum = quantize(*base) + s; + let mixed = if sum > 255 || (sum == 255 && s <= 127) { 1.0 } else { 0.0 }; + // In source-over, only the overlap uses the blend. The uncovered part keeps the + // unblended gradient colour. Normal then applies the existing coverage and alpha math. + *color = (1.0 - blend_weight) * *color + blend_weight * mixed; + } + composite_blend(BlendMode::Normal, backdrop, source, coverage, locked) +} + /// Paint bucket: fills the region similar to the seed pixel (on the layer's /// own pixels) within `area`, respecting the selection. #[allow(clippy::too_many_arguments)] @@ -352,7 +383,7 @@ fn fill_region( if hit == Some(&true) { strength(x, y) } else { 0.0 } }; let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None }; - composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, composite_blend, lock_transparency, inks, rim); } /// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its @@ -378,6 +409,14 @@ mod gradient_dither_16bit_tests; #[path = "paint_gradient_sample_tests.rs"] mod paint_gradient_sample_tests; +#[cfg(test)] +#[path = "gradient_hard_mix_tie_tests.rs"] +mod gradient_hard_mix_tie_tests; + +#[cfg(test)] +#[path = "gradient_hard_mix_rounded_source_tests.rs"] +mod gradient_hard_mix_rounded_source_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/algo/src/relight.rs b/crates/algo/src/relight.rs index d36454d238..efa96684e8 100644 --- a/crates/algo/src/relight.rs +++ b/crates/algo/src/relight.rs @@ -532,9 +532,21 @@ mod tests { assert!(read_radius(sigma(25.0, bounds)) > 97); let area = output_area(&p, s.content_bounds(), bounds, None); let full = apply_tiled(&s, &p, area, bounds, None, 4096, None); - let tiled = apply_tiled(&s, &p, area, bounds, None, 128, None); - let inner = Rect::new(0, 0, size, size); - let d = max_diff(&full.read_region(inner), &tiled.read_region(inner)); + // Keep every tile that contributes checked pixels, including each edge tile's + // original rectangle and halo. The remaining tiles lie wholly outside the canvas. + let tile = 128; + let tile_start = |pixel: i32, origin: i32| origin + (pixel - origin).div_euclid(tile) * tile; + let visible_tiles = Rect::new( + tile_start(bounds.x0, area.x0), + tile_start(bounds.y0, area.y0), + tile_start(bounds.x1 - 1, area.x0) + tile, + tile_start(bounds.y1 - 1, area.y0) + tile, + ) + .intersect(&area); + let tiled = apply_tiled(&s, &p, visible_tiles, bounds, None, tile, None); + let center = size / 2; + assert!(max_diff(&full.pixel(center, center), &s.pixel(center, center)) > 1e-4, "the full frame must be relit"); + let d = max_diff(&full.read_region(bounds), &tiled.read_region(bounds)); assert!(d <= 1e-4, "tile seam {d}"); } diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index a2633844d8..78283f5c7b 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -110,6 +110,8 @@ fn all_filters() -> Vec { FilterParams::SmartSharpen { amount: 100.0, radius: 1.0, reduce_noise: 20.0 }, FilterParams::HighPass { radius: 3.0 }, FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Gaussian, monochromatic: false, seed: 3 }, + FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Uniform, monochromatic: true, seed: 3 }, + FilterParams::AddNoise { amount: 25.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 3 }, FilterParams::Median { radius: 2.0 }, FilterParams::DustAndScratches { radius: 2.0, threshold: 10.0 }, FilterParams::Minimum { radius: 1.0, preserve: Preserve::Squareness }, @@ -291,24 +293,49 @@ fn high_pass_of_flat_is_mid_gray() { assert!((p[0] - 0.5).abs() < 1e-5 && (p[1] - 0.5).abs() < 1e-5); } +/// Both noise distributions preserve alpha and share a seeded value across color channels. #[test] fn noise_is_deterministic_monochrome_and_centred() { - let s = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]); - let p = FilterParams::AddNoise { amount: 50.0, distribution: Distribution::Uniform, monochromatic: true, seed: 1 }; - let a = run(&s, &p); - assert_eq!(a, run(&s, &p)); - let v = a.read_region(R); - let mut mean = 0.0; - for px in v.as_chunks::<4>().0 { - assert_eq!(px[0], px[1]); - assert_eq!(px[1], px[2]); - assert!((px[0] - 0.5).abs() <= 0.25 + 1e-6); - mean += px[0]; + for distribution in [Distribution::Uniform, Distribution::Gaussian] { + let s = flat(SampleType::F32, R, [0.5, 0.5, 0.5, 1.0]); + let p = FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 1 }; + let a = run(&s, &p); + assert_eq!(a, run(&s, &p)); + let v = a.read_region(R); + let mut mean = 0.0; + for px in v.as_chunks::<4>().0 { + assert_eq!(px[0], px[1]); + assert_eq!(px[1], px[2]); + if matches!(distribution, Distribution::Uniform) { + assert!((px[0] - 0.5).abs() <= 0.25 + 1e-6); + } + assert_eq!(px[3], 1.0); + mean += px[0]; + } + mean /= (v.len() / 4) as f32; + assert!((mean - 0.5).abs() < 0.03, "{mean}"); + let other_seed = run(&s, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 2 }); + assert_ne!(a, other_seed); + } +} + +/// RGB8 goldens from 799e1296's original Add Noise, before monochrome sampling was hoisted. +#[test] +fn monochrome_noise_matches_original_rgb8_bytes() { + let area = Rect::new(0, 0, 3, 2); + let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false)); + source.fill_rect(area, &[0.5, 0.5, 0.5]); + let rgb_bytes = |surface: &Surface| surface.read_region(area).iter().map(|v| (v * 255.0).round() as u8).collect::>(); + let cases: [(Distribution, [u8; 18]); 2] = [ + (Distribution::Uniform, [65, 65, 65, 96, 96, 96, 134, 134, 134, 67, 67, 67, 86, 86, 86, 118, 118, 118]), + (Distribution::Gaussian, [105, 105, 105, 104, 104, 104, 117, 117, 117, 103, 103, 103, 167, 167, 167, 136, 136, 136]), + ]; + for (distribution, expected) in cases { + let monochrome = apply(&source, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: true, seed: 1 }, area, area, None); + assert_eq!(rgb_bytes(&monochrome).as_slice(), expected.as_slice(), "{distribution:?}"); + let colored = apply(&source, &FilterParams::AddNoise { amount: 50.0, distribution, monochromatic: false, seed: 1 }, area, area, None); + assert!(rgb_bytes(&colored).as_chunks::<3>().0.iter().any(|pixel| pixel[0] != pixel[1] || pixel[1] != pixel[2]), "{distribution:?}"); } - mean /= (v.len() / 4) as f32; - assert!((mean - 0.5).abs() < 0.03, "{mean}"); - let other_seed = run(&s, &FilterParams::AddNoise { amount: 50.0, distribution: Distribution::Uniform, monochromatic: true, seed: 2 }); - assert_ne!(a, other_seed); } #[test] diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 453446642c..78c317ad11 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -191,8 +191,8 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept } None => (0.0, 0.0, 0.0), }; - let sat = colorize_saturation((*saturation / 100.0 + ds).clamp(-1.0, 1.0), *lightness / 100.0, *colorize, depth); - let out = hue_saturation_in(c, *hue + dh, sat, (*lightness / 100.0).clamp(-1.0, 1.0), *colorize, depth); + let sat = colorize_saturation((*saturation / 100.0).clamp(-1.0, 1.0), *lightness / 100.0, *colorize, depth); + let out = hue_saturation_in(c, *hue + dh, sat, ds.clamp(-1.0, 1.0), (*lightness / 100.0).clamp(-1.0, 1.0), *colorize, depth); range_lightness(out, dl) }) } @@ -434,6 +434,9 @@ mod gradient_map_grayscale_tests; #[cfg(test)] mod tone_tests; +#[cfg(test)] +mod hue_saturation_range_multiply_tests; + /// Legacy Brightness/Contrast scales contrast around 128 of 255 (contrast 80 keeps 128 at 128, /// measured on Photoshop 27.11; a 0.5 pivot moved it to 130). pub const LEGACY_PIVOT: f32 = 128.0 / 255.0; diff --git a/crates/compose/src/adjust/color.rs b/crates/compose/src/adjust/color.rs index 94a57717ce..26f6d0bfc5 100644 --- a/crates/compose/src/adjust/color.rs +++ b/crates/compose/src/adjust/color.rs @@ -30,15 +30,18 @@ pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option /// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the /// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { - hue_saturation_in(c, hue, s, l, colorize, None) + hue_saturation_in(c, hue, s, 0.0, l, colorize, None) } /// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised /// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10 /// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by /// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop -/// corpus's rgb32 hue-saturation.psd is exact so. -pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { +/// corpus's rgb32 hue-saturation.psd is exact so. A colour range's saturation `range_s` scales +/// the pixel's saturation again after the master's, so their factors multiply: Master -50 with +/// Reds -50 leaves a quarter of red's saturation, (255, 0, 0) becomes (159, 95, 95) in the +/// reference application (#14741). Colorize ignores it, as ranges don't apply there. +pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, range_s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { let hdr = depth == Some(SampleType::F32); let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; if colorize { @@ -56,12 +59,13 @@ pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, if hdr { // The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1 // and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop. - let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s); + let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * (hdr_saturation_factor(s) * hdr_saturation_factor(range_s)); return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0); } // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it // (measured in Photoshop 27.11); +100 % saturates any colour that has some. - let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); + let scale = |v: f32, by: f32| if by > 0.0 { v / (1.0 - by).max(1.0 / 512.0) } else { v * (1.0 + by) }; + let ss = scale(scale(ss, s), range_s).clamp(0.0, 1.0); hsl_to_rgb(hh, ss, ll) } @@ -71,7 +75,7 @@ pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, /// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996. /// compose.wgsl's Hue/Saturation does the same in whole numbers. pub fn hdr_saturation_factor(s: f32) -> f32 { - // The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32. + // The 1e-4 keeps a value a rounding error under a step on that step: 0.49999997 is +50 %. let s = s.clamp(-1.0, 1.0); if s <= 0.0 { return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0; diff --git a/crates/compose/src/adjust/hue_saturation_range_multiply_tests.rs b/crates/compose/src/adjust/hue_saturation_range_multiply_tests.rs new file mode 100644 index 0000000000..4e941b3fd3 --- /dev/null +++ b/crates/compose/src/adjust/hue_saturation_range_multiply_tests.rs @@ -0,0 +1,110 @@ +//! #14741: a colour range's Saturation multiplies the Master Saturation's factor instead of +//! adding to it. + +use super::*; + +fn hue_sat(master: f32, reds: f32) -> Adjustment { + let mut ranges = HueRange::defaults(); + ranges[0].saturation = reds; + Adjustment::HueSaturation { hue: 0.0, saturation: master, lightness: 0.0, colorize: false, ranges } +} + +fn run(adj: &Adjustment, c: [f32; 3], depth: SampleType) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(depth)); + [b.px[0][0], b.px[0][1], b.px[0][2]] +} + +fn levels(c: [f32; 3]) -> [f32; 3] { + c.map(|v| (v * 255.0).round()) +} + +fn within(got: [f32; 3], want: [f32; 3], tolerance: f32) -> bool { + levels(got).iter().zip(levels(want)).all(|(g, w)| (g - w).abs() <= tolerance) +} + +/// The reference application, measured: Master -50 with Reds -50 turns (255, 0, 0) into +/// (159, 95, 95), a quarter of red's saturation. Adding the two made -100 and grey. +#[test] +fn master_and_reds_minus_fifty_keep_a_quarter_of_red() { + let got = run(&hue_sat(-50.0, -50.0), [1.0, 0.0, 0.0], SampleType::U8); + let want = [159.0, 95.0, 95.0].map(|v| v / 255.0); + assert!(within(got, want, 1.0), "{:?}", levels(got)); +} + +/// The 72-hue ramp of the measurement at HSL saturation 100 % and 50 %: no Reds cell turns grey, +/// and away from the range's fades every cell has master × range of its saturation. +#[test] +fn ramp_cells_take_the_product_of_both_factors() { + let adj = hue_sat(-50.0, -50.0); + for s in [1.0, 0.5] { + for step in 0..72 { + let deg = step as f32 * 5.0; + let c = hsl_to_rgb(deg / 360.0, s, 0.5); + let got = run(&adj, c, SampleType::U8); + let from_red = deg.min(360.0 - deg); + if from_red < 45.0 { + let chroma = got[0].max(got[1]).max(got[2]) - got[0].min(got[1]).min(got[2]); + assert!(chroma * 255.0 >= 8.0, "hue {deg} at {s}: {:?} is grey", levels(got)); + } + let factor = match from_red { + d if d <= 15.0 => 0.25, + d if d >= 45.0 => 0.5, + _ => continue, + }; + let want = hsl_to_rgb(deg / 360.0, s * factor, 0.5); + assert!(within(got, want, 2.0), "hue {deg} at {s}: {:?}, want {:?}", levels(got), levels(want)); + } + } +} + +/// Raised and mixed settings combine as the same factors applied in turn: +50 doubles the +/// saturation, -50 halves it, +25 multiplies it by 4/3. +#[test] +fn raised_and_mixed_settings_multiply_their_factors() { + let red = |s: f32| hsl_to_rgb(0.0, s, 0.5); + for (master, reds, s, want) in + [(50.0, -50.0, 0.4, 0.4), (-50.0, 50.0, 0.4, 0.4), (25.0, 25.0, 0.3, 0.3 * 16.0 / 9.0), (50.0, 50.0, 0.4, 1.0), (-100.0, 50.0, 0.4, 0.0)] + { + let got = run(&hue_sat(master, reds), red(s), SampleType::U8); + assert!(within(got, red(want), 1.0), "master {master}, reds {reds}: {:?}, want {:?}", levels(got), levels(red(want))); + } +} + +/// 32 bits scale the chroma by the product of their own factors: a quarter of red's chroma for +/// -50 twice, and Reds -50 halves what Master +50 (510/256) or +100 (32767/256) alone gives. +#[test] +fn thirty_two_bits_multiply_too() { + let chroma = |c: [f32; 3]| c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2]); + for (master, reds, want) in [(-50.0, -50.0, 0.25), (50.0, -50.0, 255.0 / 256.0), (100.0, -50.0, 32767.0 / 512.0)] { + let got = run(&hue_sat(master, reds), [1.0, 0.0, 0.0], SampleType::F32); + assert!((chroma(got) - want).abs() < 1e-3 * want, "master {master}, reds {reds}: {got:?}, chroma {want}"); + assert!(got[1..].iter().all(|v| (v - (1.0 - want) / 2.0).abs() < 1e-3 * want.max(1.0)), "{got:?}"); + } +} + +/// A range alone reaches the saturation step as a master of the same value does, bit for bit, on +/// a colour inside the range: one setting alone is untouched by the change. +#[test] +fn one_setting_alone_passes_through_unchanged() { + let c = hsl_to_rgb(2.0 / 360.0, 0.6, 0.45); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for k in -20..=20 { + let v = k as f32 * 5.0; + let range = run(&hue_sat(0.0, v), c, depth).map(f32::to_bits); + let master = run(&hue_sat(v, 0.0), c, depth).map(f32::to_bits); + assert_eq!(range, master, "{depth:?}, {v}"); + } + } +} + +#[test] +fn hostile_values_stay_finite() { + for depth in [SampleType::U8, SampleType::F32] { + for (m, r) in [(f32::INFINITY, -50.0), (f32::NEG_INFINITY, 50.0), (100.0, 100.0), (-100.0, -100.0), (100.0, -100.0), (500.0, 500.0), (-500.0, 1e9)] { + let got = run(&hue_sat(m, r), [0.8, 0.1, 0.2], depth); + assert!(got.iter().all(|v| v.is_finite()), "{depth:?}, {m}, {r}: {got:?}"); + } + let _ = run(&hue_sat(f32::NAN, f32::NAN), [0.8, 0.1, 0.2], depth); + } +} diff --git a/crates/compose/src/adjust/tone_tests.rs b/crates/compose/src/adjust/tone_tests.rs index d189f95a01..3d9fc8b3ec 100644 --- a/crates/compose/src/adjust/tone_tests.rs +++ b/crates/compose/src/adjust/tone_tests.rs @@ -87,13 +87,8 @@ fn thirty_two_bit_hue_saturation_keeps_bright_colours() { let got = hdr(&adj, c); assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}"); } - // A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master - // -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997). - let mut ranges = HueRange::defaults(); - ranges[0].saturation = 96.0; - let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges }; - let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0])); + // A value a rounding error under a step stays on it: 0.49999997 is +50 %. + assert_eq!(hdr_saturation_factor(0.49999997), hdr_saturation_factor(0.5)); // Lightness 0 with a negative channel divides by zero the same way. let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite())); diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index f6af7d88ca..86f41e9865 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -258,6 +258,8 @@ mod inner_shadow_noise_tests; #[cfg(test)] mod outer_glow_noise_tests; +#[cfg(test)] +mod outer_glow_precise_edge_tests; #[cfg(test)] mod tests; @@ -274,5 +276,8 @@ mod satin_size_one_tests; #[cfg(test)] mod inner_glow_size_one_tests; + +#[cfg(test)] +mod inner_glow_noise_tests; #[cfg(test)] mod stroke_partial_alpha_tests; diff --git a/crates/compose/src/effects/inner_glow_noise_tests.rs b/crates/compose/src/effects/inner_glow_noise_tests.rs new file mode 100644 index 0000000000..ab316449c1 --- /dev/null +++ b/crates/compose/src/effects/inner_glow_noise_tests.rs @@ -0,0 +1,158 @@ +//! #14926 - BUG-LAYER-STYLE-INNER-GLOW-NOISE-TOO-WEAK. +//! +//! Measured on the issue's test document: 400 x 300 px, RGB 8 bit, white Background, an orange +//! (255, 128, 0) pixel layer covering x 100..299, y 75..224. Inner Glow black, Normal, 100 %, +//! Softer, Source Edge, Choke 0, Size 10, Contour Linear, Range 50 %. The issue counts the G +//! channel of the flattened top band y 75..83, x 110..289 (1620 px): G 128 is the layer's own +//! orange (no glow), G 0 is full black glow. The shared `noise` law (#14936, #14952) leaves 244 +//! band pixels without glow at Noise 50, while the reference application shows 343. + +use super::*; + +const DOC_W: usize = 400; +const DOC_H: usize = 300; + +/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224. +fn document_shape() -> Map { + let mut m = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + m.v[y * DOC_W + x] = 1.0; + } + } + m +} + +/// The issue's Inner Glow settings: black, Normal, 100 %, Softer, Source Edge, Choke 0, Size 10, +/// Contour Linear, Range 50 %, Jitter 0, Anti-aliased off, Noise `noise`. +fn glow(noise: f32) -> Glow { + Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(photocraft_color::Color::BLACK), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + } +} + +fn map(noise: f32) -> Map { + glow_map(&document_shape(), &glow(noise), true, (0, 0)) +} + +/// The G channel of the orange layer under a black Normal inner glow of coverage `c`. +fn g_u8(c: f32) -> u8 { + (128.0 * (1.0 - c)).round().clamp(0.0, 128.0) as u8 +} + +/// The issue's band, y 75..=83 and x 110..=289 (1620 px), as G channel values. +fn band(m: &Map) -> Vec { + let mut out = Vec::with_capacity(180 * 9); + for y in 75..=83 { + for x in 110..=289 { + out.push(g_u8(m.get(x, y))); + } + } + out +} + +/// Done when: Noise 50 on that band leaves 260..430 pixels at G 128 (no glow at all), at most +/// 30 pixels equal to the noiseless result, and reaches G 0. The shared law alone leaves 244. +#[test] +fn noise_fifty_scatters_the_glow_across_the_band() { + let plain = band(&map(0.0)); + let noisy = band(&map(0.5)); + let gone = noisy.iter().filter(|v| **v == 128).count(); + let equal = noisy.iter().zip(&plain).filter(|(a, b)| a == b).count(); + let min = noisy.iter().copied().min().unwrap_or(128); + assert!((260..=430).contains(&gone), "Noise 50: {gone} pixels without glow, want 260..430 (reference: 343)"); + assert!(equal <= 30, "Noise 50: {equal} pixels equal to the noiseless result, want at most 30 (reference: 8)"); + assert_eq!(min, 0, "Noise 50: minimum G {min}, want 0"); +} + +/// Done when: Noise 100 leaves 400..580 pixels at G 128 (reference: 490). +#[test] +fn noise_hundred_thins_the_glow_further() { + let noisy = band(&map(1.0)); + let gone = noisy.iter().filter(|v| **v == 128).count(); + assert!((400..=580).contains(&gone), "Noise 100: {gone} pixels without glow, want 400..580 (reference: 490)"); +} + +/// Done when: the interior beyond the glow's reach stays G 128 at every Noise. +#[test] +fn noise_keeps_the_interior_beyond_the_glow_clean() { + let plain = map(0.0); + for noise in [0.25f32, 0.5, 1.0] { + let noisy = map(noise); + for y in (100..=200).step_by(5) { + for x in (130..=270).step_by(7) { + assert_eq!(plain.get(x, y), 0.0, "noiseless coverage at ({x},{y}) is not empty"); + assert_eq!(noisy.get(x, y), 0.0, "noise {noise} lit up ({x},{y}): {}", noisy.get(x, y)); + assert_eq!(g_u8(noisy.get(x, y)), 128, "noise {noise} moved the interior at ({x},{y}) off 128"); + } + } + } +} + +/// Done when: the same settings give the identical image twice. +#[test] +fn the_same_noise_renders_identically_twice() { + for noise in [0.5f32, 1.0] { + let a = map(noise); + let b = map(noise); + assert_eq!(a.v, b.v, "noise {noise} is not deterministic"); + } +} + +/// Noise that is not a positive number leaves the glow exactly as Noise 0 does, and the inner +/// strength does not reach the Outer Glow, whose band was measured on the shared law (#14952). +#[test] +fn odd_noise_values_and_outer_glows_keep_the_shared_law() { + let plain = map(0.0); + for odd in [-0.5f32, f32::NAN, f32::INFINITY] { + assert_eq!(map(odd).v, plain.v, "noise {odd} changed the inner glow"); + } + let shape = document_shape(); + let outer = glow_map(&shape, &glow(0.0), false, (0, 0)); + let mut by_law = outer.clone(); + noise(&mut by_law, 0.5, 0, 0); + assert_eq!(glow_map(&shape, &glow(0.5), false, (0, 0)).v, by_law.v, "the outer glow left the shared law"); +} + +/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is. +fn bit_hash(m: &Map) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for v in &m.v { + h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Noise 0 stays bit-identical: the whole-map FNV hash `glow_map` gives for the issue's +/// document with Noise 0 on origin/main. +#[test] +fn noise_zero_maps_stay_bit_identical() { + assert_eq!(bit_hash(&map(0.0)), 0xefad_fffb_8195_d0b9, "the Noise 0 inner glow map moved"); +} + +/// The Centre source and the Precise technique were not measured, so they keep the shared law at every Noise: only +/// the measured Softer, Edge-sourced Inner Glow gets the stronger mid-Noise scatter. +#[test] +fn unmeasured_centre_and_precise_inner_glows_keep_the_shared_law() { + let shape = document_shape(); + let centre = |noise| Glow { source: GlowSource::Center, ..glow(noise) }; + let precise = |noise| Glow { technique: GlowTechnique::Precise, ..glow(noise) }; + let precise_centre = |noise| Glow { technique: GlowTechnique::Precise, source: GlowSource::Center, ..glow(noise) }; + for (name, make) in [("Centre", ¢re as &dyn Fn(f32) -> Glow), ("Precise", &precise), ("Precise Centre", &precise_centre)] { + for amount in [0.25f32, 0.5] { + let mut by_law = glow_map(&shape, &make(0.0), true, (0, 0)); + noise(&mut by_law, amount, 0, 0); + assert_eq!(glow_map(&shape, &make(amount), true, (0, 0)).v, by_law.v, "{name}, Noise {amount}: left the shared law"); + } + } +} diff --git a/crates/compose/src/effects/outer_glow_precise_edge_tests.rs b/crates/compose/src/effects/outer_glow_precise_edge_tests.rs new file mode 100644 index 0000000000..af44ed559a --- /dev/null +++ b/crates/compose/src/effects/outer_glow_precise_edge_tests.rs @@ -0,0 +1,61 @@ +//! #15006 - Outer Glow: a flat-contour Precise band's outermost pixel is soft on a pixel-aligned +//! edge. +//! +//! Measured on the issue's document: 60 x 60 px, transparent, a black 20 x 20 square at x/y +//! 20..39. Outer Glow Normal 100 %, Precise, Spread 0, Size 4 px, Range 50 %, custom flat contour +//! (0,255)-(255,255), Anti-aliased off. Along row 30, x 14 and 15 read alpha 0, x 16 (4 px out) +//! 213 and x 17..19 255. On the diagonal, (16, 16) reads 0, (17, 17) 161 and (18, 18) 255. + +use super::{Contour, Effect, FxPaint, Glow, GlowSource, GlowTechnique}; +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, FxCommon, Layer, adjust::CurvePoint}; +use photocraft_geom::{Rect, Size}; + +fn outer_glow(contour: Contour) -> Glow { + Glow { + common: FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(Color::BLACK), + technique: GlowTechnique::Precise, + spread: 0.0, + size: 4.0, + contour, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + } +} + +fn flat() -> Contour { + Contour::Custom { name: "Flat".into(), points: vec![CurvePoint { input: 0.0, output: 1.0 }, CurvePoint { input: 1.0, output: 1.0 }], corners: vec![] } +} + +fn alphas(glow: Glow) -> impl Fn(i32, i32) -> u8 { + let mut doc = Document::new("Outer glow", Size::new(60, 60), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("Square", doc.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(20, 20, 40, 40), &[0.0, 0.0, 0.0, 1.0]); + layer.effects.items.push(Effect::OuterGlow(glow)); + doc.layers.push(layer); + let image = crate::flatten(&doc); + move |x, y| (image.get(x, y)[3] * 255.0).round() as u8 +} + +#[test] +fn the_pixel_at_size_px_out_is_soft() { + let alpha = alphas(outer_glow(flat())); + for (x, expected) in [(14, 0), (15, 0), (17, 255), (18, 255), (19, 255)] { + assert_eq!(alpha(x, 30), expected, "x {x}"); + } + let edge = alpha(16, 30); + assert!(edge.abs_diff(213) <= 3, "x 16, 4 px out: expected 213, got {edge}"); +} + +#[test] +fn the_corner_diagonal_fades_the_same_way() { + let alpha = alphas(outer_glow(flat())); + assert_eq!(alpha(16, 16), 0); + assert_eq!(alpha(18, 18), 255); + let diagonal = alpha(17, 17); + assert!(diagonal.abs_diff(161) <= 5, "(17, 17), √18 px out: expected 161, got {diagonal}"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index d7d3291f5e..5ea147e744 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -109,9 +109,9 @@ fn softer_edge_floor(size: f32) -> f32 { /// rounded down to a table entry for both techniques); the coverage where it reaches 1 is per /// technique: /// -/// - Precise: the falloff is linear in distance, so the edge is the distance left to the reach's -/// end: the last pixel steps down by how far inside the reach its centre is (one soft pixel, -/// as Photoshop's flat-contour band). +/// - Precise: a fixed coverage, [`PRECISE_FULL_COVERAGE`]. The falloff is linear in distance, so +/// at Spread 0 the band fades over its last `0.24 · (size + 1)` px: about one soft pixel at +/// Size 4, two to three at Size 10, as Photoshop's flat-contour band. /// - Softer: coverage is a tent blur, and the same coverage means a different distance for a /// straight edge and a single pixel, so no coverage-only model gives the distance. The edge /// reaches 1 at the coverage one opaque pixel gives one pixel inside its reach along a row @@ -122,7 +122,7 @@ fn softer_edge_floor(size: f32) -> f32 { /// So: /// /// - coverage 0 always paints 0, for any contour (nothing beyond the reach); -/// - a high contour is solid up to the last pixel of the reach, which steps down; +/// - a high contour is solid up to the outer pixels of the reach, which step down; /// - it never paints less than the Linear contour would, so a contour that already follows or /// stays under the falloff (Linear, or a custom curve with `contour(0) = 0` rising no faster /// than the reach edge) is unchanged. The reach does not depend on Range: Range stretches the @@ -151,6 +151,14 @@ pub fn glow_paint_lut(g: &Glow, inner: bool) -> Option> { ) } +/// The Precise coverage at which a high contour's reach edge paints in full (#15006), whatever +/// the Size: with `v = ½·(1 − (d − solid) / soft)`, Photoshop paints `v / 0.12`. Measured at +/// Range 50 %, Spread 0: Size 4 at 4 px out (a pixel-aligned edge) 213 of 255 and at √18 px (a +/// corner's diagonal) 161; Size 10, #11361's ellipse row `153, 120, 92` (this gives +/// `155, 123, 92`). Other Ranges and Spreads are unmeasured. Tying the knee to the distance +/// instead (`1 / (2·soft)`, the reach's last pixel) left the pixel at Size px out solid. +const PRECISE_FULL_COVERAGE: f32 = 0.12; + /// Entries in a glow's transfer table: the GPU's `compose.wgsl` `lut` reads 4096, linearly /// interpolated, as the CPU's [`lut_at`] does. const GLOW_LUT_LEN: usize = 4096; @@ -170,16 +178,11 @@ fn glow_reach_edge(per_coverage: f32, v: f32) -> f32 { /// coverage rounded down to a whole table step (at least one), so the knee lands on a table entry /// and the table interpolates the edge exactly (rounding down only widens what paints in full). /// -/// - Precise: `v = ½·(1 − (d − solid) / soft)`, which reaches 0 at `d = size + 1` (centre to -/// centre), so the distance left to the reach's end is `size + 1 − d = 2·soft·v`: full at -/// `v = 1 / (2·soft)`. +/// - Precise: full at [`PRECISE_FULL_COVERAGE`]. /// - Softer: full at [`softer_full_coverage`]. fn glow_edge_per_coverage(g: &Glow) -> f32 { let full = match g.technique { - GlowTechnique::Precise => { - let solid = g.size * g.spread; - 0.5 / (g.size + 1.0 - solid).max(1e-3) - } + GlowTechnique::Precise => PRECISE_FULL_COVERAGE, GlowTechnique::Softer => softer_full_coverage(spread_split(g.size, g.spread).1), }; let steps = (GLOW_LUT_LEN - 1) as f32; @@ -582,7 +585,13 @@ pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) - if inner && g.source == GlowSource::Center { m = m.map(|v| 1.0 - v); } - noise(&mut m, g.noise, origin.0, origin.1); + // #14926: an Inner Glow scatters harder at mid Noise than the shared law gives (measured + // band: Noise 50 leaves 343 of 1620 px without glow, Noise 100 490). The square root keeps + // Noise 0 and Noise 100 where they are and lifts Noise 50 to the law's 0.71 (about 340 px). + // Only the measured Softer, Edge-sourced case; Centre and Precise keep the shared law. + let measured = inner && g.technique == GlowTechnique::Softer && g.source == GlowSource::Edge; + let amount = if measured && g.noise > 0.0 { g.noise.sqrt() } else { g.noise }; + noise(&mut m, amount, origin.0, origin.1); if inner { for (v, a) in m.v.iter_mut().zip(&shape.v) { *v *= a; diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 3e0eb82a61..610b0244e3 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -1004,8 +1004,8 @@ fn flat_contour_outer_glow_is_a_solid_band_with_one_soft_pixel() { let n = 60; let at = |m: &Map, x: usize| m.v[30 * n + x]; // Precise, with the square's left column half covered: its edge sits mid-pixel, so the - // pixels out from it are 1.5, 2.5, 3.5, 4.5, 5.5 px (centre to centre) from the shape, and - // the reach (size + 1 = 5) ends half-way across the 4.5 px one. + // pixels out from it are 1.5, 2.5, 3.5, 4.5, 5.5 px (centre to centre) from the shape. The + // 4.5 px one has coverage 0.05, which the 0.12 knee (#15006) paints at 5/12. let mut shape = square_20_40(); for y in 20..40 { shape.v[y * n + 19] = 0.5; @@ -1014,18 +1014,17 @@ fn flat_contour_outer_glow_is_a_solid_band_with_one_soft_pixel() { for x in 16..=19 { assert!(at(&m, x) > 0.999, "precise, solid band at x {x}: {}", at(&m, x)); } - assert!((at(&m, 15) - 0.5).abs() < 0.05, "precise, the soft outer pixel: {}", at(&m, 15)); + assert!((at(&m, 15) - 5.0 / 12.0).abs() < 0.01, "precise, the soft outer pixel: {}", at(&m, 15)); assert!(at(&m, 14) == 0.0 && at(&m, 0) == 0.0, "precise, beyond the reach: {} {}", at(&m, 14), at(&m, 0)); // Precise, pixel-aligned edge: the pixels out from it are 1..5 px (centre to centre) from the - // shape and the reach ends at the 5 px one's centre, so the band is solid through Size (x 16, - // 4 px out, 1.0) and the next pixel (x 15) is beyond it. Point-sampled, as the measured Linear - // falloff is: an area-averaged falloff would leave x 15 half covered (the reach ends 4.5 px - // past the shape's edge, half-way across it), not 0.84. + // shape and the reach ends at the 5 px one's centre. Photoshop's x 16 (4 px out, coverage + // 0.1) reads 213 of 255 (#15006), and x 15 is beyond the reach. let shape = square_20_40(); let m = glow_map(&shape, &contour_glow(GlowTechnique::Precise, 4.0, &FLAT), false, (0, 0)); - for x in 16..20 { + for x in 17..20 { assert!(at(&m, x) > 0.999, "precise aligned, solid band at x {x}: {}", at(&m, x)); } + assert!((at(&m, 16) * 255.0 - 213.0).abs() <= 1.0, "precise aligned, the soft outer pixel: {}", at(&m, 16)); assert!(at(&m, 15) == 0.0, "precise aligned, beyond the reach: {}", at(&m, 15)); // Softer, size 4: the tent's last tap (1/64, at x 16) is above what one opaque pixel gives one // pixel inside its reach (t[3]·t[0] ≈ 0.0137), so a straight edge is solid through its reach. diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index fa15aaeb67..e931a08f0c 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -87,6 +87,8 @@ pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; pub mod layer_menu_cmds; +#[cfg(test)] +mod layer_merge_clipping_mask_tests; pub mod layer_multi_cmds; pub mod layer_nav_cmds; mod layer_params; diff --git a/crates/engine-core/src/cmd/adjust_cmds.rs b/crates/engine-core/src/cmd/adjust_cmds.rs index af4c957132..d5ffd13303 100644 --- a/crates/engine-core/src/cmd/adjust_cmds.rs +++ b/crates/engine-core/src/cmd/adjust_cmds.rs @@ -537,6 +537,33 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } +/// HDR Toning is greyed with an active selection and in CMYK, Lab and Indexed Color documents +/// (#14735). RGB and Grayscale keep it; Duotone and Multichannel were not measured and keep +/// today's behaviour (`Session::precondition` refuses Bitmap for every adjustment but Invert). +fn hdr_toning_enabled(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + // The mode comes first: deselecting can't fix it. + if let Some(reason) = hdr_toning_mode_refusal(d.doc.mode) { + return Err(reason); + } + if d.doc.selection.is_some() { + return Err("HDR Toning works on the whole image: deselect first".into()); + } + Ok(()) +} + +/// A document mode that excludes HDR Toning even when the composite channel is targeted. +pub(crate) fn hdr_toning_mode_refusal(mode: photocraft_color::ColorMode) -> Option { + use photocraft_color::ColorMode; + let label = match mode { + ColorMode::Cmyk => "CMYK Color", + ColorMode::Lab => "Lab Color", + ColorMode::Indexed => "Indexed Color", + _ => return None, + }; + Some(format!("HDR Toning needs an RGB or Grayscale document (this one is {label})")) +} + // ---------- commands ---------- /// Image › Adjustments run as a smart filter (`image.adjustments.` recorded on a smart @@ -861,7 +888,7 @@ pub fn specs() -> Vec { "HDR Toning…", ["Image", "Adjustments"], r##"{"radius":1..500=30,"strength":0.1..4=0.5,"gamma":0.1..2=1,"exposure":-5..5=0,"detail":-100..300=30,"shadow":-100..100=0,"highlight":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=20,"curve":[[in,out],…] 0..255} (flattens the image)"##, - has_doc, + hdr_toning_enabled, hdr_toning ), CommandSpec { @@ -1011,6 +1038,8 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result { Ok(Value::Object(crate::adjust_params::HUE_RANGES.iter().zip(w).map(|(k, v)| ((*k).to_string(), json!(v))).collect())) } +#[cfg(test)] +mod hdr_toning_enabled_tests; #[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/adjust_cmds/hdr_toning_enabled_tests.rs b/crates/engine-core/src/cmd/adjust_cmds/hdr_toning_enabled_tests.rs new file mode 100644 index 0000000000..7caaad9821 --- /dev/null +++ b/crates/engine-core/src/cmd/adjust_cmds/hdr_toning_enabled_tests.rs @@ -0,0 +1,119 @@ +//! Image > Adjustments > HDR Toning is greyed with an active selection and in CMYK, Lab and +//! Indexed Color documents (#14735), stays available in RGB at 8, 16 and 32 bit and Grayscale 8 +//! bit (keeping the mode and depth), and Duotone, Multichannel and deeper Grayscale (not measured) +//! keep today's behaviour. + +use crate::Session; +use serde_json::json; + +const HDR: &str = "image.adjustments.hdrToning"; + +fn new_doc(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s +} + +fn assert_refused(mut s: Session, what: &str) { + assert!(!s.is_enabled(HDR), "{what}: the menu entry is greyed out"); + let d = s.active().unwrap(); + let (steps, selection, mode) = (d.history.past_len(), d.doc.selection.clone(), d.doc.mode); + assert!(s.execute(HDR, json!({})).is_err(), "{what}: running it is refused"); + let d = s.active().unwrap(); + assert_eq!(d.history.past_len(), steps, "{what}: no history state"); + assert_eq!(d.doc.selection, selection, "{what}: the selection stays"); + assert_eq!(d.doc.mode, mode, "{what}: the mode stays"); +} + +#[test] +fn an_active_selection_refuses_hdr_toning() { + let mut s = new_doc("rgb", 8); + s.execute("select.all", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_some()); + assert_refused(s, "RGB with a selection"); +} + +#[test] +fn cmyk_lab_and_indexed_documents_refuse_hdr_toning() { + assert_refused(new_doc("cmyk", 8), "CMYK 8 bit"); + assert_refused(new_doc("lab", 8), "Lab 8 bit"); + let mut indexed = new_doc("rgb", 8); + indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + assert_refused(indexed, "Indexed Color"); +} + +#[test] +fn targeted_hdr_toning_names_the_unsupported_mode_before_the_channel() { + let mut indexed = new_doc("rgb", 8); + indexed.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + let target = json!({"target": {"color": 0}}); + for (mut s, reason) in [ + (new_doc("cmyk", 8), "CMYK Color"), + (new_doc("lab", 8), "Lab Color"), + (indexed, "Indexed Color"), + (new_doc("rgb", 8), "requires the composite channel"), + ] { + let disabled = s.disabled_reason_with(HDR, &target).unwrap(); + assert!(disabled.contains(reason), "{disabled}"); + let error = s.execute(HDR, target.clone()).unwrap_err().to_string(); + assert!(error.contains(reason), "{error}"); + } +} + +#[test] +fn rgb_all_depths_and_grayscale_8_bit_keep_hdr_toning_and_their_mode_and_depth() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8)] { + let mut s = new_doc(mode, depth); + assert!(s.is_enabled(HDR), "{mode} {depth} bit"); + let d = s.active().unwrap(); + let (steps, before_mode, before_depth) = (d.history.past_len(), d.doc.mode, d.doc.depth); + s.execute(HDR, json!({})).unwrap(); + let d = s.active().unwrap(); + assert_eq!(d.history.past_len(), steps + 1, "{mode} {depth} bit: one history state"); + assert_eq!((d.doc.mode, d.doc.depth), (before_mode, before_depth), "{mode} {depth} bit keeps its mode and depth"); + } +} + +/// Not measured: Multichannel, Duotone and Grayscale at 16 and 32 bit keep today's behaviour. +#[test] +fn unmeasured_documents_keep_todays_behaviour() { + let mut multi = new_doc("rgb", 8); + multi.execute("image.mode.multichannel", json!({})).unwrap(); + assert!(multi.is_enabled(HDR), "Multichannel"); + + let mut duotone = new_doc("grayscale", 8); + duotone + .edit("duotone", |d, _| { + d.mode = photocraft_color::ColorMode::Duotone; + Ok(()) + }) + .unwrap(); + assert!(duotone.is_enabled(HDR), "Duotone"); + + for depth in [16, 32] { + assert!(new_doc("grayscale", depth).is_enabled(HDR), "Grayscale {depth} bit"); + } +} + +#[test] +fn the_refusals_say_why() { + let why = super::hdr_toning_enabled(&new_doc("lab", 8)).unwrap_err(); + assert!(why.contains("Lab Color"), "{why}"); + let mut s = new_doc("rgb", 8); + s.execute("select.all", json!({})).unwrap(); + let why = super::hdr_toning_enabled(&s).unwrap_err(); + assert!(why.contains("deselect"), "{why}"); + // A CMYK document with a selection names the mode: deselecting would not help. + let mut s = new_doc("cmyk", 8); + s.execute("select.all", json!({})).unwrap(); + let why = super::hdr_toning_enabled(&s).unwrap_err(); + assert!(why.contains("CMYK Color"), "{why}"); +} + +#[test] +fn no_document_is_unchanged() { + let mut s = crate::session(); + assert!(!s.is_enabled(HDR)); + assert_eq!(super::hdr_toning_enabled(&s).unwrap_err(), "no document open"); + assert!(s.execute(HDR, json!({})).is_err()); +} diff --git a/crates/engine-core/src/cmd/adjust_cmds/tests.rs b/crates/engine-core/src/cmd/adjust_cmds/tests.rs index e90104d0d5..04833b0899 100644 --- a/crates/engine-core/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine-core/src/cmd/adjust_cmds/tests.rs @@ -57,7 +57,14 @@ fn destructive_adjustments_all_depths_and_modes_one_undo_step() { for (id, params) in &cases { for depth in DEPTHS { for mode in MODES { + // CMYK and Lab documents grey HDR Toning (#14735, hdr_toning_enabled_tests). let mut s = session(depth, mode); + if id.ends_with("hdrToning") && matches!(mode, "cmyk" | "lab") { + let steps = s.active().unwrap().history.past_len(); + assert!(s.execute(id, params.clone()).is_err(), "{id} {depth} {mode}: refused"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{id} {depth} {mode}: no history step"); + continue; + } let before = rgba(&s, 3, 3); let steps = s.active().unwrap().history.past_len(); s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{id} {depth} {mode}: {e}")); diff --git a/crates/engine-core/src/cmd/analysis_cmds.rs b/crates/engine-core/src/cmd/analysis_cmds.rs index 6e65c4f0a0..c20e3c5ddf 100644 --- a/crates/engine-core/src/cmd/analysis_cmds.rs +++ b/crates/engine-core/src/cmd/analysis_cmds.rs @@ -296,8 +296,10 @@ fn set_scale(s: &mut Session, p: &Value) -> Result { other => return Err(bad(CMD, format!("unknown preset `{other}` (default|custom)"))), }; if next != cur { + // The reference names the step after the submenu entry that made it (#17410). + let label = if preset == "default" { "Set Default Measurement Scale" } else { "Custom Measurement Scale" }; let n = next.clone(); - s.edit("Set Measurement Scale", move |d, _| { + s.edit(label, move |d, _| { d.measurement.scale = n; Ok(()) })?; @@ -1460,4 +1462,6 @@ mod data_points_one_list_tests; #[cfg(test)] mod record_no_data_points_tests; #[cfg(test)] +mod scale_history_names_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs b/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs new file mode 100644 index 0000000000..de5298f1b3 --- /dev/null +++ b/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs @@ -0,0 +1,60 @@ +//! History step names of Image › Analysis › Set Measurement Scale, measured against the reference +//! application (#17410): Custom (the dialog, a preset, a script set) adds one step "Custom +//! Measurement Scale", Default adds one step "Set Default Measurement Scale", and a call that +//! leaves the scale as it is adds no step. + +use super::*; + +const CMD: &str = "image.analysis.setMeasurementScale"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn last_step(s: &Session) -> String { + s.active().unwrap().history.entries().last().cloned().unwrap_or_default() +} + +#[test] +fn custom_and_bare_values_add_one_custom_step() { + for p in [ + json!({"preset": "custom", "pixelLength": 100, "logicalLength": 2.5, "units": "cm"}), + json!({"pixelLength": 100, "logicalLength": 2.5, "units": "cm"}), + json!({"units": "mm"}), + ] { + let mut s = session(); + let before = steps(&s); + s.execute(CMD, p.clone()).unwrap(); + assert_eq!(steps(&s), before + 1, "{p}"); + assert_eq!(last_step(&s), "Custom Measurement Scale", "{p}"); + } +} + +#[test] +fn default_adds_one_default_step() { + let mut s = session(); + s.execute(CMD, json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"})).unwrap(); + let before = steps(&s); + s.execute(CMD, json!({"preset": "default"})).unwrap(); + assert_eq!(steps(&s), before + 1); + assert_eq!(last_step(&s), "Set Default Measurement Scale"); +} + +#[test] +fn unchanged_scale_adds_no_step() { + let mut s = session(); + let before = steps(&s); + s.execute(CMD, json!({"preset": "default"})).unwrap(); + assert_eq!(steps(&s), before, "Default on a default scale"); + let p = json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"}); + s.execute(CMD, p.clone()).unwrap(); + let before = steps(&s); + s.execute(CMD, p).unwrap(); + assert_eq!(steps(&s), before, "the same custom values again"); +} diff --git a/crates/engine-core/src/cmd/background_cmds.rs b/crates/engine-core/src/cmd/background_cmds.rs index 90ed98c578..4976894bc8 100644 --- a/crates/engine-core/src/cmd/background_cmds.rs +++ b/crates/engine-core/src/cmd/background_cmds.rs @@ -86,6 +86,13 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { } let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; convertible(l).map_err(EngineError::Other)?; + // Keep the one measured clipped sibling with its top-level base. Leave nested + // targets and stacks with several clipped layers on the existing path. + let mut above = doc.layers.iter().skip_while(|layer| layer.id != id).skip(1); + let clipped = match (above.next(), above.next()) { + (Some(layer), next) if !l.clipped && layer.clipped && !next.is_some_and(|layer| layer.clipped) => Some(layer.id), + _ => None, + }; // Render the layer alone, as it looks (mask, opacity and effects applied), over the // background colour: the Background is opaque and plain. let mut only = l.clone(); @@ -104,6 +111,10 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { *crate::pixels_mut(&mut out)? = pixels; doc.remove(id).ok_or(EngineError::NoLayer(id))?; doc.layers.insert(0, out); + if let Some(clipped) = clipped { + let layer = doc.remove(clipped).ok_or(EngineError::NoLayer(clipped))?; + doc.layers.insert(1, layer); + } *active = Some(id); Ok(()) })?; diff --git a/crates/engine-core/src/cmd/channel_cmds/selection.rs b/crates/engine-core/src/cmd/channel_cmds/selection.rs index 971d6c2ce1..ee81444c11 100644 --- a/crates/engine-core/src/cmd/channel_cmds/selection.rs +++ b/crates/engine-core/src/cmd/channel_cmds/selection.rs @@ -164,7 +164,7 @@ pub(super) fn quick_mask(s: &mut Session, p: &Value) -> Result { } let opts = s.quick_mask_options; if want { - s.edit("Edit in Quick Mask", |doc, _| { + s.edit("Enter Quick Mask", |doc, _| { doc.quick_mask = Some(quick_mask_from(doc, &opts)); doc.quick_mask_unselected = doc.selection.is_none(); doc.selection = None; diff --git a/crates/engine-core/src/cmd/edit_menu_cmds.rs b/crates/engine-core/src/cmd/edit_menu_cmds.rs index 3633d630a1..f8ffa52811 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds.rs @@ -370,7 +370,7 @@ pub fn specs() -> Vec { ["Edit"], None, r##"{"name":text}"##, - |s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) }, + |s| s.disabled_reason("brush.defineFromSelection").map_or(Ok(()), Err), define_brush_preset ), spec!( diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs index a40737910f..8a2e9fe971 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs @@ -5,14 +5,20 @@ use photocraft_doc::vector::PathOp; // ------------------------------------------------------------------ Define Brush / Custom Shape pub(super) fn define_brush_preset(s: &mut Session, p: &Value) -> Result { - let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { - Some(n) => n.to_string(), - None => { - let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; - format!("Sampled Brush {n}") - } - }; - s.execute("brush.defineFromSelection", json!({"name": name})) + let typed = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + // The default counts the defaults stored this session; presets that merely share the name don't raise it (#18228). A + // number a preset already uses is skipped, since storing under that name would replace that preset; the store matches + // names ignoring ASCII case, so this does too. + let mut number = s.tools.sampled_brushes.saturating_add(1); + while typed.is_none() && s.tools.presets.iter().any(|b| b.name.eq_ignore_ascii_case(&format!("Sampled Brush {number}"))) { + number = number.saturating_add(1); + } + let name = typed.map_or_else(|| format!("Sampled Brush {number}"), str::to_string); + let defined = s.execute("brush.defineFromSelection", json!({"name": name}))?; + if typed.is_none() { + s.tools.sampled_brushes = number; + } + Ok(defined) } /// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the diff --git a/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs b/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs new file mode 100644 index 0000000000..4455a9811d --- /dev/null +++ b/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs @@ -0,0 +1,145 @@ +//! #18481: `Ctrl+E` (`layer.mergeLayers`) with the base of a clip group alone selected is Merge Clipping Mask: the base +//! and the layers clipped to it become one layer with the base's identity, name, place, blend mode and opacity; the +//! composite does not change, and clipped pixels outside the base are gone. Other layers, and the cases the issue did +//! not measure, keep Merge Down. + +use photocraft_doc::{BlendMode, LayerId}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// `Top` (blue, wider than `Red`) clipped onto `Red`, `Masked` below, on a white Background; `Red` active. +fn clip_group() -> (Session, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap(); + let fill = |s: &mut Session, name: &str, rect: Rect, color: [f32; 4]| { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit("Paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(rect, &color); + Ok(()) + }) + .unwrap(); + s.active().unwrap().active_layer.unwrap() + }; + fill(&mut s, "Masked", Rect::new(0, 20, 60, 40), [0.0, 0.6, 0.0, 1.0]); + let red = fill(&mut s, "Red", Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + fill(&mut s, "Top", Rect::new(20, 0, 50, 25), [0.0, 0.0, 1.0, 0.7]); + s.execute("layer.createClippingMask", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": red.0})).unwrap(); + (s, red) +} + +fn names(s: &Session) -> Vec { + s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() +} + +fn flat(s: &Session) -> Vec<[f32; 4]> { + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() +} + +fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { + a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max) +} + +fn undo_label(s: &Session) -> String { + s.active().unwrap().history.undo_label().unwrap_or_default().to_string() +} + +/// The merged layer's pixel at canvas `(x, y)`. +fn pixel(s: &Session, id: LayerId, x: i32, y: i32) -> Vec { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().pixel(x, y) +} + +#[test] +fn ctrl_e_on_a_clip_base_merges_the_clipped_layers_into_it() { + let (mut s, red) = clip_group(); + let before = flat(&s); + let steps = s.active().unwrap().history.past_len(); + + s.execute("layer.mergeLayers", json!({})).unwrap(); + + assert!(!names(&s).contains(&"Top".to_string()), "Top is merged: {:?}", names(&s)); + assert!(names(&s).contains(&"Masked".to_string()), "Masked is untouched: {:?}", names(&s)); + let d = s.active().unwrap(); + let merged = d.doc.layer(red).expect("the result keeps the base's id"); + assert_eq!(merged.name, "Red"); + assert!(!merged.clipped); + assert_eq!(d.active_layer, Some(red)); + assert_eq!(d.history.past_len(), steps + 1, "one History state"); + assert_eq!(undo_label(&s), "Merge Clipping Mask"); + assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change"); + + // Inside the base the blue is blended over the red; outside the base the clipped blue is gone. + let inside = pixel(&s, red, 25, 15); + assert!(inside[2] > inside[0] && inside[3] > 0.99, "{inside:?}"); + assert!(pixel(&s, red, 40, 5)[3] < 1e-3, "clipped pixels outside the base are dropped"); +} + +#[test] +fn the_result_keeps_the_bases_blend_mode_and_opacity() { + let (mut s, red) = clip_group(); + s.execute("layer.setProps", json!({"blend": "Multiply", "opacity": 0.6})).unwrap(); + let before = flat(&s); + + s.execute("layer.mergeLayers", json!({})).unwrap(); + + let merged = s.active().unwrap().doc.layer(red).unwrap().clone(); + assert_eq!(merged.blend, BlendMode::Multiply); + assert!((merged.opacity - 0.6).abs() < 1e-3, "{}", merged.opacity); + assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change"); +} + +#[test] +fn a_layer_that_is_not_a_clip_base_still_merges_down() { + // The clipped layer itself, and a layer with nothing clipped to it. + for name in ["Top", "Masked"] { + let (mut s, _) = clip_group(); + let id = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id; + s.execute("layer.select", json!({"layer": id.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "{name}"); + } +} + +/// Not measured in the issue: these keep today's Merge Down. +#[test] +fn a_base_with_a_layer_mask_or_inside_a_group_keeps_merge_down() { + let (mut s, _) = clip_group(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "a base with a layer mask"); + + let (mut s, red) = clip_group(); + let masked = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Masked").unwrap().2.id; + let top = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Top").unwrap().2.id; + s.execute("layer.select", json!({"layers": [masked.0, red.0, top.0]})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(top).unwrap().clipped, "Top is still clipped inside the group"); + s.execute("layer.select", json!({"layer": red.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "a base inside a group"); +} + +/// A base whose Fill, Blend If, Advanced Blending or excluded channels the merged layer could not carry keeps Merge +/// Down, so the composite is never changed by Merge Clipping Mask. +#[test] +fn a_base_with_settings_the_result_cannot_carry_keeps_merge_down() { + type Set = fn(&mut photocraft_doc::Layer); + let cases: [(&str, Set); 4] = [ + ("Fill 50 %", |l| l.fill_opacity = 0.5), + ("Blend If", |l| l.blend_if.ranges = vec![[photocraft_doc::BlendRange { black: [0, 0], white: [128, 128] }, photocraft_doc::BlendRange::FULL]]), + ("Blend Clipped Layers as Group off", |l| l.advanced.blend_clipped = false), + ("an excluded channel", |l| l.excluded_channels = 1), + ]; + for (case, set) in cases { + let (mut s, red) = clip_group(); + s.edit("Set", |doc, _| { + set(doc.layer_mut(red).unwrap()); + Ok(()) + }) + .unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "{case}"); + } +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index 4ce80a67f4..bdc21ec466 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -31,9 +31,9 @@ pub use selection::top_level; use selection::{doc_state, find_layers, select_all_layers, select_linked}; pub(crate) use selection::{mask_targets, recorded_step, reselect}; pub use selection::{select, selected, set_selection}; -pub use structure::deletion_neighbours; pub(crate) use structure::{check_group_depth, relink_copies}; pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected}; +pub use structure::{deletion_neighbours, merges_clipping_mask}; use structure::{link_layers, lock_layers, merge_layers, rename_layer, reverse}; // ---------- enabled predicates ---------- diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_lock_carry_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_lock_carry_tests.rs new file mode 100644 index 0000000000..d04812e2ee --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_lock_carry_tests.rs @@ -0,0 +1,109 @@ +use photocraft_doc::{Layer, LayerId, Locks}; +use serde_json::json; + +use crate::Session; + +const GROUP_FROM_LAYERS: &str = "layer.new.groupFromLayers"; + +struct Fixture { + session: Session, + shared: LayerId, + source: LayerId, + leaving: LayerId, + staying: LayerId, +} + +fn fixture(source_locks: Locks, shared_locks: Locks, own_locks: Locks) -> Fixture { + let mut session = crate::session(); + session.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + let (shared, source, leaving, staying) = session + .edit("Fixture layers", |doc, active| { + let mut leaving = Layer::raster("Leaving", doc.pixel_format()); + leaving.locks = own_locks; + let staying = Layer::raster("Staying", doc.pixel_format()); + let (leaving_id, staying_id) = (leaving.id, staying.id); + let mut source = Layer::group("Source", vec![leaving]); + source.locks = source_locks; + let source_id = source.id; + let destination = Layer::group("Destination", vec![staying]); + let mut shared = Layer::group("Shared", vec![source, destination]); + shared.locks = shared_locks; + let shared_id = shared.id; + doc.layers.push(shared); + *active = Some(staying_id); + Ok((shared_id, source_id, leaving_id, staying_id)) + }) + .unwrap(); + for (layer, mode) in [(leaving, "replace"), (staying, "add")] { + session.execute("layer.select", json!({"layer": layer.0, "mode": mode})).unwrap(); + } + Fixture { session, shared, source, leaving, staying } +} + +fn group(session: &mut Session, command: &str) -> LayerId { + LayerId(session.execute(command, json!({})).unwrap()["layer"].as_u64().unwrap()) +} + +#[test] +fn group_from_layers_carries_each_departed_lock_in_the_grouping_undo_step() { + for locks in [ + Locks { all: true, ..Default::default() }, + Locks { position: true, ..Default::default() }, + Locks { transparency: true, ..Default::default() }, + Locks { pixels: true, ..Default::default() }, + Locks { artboard: true, ..Default::default() }, + Locks { position: true, transparency: true, ..Default::default() }, + ] { + let Fixture { mut session, source, leaving, staying, .. } = fixture(locks, Locks::default(), Locks::default()); + let state = session.active().unwrap(); + let before = state.doc.clone(); + let steps = state.history.past_len(); + let group = group(&mut session, GROUP_FROM_LAYERS); + let state = session.active().unwrap(); + let doc = &state.doc; + assert_eq!(state.history.past_len(), steps + 1); + assert!(doc.layer(source).unwrap().children().unwrap().is_empty()); + assert_eq!(doc.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::>(), [leaving, staying]); + assert_eq!(doc.layer(group).unwrap().locks, Locks::default()); + assert_eq!(doc.layer(leaving).unwrap().locks, locks); + assert_eq!(doc.layer(staying).unwrap().locks, Locks::default()); + session.undo(); + assert_eq!(session.active().unwrap().doc, before); + } +} + +#[test] +fn group_from_layers_keeps_shared_locks_inherited_and_keeps_own_locks() { + let shared_locks = Locks { pixels: true, position: true, ..Default::default() }; + let source_locks = Locks { position: true, ..Default::default() }; + let own_locks = Locks { artboard: true, ..Default::default() }; + let Fixture { mut session, shared, leaving, staying, .. } = fixture(source_locks, shared_locks, own_locks); + let group = group(&mut session, GROUP_FROM_LAYERS); + let doc = &session.active().unwrap().doc; + let new_own_locks = own_locks.union(source_locks); + assert_eq!(doc.layer(leaving).unwrap().locks, new_own_locks); + assert_eq!(doc.layer(staying).unwrap().locks, Locks::default()); + assert_eq!(doc.layer(group).unwrap().locks, Locks::default()); + assert_eq!(doc.effective_locks(staying), shared_locks); + + session + .edit("Unlock ancestor", |doc, _| { + doc.layer_mut(shared).unwrap().locks = Locks::default(); + Ok(()) + }) + .unwrap(); + let doc = &session.active().unwrap().doc; + assert_eq!(doc.effective_locks(leaving), new_own_locks); + assert!(!doc.effective_locks(staying).any()); + let error = session.execute("layer.translate", json!({"layer": leaving.0, "dx": 1})).unwrap_err(); + assert!(error.to_string().contains("locked"), "{error}"); +} + +#[test] +fn group_layers_shortcut_keeps_its_existing_lock_behavior() { + let locks = Locks { all: true, ..Default::default() }; + let Fixture { mut session, leaving, .. } = fixture(locks, Locks::default(), Locks::default()); + group(&mut session, "layer.groupLayers"); + let doc = &session.active().unwrap().doc; + assert!(!doc.layer(leaving).unwrap().locks.any()); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index e899a90437..0adca72451 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -1,3 +1,7 @@ +use std::collections::HashMap; + +use photocraft_doc::Locks; + use super::selection::{reselect, selected, top_level}; use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Result, Session, Value, bad, json}; @@ -135,7 +139,7 @@ pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result { if ids.iter().any(|id| doc.is_background(*id)) { return Err(EngineError::Other("the Background layer can't go into a group".into())); } - group_layers_with(s, p, &ids, ids.len() == 1, false) + group_layers_with(s, p, &ids, true) } /// Group Layers (⌘G) moves the explicit layer or the selection into a new, collapsed group. @@ -144,23 +148,24 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result { Some(id) => vec![id], None => selected(s), }; - group_layers_with(s, p, &ids, false, true) + group_layers_with(s, p, &ids, false) } /// Creates the group at the topmost target, preserving layer order and applying the dialog's -/// options in the same history step. `tag_layers` passes a colour on to the layers inside. -fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool, tag_layers: bool) -> Result { +/// options in the same history step. +fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], from_layers: bool) -> Result { if ids.is_empty() { return Err(EngineError::Other("no layer selected".into())); } let opts = crate::group_options::GroupOptions::parse("layer.groupLayers", p)?; + let expanded = from_layers && ids.len() == 1; let gid = s.edit("Group Layers", |doc, active| { // A base takes the layers clipped to it into the group, still clipped, whether they were // selected or not; a clipped layer that goes in without its base is released, as in the // reference application (#14713). - let mut ids = top_level(doc, ids); - let bases: Vec = ids.clone(); - for id in bases { + let selected_roots = top_level(doc, ids); + let mut ids = selected_roots.clone(); + for &id in &selected_roots { ids.extend(crate::clip_group::clipped_to(doc, id)); } let ids = top_level(doc, &ids); @@ -174,6 +179,24 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool return Err(EngineError::Other("artboards can't go into a group".into())); } let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; + let mut carried_locks = HashMap::new(); + if from_layers { + // Only ancestors the selected layer leaves become own locks. Shared ancestors still + // supply their inherited locks, including when the new group is nested below them. + let insertion_path = doc.insertion_path(top).ok_or(EngineError::NoLayer(top))?; + let (_, destination) = insertion_path.split_last().ok_or(EngineError::NoLayer(top))?; + for id in selected_roots { + let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; + let (_, parents) = path.split_last().ok_or(EngineError::NoLayer(id))?; + let shared = parents.iter().zip(destination).take_while(|(old, new)| old == new).count(); + let locks = (shared + 1..=parents.len()) + .filter_map(|depth| doc.layer_at(&parents[..depth])) + .fold(Locks::default(), |locks, layer| locks.union(layer.locks)); + if locks.any() { + carried_locks.insert(id, locks); + } + } + } let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); let mut group = Layer::group(name, vec![]); if let LayerContent::Group(g) = &mut group.content { @@ -182,14 +205,18 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool let gid = doc.insert_above(Some(top), group); let mut children = Vec::with_capacity(ids.len()); for id in &ids { - children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); + let mut child = doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; + if let Some(&locks) = carried_locks.get(id) { + child.locks = child.locks.union(locks); + } + children.push(child); } for child in children.iter_mut().filter(|l| release.contains(&l.id)) { child.clipped = false; } let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; *group.children_mut().ok_or(EngineError::NoLayer(gid))? = children; - opts.apply(group, tag_layers); + opts.apply(group, !from_layers); check_group_depth(doc, "Group Layers")?; *active = Some(gid); Ok(gid) @@ -201,7 +228,13 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool pub(super) fn merge_layers(s: &mut Session) -> Result { let sel = selected(s); if sel.len() < 2 { - // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. + // ⌘E on a lone clip base is Merge Clipping Mask (#18481); on a lone group, Photoshop's Merge Group (#3832); on a + // layer, Merge Down. + if let Some(&id) = sel.first() + && s.active().is_some_and(|d| merges_clipping_mask(&d.doc, id)) + { + return merge_clipping_mask(s, id); + } if let Some(&id) = sel.first() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { @@ -271,6 +304,66 @@ pub(super) fn merge_layers(s: &mut Session) -> Result { Ok(json!({ "layer": mid.0 })) } +/// `⌘E` on `id` alone is Merge Clipping Mask: a visible pixel-bearing top-level layer with layers clipped to it. A base +/// inside a group, with a layer or vector mask or effects, a group or an adjustment layer as the base, and a hidden base +/// were not measured (#18481) and keep Merge Down or Merge Group. So does a base whose Fill, Blend If, Advanced Blending +/// or excluded channels the merged layer could not carry without changing the composite (review of #18858). +pub fn merges_clipping_mask(doc: &Document, id: LayerId) -> bool { + let Some(l) = doc.layer(id) else { return false }; + doc.path_of(id).is_some_and(|p| p.len() == 1) + && l.visible + && l.mask.is_none() + && l.vector_mask.is_none() + && l.effects.items.is_empty() + && l.fill_opacity >= 1.0 + && l.blend_if.is_default() + && l.advanced.is_default() + && l.excluded_channels == 0 + && !matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) + && !crate::clip_group::clipped_to(doc, id).is_empty() +} + +/// Merge Clipping Mask: the base and the layers clipped to it become one layer with the base's id, name, place, blend mode, +/// opacity, locks, colour label and link. Clipped pixels are blended inside the base's pixels and dropped outside it, so +/// the composite does not change; hidden clipped layers are discarded, as Merge Layers does. +fn merge_clipping_mask(s: &mut Session, base_id: LayerId) -> Result { + s.edit("Merge Clipping Mask", |doc, active| { + let clipped = crate::clip_group::clipped_to(doc, base_id); + let base = doc.layer(base_id).ok_or(EngineError::NoLayer(base_id))?.clone(); + let format = doc.pixel_format(); + // The group alone, the base drawn plainly: its blend mode and opacity stay on the result. + let mut plain = base.clone(); + plain.blend = photocraft_doc::BlendMode::Normal; + plain.opacity = 1.0; + let mut solo = Document::new("merge", doc.size, format.mode, format.sample); + solo.icc_profile = doc.icc_profile.clone(); + let mut stack = vec![plain]; + stack.extend(clipped.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned()); + solo.layers = stack.into(); + // A Background stays canvas-sized and opaque; any other layer keeps its pixels outside the canvas. + let pixels = if doc.is_background(base_id) { + crate::pixels::composite_layers(&solo, format, None) + } else { + crate::pixels::composite_layers_uncropped(&solo, PixelFormat::new(format.mode, format.sample, true)) + }; + let mut merged = Layer::new(base.name.clone(), LayerContent::Raster(pixels)); + merged.id = base_id; + merged.blend = base.blend; + merged.opacity = base.opacity; + merged.locks = base.locks; + merged.label = base.label; + merged.link_group = base.link_group; + for id in &clipped { + doc.remove(*id); + } + *doc.layer_mut(base_id).ok_or(EngineError::NoLayer(base_id))? = merged; + *active = Some(base_id); + Ok(()) + })?; + reselect(s, vec![base_id], Some(base_id)); + Ok(json!({ "layer": base_id.0 })) +} + /// Next visible layer row below the deleted target, then rows above in reverse order. /// Group headers precede their children in the UI, unlike Document::walk's storage order. pub fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { @@ -430,6 +523,10 @@ pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { #[path = "group_from_layers_keeps_layer_tags_tests.rs"] mod group_from_layers_keeps_layer_tags_tests; +#[cfg(test)] +#[path = "group_from_layers_lock_carry_tests.rs"] +mod group_from_layers_lock_carry_tests; + #[cfg(test)] #[path = "group_from_layers_artboard_tests.rs"] mod group_from_layers_artboard_tests; diff --git a/crates/engine-core/src/cmd/pattern_cmds.rs b/crates/engine-core/src/cmd/pattern_cmds.rs index 8a6e108e7e..4ba1488a97 100644 --- a/crates/engine-core/src/cmd/pattern_cmds.rs +++ b/crates/engine-core/src/cmd/pattern_cmds.rs @@ -456,6 +456,33 @@ fn for_each_band(p: &Pattern, w: u32, h: u32, mut f: impl FnMut(&[[f32; 4]])) { } } +/// A layer mask is the edit target: the active pixel layer's or group's mask is targeted, the active layer is an +/// adjustment layer with a mask, which is what it edits, or every colour channel is hidden with no alpha channel shown, so +/// the mask is the picture (as the desktop's target rule reads it). A shown filter mask is not the layer mask. Define +/// Pattern and Define Brush Preset are greyed then (#18232). +pub fn layer_mask_targeted(s: &Session) -> bool { + let Some(st) = s.active() else { return false }; + let Some(layer) = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| l.mask.is_some()) else { return false }; + if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) { + return false; + } + match st.channel_view.target { + crate::channel_cmds::ChannelTarget::LayerMask => true, + crate::channel_cmds::ChannelTarget::Composite if st.doc.quick_mask.is_none() => { + let view = &st.channel_view; + let colors_off = view.visible_colors(crate::channel_cmds::color_count(&st.doc)) == 0; + let alpha_on = (0..st.doc.channels.len()).any(|i| view.alpha_shown(i)); + matches!(layer.content, LayerContent::Adjustment(_)) || (colors_off && !alpha_on) + } + _ => false, + } +} + +fn can_define(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if layer_mask_targeted(s) { Err("a layer mask is the target".into()) } else { Ok(()) } +} + pub fn specs() -> Vec { vec![ CommandSpec { @@ -464,7 +491,7 @@ pub fn specs() -> Vec { menu: &["Edit"], shortcut: None, params: r##"{"name":text,"rect":[x0,y0,x1,y1]?} → {"pattern":id} (name: default the document's name numbered past the library's names; rect: default the selection bounds or else the canvas; added to the library from the visible composite)"##, - enabled: has_doc, + enabled: can_define, journal: true, run: define, }, diff --git a/crates/engine-core/src/cmd/smart_cmds.rs b/crates/engine-core/src/cmd/smart_cmds.rs index 9959e75cb2..222cb9f428 100644 --- a/crates/engine-core/src/cmd/smart_cmds.rs +++ b/crates/engine-core/src/cmd/smart_cmds.rs @@ -148,7 +148,7 @@ fn embed_all_linked(s: &mut Session, _p: &Value) -> Result { } let parent = doc.id; let contents: Vec = ids.iter().map(|id| smart(doc, *id).map(|sm| sm.contents_id)).collect::>()?; - s.edit("Embed All Linked", |doc, _| { + s.edit("Embed All Linked Smart Objects", |doc, _| { for (id, src) in ids.iter().zip(sources) { smart_mut(doc, *id)?.source = src; refresh_or_fail(doc, *id)?; @@ -209,6 +209,8 @@ mod contents; mod filters; mod placing; mod rendering; +#[cfg(test)] +mod reset_transform_noop_tests; mod source; pub(crate) use contents::on_close; @@ -294,7 +296,7 @@ pub fn specs() -> Vec { }), spec!("layer.smartObjects.updateModifiedContent", "Update Modified Content", SO, r##"{"layer":id?}"##, has_linked, |s, p| { let id = layer_param(s, p)?; - s.edit("Update Modified Content", |doc, _| refresh_or_fail(doc, id))?; + s.edit("Update Modified Smart Object", |doc, _| refresh_or_fail(doc, id))?; Ok(json!({"layer": id.0})) }), spec!( diff --git a/crates/engine-core/src/cmd/smart_cmds/contents.rs b/crates/engine-core/src/cmd/smart_cmds/contents.rs index 08292afc6c..ead4d2bfda 100644 --- a/crates/engine-core/src/cmd/smart_cmds/contents.rs +++ b/crates/engine-core/src/cmd/smart_cmds/contents.rs @@ -159,7 +159,7 @@ pub fn commit_child(s: &mut Session, index: usize) -> Result { let prev = s.active; s.active = Some(parent); s.note_active_change(); - let r = s.edit("Edit Contents", |doc, _| { + let r = s.edit("Update Smart Objects", |doc, _| { let ids = instances(doc, link.contents_id); if ids.is_empty() { return Err(other("the smart object's instances were removed")); diff --git a/crates/engine-core/src/cmd/smart_cmds/contents_unpack_history_names_tests.rs b/crates/engine-core/src/cmd/smart_cmds/contents_unpack_history_names_tests.rs new file mode 100644 index 0000000000..7f60c66514 --- /dev/null +++ b/crates/engine-core/src/cmd/smart_cmds/contents_unpack_history_names_tests.rs @@ -0,0 +1,103 @@ +//! #18466: saving a smart object's contents, Convert to Layers, Update Modified Content and Embed All Linked add +//! History states with the names measured in the reference application. The menu labels keep their own wording. + +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// A document whose active layer is a smart object made from one painted layer. +fn smart_object() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, [1.0, 0.0, 0.0, 1.0]); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s +} + +/// The same, with the smart object linked to a file in a directory of its own. Returns the directory too. +fn linked_smart_object(name: &str) -> (Session, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("pc-so-history-names-{name}-{}", std::process::id())); + std::fs::remove_dir_all(&dir).ok(); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = smart_object(); + s.execute("layer.smartObjects.convertToLinked", json!({"path": dir.join("linked.pcraft").to_str().unwrap()})).unwrap(); + (s, dir) +} + +/// Fills a corner of the active document's top layer. +fn paint(s: &mut Session, colour: [f32; 4]) { + s.edit("setup", |doc, _| { + doc.layers.last_mut().unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &colour); + Ok(()) + }) + .unwrap(); +} + +/// The number of History states of the active document and the name of the last one. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(str::to_string)) +} + +fn named(states: usize, name: &str) -> (usize, Option) { + (states, Some(name.to_string())) +} + +#[test] +fn saving_the_contents_adds_update_smart_objects_to_the_parent() { + let mut s = smart_object(); + let parent = s.active_index().unwrap(); + let (states, _) = history(&s); + let child = s.execute("layer.smartObjects.editContents", json!({})).unwrap()["document"].as_u64().unwrap() as usize; + paint(&mut s, [0.0, 1.0, 0.0, 1.0]); + s.execute("layer.smartObjects.saveContents", json!({})).unwrap(); + s.set_active(parent); + assert_eq!(history(&s), named(states + 1, "Update Smart Objects")); + // Closing a changed contents document saves it the same way, under the same name. + s.set_active(child); + paint(&mut s, [0.0, 0.0, 1.0, 1.0]); + s.execute("file.close", json!({})).unwrap(); + s.set_active(parent); + assert_eq!(history(&s), named(states + 2, "Update Smart Objects")); +} + +#[test] +fn convert_to_layers_adds_convert_smart_object_to_layers() { + let mut s = smart_object(); + let (states, _) = history(&s); + s.execute("layer.smartObjects.convertToLayers", json!({})).unwrap(); + assert_eq!(history(&s), named(states + 1, "Convert Smart Object to Layers")); +} + +#[test] +fn update_modified_content_adds_update_modified_smart_object() { + let (mut s, dir) = linked_smart_object("update"); + let (states, _) = history(&s); + s.execute("layer.smartObjects.updateModifiedContent", json!({})).unwrap(); + assert_eq!(history(&s), named(states + 1, "Update Modified Smart Object")); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn embed_all_linked_adds_embed_all_linked_smart_objects() { + let (mut s, dir) = linked_smart_object("embed"); + let (states, _) = history(&s); + s.execute("layer.smartObjects.embedAllLinked", json!({})).unwrap(); + assert_eq!(history(&s), named(states + 1, "Embed All Linked Smart Objects")); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn the_menu_entries_keep_their_labels() { + let _session = crate::session(); + for (id, label) in [ + ("layer.smartObjects.editContents", "Edit Contents"), + ("layer.smartObjects.convertToLayers", "Convert to Layers"), + ("layer.smartObjects.updateModifiedContent", "Update Modified Content"), + ("layer.smartObjects.embedAllLinked", "Embed All Linked"), + ] { + assert_eq!(crate::commands::find(id).unwrap().label, label, "{id}"); + } +} diff --git a/crates/engine-core/src/cmd/smart_cmds/placing.rs b/crates/engine-core/src/cmd/smart_cmds/placing.rs index e207e9f8a3..cbef0bde4c 100644 --- a/crates/engine-core/src/cmd/smart_cmds/placing.rs +++ b/crates/engine-core/src/cmd/smart_cmds/placing.rs @@ -82,6 +82,18 @@ pub(super) fn reset_transform(s: &mut Session, p: &Value) -> Result { if let Some(name) = stuck.first() { return Err(other(format!("the {name} smart filter is not supported, so the smart object's transform can't be reset"))); } + // Already at 100 %, unrotated, unskewed, without Distort, Perspective or Warp (a whole-pixel move + // is no transform: the reset keeps the object where it sits): the reference application leaves + // the item enabled and changes nothing, adding no History state (#18286), so the document's + // changed flag stays as it was too. Checked after the refusals the step has always made (a filter + // it can't apply, a layer locked in place), which stay as they were. + if sm.warp.is_none() && sm.perspective.is_none() && sm.transform.m[..4] == [1.0, 0.0, 0.0, 1.0] { + if crate::transform_cmds::locked_for_transform(&st.doc, id) { + let name = st.doc.layer(id).map_or("", |l| l.name.as_str()); + return Err(other(format!("layer \"{name}\" is locked"))); + } + return Ok(json!({"layer": id.0, "transform": sm.transform.m})); + } // The contents' own box in source pixels: 100 % maps it one-to-one onto the document. let [x0, y0, x1, y1] = source_box(&st.doc, sm).ok_or_else(|| other("the smart object's contents are unavailable"))?; let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); diff --git a/crates/engine-core/src/cmd/smart_cmds/reset_transform_noop_tests.rs b/crates/engine-core/src/cmd/smart_cmds/reset_transform_noop_tests.rs new file mode 100644 index 0000000000..ee39d9d7cc --- /dev/null +++ b/crates/engine-core/src/cmd/smart_cmds/reset_transform_noop_tests.rs @@ -0,0 +1,134 @@ +//! Reset Transform on a smart object that has no transform changes nothing: no History state, and +//! the document's changed flag stays as it was (#18286). Measured in the reference application: the +//! menu item stays enabled on such an object, and choosing it adds no state; on a transformed +//! object it adds exactly one. + +use super::*; + +const RESET: &str = "layer.smartObjects.resetTransform"; + +/// A document with one painted layer converted to a smart object; the smart object's id. +fn smart_session() -> (Session, u64) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("setup", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(8, 6, 40, 30), &[0.8, 0.3, 0.1, 1.0]); + Ok(()) + }) + .unwrap(); + let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + (s, id) +} + +fn state_count(s: &Session) -> usize { + s.active().unwrap().history.entries().len() +} + +fn dirty(s: &Session) -> bool { + s.active().unwrap().is_dirty() +} + +/// Marks the document saved, as File ▸ Save would. +fn mark_saved(s: &mut Session) { + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; +} + +fn layer(s: &Session, id: u64) -> Layer { + s.active().unwrap().doc.layer(LayerId(id)).unwrap().clone() +} + +/// The issue's steps: Convert to Smart Object, then Reset Transform. Enabled, and nothing happens: +/// the layer, the History and a saved document's clean state all stay. +#[test] +fn an_untransformed_smart_object_resets_without_a_state_and_stays_clean() { + let (mut s, id) = smart_session(); + assert!(s.is_enabled(RESET), "the item stays enabled on an untransformed smart object"); + mark_saved(&mut s); + let (states, before) = (state_count(&s), layer(&s, id)); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states, "no history state"); + assert!(!dirty(&s), "a saved document stays unmodified"); + assert_eq!(layer(&s, id), before, "the layer is unchanged"); + assert!(s.is_enabled(RESET), "still enabled afterwards"); +} + +/// A document that already had changes keeps them marked: the no-op neither adds a step nor +/// clears the flag. +#[test] +fn a_modified_document_stays_modified() { + let (mut s, id) = smart_session(); + assert!(dirty(&s), "the fixture's edits mark the document changed"); + let states = state_count(&s); + s.execute(RESET, json!({"layer": id})).unwrap(); + assert_eq!(state_count(&s), states, "no history state for a named layer either"); + assert!(dirty(&s), "still changed"); +} + +/// Moving by whole pixels is no transform: the placement is still 100 %, unrotated and unskewed, +/// and Reset Transform keeps the object where it is, so it changes nothing. +#[test] +fn a_moved_smart_object_is_untransformed() { + let (mut s, id) = smart_session(); + s.execute("layer.translate", json!({"dx": 7, "dy": -3})).unwrap(); + let (states, before) = (state_count(&s), layer(&s, id)); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states, "no history state"); + assert_eq!(layer(&s, id), before, "the layer stays where it was moved to"); +} + +/// On a transformed object the reset is still one state, and a second reset (now untransformed) +/// adds none. +#[test] +fn a_transformed_smart_object_still_adds_exactly_one_state() { + let (mut s, id) = smart_session(); + s.execute("edit.transform", json!({"layer": id, "scaleX": 50, "scaleY": 30, "rotate": 30})).unwrap(); + mark_saved(&mut s); + let states = state_count(&s); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states + 1, "one history state"); + assert!(dirty(&s), "a real reset changes the document"); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states + 1, "the second reset finds nothing to do"); +} + +/// Only a Warp, no other transform: still transformed (unmeasured in the reference; the issue keeps +/// today's behaviour), so the reset takes the Warp off in one state. +#[test] +fn a_warp_alone_counts_as_a_transform() { + let (mut s, _) = smart_session(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); + let states = state_count(&s); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states + 1, "one history state"); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("a smart object") }; + assert!(sm.warp.is_none(), "the Warp is gone"); +} + +/// Distort leaves a projective placement whose affine part can read as 100 %: still transformed. +#[test] +fn a_distorted_smart_object_counts_as_transformed() { + let (mut s, id) = smart_session(); + let r = layer(&s, id).surface().unwrap().content_bounds(); + let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)); + s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": [[x0, y0], [x1, y0], [x1 - 6.0, y1 - 4.0], [x0, y1]]})).unwrap(); + let states = state_count(&s); + s.execute(RESET, json!({})).unwrap(); + assert_eq!(state_count(&s), states + 1, "one history state"); +} + +/// A position-locked object was refused before and still is, transformed or not (unmeasured in the +/// reference; the issue keeps today's behaviour): nothing changes and no state is added. +#[test] +fn a_position_locked_untransformed_object_is_still_refused() { + let (mut s, id) = smart_session(); + s.execute("layer.lockLayers", json!({"position": true})).unwrap(); + let (states, before) = (state_count(&s), layer(&s, id)); + let err = s.execute(RESET, json!({})).unwrap_err().to_string(); + assert!(err.contains("locked"), "{err}"); + assert_eq!(state_count(&s), states, "no history state"); + assert_eq!(layer(&s, id), before); +} diff --git a/crates/engine-core/src/cmd/smart_cmds/unpack.rs b/crates/engine-core/src/cmd/smart_cmds/unpack.rs index a0bc6c2e73..a2dfbc61f9 100644 --- a/crates/engine-core/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine-core/src/cmd/smart_cmds/unpack.rs @@ -187,7 +187,7 @@ pub(super) fn convert_to_layers(s: &mut Session, p: &Value) -> Result { let discarded = sm.smart_filters.len(); let out = unpacked(so, layers); let (new_id, group) = (out.id, out.is_group()); - s.edit("Convert to Layers", |doc, active| { + s.edit("Convert Smart Object to Layers", |doc, active| { let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; *doc.layer_at_mut(&path).ok_or(EngineError::NoLayer(id))? = out; *active = Some(new_id); @@ -224,3 +224,7 @@ fn check_destination_shapes( } Ok(()) } + +#[cfg(test)] +#[path = "contents_unpack_history_names_tests.rs"] +mod contents_unpack_history_names_tests; diff --git a/crates/engine-core/src/cmd/vector_cmds.rs b/crates/engine-core/src/cmd/vector_cmds.rs index e7fc5f6670..22558ba59d 100644 --- a/crates/engine-core/src/cmd/vector_cmds.rs +++ b/crates/engine-core/src/cmd/vector_cmds.rs @@ -173,7 +173,7 @@ pub fn specs() -> Vec { "path.transform", "Free Transform Path", [], - r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"vectorMask":bool=false (with the layer target: its vector mask's path, not a shape layer's path),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = path control bounds)} (numeric transforms pivot on path bounds center)"##, + r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"vectorMask":bool=false (with the layer target: its vector mask's path, not a shape layer's path),"anchors":[[subpath,knot]×…] (Free Transform Points: only these anchors, each with its own handles, follow the map, and translate/scale/angle and the Distort/Warp frame use their bounds; one "Transform Points" step),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = the bounds of what is transformed)} (numeric transforms pivot on those bounds' center)"##, has_doc, path_transform ), diff --git a/crates/engine-core/src/cmd/vector_cmds/combine_shapes_locked_layers_tests.rs b/crates/engine-core/src/cmd/vector_cmds/combine_shapes_locked_layers_tests.rs new file mode 100644 index 0000000000..18af379e49 --- /dev/null +++ b/crates/engine-core/src/cmd/vector_cmds/combine_shapes_locked_layers_tests.rs @@ -0,0 +1,124 @@ +//! #18452: no lock blocks the four Layer › Combine Shapes operations, as in the reference application. The result is +//! the top layer, with the locks it had. Lock Pixels, Lock Transparent Pixels and a lock inherited from a group were +//! not measured and follow the same rule. Merge Shape Components was not measured and still refuses. + +use photocraft_doc::vector::Path; +use photocraft_doc::{Document, LayerContent, LayerId, Locks}; +use serde_json::json; + +use crate::Session; + +const OPERATIONS: [&str; 4] = [ + "layer.combineShapes.unite", + "layer.combineShapes.subtractFrontShape", + "layer.combineShapes.intersectShapeAreas", + "layer.combineShapes.excludeOverlappingShapes", +]; +const MERGE_COMPONENTS: &str = "layer.combineShapes.mergeShapeComponents"; + +const ALL: Locks = Locks { transparency: false, pixels: false, position: false, artboard: false, all: true }; +const POSITION: Locks = Locks { transparency: false, pixels: false, position: true, artboard: false, all: false }; +const PIXELS: Locks = Locks { transparency: false, pixels: true, position: false, artboard: false, all: false }; +const TRANSPARENCY: Locks = Locks { transparency: true, pixels: false, position: false, artboard: false, all: false }; + +/// Two overlapping rectangle shape layers, both selected. Returns the bottom and the top one. +fn two_selected_shapes() -> (Session, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + let bottom = s.execute("shape.create", json!({"rect": [10, 10, 40, 40]})).unwrap()["layer"].as_u64().unwrap(); + let top = s.execute("shape.create", json!({"rect": [30, 30, 40, 40]})).unwrap()["layer"].as_u64().unwrap(); + select(&mut s, LayerId(bottom), LayerId(top)); + (s, LayerId(bottom), LayerId(top)) +} + +fn select(s: &mut Session, bottom: LayerId, top: LayerId) { + s.execute("layer.select", json!({"layer": bottom.0})).unwrap(); + s.execute("layer.select", json!({"layer": top.0, "mode": "add"})).unwrap(); +} + +fn lock(s: &mut Session, id: LayerId, locks: Locks) { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks = locks; + Ok(()) + }) + .unwrap(); +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn path(s: &Session, id: LayerId) -> Path { + match &doc(s).layer(id).unwrap().content { + LayerContent::Shape(shape) => shape.path.clone(), + _ => panic!("not a shape layer"), + } +} + +/// The path `operation` gives without any lock. +fn unlocked(operation: &str) -> Path { + let (mut s, _, top) = two_selected_shapes(); + s.execute(operation, json!({})).unwrap(); + path(&s, top) +} + +/// Runs `operation` and checks that it merged the bottom layer into the top one as without a lock, left the top layer +/// with `kept` as its own locks, and that one Undo brings back both layers and their locks. +fn assert_merges(s: &mut Session, bottom: LayerId, top: LayerId, operation: &str, kept: Locks, case: &str) { + let before = doc(s).clone(); + s.execute(operation, json!({})).unwrap_or_else(|e| panic!("{operation}, {case}: {e}")); + assert!(doc(s).layer(bottom).is_none(), "{operation}, {case}: the bottom layer is merged away"); + assert!(path(s, top) == unlocked(operation), "{operation}, {case}: the same shape as without the lock"); + assert_eq!(doc(s).layer(top).unwrap().locks, kept, "{operation}, {case}: the top layer's own locks"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(*doc(s) == before, "{operation}, {case}: one Undo restores the layers and their locks"); +} + +#[test] +fn lock_all_on_the_bottom_layer_does_not_block_and_the_result_has_no_lock() { + for operation in OPERATIONS { + let (mut s, bottom, top) = two_selected_shapes(); + lock(&mut s, bottom, ALL); + assert_merges(&mut s, bottom, top, operation, Locks::default(), "Lock All on the bottom layer"); + } +} + +#[test] +fn a_lock_on_the_top_layer_does_not_block_and_stays_on_the_result() { + for operation in OPERATIONS { + for (locks, case) in [(ALL, "Lock All on the top layer"), (POSITION, "Lock Position on the top layer")] { + let (mut s, bottom, top) = two_selected_shapes(); + lock(&mut s, top, locks); + assert_merges(&mut s, bottom, top, operation, locks, case); + } + } +} + +/// Not measured; the item asks for the same rule. +#[test] +fn lock_pixels_lock_transparency_and_a_locked_group_do_not_block_either() { + for operation in OPERATIONS { + for (locks, case) in [(PIXELS, "Lock Pixels"), (TRANSPARENCY, "Lock Transparent Pixels")] { + let (mut s, bottom, top) = two_selected_shapes(); + lock(&mut s, bottom, locks); + lock(&mut s, top, locks); + assert_merges(&mut s, bottom, top, operation, locks, case); + } + let (mut s, bottom, top) = two_selected_shapes(); + let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + lock(&mut s, group, ALL); + select(&mut s, bottom, top); + assert!(doc(&s).effective_locks(top).all, "the group's lock reaches the layers"); + assert_merges(&mut s, bottom, top, operation, Locks::default(), "Lock All on the group around both"); + } +} + +/// Not measured, so Merge Shape Components keeps refusing locked layers. +#[test] +fn merge_shape_components_still_refuses_a_locked_layer() { + let (mut s, bottom, _) = two_selected_shapes(); + lock(&mut s, bottom, ALL); + let before = doc(&s).clone(); + assert!(s.execute(MERGE_COMPONENTS, json!({})).is_err()); + assert!(*doc(&s) == before, "nothing changed"); +} diff --git a/crates/engine-core/src/cmd/vector_cmds/paths.rs b/crates/engine-core/src/cmd/vector_cmds/paths.rs index d3e07b2a2d..7ff11d8186 100644 --- a/crates/engine-core/src/cmd/vector_cmds/paths.rs +++ b/crates/engine-core/src/cmd/vector_cmds/paths.rs @@ -1,8 +1,8 @@ use super::params::{color, f64p, layer_id, op_from, parse_path, path_json}; use super::shape::{map_path, map_shape, transform_shape, with_shape}; use super::{ - Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad, - json, parse_blend, sel, vector, + Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Point, Rect, Result, SelectionMode, Session, Value, + bad, json, parse_blend, sel, vector, }; // --------------------------------------------------------------------------- @@ -233,6 +233,88 @@ enum PathMap { Warp(Box), } +/// One point of the path through `map`; a point the map sends out of bounds is an error. +fn point_through(map: &PathMap, p: Point) -> Result { + let q = match map { + PathMap::Affine(a) => a.apply(p), + PathMap::Projective(h) => { + let (x, y) = h.apply(p.x, p.y); + Point::new(x, y) + } + PathMap::Warp(w) => { + let (x, y) = w.map(p.x, p.y); + Point::new(x, y) + } + }; + (q.x.is_finite() && q.y.is_finite()).then_some(q).ok_or_else(|| EngineError::Other("the distortion sends part of the path out of bounds".into())) +} + +/// The anchors `path.transform` moves on their own (Free Transform Points, #13209), named as +/// `path.moveAnchors` names them: `[subpath, knot]` pairs. `None` transforms the whole path; an empty +/// or malformed list is an error, and a repeated pair moves that point once. +fn anchor_list(cmd: &str, p: &Value) -> Result>> { + let Some(v) = p.get("anchors") else { return Ok(None) }; + if v.is_null() { + return Ok(None); + } + let Some(list) = v.as_array().filter(|list| !list.is_empty()) else { + return Err(bad(cmd, "`anchors` must list [subpath, knot] pairs")); + }; + let mut out: Vec<[usize; 2]> = Vec::with_capacity(list.len()); + for a in list { + let [s, k] = a + .as_array() + .filter(|a| a.len() == 2) + .and_then(|a| Some([a[0].as_u64()?, a[1].as_u64()?])) + .and_then(|v| Some([usize::try_from(v[0]).ok()?, usize::try_from(v[1]).ok()?])) + .ok_or_else(|| bad(cmd, "each anchor is [subpath, knot] with whole numbers"))?; + if !out.contains(&[s, k]) { + out.push([s, k]); + } + } + Ok(Some(out)) +} + +/// The bounds the transform acts on, as `[x0, y0, x1, y1]`: the anchors and their own handles a point +/// transform names — the same measure [`Path::control_bounds`] is for the whole path — or the whole +/// path's control bounds. An index that is not a knot of `path` is an error. +fn acted_on_bounds(cmd: &str, path: &Path, anchors: Option<&[[usize; 2]]>) -> Result<[f64; 4]> { + let mut b: Option<[f64; 4]> = None; + if let Some(anchors) = anchors { + for &[s, k] in anchors { + let Some(node) = path.subpaths.get(s).and_then(|sp| sp.knots.get(k)) else { + return Err(bad(cmd, format!("no anchor [{s}, {k}] on this path"))); + }; + for p in [node.anchor, node.in_ctrl, node.out_ctrl] { + b = Some(match b { + Some([x0, y0, x1, y1]) => [x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)], + None => [p.x, p.y, p.x, p.y], + }); + } + } + } else { + b = path.control_bounds().map(|(x0, y0, x1, y1)| [x0, y0, x1, y1]); + } + b.ok_or_else(|| bad(cmd, "path has no points to transform")) +} + +/// Free Transform Points (#13209): only the listed knots follow the map, each with its own handles; +/// every other anchor and handle of the path stays exactly where it is. +fn map_selected_points(path: &Path, anchors: &[[usize; 2]], map: &PathMap) -> Result { + let mut out = path.clone(); + for &[s, k] in anchors { + // The indices were checked against the same path before anything was edited. + let Some(node) = out.subpaths.get_mut(s).and_then(|sp| sp.knots.get_mut(k)) else { + return Err(EngineError::Other(format!("no anchor [{s}, {k}] on this path"))); + }; + let (anchor, handle_in, handle_out) = (point_through(map, node.anchor)?, point_through(map, node.in_ctrl)?, point_through(map, node.out_ctrl)?); + node.anchor = anchor; + node.in_ctrl = handle_in; + node.out_ctrl = handle_out; + } + Ok(out) +} + pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.transform"; let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); @@ -251,15 +333,17 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result { // its groups. Pixel-only locks still allow mask edits; shape content checks them below. crate::commands::check_all_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; } - // The box Distort, Perspective and Warp frame: `rect`, else the path's control bounds. + // The anchors of a point-level transform (Free Transform Points, #13209), checked against the + // path before anything changes: a stale anchor list must refuse, not move another point. + let anchors = anchor_list(CMD, p)?; + if let Some(anchors) = &anchors { + acted_on_bounds(CMD, &transform_target(s, &name, layer_id, vector_mask)?, Some(anchors))?; + } + // The box Distort, Perspective and Warp frame: `rect`, else the bounds of what is transformed. let frame = |s: &Session| -> Result<[f64; 4]> { let r = match coords(p, "rect", 4)? { Some(r) => [r[0], r[1], r[2], r[3]], - None => { - let (x0, y0, x1, y1) = - transform_target(s, &name, layer_id, vector_mask)?.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; - [x0, y0, x1, y1] - } + None => acted_on_bounds(CMD, &transform_target(s, &name, layer_id, vector_mask)?, anchors.as_deref())?, }; if r[2] - r[0] <= 0.0 || r[3] - r[1] <= 0.0 { return Err(bad(CMD, "`rect` must have a positive width and height (a straight path needs a `rect`)")); @@ -311,9 +395,10 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result { let (tx, ty) = (number("translateX", 0.0)?, number("translateY", 0.0)?); let (sx, sy) = (number("scaleX", 1.0)?, number("scaleY", 1.0)?); let angle = number("angle", 0.0)?; - // An explicit `layer` parameter determines both the transformed path and its pivot (#3062). + // An explicit `layer` parameter determines both the transformed path and its pivot (#3062); + // `anchors` pivots on the bounds of the anchors it names. let path = transform_target(s, &name, layer_id, vector_mask)?; - let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; + let [x0, y0, x1, y1] = acted_on_bounds(CMD, &path, anchors.as_deref())?; let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5); PathMap::Affine( Affine::translate(-cx, -cy) @@ -327,27 +412,38 @@ pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result { PathMap::Projective(h) => json!({ "name": name, "homography": h.0 }), PathMap::Warp(_) => json!({ "name": name, "warp": true }), }; + let label = if anchors.is_some() { "Transform Points" } else { "Transform Path" }; if !vector_mask && let Some(id) = layer_id && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|layer| matches!(layer.content, LayerContent::Shape(_))) { - with_shape(s, id, "Transform Path", |shape, _| { - match &map { - PathMap::Affine(a) => transform_shape(shape, a), - PathMap::Projective(h) => map_shape(shape, Some(h), None)?, - PathMap::Warp(w) => map_shape(shape, None, Some(w))?, + with_shape(s, id, label, |shape, _| { + if let Some(anchors) = &anchors { + // Only part of the outline moved: the live shape's parameters cannot describe that, + // as with any other point-level path edit. + shape.path = map_selected_points(&shape.path, anchors, &map)?; + shape.live = None; + } else { + match &map { + PathMap::Affine(a) => transform_shape(shape, a), + PathMap::Projective(h) => map_shape(shape, Some(h), None)?, + PathMap::Warp(w) => map_shape(shape, None, Some(w))?, + } } shape.psd_raw = None; Ok(()) })?; return Ok(out); } - s.edit("Transform Path", |doc, _| { + s.edit(label, |doc, _| { let path = path_mut(doc, &name, layer_id)?; - *path = match &map { - PathMap::Affine(a) => path.transform(a), - PathMap::Projective(h) => map_path(path, Some(h), None)?, - PathMap::Warp(w) => map_path(path, None, Some(w))?, + *path = match &anchors { + Some(anchors) => map_selected_points(path, anchors, &map)?, + None => match &map { + PathMap::Affine(a) => path.transform(a), + PathMap::Projective(h) => map_path(path, Some(h), None)?, + PathMap::Warp(w) => map_path(path, None, Some(w))?, + }, }; Ok(()) })?; diff --git a/crates/engine-core/src/cmd/vector_cmds/shape.rs b/crates/engine-core/src/cmd/vector_cmds/shape.rs index c72860c4f7..065a82d481 100644 --- a/crates/engine-core/src/cmd/vector_cmds/shape.rs +++ b/crates/engine-core/src/cmd/vector_cmds/shape.rs @@ -861,7 +861,9 @@ fn combine_targets(s: &Session, p: &Value, narrow: &[&str]) -> Result, label: &str, bake: Option) -> Result { let (&keep, _) = ids.split_last().ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?; - if let Some(st) = s.active() { + // No lock blocks the four Combine Shapes operations; the result is the top layer, with its own locks (#18452). + // Merge Shape Components was not measured and still refuses. + if let Some(st) = s.active().filter(|_| op.is_none()) { for id in ids { let locks = st.doc.effective_locks(*id); if locks.all || locks.pixels { @@ -951,6 +953,10 @@ mod triangle_layer_name_tests; #[path = "triangle_box_geometry_tests.rs"] mod triangle_box_geometry_tests; +#[cfg(test)] +#[path = "combine_shapes_locked_layers_tests.rs"] +mod combine_shapes_locked_layers_tests; + #[cfg(test)] mod arrow_affine_regression_tests { use super::*; diff --git a/crates/engine-core/src/cmd/vector_cmds/tests.rs b/crates/engine-core/src/cmd/vector_cmds/tests.rs index 732f566cbd..b238ea2c98 100644 --- a/crates/engine-core/src/cmd/vector_cmds/tests.rs +++ b/crates/engine-core/src/cmd/vector_cmds/tests.rs @@ -1300,12 +1300,11 @@ fn combine_shapes_fails_gracefully() { } } assert_eq!(s.active().unwrap().history.past_len(), history); - // Locked layers refuse the merge without touching the document. + // Locks do not block the merge (#18452). s.execute("layer.lockLayers", json!({"all": true})).unwrap(); assert!(doc(&s).effective_locks(LayerId(a)).all); - let before = doc(&s).clone(); - assert!(s.execute("layer.combineShapes.unite", json!({})).is_err()); - assert_eq!(*doc(&s), before); + s.execute("layer.combineShapes.unite", json!({})).unwrap(); + assert!(doc(&s).layer(LayerId(a)).is_none(), "the locked layers merge"); } #[test] diff --git a/crates/engine-core/src/color_channels.rs b/crates/engine-core/src/color_channels.rs index c22ff8093d..20cc347f7c 100644 --- a/crates/engine-core/src/color_channels.rs +++ b/crates/engine-core/src/color_channels.rs @@ -63,7 +63,10 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option { } } if id == "image.adjustments.hdrToning" { - return Some("HDR Toning requires the composite channel".into()); + return s + .active() + .and_then(|state| crate::adjust_cmds::hdr_toning_mode_refusal(state.doc.mode)) + .or_else(|| Some("HDR Toning requires the composite channel".into())); } if crate::channel_cmds::routed(id) && p.get("newLayer").and_then(Value::as_bool) == Some(true) { return Some("Creating a new layer requires the composite channel".into()); diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 836c5837b6..8a5f7604c6 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -412,6 +412,9 @@ pub struct ToolState { /// The pair Quick Mask put aside, with its CMYK roles: the Quick Mask pair outside Quick /// Mask, the pixel (or layer mask) pair inside it (#17490). pub quick_mask_aside: ([[f32; 4]; 2], CmykPair), + /// How many "Sampled Brush N" defaults Define Brush Preset stored in this session, which gives the next N. Deleting + /// or renaming those presets doesn't lower it, and is not saved to settings (#18228). + pub sampled_brushes: u32, } /// Native CMYK inks associated with each color role. @@ -565,6 +568,7 @@ impl Default for ToolState { cmyk_roles: [[None; 2]; 2], quick_mask_on: false, quick_mask_aside: (Self::MASK_COLORS, [None; 2]), + sampled_brushes: 0, } } } diff --git a/crates/engine-core/src/embed_all_linked_tests.rs b/crates/engine-core/src/embed_all_linked_tests.rs index 11fd04dc6b..d3b5284e7f 100644 --- a/crates/engine-core/src/embed_all_linked_tests.rs +++ b/crates/engine-core/src/embed_all_linked_tests.rs @@ -99,7 +99,7 @@ fn embed_all_linked_embeds_both_linked_objects_in_one_undoable_step() { assert_eq!(embedded(&s, ids[2]), third, "the already embedded object is untouched"); let entries = s.active().unwrap().history.entries(); assert_eq!(entries.len(), before + 1, "one history step"); - assert_eq!(entries.last().map(String::as_str), Some("Embed All Linked")); + assert_eq!(entries.last().map(String::as_str), Some("Embed All Linked Smart Objects")); assert!(!s.is_enabled("layer.smartObjects.embedAllLinked"), "nothing left to embed"); s.execute("edit.undo", json!({})).unwrap(); diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index d3e06552f7..4c5f3ac5a4 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -159,7 +159,7 @@ pub fn effect_defaults(kind: &str) -> Value { json!({"blend": "Screen", "opacity": 35, "color": "#ffffff", "technique": "softer", "spread": 0, "size": 7, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) } "innerGlow" => { - json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "technique": "softer", "source": "edge", "choke": 0, "size": 5, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) + json!({"blend": "Screen", "opacity": 35, "color": "#ffffff", "technique": "softer", "source": "edge", "choke": 0, "size": 7, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) } "stroke" => json!({"size": 1, "position": "inside", "blend": "Normal", "opacity": 100, "overprint": false, "color": "#000000"}), "colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}), @@ -576,15 +576,13 @@ fn fresh_effect(kind: &str) -> Option { noise: 0.0, knocks_out: !inner, }; - // The two glows share their shape, but not their factory values: the Outer Glow starts at - // the reference application's white 35 % Size 7 (#14944), the Inner Glow at today's values - // until #14917 measures its own. - let glow = |inner: bool| Glow { - common: FxCommon::new(BlendMode::Screen, if inner { 0.75 } else { 0.35 }), - paint: FxPaint::Color(if inner { Color::rgb(1.0, 1.0, 190.0 / 255.0) } else { Color::WHITE }), + // Both glows start at the reference application's white 35 % Size 7 (#14944, #14917). + let glow = || Glow { + common: FxCommon::new(BlendMode::Screen, 0.35), + paint: FxPaint::Color(Color::WHITE), technique: GlowTechnique::Softer, spread: 0.0, - size: if inner { 5.0 } else { 7.0 }, + size: 7.0, contour: Contour::Linear, anti_alias: false, range: 0.5, @@ -595,8 +593,8 @@ fn fresh_effect(kind: &str) -> Option { Some(match kind { "dropShadow" => Effect::DropShadow(shadow(false)), "innerShadow" => Effect::InnerShadow(shadow(true)), - "outerGlow" => Effect::OuterGlow(glow(false)), - "innerGlow" => Effect::InnerGlow(glow(true)), + "outerGlow" => Effect::OuterGlow(glow()), + "innerGlow" => Effect::InnerGlow(glow()), "stroke" => Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size: 1.0, @@ -1227,7 +1225,7 @@ pub fn specs() -> Vec { style_cmd!( "innerGlow", "Inner Glow…", - r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"range":1..100=50,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## + r##"{"color":"#rrggbb","opacity":0..100=35,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"range":1..100=50,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## ), style_cmd!( "stroke", @@ -1343,6 +1341,9 @@ mod satin_defaults_tests; #[cfg(test)] mod outer_glow_defaults_tests; +#[cfg(test)] +mod inner_glow_defaults_tests; + #[cfg(test)] mod inner_shadow_ranges_tests; #[cfg(test)] diff --git a/crates/engine-core/src/layer_style/inner_glow_defaults_tests.rs b/crates/engine-core/src/layer_style/inner_glow_defaults_tests.rs new file mode 100644 index 0000000000..f12cf36e63 --- /dev/null +++ b/crates/engine-core/src/layer_style/inner_glow_defaults_tests.rs @@ -0,0 +1,124 @@ +//! #14917: the Inner Glow page's factory values (Screen, 35 %, Noise 0, white, Softer, Edge, +//! Choke 0, Size 7, Linear, Anti-aliased off, Range 50) and the rule that a glow already stored +//! keeps its own values. The measured pixels of the factory glow sit within 1 level of the +//! reference application's on the white test document. + +use super::*; +use crate::Session; +use serde_json::json; + +/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a white Background and a pixel +/// layer with an orange (255,128,0) rectangle at x 100..299, y 75..224. +fn test_document() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#ffffff"})).unwrap(); + let layer = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.edit("Pixels", |doc, _| { + let orange = [1.0, 128.0 / 255.0, 0.0, 1.0]; + doc.layer_mut(photocraft_doc::LayerId(layer)).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::from_xywh(100, 75, 200, 150), &orange); + Ok(()) + }) + .unwrap(); + s +} + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one glow the active layer carries, as an inner glow. +fn inner_glow(s: &Session) -> Glow { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [Effect::InnerGlow(g)] => g.clone(), + other => panic!("no inner glow: {other:?}"), + } +} + +/// #14917: Layer > Layer Style > Inner Glow... on a layer without one starts from the reference +/// application's factory values; the dialog seeds a new instance from `effect_defaults`. +#[test] +fn a_new_inner_glow_starts_at_the_factory_values() { + let d = effect_defaults("innerGlow"); + assert_eq!(d["blend"], json!("Screen"), "blend"); + assert_eq!(d["opacity"], json!(35), "opacity"); + assert_eq!(d["noise"], json!(0), "noise"); + assert_eq!(d["color"], json!("#ffffff"), "colour"); + assert_eq!(d["technique"], json!("softer"), "technique"); + assert_eq!(d["source"], json!("edge"), "source"); + assert_eq!(d["choke"], json!(0), "choke"); + assert_eq!(d["size"], json!(7), "size"); + assert_eq!(d["contour"], json!("Linear"), "contour"); + assert_eq!(d["antiAlias"], json!(false), "anti-aliased"); + assert_eq!(d["range"], json!(50), "range"); +} + +/// #14917: `layer.layerStyle.innerGlow` without params makes the same effect the page starts at. +#[test] +fn an_inner_glow_command_without_params_makes_the_factory_effect() { + let mut s = session(); + s.execute("layer.layerStyle.innerGlow", json!({})).unwrap(); + let g = inner_glow(&s); + assert_eq!(g.common.blend, BlendMode::Screen, "blend mode"); + assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4, "opacity {} %", g.common.opacity * 100.0); + let FxPaint::Color(c) = g.paint else { panic!("not a plain colour: {:?}", g.paint) }; + let rgb = c.to_rgb(); + assert!(rgb.iter().all(|v| (v - 1.0).abs() < 1e-4), "colour {rgb:?} is not white"); + assert_eq!((g.technique, g.source, g.spread, g.size), (GlowTechnique::Softer, GlowSource::Edge, 0.0, 7.0)); + assert!(matches!(g.contour, Contour::Linear), "contour {:?}", g.contour); + assert!(!g.anti_alias, "anti-aliased"); + assert!((g.range - 0.5).abs() < 1e-4, "range {}", g.range); + assert_eq!(g.noise, 0.0, "noise"); +} + +/// #14917: Reset to Default reads these factory values through `layer.layerStyle.defaultFor` +/// until a Make Default stores other ones; the saved values keep winning (the Make Default path +/// is not measured, so it keeps today's behaviour). +#[test] +fn reset_to_default_restores_the_inner_glow_factory_values() { + let mut s = session(); + let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "innerGlow"})).unwrap(); + assert_eq!(d["user"], json!(false)); + assert_eq!((d["params"]["opacity"].as_f64(), d["params"]["color"].as_str(), d["params"]["size"].as_f64()), (Some(35.0), Some("#ffffff"), Some(7.0))); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "innerGlow", "params": {"opacity": 12, "size": 3}})).unwrap(); + let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "innerGlow"})).unwrap(); + assert_eq!(saved["user"], json!(true)); + assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["size"].as_f64()), (Some(12.0), Some(3.0)), "a saved default still wins"); +} + +/// #14917 measured: OK on the factory values over the white test document. Top edge of the +/// flattened image at x 200, y 75 inwards to 81, R.G.B; the reference application's are +/// 255.166.76 255.155.54 255.146.36 255.139.22 255.133.11 255.129.3 255.128.0, within 1 level. +#[test] +fn the_factory_inner_glow_paints_the_measured_edge() { + let mut s = test_document(); + s.execute("layer.layerStyle.innerGlow", json!({})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let rgb = |x: usize, y: usize| px[y * 400 + x].map(|v| (v * 255.0).round() as i32); + for (y, want) in + [(75, [255, 166, 76]), (76, [255, 155, 54]), (77, [255, 146, 36]), (78, [255, 139, 22]), (79, [255, 133, 11]), (80, [255, 129, 3]), (81, [255, 128, 0])] + { + let got = rgb(200, y); + assert!(got[..3].iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "top edge at (200, {y}): {:?}, the reference gives {want:?}", &got[..3]); + } +} + +/// #14917: an Inner Glow the document already carries keeps the values it was read with. The +/// Layer Style dialog's OK (and so a PSD or `.pcraft` effect edited in it) goes through +/// `layer.layerStyle.replace` with the effect's own snapshot: absent params leave it alone. +#[test] +fn a_stored_inner_glow_keeps_its_own_values_through_replace() { + let mut s = session(); + s.execute("layer.layerStyle.innerGlow", json!({"opacity": 75, "color": "#ffffbe", "size": 5})).unwrap(); + let stored = inner_glow(&s); + let snapshot = serde_json::to_value(Effect::InnerGlow(stored.clone())).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "innerGlow", "params": {}, "fx": snapshot}]})).unwrap(); + let kept = inner_glow(&s); + assert_eq!(kept, stored, "an edited effect list left the glow's values alone"); + assert!((kept.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (kept.size - 5.0).abs() < 1e-4, "kept {kept:?}"); +} diff --git a/crates/engine-core/src/layer_style/outer_glow_defaults_tests.rs b/crates/engine-core/src/layer_style/outer_glow_defaults_tests.rs index 4a16afd40c..49c8563c73 100644 --- a/crates/engine-core/src/layer_style/outer_glow_defaults_tests.rs +++ b/crates/engine-core/src/layer_style/outer_glow_defaults_tests.rs @@ -89,22 +89,3 @@ fn a_stored_outer_glow_keeps_its_own_values_through_replace() { assert_eq!(kept, stored, "an edited effect list left the glow's values alone"); assert!((kept.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (kept.size - 5.0).abs() < 1e-4, "kept {kept:?}"); } - -/// #14944 is only about the Outer Glow page; the Inner Glow's factory values are #14917 and stay -/// as they are today (the two glows share their fresh effect in the engine). -#[test] -fn an_inner_glow_still_starts_at_todays_values() { - let d = effect_defaults("innerGlow"); - assert_eq!((d["opacity"].as_f64(), d["color"].as_str(), d["size"].as_f64()), (Some(75.0), Some("#ffffbe"), Some(5.0))); - let mut s = session(); - s.execute("layer.layerStyle.innerGlow", json!({})).unwrap(); - let g = match &s.active().unwrap().doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().effects.items[0] { - Effect::InnerGlow(g) => g.clone(), - other => panic!("{other:?}"), - }; - assert!((g.common.opacity * 100.0 - 75.0).abs() < 1e-4, "opacity {}", g.common.opacity); - assert_eq!(g.size, 5.0, "size"); - let FxPaint::Color(c) = g.paint else { panic!("{:?}", g.paint) }; - let rgb = c.to_rgb(); - assert!((rgb[0] - 1.0).abs() < 1e-3 && (rgb[1] - 1.0).abs() < 1e-3 && (rgb[2] - 190.0 / 255.0).abs() < 1e-3, "colour {rgb:?}"); -} diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 3f6f605c33..2e4ee4c413 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -309,6 +309,9 @@ pub struct Session { next_pending_preflight: u64, /// Shared native memory supervision, owned and stopped by the last session using it. scratch_runtime: Option, + /// The scratch disk and memory settings [`Session::apply_prefs`] last configured: an edit of + /// other preferences configures nothing again. + scratch_applied: Option, /// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a /// scratch disk that pauses or resumes changes the limit ([`Session::sync_scratch_state`]). scratch_epoch: u64, @@ -334,6 +337,8 @@ mod embed_all_linked_tests; mod fill_layer_mode_tests; #[cfg(test)] mod new_layer_name_counter_tests; +#[cfg(test)] +mod quick_mask_history_name_tests; #[cfg(test)] mod second_keys_zoom_actions_tests; diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index 76d893ed93..8d56154bb3 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -1902,7 +1902,11 @@ impl Session { /// missing-glyph protection. pub fn apply_prefs(&mut self) { self.scratch_runtime.get_or_insert_with(crate::scratch::Runtime::default); - crate::scratch::configure(self.prefs()); + let scratch = crate::scratch::Settings::of(self.prefs()); + if self.scratch_applied.as_ref() != Some(&scratch) { + crate::scratch::configure(&scratch); + self.scratch_applied = Some(scratch); + } self.scratch_epoch = photocraft_raster::spill::epoch(); let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_cap_bytes(); diff --git a/crates/engine-core/src/quick_mask_history_name_tests.rs b/crates/engine-core/src/quick_mask_history_name_tests.rs new file mode 100644 index 0000000000..3c945baf25 --- /dev/null +++ b/crates/engine-core/src/quick_mask_history_name_tests.rs @@ -0,0 +1,21 @@ +//! #17493: entering Quick Mask is the History state "Enter Quick Mask", as in the reference +//! application; leaving stays "Exit Quick Mask". + +use serde_json::{Value, json}; + +use crate::Session; + +/// Runs `cmd` and returns the History states it added. +fn added(s: &mut Session, cmd: &str, p: Value) -> Vec { + let before = s.active().unwrap().history.entries().len(); + s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + s.active().unwrap().history.entries()[before..].to_vec() +} + +#[test] +fn entering_and_leaving_quick_mask_name_their_states() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + assert_eq!(added(&mut s, "select.editInQuickMaskMode", json!({"on": true})), ["Enter Quick Mask"]); + assert_eq!(added(&mut s, "select.editInQuickMaskMode", json!({"on": false})), ["Exit Quick Mask"]); +} diff --git a/crates/engine-core/src/scratch.rs b/crates/engine-core/src/scratch.rs index 9133f76f03..6c46f15883 100644 --- a/crates/engine-core/src/scratch.rs +++ b/crates/engine-core/src/scratch.rs @@ -129,42 +129,101 @@ mod native { // If configure uses this query even once, it pauses for lack of room. This catches an // override that is missing or is installed after configuring the scratch directory. photocraft_raster::spill::set_volume_space_for_tests(|_| Some((0, 64 << 30))); - super::super::configure(&crate::prefs::Preferences::default()); + super::super::configure(&super::super::Settings::of(&crate::prefs::Preferences::default())); assert!(!photocraft_raster::spill::paused()); let room = (32_u64 << 30) - (64_u64 << 30) / 20; assert_eq!(photocraft_raster::spill::scratch_capacity(), Some(room - room / 64)); } + + /// A preference edit that changes neither Memory Usage nor the scratch disks configures + /// neither again: a dragged dialog remembers its place through a preference edit every + /// frame, and configuring took milliseconds each time. + #[test] + fn unrelated_preference_edits_leave_the_scratch_disk_alone() { + const CHILD: &str = "PHOTOCRAFT_SCRATCH_UNRELATED_EDIT_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "scratch::native::tests::unrelated_preference_edits_leave_the_scratch_disk_alone"]) + .env(CHILD, "1") + .status() + .unwrap(); + assert!(status.success(), "isolated scratch test failed: {status}"); + return; + } + + let mut session = crate::Session::new(); + // As at startup (`prefs_ui::startup`). + session.apply_prefs(); + let configured = photocraft_raster::memory::configuration_generation; + let before = configured(); + session.edit_prefs(|p| { + p.sections.insert("photocraft.test.window".into(), serde_json::json!({"x": 1})); + }); + assert_eq!(configured(), before, "a section edit configured the scratch disk again"); + session.edit_prefs(|p| p.performance.memory_usage_percent = Some(p.performance.memory_usage_percent.unwrap_or(70) - 10)); + assert!(configured() > before, "a Memory Usage edit must reach the memory budgets"); + } } } -pub(crate) fn configure(prefs: &Preferences) { +/// What [`configure`] reads from the preferences. An edit that leaves it the same leaves the +/// scratch disk and the memory budgets as they are ([`crate::Session::apply_prefs`]): configuring +/// them again re-measures memory, probes the scratch folder and restarts a paused disk's backoff, +/// which takes milliseconds, and preference edits come once per frame while a remembered window +/// is dragged. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Settings { + percent: Option, + absolute_mb: u32, + /// The first enabled scratch disk. + #[cfg(not(target_arch = "wasm32"))] + dir: Option, + #[cfg(not(target_arch = "wasm32"))] + size_limit_mb: u32, + /// The tile budget's override (`PHOTOCRAFT_TILE_BUDGET_MB`), when set. + #[cfg(not(target_arch = "wasm32"))] + tile_override: Option, +} + +impl Settings { + pub(crate) fn of(prefs: &Preferences) -> Self { + Settings { + percent: prefs.performance.memory_usage_percent, + // The web build's cap applies here too (effective_memory_usage_mb). + absolute_mb: prefs.performance.effective_memory_usage_mb(), + #[cfg(not(target_arch = "wasm32"))] + dir: prefs + .scratch_disks + .disks + .iter() + .find(|d| d.enabled && !d.path.trim().is_empty()) + .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }), + #[cfg(not(target_arch = "wasm32"))] + size_limit_mb: prefs.scratch_disks.size_limit_mb, + #[cfg(not(target_arch = "wasm32"))] + tile_override: std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some().then(|| prefs.performance.tile_budget_bytes()), + } + } +} + +/// Configures the memory budgets and the scratch disk as `settings` say. +pub(crate) fn configure(settings: &Settings) { #[cfg(all(test, not(target_arch = "wasm32")))] photocraft_raster::spill::use_test_volume_space(); let budget = photocraft_raster::memory::configure(photocraft_raster::memory::Policy { - percent: prefs.performance.memory_usage_percent, - // The web build's cap applies here too (effective_memory_usage_mb). - absolute_bytes: u64::from(prefs.performance.effective_memory_usage_mb()).saturating_mul(1 << 20), + percent: settings.percent, + absolute_bytes: u64::from(settings.absolute_mb).saturating_mul(1 << 20), }); #[cfg(not(target_arch = "wasm32"))] { - let dir = prefs - .scratch_disks - .disks - .iter() - .find(|d| d.enabled && !d.path.trim().is_empty()) - .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }); // An unusable or full directory pauses eviction without dropping resident pixels and // is retried with backoff; History's byte limit applies meanwhile (sync_scratch_state). // The reason is exposed in ui.inspect and the application's status bar. - let tiles = if std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some() { - prefs.performance.tile_budget_bytes() - } else { - usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX) - }; - let limit = prefs.scratch_disks.size_limit_mb; + let tiles = settings.tile_override.unwrap_or_else(|| usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX)); + let limit = settings.size_limit_mb; photocraft_raster::spill::set_size_cap((limit > 0).then(|| u64::from(limit).saturating_mul(1 << 20))); - let _ = photocraft_raster::spill::configure(dir.as_deref(), tiles); + let _ = photocraft_raster::spill::configure(settings.dir.as_deref(), tiles); } #[cfg(target_arch = "wasm32")] - let _ = (prefs, budget); + let _ = budget; } diff --git a/crates/engine-core/src/shell_commands.rs b/crates/engine-core/src/shell_commands.rs index 718454fba3..08dc7b21df 100644 --- a/crates/engine-core/src/shell_commands.rs +++ b/crates/engine-core/src/shell_commands.rs @@ -58,6 +58,7 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")), ("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")), ("view.actualPixels", "100%", &["View"], Some("Cmd+1")), + ("view.actualSize", "Actual Size", &["View"], None), ("view.rotateView", "Rotate View", &[], None), ("view.rotateLeft", "Rotate View Left", &["View"], Some("Alt+Shift+,")), ("view.rotateRight", "Rotate View Right", &["View"], Some("Alt+Shift+.")), diff --git a/crates/engine-paint/src/cmd.rs b/crates/engine-paint/src/cmd.rs index 757472f0ae..6d653b8062 100644 --- a/crates/engine-paint/src/cmd.rs +++ b/crates/engine-paint/src/cmd.rs @@ -19,6 +19,8 @@ mod gradient_alpha_method_tests; mod gradient_behind_mode_tests; #[cfg(test)] mod gradient_mask_history_name_tests; +#[cfg(test)] +mod gradient_mask_opacity_half_tests; pub mod paint_cmds; pub mod pick_cmds; pub mod redeye_cmds; diff --git a/crates/engine-paint/src/cmd/brush_cmds.rs b/crates/engine-paint/src/cmd/brush_cmds.rs index e07b0102ed..6cc12942b3 100644 --- a/crates/engine-paint/src/cmd/brush_cmds.rs +++ b/crates/engine-paint/src/cmd/brush_cmds.rs @@ -1166,6 +1166,9 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result { fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document")?; + if crate::pattern_cmds::layer_mask_targeted(s) { + return Err("a layer mask is the target".into()); + } // The area the command reads (selection, else canvas) is limited, not just the painted // extent, like Photoshop (#14275). let area = d.doc.selection.as_ref().map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds())); @@ -1706,3 +1709,6 @@ mod filter_mask_stroke_tests; #[cfg(test)] mod define_brush_size_limit_tests; + +#[cfg(test)] +mod define_brush_mask_target_tests; diff --git a/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs b/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs new file mode 100644 index 0000000000..76a76fdeca --- /dev/null +++ b/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs @@ -0,0 +1,150 @@ +//! #18232: Define Brush Preset (and the brush command it runs) and Define Pattern are greyed and refused while a layer +//! mask is the edit target: a pixel layer's or a group's mask targeted, or an adjustment layer with its mask. Targeting +//! the composite again, or deleting the adjustment layer's mask, makes them available. Other targets and layer kinds +//! keep today's gates. + +use super::*; + +const COMMANDS: [&str; 3] = ["edit.defineBrushPreset", "brush.defineFromSelection", "edit.definePattern"]; + +/// A white 60 x 40 document with a new layer holding a black rectangle, the layer active. +fn document() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap(); + s.edit("BrushSrc", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 25), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn target(s: &mut Session, channel: Value) { + s.execute("channel.target", json!({"channel": channel})).unwrap(); +} + +/// The brush, the brush presets, the pattern library and the document, to show that a refusal changes none of them. +fn snapshot(s: &Session) -> (BrushSettings, Vec, usize, usize) { + let patterns = s.patterns.items.len(); + ((*s.tools.brush).clone(), s.tools.presets.to_vec(), patterns, s.active().unwrap().history.past_len()) +} + +fn assert_refused(s: &mut Session, case: &str) { + for command in COMMANDS { + assert!(s.disabled_reason(command).is_some(), "{case}: {command} stays enabled"); + let before = snapshot(s); + assert!(s.execute(command, json!({"name": "Refused"})).is_err(), "{case}: {command} ran"); + assert!(snapshot(s) == before, "{case}: {command} changed the brush, the presets, the patterns or the History"); + } +} + +fn assert_enabled(s: &mut Session, case: &str) { + for command in COMMANDS { + assert_eq!(s.disabled_reason(command), None, "{case}: {command}"); + } +} + +#[test] +fn a_pixel_layers_targeted_mask_greys_them() { + for enabled in [true, false] { + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + if !enabled { + s.execute("layer.layerMask.enabled", json!({"enabled": false})).unwrap(); + } + target(&mut s, json!("mask")); + assert_refused(&mut s, if enabled { "a pixel layer's mask" } else { "a pixel layer's disabled mask" }); + } +} + +#[test] +fn a_groups_targeted_mask_greys_them() { + let mut s = document(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("mask")); + assert_refused(&mut s, "a group's mask"); +} + +#[test] +fn a_new_adjustment_layer_greys_them_until_its_mask_is_deleted() { + let mut s = document(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + assert_refused(&mut s, "a new adjustment layer"); + s.execute("layer.layerMask.delete", json!({})).unwrap(); + assert_enabled(&mut s, "the adjustment layer without its mask"); +} + +/// Back on the composite, the items work as before and make the same tip as a document that never targeted a mask. +#[test] +fn targeting_the_composite_again_enables_them_with_the_same_tip() { + let mut plain = document(); + plain.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut plain, json!("composite")); + plain.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap(); + + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("mask")); + assert_refused(&mut s, "the mask"); + target(&mut s, json!("composite")); + assert_enabled(&mut s, "the composite again"); + s.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap(); + assert!(s.tools.brush.tip == plain.tools.brush.tip, "the tip is the one made without a mask target"); + s.execute("edit.definePattern", json!({"name": "Pattern"})).unwrap(); +} + +/// With every colour channel hidden and no alpha channel shown, the mask is the picture and the target; showing a colour +/// channel or an alpha channel again makes the items available. +#[test] +fn hiding_every_colour_channel_greys_them_on_a_masked_layer() { + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("composite")); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + assert_refused(&mut s, "every colour channel hidden"); + s.execute("channel.setVisible", json!({"channel": {"color": 0}, "visible": true})).unwrap(); + assert_enabled(&mut s, "one colour channel shown again"); + + s.execute("channel.new", json!({})).unwrap(); + target(&mut s, json!("composite")); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + s.execute("channel.setVisible", json!({"channel": {"alpha": 0}, "visible": true})).unwrap(); + assert_enabled(&mut s, "an alpha channel shown"); + + // Without a mask there is nothing else to target. + let mut s = document(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + assert_enabled(&mut s, "no mask, every colour channel hidden"); +} + +/// Not a layer mask target: these keep today's gates. +#[test] +fn other_targets_and_layer_kinds_stay_enabled() { + // A pixel layer with a mask, the composite targeted. + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert_enabled(&mut s, "a masked pixel layer, composite targeted"); + + // An alpha channel, and Quick Mask. + s.execute("channel.new", json!({})).unwrap(); + target(&mut s, json!({"alpha": 0})); + assert_enabled(&mut s, "an alpha channel"); + target(&mut s, json!("composite")); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + assert_enabled(&mut s, "Quick Mask"); + + // A locked layer, a group, the Background and a Solid Color fill layer with its mask. + let mut s = document(); + s.execute("layer.setProps", json!({"locks": {"all": true}})).unwrap(); + assert_enabled(&mut s, "a locked layer"); + let mut s = document(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert_enabled(&mut s, "a group"); + let background = s.active().unwrap().doc.layers[0].id; + s.execute("layer.select", json!({"layer": background.0})).unwrap(); + assert_enabled(&mut s, "the Background"); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#336699"})).unwrap(); + assert_enabled(&mut s, "a Solid Color fill layer"); +} diff --git a/crates/engine-paint/src/cmd/gradient_mask_greyed_modes_tests.rs b/crates/engine-paint/src/cmd/gradient_mask_greyed_modes_tests.rs new file mode 100644 index 0000000000..6e66d612ef --- /dev/null +++ b/crates/engine-paint/src/cmd/gradient_mask_greyed_modes_tests.rs @@ -0,0 +1,76 @@ +use photocraft_color::BlendMode; +use serde_json::{Value, json}; + +use crate::{Session, channel_cmds}; + +const MASK_LEVEL: f32 = 128.0 / 255.0; + +fn seeded_surface(mode: &str, depth: u8, target: &Value) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap(); + match target.as_str() { + Some("mask") => s.execute("layer.layerMask.revealAll", json!({})).unwrap(), + Some("quickMask") => s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(), + Some("pixels") => Value::Null, + _ => s.execute("channel.new", json!({})).unwrap(), + }; + let active = s.active().unwrap().active_layer; + let params = json!({"target": target}); + s.edit("Seed the backdrop", |doc, _| { + let (surface, _) = channel_cmds::target_surface(doc, active, ¶ms)?; + let gray = [MASK_LEVEL]; + let rgba = [MASK_LEVEL, MASK_LEVEL, MASK_LEVEL, 1.0]; + let sample: &[f32] = if target == "pixels" { &rgba } else { &gray }; + for x in 0..40 { + surface.write_pixel(x, 3, sample); + } + Ok(()) + }) + .unwrap(); + s +} + +fn gradient_row(mut s: Session, target: &Value, blend: &str) -> Vec { + let params = json!({ + "from": [4, 3], "to": [32, 3], "stops": [[0, "#000000"], [1, "#ffffff"]], + "target": target, "mode": blend, "method": "smooth", "dither": false + }); + s.execute("paint.gradient", params.clone()).unwrap(); + let state = s.active().unwrap(); + let surface = channel_cmds::read_target_surface(&state.doc, state.active_layer, ¶ms).unwrap(); + (0..40).map(|x| surface.pixel(x, 3)[0]).collect() +} + +#[test] +fn nonseparable_gradient_modes_match_normal_throughout_rgb_layer_masks() { + let target = json!("mask"); + for depth in [8, 16] { + let normal = gradient_row(seeded_surface("rgb", depth, &target), &target, "normal"); + assert_eq!(normal[0], 0.0); + assert_eq!(normal[39], 1.0); + for mode in ["darkerColor", "lighterColor", "hue", "saturation", "color", "luminosity"] { + assert_eq!(gradient_row(seeded_surface("rgb", depth, &target), &target, mode), normal, "{depth}-bit {mode}"); + } + let darken = gradient_row(seeded_surface("rgb", depth, &target), &target, "darken"); + assert_eq!(darken[0], 0.0); + assert!((darken[39] - MASK_LEVEL).abs() < 1.0 / 65535.0); + } +} + +#[test] +fn outside_the_rgb_mask_depths_darker_color_still_keeps_the_darker_backdrop() { + for (mode, depth, target) in [ + ("rgb", 8, json!("pixels")), + ("rgb", 8, json!("quickMask")), + ("rgb", 8, json!({"channel": 0})), + ("rgb", 32, json!("mask")), + ("gray", 16, json!("mask")), + ] { + let normal = gradient_row(seeded_surface(mode, depth, &target), &target, "normal"); + // Float mask luma can be one representable step below white. Integer storage rounds it. + let white_tolerance = if depth == 32 { 4.0 * f32::EPSILON } else { 0.0 }; + assert!((normal[39] - 1.0).abs() <= white_tolerance, "{mode} {depth}-bit {target}: {}", normal[39]); + let row = gradient_row(seeded_surface(mode, depth, &target), &target, BlendMode::DarkerColor.label()); + assert!((row[39] - MASK_LEVEL).abs() < 1.0 / 65535.0, "{mode} {depth}-bit {target}"); + } +} diff --git a/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs b/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs new file mode 100644 index 0000000000..fce981d0ef --- /dev/null +++ b/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs @@ -0,0 +1,85 @@ +//! #18669: at 50% opacity a gradient covers 128/255 of a layer mask. + +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::Session; + +fn document(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap(); + s +} + +fn gradient(opacity: f64, target: Value, method: Option<&str>) -> Value { + let mut p = json!({"from": [8, 4], "to": [56, 4], "colors": ["#000000", "#ffffff"], "opacity": opacity, "target": target, "dither": false}); + if let Some(method) = method { + p["method"] = json!(method); + } + p +} + +fn target<'a>(s: &'a Session, p: &Value) -> &'a Surface { + let state = s.active().unwrap(); + crate::channel_cmds::read_target_surface(&state.doc, state.active_layer, p).unwrap() +} + +fn layer_mask_row(mode: &str, depth: u32, opacity: f64, method: Option<&str>) -> [f32; 3] { + let mut s = document(mode, depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let p = gradient(opacity, json!("mask"), method); + s.execute("paint.gradient", p.clone()).unwrap(); + [4, 32, 60].map(|x| target(&s, &p).pixel(x, 4)[0]) +} + +#[test] +fn half_opacity_leaves_127_levels_of_white_on_the_layer_mask() { + for (mode, depth, step) in [ + ("rgb", 8, 1.0 / 255.0), + ("rgb", 16, 1.0 / 65535.0), + ("rgb", 32, 0.0), + ("gray", 8, 1.0 / 255.0), + ("gray", 16, 1.0 / 65535.0), + ("gray", 32, 0.0), + ("cmyk", 8, 1.0 / 255.0), + ("lab", 8, 1.0 / 255.0), + ] { + // The desktop dispatches the Classic gradient without a method. The report used Smooth. + for method in [None, Some("smooth")] { + let case = format!("{mode}/{depth} {method:?}"); + let [black, middle, white] = layer_mask_row(mode, depth, 50.0, method); + let [full_black, full_middle, full_white] = layer_mask_row(mode, depth, 100.0, method); + assert_eq!(full_black, 0.0, "{case} at full opacity"); + assert!((full_white - 1.0).abs() <= 0.00001, "{case}: white end at full opacity {full_white}"); + assert!((black - 127.0 / 255.0).abs() <= 0.5 * step + 0.00001, "{case}: black end left {black} white"); + let expected_middle = 1.0 - (1.0 - full_middle) * (128.0 / 255.0); + assert!((middle - expected_middle).abs() <= step + 0.00001, "{case}: ramp midpoint {middle}, expected {expected_middle}"); + assert!((white - 1.0).abs() <= 0.00001, "{case}: white end left {white} white"); + } + } +} + +#[test] +fn other_opacity_and_non_layer_mask_targets_keep_the_requested_coverage() { + // Include a value that rounds to 50% after the command converts to f32. + for opacity in [49.9, 50.000_000_1] { + let [black, _, _] = layer_mask_row("rgb", 32, opacity, Some("smooth")); + assert!((f64::from(black) - (1.0 - opacity / 100.0)).abs() < 0.00001, "{opacity}% opacity left {black} white"); + } + + let mut s = document("rgb", 32); + let pixels = gradient(50.0, json!("pixels"), Some("smooth")); + s.execute("paint.gradient", pixels.clone()).unwrap(); + assert!((target(&s, &pixels).pixel(4, 4)[3] - 0.5).abs() < 0.00001, "pixel coverage"); + + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + let alpha = gradient(50.0, json!({"channel": 0}), Some("smooth")); + s.execute("paint.gradient", alpha.clone()).unwrap(); + assert!((target(&s, &alpha).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "saved alpha channel"); + + s.execute("select.all", json!({})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + let quick_mask = gradient(50.0, json!("quickMask"), Some("smooth")); + s.execute("paint.gradient", quick_mask.clone()).unwrap(); + assert!((target(&s, &quick_mask).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "Quick Mask"); +} diff --git a/crates/engine-paint/src/cmd/gradient_mask_smooth_transparency_tests.rs b/crates/engine-paint/src/cmd/gradient_mask_smooth_transparency_tests.rs new file mode 100644 index 0000000000..661c9115ed --- /dev/null +++ b/crates/engine-paint/src/cmd/gradient_mask_smooth_transparency_tests.rs @@ -0,0 +1,63 @@ +use serde_json::{Value, json}; + +const MASK_ROW: [f32; 21] = + [0.0, 15.0, 34.0, 53.0, 73.0, 93.0, 113.0, 131.0, 148.0, 164.0, 178.0, 191.0, 204.0, 215.0, 226.0, 235.0, 242.0, 248.0, 253.0, 255.0, 255.0]; + +fn row(mode: &str, depth: u8, target: &str, method: &str, stops: Value, opacity: Option) -> Vec { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 800, "height": 16, "mode": mode, "depth": depth, "background": "transparent"})).unwrap(); + if target == "mask" { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + } + let mut params = json!({"from": [100, 10], "to": [700, 10], "stops": stops, "method": method, "dither": false, "target": target}); + if let Some(opacity) = opacity { + params["transparency"] = opacity; + } + s.execute("paint.gradient", params.clone()).unwrap(); + let st = s.active().unwrap(); + let surface = crate::channel_cmds::read_target_surface(&st.doc, st.active_layer, ¶ms).unwrap(); + (0..800).map(|x| if target == "mask" { surface.pixel(x, 10)[0] } else { surface.rgba(x, 10)[3] }).map(|value| value * 255.0).collect() +} + +fn fade(mode: &str, depth: u8, target: &str, method: &str) -> Vec { + row(mode, depth, target, method, json!([[0, "#000000"], [1, "#000000"]]), Some(json!([[0, 100], [1, 0]]))) +} + +#[test] +fn smooth_transparency_follows_the_measured_layer_mask_fade() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for depth in [8, 16] { + let output = fade(mode, depth, "mask", "smooth"); + for (i, expected) in MASK_ROW.into_iter().enumerate() { + let x = 100 + 30 * i; + assert!((output[x] - expected).abs() <= 2.0, "{mode} {depth}-bit, x={x}: {}, expected {expected}", output[x]); + } + assert!(output.windows(2).all(|w| w[0] <= w[1])); + assert_eq!(output[50], 0.0); + assert_eq!(output[750], 255.0); + } + } +} + +#[test] +fn smooth_mask_fade_keeps_existing_pixel_deep_mask_and_other_method_curves() { + let pixels = fade("rgb", 8, "pixels", "smooth"); + let deep_mask = fade("rgb", 32, "mask", "smooth"); + for (x, alpha) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + assert!((pixels[x] - alpha).abs() <= 2.0, "pixel alpha at {x}: {}", pixels[x]); + assert!((deep_mask[x] - (255.0 - alpha)).abs() <= 2.0, "float mask at {x}: {}", deep_mask[x]); + } + + for method in ["classic", "perceptual", "linear"] { + let pixels = fade("rgb", 8, "pixels", method); + let mask = fade("rgb", 8, "mask", method); + for x in [50, 250, 400, 550, 750] { + assert!((pixels[x] + mask[x] - 255.0).abs() <= 1.0, "{method} at {x}: pixel {}, mask {}", pixels[x], mask[x]); + } + } + + let colors = json!([[0, "#000000"], [1, "#ffffff"]]); + let opaque = row("rgb", 16, "mask", "smooth", colors.clone(), None); + assert_eq!(opaque, row("rgb", 16, "mask", "smooth", colors, Some(json!([[0, 100], [1, 100]])))); + assert_eq!((opaque[50], opaque[750]), (0.0, 255.0)); +} diff --git a/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs b/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs new file mode 100644 index 0000000000..2f4e353fef --- /dev/null +++ b/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs @@ -0,0 +1,91 @@ +use photocraft_algo::paint::{FillMode, GradientShape, paint_gradient}; +use photocraft_color::BlendMode; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba}; +use serde_json::json; + +use crate::Session; + +const SOURCE: [f32; 4] = [0.25, 0.5, 0.75, 1.0]; + +fn active_surface(s: &Session) -> &Surface { + let state = s.active().unwrap(); + state.doc.layer(state.active_layer.unwrap()).unwrap().surface().unwrap() +} + +fn document(mode: &str, depth: u8) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap(); + s.edit("Set the three backdrop alphas", |doc, _| { + let surface = doc.layers[0].surface_mut().unwrap(); + let format = surface.format(); + for (x, alpha) in [(3, 1.0), (4, 0.0), (5, 0.5)] { + surface.write_pixel(x, 3, &from_rgba(&format, [0.8, 0.3, 0.2, alpha])); + } + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn gradient_uses_the_measured_half_opacity_step_only_on_deep_rgb_and_cmyk_pixels() { + for (mode, depth, uses_step) in [("rgb", 8, false), ("rgb", 16, true), ("rgb", 32, true), ("cmyk", 8, false), ("cmyk", 16, true), ("gray", 16, false)] { + for blend in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen] { + for (percent, coverage) in [(50.0, if uses_step { 128.0 / 255.0 } else { 0.5 }), (23.5, 0.235)] { + let mut s = document(mode, depth); + let mut wanted = active_surface(&s).clone(); + paint_gradient( + &mut wanted, + Rect::new(0, 0, 16, 8), + (2.0, 3.0), + (9.0, 3.0), + GradientShape::Linear, + &[(0.0, SOURCE), (1.0, SOURCE)], + false, + coverage, + FillMode::Blend(blend), + false, + None, + false, + ); + s.execute( + "paint.gradient", + json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "opacity": percent, "mode": blend.label(), "dither": false}), + ) + .unwrap(); + + let actual = active_surface(&s); + for x in 3..=5 { + assert_eq!(actual.pixel(x, 3), wanted.pixel(x, 3), "{mode} {depth}-bit, {blend:?}, {percent}%, x={x}"); + } + if uses_step && percent == 50.0 { + assert!((actual.rgba(4, 3)[3] - 128.0 / 255.0).abs() < 0.0005); + assert!((actual.rgba(5, 3)[3] - (0.5 + 64.0 / 255.0)).abs() < 0.0005); + } + } + } + } +} + +#[test] +fn only_explicit_classic_uses_the_half_opacity_step() { + for (method, coverage) in [("Classic", 128.0 / 255.0), ("linear", 0.5), ("perceptual", 0.5), ("smooth", 0.5)] { + let mut s = document("rgb", 32); + s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": [SOURCE, SOURCE], "method": method, "opacity": 50, "dither": false})) + .unwrap(); + let alpha = active_surface(&s).rgba(4, 3)[3]; + assert!((alpha - coverage).abs() < 0.0005, "{method}: alpha {alpha}, expected {coverage}"); + } +} + +#[test] +fn the_half_opacity_pixel_step_does_not_change_deep_cmyk_layer_masks() { + let mut s = document("cmyk", 16); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": ["#000000", "#ffffff"], "opacity": 50, "target": "mask", "dither": false})) + .unwrap(); + let state = s.active().unwrap(); + let mask = &state.doc.layer(state.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; + assert_eq!((mask.pixel(2, 3)[0] * 65535.0).round(), 32768.0); +} diff --git a/crates/engine-paint/src/cmd/paint_cmds.rs b/crates/engine-paint/src/cmd/paint_cmds.rs index 50639b6fce..53a8ca0418 100644 --- a/crates/engine-paint/src/cmd/paint_cmds.rs +++ b/crates/engine-paint/src/cmd/paint_cmds.rs @@ -1,6 +1,7 @@ //! Paint helpers: Paint Bucket and Gradient tool. use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient}; +use photocraft_color::{ColorMode, SampleType}; use serde_json::{Value, json}; use crate::commands::{CommandSpec, parse_blend}; @@ -172,7 +173,9 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense // stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16 // where straight stops give 0.0625. - let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { + let method_param = p.get("method"); + let method = method_param.and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name); + let stops = match method { Some(m) if stops.len() >= 2 => { let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); // Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by @@ -181,6 +184,16 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // were not measured in the Gradient tool and keep the merged stops. let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; match split { + Some(split) + if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask + && s.active().is_some_and(|st| { + use photocraft_color::{ColorMode, SampleType}; + matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab) + && matches!(st.doc.depth, SampleType::U8 | SampleType::U16) + }) => + { + smooth_split_stops_with(split, photocraft_io::gradient_bake::bake_smooth_mask_opacity) + } Some(split) => smooth_split_stops(split), None => { let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); @@ -200,15 +213,42 @@ fn gradient(s: &mut Session, p: &Value) -> Result { let reverse = b(p, "reverse", false); let opacity = opacity(p, "paint.gradient")?; let mode = fill_mode(p, "paint.gradient", false)?; + let target = crate::channel_cmds::target_of(p); // Masks and channels have no transparency to paint behind: Behind would change nothing there. - if mode == FillMode::Behind && crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels { + if mode == FillMode::Behind && target != crate::channel_cmds::Target::Pixels { return Err(EngineError::BadParams { cmd: "paint.gradient".into(), msg: "mode `behind` paints only a layer's pixels, not a mask or channel".into() }); } let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) }; s.edit(step_name(p), |doc, _| { + // The measured 50% setting uses 8-bit source coverage for these layer masks and Classic pixel gradients. + let opacity = if p.get("opacity").and_then(Value::as_f64) == Some(50.0) + && match target { + crate::channel_cmds::Target::Mask => { + matches!((doc.mode, doc.depth), (ColorMode::Rgb | ColorMode::Grayscale, _) | (ColorMode::Cmyk | ColorMode::Lab, SampleType::U8)) + } + crate::channel_cmds::Target::Pixels => { + (method_param.is_none() || method == Some(photocraft_io::GradientMethod::Classic)) + && matches!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::U16 | SampleType::F32) | (ColorMode::Cmyk, SampleType::U16)) + } + _ => false, + } { + 128.0 / 255.0 + } else { + opacity + }; let sel = doc.selection.clone(); let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds()); + // The RGB 8- and 16-bit layer mask uses Normal for modes that need a colour backdrop. + let mode = if matches!(mode, FillMode::Blend(blend) if !blend.is_separable()) + && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask + && doc.mode == photocraft_color::ColorMode::Rgb + && matches!(doc.depth, photocraft_color::SampleType::U8 | photocraft_color::SampleType::U16) + { + FillMode::Blend(photocraft_color::BlendMode::Normal) + } else { + mode + }; let (surf, lock) = crate::channel_cmds::target_surface(doc, layer, p)?; paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, mode, dither, sel.as_ref(), lock); Ok(()) @@ -234,7 +274,11 @@ pub(crate) const GRADIENT_MASK_STEP: &str = "Draw gradient on mask"; /// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut /// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for /// every pixel. Positions that differ still go through `apply_opacity`. -pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops { +pub(crate) fn smooth_split_stops(stops: gradients::FillStops) -> gradients::Stops { + smooth_split_stops_with(stops, photocraft_io::bake_gradient_smooth_opacity) +} + +fn smooth_split_stops_with((cs, os): gradients::FillStops, bake_opacity: impl FnOnce(Vec<(f32, f32)>, &[f32]) -> Vec<(f32, f32)>) -> gradients::Stops { let mids = vec![0.5; cs.len().saturating_sub(1)]; let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth) .into_iter() @@ -244,7 +288,7 @@ pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::S }) .collect(); let omids = vec![0.5; os.len().saturating_sub(1)]; - let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids); + let opacity = bake_opacity(os, &omids); if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) { return gradients::apply_opacity(colours, &opacity); } @@ -317,11 +361,23 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +#[path = "gradient_mask_greyed_modes_tests.rs"] +mod gradient_mask_greyed_modes_tests; + #[cfg(test)] mod bucket_no_op_history_tests; #[cfg(test)] mod bucket_bitmap_tests; +#[cfg(test)] +#[path = "gradient_mask_smooth_transparency_tests.rs"] +mod gradient_mask_smooth_transparency_tests; + #[cfg(test)] mod bucket_behind_tests; + +#[cfg(test)] +#[path = "gradient_opacity_step_tests.rs"] +mod gradient_opacity_step_tests; diff --git a/crates/engine/tests/it/background_from_layer_clip_base.rs b/crates/engine/tests/it/background_from_layer_clip_base.rs new file mode 100644 index 0000000000..151eacc716 --- /dev/null +++ b/crates/engine/tests/it/background_from_layer_clip_base.rs @@ -0,0 +1,80 @@ +//! Background from Layer keeps a single clipped layer on its original base (#17307). + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use serde_json::json; + +const CONVERT: &str = "layer.new.backgroundFromLayer"; + +fn active(session: &Session) -> LayerId { + session.active().unwrap().active_layer.unwrap() +} + +fn order(session: &Session) -> Vec { + session.active().unwrap().doc.layers.iter().map(|layer| layer.id).collect() +} + +fn stack() -> (Session, [LayerId; 7]) { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 200, "height": 150, "background": "transparent"})).unwrap(); + let base = active(&session); + session.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 150})).unwrap(); + session.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + session.execute("layer.new.layer", json!({"name": "SO"})).unwrap(); + session.execute("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + session.execute("edit.fill", json!({"color": "#c81e1e"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let smart = active(&session); + session.execute("layer.new.layer", json!({"name": "Clipped"})).unwrap(); + let clipped = active(&session); + session.execute("edit.fill", json!({"color": "#1e1ec8"})).unwrap(); + session.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + session.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let adjustment = active(&session); + session.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap(); + let fill = active(&session); + session.execute("layer.setProps", json!({"layer": fill.0, "opacity": 0.5})).unwrap(); + let shape = session.execute("shape.create", json!({"kind": "rect", "rect": [80, 60, 100, 80], "fill": "#308020"})).unwrap(); + let shape = LayerId(shape["layer"].as_u64().unwrap()); + session.execute("layer.select", json!({"layer": shape.0})).unwrap(); + session.execute("layer.new.layer", json!({"name": "Off"})).unwrap(); + let off = active(&session); + let ids = [base, smart, clipped, adjustment, fill, shape, off]; + assert_eq!(order(&session), ids); + (session, ids) +} + +#[test] +fn converting_a_clipping_base_moves_its_clip_and_one_undo_restores_the_tree() { + let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack(); + session.execute("layer.select", json!({"layer": smart.0})).unwrap(); + let before = session.active().unwrap().history.past_len(); + session.execute(CONVERT, json!({})).unwrap(); + assert_eq!(order(&session), [smart, clip, base, adjustment, fill, shape, off]); + let doc = &session.active().unwrap().doc; + assert!(doc.is_background(smart)); + assert!(doc.layer(clip).unwrap().clipped); + assert_eq!(active(&session), smart); + assert_eq!(session.active().unwrap().history.past_len(), before + 1); + session.execute("history.undo", json!({})).unwrap(); + assert_eq!(order(&session), [base, smart, clip, adjustment, fill, shape, off]); + let doc = &session.active().unwrap().doc; + assert!(doc.background().is_none()); + assert!(doc.layer(clip).unwrap().clipped); +} + +#[test] +fn converting_an_unclipped_layer_or_the_clip_itself_keeps_other_layers_in_order() { + for convert_clip in [false, true] { + let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack(); + let target = if convert_clip { clip } else { fill }; + session.execute(CONVERT, json!({"layer": target.0})).unwrap(); + let expected = if convert_clip { [clip, base, smart, adjustment, fill, shape, off] } else { [fill, base, smart, clip, adjustment, shape, off] }; + assert_eq!(order(&session), expected); + let doc = &session.active().unwrap().doc; + assert!(doc.is_background(target)); + assert_eq!(doc.layer(clip).unwrap().clipped, !convert_clip); + } +} diff --git a/crates/engine/tests/it/define_brush_sampled_number.rs b/crates/engine/tests/it/define_brush_sampled_number.rs new file mode 100644 index 0000000000..d082a66282 --- /dev/null +++ b/crates/engine/tests/it/define_brush_sampled_number.rs @@ -0,0 +1,97 @@ +//! #18228 (Edit › Define Brush Preset runs the brush command of `photocraft-engine-paint`, so this runs here): Define Brush Preset's "Sampled Brush N" default counts the defaults stored in this session. Deleting or +//! renaming presets does not lower N, and a preset with such a name from elsewhere (a typed name, an imported set) does +//! not raise it, but N skips a number such a preset already uses instead of replacing that preset. A call that stores +//! nothing leaves N as it is. + +use serde_json::{Value, json}; + +use photocraft_engine::Session; + +const DEFINE: &str = "edit.defineBrushPreset"; + +/// Opens a new white document with a black rectangle on a layer, ready for Define Brush Preset. +fn new_document(s: &mut Session) { + s.execute("file.new", json!({"width": 40, "height": 30, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("BrushSrc", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(5, 5, 20, 15), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); +} + +/// Defines a brush with `params` and returns the name it was stored under. +fn define(s: &mut Session, params: Value) -> String { + s.execute(DEFINE, params).unwrap(); + s.tools.current_preset.clone().expect("the new preset is the current brush") +} + +fn session() -> Session { + let mut s = Session::new(); + new_document(&mut s); + s +} + +#[test] +fn each_stored_default_raises_the_number() { + let mut s = session(); + let mut names = vec![define(&mut s, json!({}))]; + for _ in 0..2 { + new_document(&mut s); + names.push(define(&mut s, json!({}))); + } + assert_eq!(names, ["Sampled Brush 1", "Sampled Brush 2", "Sampled Brush 3"]); +} + +#[test] +fn deleting_or_renaming_the_presets_does_not_lower_it() { + let mut s = session(); + let names: Vec = (0..3).map(|_| define(&mut s, json!({}))).collect(); + for name in &names { + s.execute("brush.presets.delete", json!({"name": name})).unwrap(); + } + assert_eq!(define(&mut s, json!({})), "Sampled Brush 4", "after deleting presets 1-3"); + + let mut s = session(); + let first = define(&mut s, json!({})); + s.execute("brush.presets.rename", json!({"name": first, "newName": "Renamed"})).unwrap(); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 2", "after renaming preset 1"); +} + +/// A preset named "Sampled Brush …" that the default did not make, such as a typed name, does not raise the number. +#[test] +fn a_typed_sampled_brush_name_does_not_raise_it() { + let mut s = session(); + assert_eq!(define(&mut s, json!({"name": "Sampled Brush 7"})), "Sampled Brush 7"); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 1", "the first default"); +} + +/// The default never takes a name a preset already has: storing under it would replace that preset's tip. +#[test] +fn a_taken_number_is_skipped_and_the_preset_is_kept() { + let mut s = session(); + let user_presets = |s: &Session| s.tools.presets.iter().filter(|b| !b.builtin).map(|b| b.name.clone()).collect::>(); + define(&mut s, json!({"name": "Sampled Brush 1"})); + let first = define(&mut s, json!({})); + assert_ne!(first, "Sampled Brush 1", "the typed preset's name"); + assert_eq!(user_presets(&s).len(), 2, "both presets are kept: {:?}", user_presets(&s)); + let second = define(&mut s, json!({})); + assert!(![first.as_str(), "Sampled Brush 1"].contains(&second.as_str()), "{second}"); + assert_eq!(user_presets(&s).len(), 3, "{:?}", user_presets(&s)); + + // The store matches names ignoring case, so a typed "sampled brush 1" is taken too. + let mut s = session(); + define(&mut s, json!({"name": "sampled brush 1"})); + let first = define(&mut s, json!({})); + assert!(!first.eq_ignore_ascii_case("sampled brush 1"), "{first}"); + assert_eq!(user_presets(&s).len(), 2, "{:?}", user_presets(&s)); +} + +/// A call that stores no preset leaves the number as it is. +#[test] +fn a_refused_call_does_not_raise_it() { + let mut s = Session::new(); + assert!(s.execute(DEFINE, json!({})).is_err(), "no document"); + new_document(&mut s); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 1"); +} diff --git a/crates/engine/tests/it/gallery_colours.rs b/crates/engine/tests/it/gallery_colours.rs index d1561e8aad..e8ae544832 100644 --- a/crates/engine/tests/it/gallery_colours.rs +++ b/crates/engine/tests/it/gallery_colours.rs @@ -31,3 +31,65 @@ fn colored_pencil_honours_session_background() { fn neon_glow_honours_session_background() { assert_ne!(one("neonGlow", "#ffffff"), one("neonGlow", "#0000ff"), "filter.gallery.neonGlow must honour the session background"); } + +/// Stamp uses the selected ink and paper without adding intermediate colors (#9912). +#[test] +fn stamp_uses_only_the_selected_colors() { + for depth in [8, 16, 32] { + for (fg, bg, ink, paper) in [("#000000", "#ffffff", [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]), ("#ff0000", "#0000ff", [1.0, 0.0, 0.0], [0.0, 0.0, 1.0])] { + for smoothness in [1, 5, 50] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#808080"})).unwrap(); + s.execute("tools.setColors", json!({"foreground": fg, "background": bg})).unwrap(); + s.execute("filter.gallery.stamp", json!({"lightDarkBalance": 25, "smoothness": smoothness})).unwrap(); + for p in image(&mut s).as_chunks::<4>().0 { + assert!(p[..3] == ink || p[..3] == paper, "{depth}-bit, smoothness {smoothness}: Stamp added an intermediate color: {p:?}"); + assert_eq!(p[3], 1.0); + } + } + } + } +} + +/// Balance controls the chosen color, with the selection boundary and one-step Undo intact. +#[test] +fn stamp_balance_selection_and_undo() { + for depth in [8, 16, 32] { + for (balance, expected) in [(0, 1.0), (40, 0.0), (50, 0.0)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#808080"})).unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8, "antiAlias": false})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let outside = px(&mut s, 2, 2); + s.execute("filter.gallery.stamp", json!({"lightDarkBalance": balance, "smoothness": 1})).unwrap(); + assert_eq!(px(&mut s, 8, 8), [expected, expected, expected, 1.0]); + assert_eq!(px(&mut s, 2, 2), outside); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.undo(); + assert_eq!(*s.active().unwrap().doc, *before); + } + } +} + +/// Smoothness changes spatial detail without adding intermediate colors. +#[test] +fn stamp_smoothness_changes_spatial_detail() { + for depth in [8, 16, 32] { + let render = |smoothness| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "#ffffff"})).unwrap(); + s.execute("select.rect", json!({"x": 6, "y": 6, "width": 4, "height": 4, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("filter.gallery.stamp", json!({"lightDarkBalance": 25, "smoothness": smoothness})).unwrap(); + image(&mut s) + }; + let fine = render(1); + let smooth = render(50); + assert_ne!(fine, smooth, "{depth}-bit: Smoothness must change the spatial result"); + for p in fine.as_chunks::<4>().0.iter().chain(smooth.as_chunks::<4>().0.iter()) { + assert!(p[..3] == [0.0; 3] || p[..3] == [1.0; 3]); + } + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 74e8fba6dd..fee7cd4897 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod atn_video_frames; mod auto_blend_layer_kinds; mod average_smart; mod background_and_mask_depth; +mod background_from_layer_clip_base; mod background_from_layer_grayscale; mod background_from_layer_history_name; mod background_from_layer_multi_select; @@ -66,6 +67,7 @@ mod crop_content_aware_layers; mod crop_delete_off_background; mod csh_import; mod current_affinity_artboards; +mod define_brush_sampled_number; mod duplicate_layer_comps; mod duplicate_slices; mod duplicate_variables; diff --git a/crates/engine/tests/it/paint_in_channel_cmds.rs b/crates/engine/tests/it/paint_in_channel_cmds.rs index 504076a07b..a54bc16146 100644 --- a/crates/engine/tests/it/paint_in_channel_cmds.rs +++ b/crates/engine/tests/it/paint_in_channel_cmds.rs @@ -695,7 +695,7 @@ mod tests { assert_eq!(sel_at(&s, 35, 2), 0.0); // History: enter and exit are steps; undo goes back into Quick Mask with the paint. let labels: Vec = s.active().unwrap().history.entries().iter().map(|e| e.to_string()).collect(); - assert!(labels.iter().any(|l| l.contains("Edit in Quick Mask")) && labels.iter().any(|l| l.contains("Exit Quick Mask")), "{labels:?}"); + assert!(labels.iter().any(|l| l.contains("Enter Quick Mask")) && labels.iter().any(|l| l.contains("Exit Quick Mask")), "{labels:?}"); s.undo(); assert!(doc(&s).quick_mask.is_some()); assert!(doc(&s).selection.is_none()); diff --git a/crates/format/tests/it/autosave.rs b/crates/format/tests/it/autosave.rs index f6fb88343a..7627348743 100644 --- a/crates/format/tests/it/autosave.rs +++ b/crates/format/tests/it/autosave.rs @@ -340,43 +340,38 @@ fn a_listing_during_an_autosave_sees_the_entry_exactly_once() { let dir = temp_dir("listing-during-autosave"); let doc = Document::new("Busy", photocraft_doc::Size { width: 4, height: 4 }, ColorMode::Rgb, SampleType::U8); save_once(&dir, "busy", doc.clone()); - let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let writer = { - let (dir, done) = (dir.clone(), done.clone()); - std::thread::spawn(move || { - // Sets `done` however the thread ends, so a failing writer stops the listing loop - // and `join` reports its panic instead of the test hanging. - struct SetOnDrop(Arc); - impl Drop for SetOnDrop { - fn drop(&mut self) { - self.0.store(true, std::sync::atomic::Ordering::SeqCst); - } - } - let _done = SetOnDrop(done); - let saver = Autosaver::new(&dir, "busy"); - for revision in 2..=200 { - saver.request(Arc::new(doc.clone()), revision, None, SaveOptions::default()); - // Wait for this write, so every revision replaces the sidecar once. - let completed = loop { - let completed = saver.take_completed(); - if !completed.is_empty() { - break completed; - } - std::thread::yield_now(); - }; - assert!(completed.iter().all(|(_, result)| result.is_ok()), "revision {revision}: {completed:?}"); - } - saver.flush() - }) - }; - let mut listings = 0u32; - while !done.load(std::sync::atomic::Ordering::SeqCst) { + let doc = Arc::new(doc); + let saver = Autosaver::new(&dir, "busy"); + let listed_revision = || { let entries = list_recovery(&dir); - let keys: Vec<&str> = entries.iter().map(|e| e.info.key.as_str()).collect(); - assert_eq!(keys, ["busy"], "listing {listings} during an autosave: {entries:?}"); - listings += 1; + let [entry] = entries.as_slice() else { panic!("expected one entry during autosave: {entries:?}") }; + assert_eq!(entry.info.key, "busy"); + entry.info.revision + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5 * 60); + // Each replacement is another opportunity to observe a transient missing sidecar. + for revision in 2..=200 { + saver.request_checked(doc.clone(), revision, None, SaveOptions::default()).unwrap(); + loop { + let completed = saver.take_completed(); + // List on this thread while the autosave worker writes. The preceding sidecar or + // its replacement supplies the revision. A sidecar-less fallback reports zero. + let listed = listed_revision(); + match completed.as_slice() { + [] => { + assert!((revision - 1..=revision).contains(&listed), "listed revision {listed} while writing {revision}"); + assert!(std::time::Instant::now() < deadline, "autosave did not complete revision {revision}"); + } + [(written, result)] => { + assert_eq!(*written, revision); + result.as_ref().unwrap(); + assert_eq!(listed, revision, "the completed replacement is visible"); + break; + } + _ => panic!("expected one completed write: {completed:?}"), + } + } } - assert!(writer.join().unwrap().is_some_and(|r| r.is_ok())); - assert!(listings > 0); + assert!(saver.flush().is_some_and(|r| r.is_ok())); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 8f0e10bee9..3525853e89 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -479,6 +479,20 @@ fn rgb_to_hsl(c: vec3) -> vec3 { } return vec3(h / 6.0, s, l); } + +// compose::adjust::hue_saturation_in at 8/16 bits. +fn scale_saturation(v: f32, s: f32) -> f32 { + if (s > 0.0) { return v / max(1.0 - s, 1.0 / 512.0); } + return v * (1.0 + s); +} + +// compose::adjust::color::hdr_saturation_factor, in whole numbers. +fn hdr_saturation_factor(s: f32) -> f32 { + if (s <= 0.0) { return 1.0 - floor(-s * 256.0 + 1e-4) / 256.0; } + let steps = min(u32(floor(s * 254.0 + 1e-4)), 254u); + return f32(min(65280u / (255u - steps), 32767u)) / 256.0; +} + fn hue_ch(p: f32, q: f32, t0: f32) -> f32 { let t = rem_euclid(t0, 1.0); if (t < 1.0 / 6.0) { return p + (q - p) * 6.0 * t; } @@ -677,7 +691,8 @@ fn adjust(c: vec3) -> vec3 { ds = lut(1, hsl.x); dl = lut(2, hsl.x); } - let sat = clamp(p0.y + ds, -1.0, 1.0); + let sat = clamp(p0.y, -1.0, 1.0); + let rs = clamp(ds, -1.0, 1.0); let light = clamp(p0.z, -1.0, 1.0); if (p0.w > 0.5) { // compose::adjust::hue_saturation: Colorize at the lightened / darkened lightness. @@ -694,24 +709,13 @@ fn adjust(c: vec3) -> vec3 { if (hdr) { // 32-bit: the chroma scaled around the lightness, unclipped, by Photoshop's factor // in whole numbers (compose::adjust::hue_saturation_in, hdr_saturation_factor). - var k: f32; - if (sat <= 0.0) { - k = 1.0 - floor(-sat * 256.0 + 1e-4) / 256.0; - } else { - let steps = min(u32(floor(sat * 254.0 + 1e-4)), 254u); - k = f32(min(65280u / (255u - steps), 32767u)) / 256.0; - } + let k = hdr_saturation_factor(sat) * hdr_saturation_factor(rs); let d = (max(max(lc.r, lc.g), lc.b) - min(min(lc.r, lc.g), lc.b)) * k; let lo = lh.z - d / 2.0; let hi = lh.z + d / 2.0; rgb = vec3(hue_ch(lo, hi, hh + 1.0 / 3.0), hue_ch(lo, hi, hh), hue_ch(lo, hi, hh - 1.0 / 3.0)); } else { - // Raising saturation divides by 1 - s; lowering it multiplies by 1 + s. - if (sat > 0.0) { - ss = clamp(lh.y / max(1.0 - sat, 1.0 / 512.0), 0.0, 1.0); - } else { - ss = clamp(lh.y * (1.0 + sat), 0.0, 1.0); - } + ss = clamp(scale_saturation(scale_saturation(lh.y, sat), rs), 0.0, 1.0); rgb = hsl_to_rgb(hh, ss, lh.z); } // compose::adjust::range_lightness: towards the brightest channel when raised, the darkest when lowered. diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 557a471abf..b5e8c59f72 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -858,6 +858,12 @@ fn adjustment_layers() { let hs = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() }; d.layers.push(Layer::new("hs2", LayerContent::Adjustment(hs))); check(&mut g, &d, &format!("hue/saturation {depth:?}")); + // A range's saturation multiplies the master's factor (#14741). + let hs = Adjustment::HueSaturation { hue: 0.0, saturation: 60.0, lightness: 0.0, colorize: false, ranges: hue_ranges() }; + d.layers.push(Layer::new("hs3", LayerContent::Adjustment(hs))); + check(&mut g, &d, &format!("hue/saturation ranges {depth:?}")); + // Off again: stacked under Threshold, it puts a 16-bit sample on the level's edge. + d.layers.pop(); // Threshold: whole 16-bit samples against the level in 16 bits, or the float luminosity. d.layers.push(Layer::new("th", LayerContent::Adjustment(Adjustment::Threshold { level: 0.5 }))); check(&mut g, &d, &format!("threshold {depth:?}")); diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index 7f8900d70f..082c6f165f 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -366,19 +366,35 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2; /// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it. /// Constant opacity comes back as it is, clamped to 0..=1. pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + bake_smooth_opacity_with(stops, midpoints, |o| o.powf(SMOOTH_OPACITY_GAMMA).cbrt(), |l| l.powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA)) +} + +/// Smooth's opacity response for the Gradient tool on an 8- or 16-bit layer mask. The same +/// Smooth easing with a lightness response of `L^1.75` fits the measured mask fade (#18670). +pub fn bake_smooth_mask_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + const MASK_POWER: f32 = 1.75; + bake_smooth_opacity_with(stops, midpoints, |o| o.powf(1.0 / MASK_POWER), |l| l.powf(MASK_POWER)) +} + +fn bake_smooth_opacity_with( + stops: Vec<(f32, f32)>, + midpoints: &[f32], + to_lightness: impl Fn(f32) -> f32, + from_lightness: impl Fn(f32) -> f32, +) -> Vec<(f32, f32)> { let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect(); } let mut s = stops; s.sort_by(|a, b| a.0.total_cmp(&b.0)); - let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect(); + let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [to_lightness(clamp(*o)); 3])).collect(); const N: usize = 96; let mut baked: Vec<(f32, f32)> = (0..=N) .map(|k| { let t = k as f32 / N as f32; let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0]; - (t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 }) + (t, if l.is_finite() { from_lightness(l.clamp(0.0, 1.0)) } else { 1.0 }) }) .collect(); baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 647e7decb9..68e4fb0815 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -69,7 +69,14 @@ sys-locale = "=0.3.2" # symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already # uses, pinned to the same version. [target.'cfg(target_os = "windows")'.dependencies] -winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] } +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi", "user"] } + +# Safe physical display dimensions for View > Actual Size. Both are already in the lockfile. +[target.'cfg(target_os = "macos")'.dependencies] +core-graphics = "=0.23.2" + +[target.'cfg(target_os = "linux")'.dependencies] +x11rb = { version = "=0.13.2", features = ["randr"] } [dev-dependencies] photocraft-io = { workspace = true, features = ["testgen"] } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d10a998347..b4ed47a136 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -93,6 +93,8 @@ impl PhotocraftApp { #[cfg(not(target_arch = "wasm32"))] control: None, live_adjust: None, + #[cfg(test)] + preview_test_area_multiplier: 1, frame: 0, notices_live: notices::Live::default(), low_memory: crate::memory_warning::Watch::default(), diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 744e8358f8..ea8e63a486 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -831,8 +831,11 @@ impl PrefSections { .filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?))) .filter(|(key, value)| session.prefs().sections.get(key) != Some(value)) .collect(); + // Remembered, not a settings edit: no view reads the sections back from the preferences (the components + // read them here), so the panels keep their versions and the engine applies nothing. A dialog that + // remembers its place writes on every frame of a drag. if !changed.is_empty() { - session.edit_prefs(|p| p.sections.extend(changed)); + session.prefs.remember(|p| p.sections.extend(changed)); } for key in written { let rev = session.section_rev(&key); @@ -986,6 +989,19 @@ mod tests { assert_eq!(store.read("one"), None); } + /// A component's section write is saved, but is no settings edit: the panels' versions hold the settings revision, + /// so an edit would rebuild every panel on each frame a dialog that remembers its place is dragged. + #[test] + fn a_section_write_is_saved_without_a_settings_edit() { + let store = PrefSections::default(); + let mut session = Session::new(); + let (saved, settings) = (session.prefs.rev(), session.prefs.settings_rev()); + store.write("one", table(1)); + store.sync(&mut session); + assert_ne!(session.prefs.rev(), saved, "the write reaches the saved preferences"); + assert_eq!(session.prefs.settings_rev(), settings, "the panels keep their versions"); + } + /// Every theme PhotoCraft has a palette for names a framework built-in. #[test] fn every_palette_theme_is_a_builtin() { diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index b9f0abb6f2..a3a6a25ded 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -276,7 +276,7 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { crate::brush_picker::open(app, at); } } - Item::Eraser(m) => app.ui.tool_options.eraser_mode = m.into(), + Item::Eraser(m) => crate::canvas::strokes::set_eraser_mode(app, m), Item::Range(r) => app.ui.tool_options.tone_range = r.into(), Item::Sponge(m) => app.ui.tool_options.sponge_mode = m.into(), // Replace is a tool option: it runs no command and adds no History step (#12101). diff --git a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs index e3297baeee..ec81aeb995 100644 --- a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs @@ -36,24 +36,23 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - // Half the 1024 × 768 canvas these views were first written for (see `check_blend_viewport`): `a` still runs off - // the right edge and `b` still lies apart from it. - app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); + // One view crosses the right edge; the other sits apart from it. The + // intervening pixels still have to be refreshed when Pattern Preview opens. + app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); let ctx = app.ctx().clone(); - let a = DRect::new(362, 100, 662, 250); - let b = DRect::new(0, 100, 150, 250); + let a = DRect::new(181, 50, 331, 125); + let b = DRect::new(0, 50, 75, 125); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); app.ui.view.pattern_preview = true; crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, b); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); app.ui.view.pattern_preview = false; for mode in [BlendMode::Multiply, BlendMode::Screen] { @@ -64,16 +63,16 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together"); - assert_visible_pixels(&mut app, visible.intersect(&bounds)); + assert_visible_pixels(&mut app, &[visible.intersect(&bounds)]); } } // Enabling periodic display during an existing hover must catch up the unseen gap too. app.ui.view.pattern_preview = true; assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } #[test] @@ -96,12 +95,12 @@ fn blend_hover_during_background_redraw_restores_committed_pixels() { let panned = DRect::new(2048, 1024, 2304, 1280); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); - assert_visible_pixels(&mut app, panned); + assert_visible_pixels(&mut app, &[panned]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } fn settle_redraw(app: &mut PhotocraftApp) { @@ -115,19 +114,33 @@ fn settle_redraw(app: &mut PhotocraftApp) { } } -fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) { +fn assert_visible_pixels(app: &mut PhotocraftApp, regions: &[DRect]) { let (doc, _) = display_doc(app, 0); let gpu = app.gpu.clone().unwrap(); - let reference = doc.id.0 ^ (1u64 << 60); let (display, _) = canvas_display(app, &doc, None); - gpu.upload_composite(reference, &doc, display.as_deref()); - let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap(); - let (_, _, want) = gpu.read_texels(reference).unwrap(); - for y in visible.y0..visible.y1 { - for x in visible.x0..visible.x1 { - let index = y as usize * size[0] as usize + x as usize; - for channel in 0..4 { - assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}"); + let format = eframe::wgpu::TextureFormat::Rgba8Unorm; + // Prepare the CPU reference while the GPU can still be drawing. Each requested + // region is compared to the same captured canvas texture. + let references: Vec<_> = regions + .iter() + .map(|®ion| { + assert!(doc.bounds().contains_rect(®ion)); + let reference = photocraft_compose::render(&doc, region); + (region, gpu_canvas::display_texels(format, display.as_deref(), &reference)) + }) + .collect(); + let (actual_format, size, shown) = gpu.read_texels(doc.id.0).expect("read visible canvas"); + assert_eq!(actual_format, format); + assert_eq!(size, [doc.size.width, doc.size.height]); + for (region, expected) in references { + let expected = expected.as_chunks::<4>().0; + for y in region.y0..region.y1 { + for x in region.x0..region.x1 { + let actual = shown[y as usize * size[0] as usize + x as usize]; + let index = ((y - region.y0) as usize) * region.width() as usize + (x - region.x0) as usize; + for (channel, (actual, expected)) in actual.into_iter().zip(expected[index]).enumerate() { + assert!((actual - f32::from(expected) / 255.0).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel {channel}"); + } } } } @@ -138,11 +151,9 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - // Every view and count below is half of the 1024 × 768 fixture first used: the clip to the view - // (`blend_preview::clip_damage`) and the catch-up (`blend_preview::uncovered`) are rectangle arithmetic with no - // size threshold, and the canvas stays far below the background redraw's (that case is - // `blend_hover_during_background_redraw_restores_committed_pixels`). The whole-canvas pixel checks cost a quarter. - app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); + // View clipping and catch-up use rectangles at any size. The visible, + // expanded and disjoint views below still require different refreshes. + app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); if cpu_fallback { @@ -156,7 +167,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { layers.push(photocraft_doc::LayerId(other)); } let ctx = app.ctx().clone(); - let visible = DRect::new(128, 128, 256, 256); + let visible = DRect::new(64, 64, 128, 128); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); if cpu_fallback { @@ -167,25 +178,24 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let original = gpu.read_texels(id.0).unwrap(); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply)); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 128 * 128, app.perf.gpu_info); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "hover must not recomposite offscreen pixels of a full-canvas layer"); - assert_visible_pixels(&mut app, visible); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 64 * 64, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "hover must not recomposite offscreen pixels of a full-canvas layer"); + assert_visible_pixels(&mut app, &[visible]); app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture"); - let zoomed_out = DRect::new(64, 64, 320, 320); + let zoomed_out = DRect::new(32, 32, 160, 160); assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None)); - assert_eq!(app.perf.last_refresh_px, 256 * 256, "zooming out catches up the larger visible area"); - let panned = DRect::new(320, 128, 448, 256); + assert_eq!(app.perf.last_refresh_px, 128 * 128, "zooming out catches up the larger visible area"); + let panned = DRect::new(160, 64, 224, 128); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change"); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "newly exposed pixels must catch up without a mode change"); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen)); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128); + assert_eq!(app.perf.last_refresh_px, 64 * 64); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "returning view must show the current mode"); - assert_visible_pixels(&mut app, visible); - assert_visible_pixels(&mut app, panned); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "returning view must show the current mode"); + assert_visible_pixels(&mut app, &[visible, panned]); crate::blend_preview::hover(&mut app, &layers, None); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels"); @@ -194,11 +204,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); - app.run("file.new", json!({"width":512,"height":384,"background":"white"})).unwrap(); + assert_visible_pixels(&mut app, &[bounds]); + app.run("file.new", json!({"width":256,"height":192,"background":"white"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 1, visible, None)); app.session.set_active(0); app.sync_views(); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index e0c6df2c2e..08e063d974 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -28,6 +28,10 @@ use photocraft_geom::Rect as DRect; #[path = "layer_edges_drawing_tests.rs"] mod layer_edges_drawing_tests; +#[cfg(test)] +#[path = "hand_scroll_all_windows_tests.rs"] +mod hand_scroll_all_windows_tests; + impl View { /// This view as the framework's canvas view of `rect` at `ppp` device pixels per point, mirrored by View › Flip /// Horizontal and stretched by View › Pixel Aspect Ratio Correction. @@ -146,7 +150,7 @@ pub(crate) fn view_follows_pointer(app: &PhotocraftApp, idx: usize) -> bool { crate::crop_ui::moves_view(app) && app.session.active_index() == Some(idx) } -/// The user's navigation choices from Preferences (General, Tools, Enhanced Controls). +/// The user's navigation preferences and Hand tool option. pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions { let p = app.session.prefs(); let mut options = NavigationOptions::default(); @@ -154,6 +158,7 @@ pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions { options.animated_zoom = p.general.animated_zoom; options.zoom_clicked_point_to_center = p.tools.zoom_clicked_point_to_center; options.flick_panning = p.tools.enable_flick_panning; + options.scroll_all_windows = app.ui.tool_options.hand_scroll_all; options.overscroll = p.tools.overscroll; options.pinch_zooms = p.enhanced_controls.zoom_with_trackpad_pinch; options.trackpad_rotate = p.enhanced_controls.rotate_view_with_trackpad; diff --git a/crates/ui-egui/src/canvas/eraser_shift_click_mode_change_tests.rs b/crates/ui-egui/src/canvas/eraser_shift_click_mode_change_tests.rs new file mode 100644 index 0000000000..be1907d2c1 --- /dev/null +++ b/crates/ui-egui/src/canvas/eraser_shift_click_mode_change_tests.rs @@ -0,0 +1,136 @@ +//! #18630: Changing Eraser mode forgets the previous Shift-click endpoint. + +use egui::accesskit::Role; +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use std::ops::RangeInclusive; + +use crate::PhotocraftApp; +use crate::app::framework::BuildApp as _; +use crate::brush_mode_menu::{self, Item}; +use crate::canvas::testing; +use crate::state::Tool; + +// Click inside the named pixels, away from the even-sized Block tip's nearest-corner tie. +const START: [f64; 2] = [100.75, 300.75]; +const END: [f64; 2] = [300.75, 300.75]; + +fn document(mode: &str) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 1.0}})).unwrap(); + app.session.tools.brush.smoothing.amount = 0.0; + app.ui.tool = Tool::Eraser; + app.ui.tool_options.eraser_mode = mode.into(); + app.sync_views(); + testing::shown(&mut app); + let scale = app.canvas_ppp(); + let view = &mut app.ui.views[0]; + view.zoom = scale; + view.clear_pending(); + testing::shown(&mut app); + assert_eq!(app.point_zoom(), 1.0, "the Block tests use one canvas point per image pixel"); + app +} + +fn alpha(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] +} + +fn block_pixels(app: &PhotocraftApp, xs: RangeInclusive) -> Vec { + (280..=320).flat_map(|y| xs.clone().map(move |x| alpha(app, x, y))).collect() +} + +fn mode_dropdown(mode: &str) -> Harness<'static, Box> { + let mut h = + Harness::builder().with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_app(|ui, app| crate::panels::options_bar(app, ui), document(mode)); + h.run_steps(4); + h +} + +fn choose_mode(h: &mut Harness<'_, Box>, label: &str) { + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label(label).click(); + h.run_steps(3); +} + +#[test] +fn changing_eraser_mode_in_the_dropdown_starts_a_separate_mark() { + let mut control = document("block"); + testing::click(&mut control, END, Modifiers::NONE); + let block = block_pixels(&control, 280..=320); + let erased_x: Vec<_> = (280..=320).filter(|&x| alpha(&control, x, 300) == 0.0).collect(); + let erased_y: Vec<_> = (280..=320).filter(|&y| alpha(&control, 300, y) == 0.0).collect(); + assert_eq!((erased_x.len(), erased_y.len()), (16, 16)); + assert_eq!(erased_x[15] - erased_x[0], 15); + assert_eq!(erased_y[15] - erased_y[0], 15); + for y in 280..=320 { + for x in 280..=320 { + let want = if erased_x.contains(&x) && erased_y.contains(&y) { 0.0 } else { 1.0 }; + assert_eq!(alpha(&control, x, y), want, "the ordinary Block dab at ({x}, {y})"); + } + } + + let modes = [("brush", "Brush"), ("pencil", "Pencil"), ("block", "Block")]; + for (from, _) in modes { + for (to, label) in modes.into_iter().filter(|(to, _)| *to != from) { + let mut h = mode_dropdown(from); + testing::click(h.state_mut(), START, Modifiers::NONE); + assert!(alpha(h.state(), 100, 300) < 0.1, "{from} marks the first click"); + let history = h.state().session.active().unwrap().history.past_len(); + choose_mode(&mut h, label); + assert_eq!(h.state().ui.tool_options.eraser_mode, to); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); + + testing::click(h.state_mut(), END, Modifiers::SHIFT); + assert!(alpha(h.state(), 300, 300) < 0.1, "{from} to {to} marks the second click"); + assert!((110..=290).all(|x| alpha(h.state(), x, 300) == 1.0), "{from} to {to} leaves the gap opaque"); + if to == "block" { + assert!(block_pixels(h.state(), 280..=320) == block, "{from} to {to} matches the ordinary Block dab exactly"); + } + } + } +} + +#[test] +fn picking_the_current_eraser_mode_or_leaving_it_alone_keeps_the_line() { + let mut ordinary = None; + for pick_current_mode in [false, true] { + let mut h = mode_dropdown("block"); + testing::click(h.state_mut(), START, Modifiers::NONE); + if pick_current_mode { + choose_mode(&mut h, "Block"); + } + testing::click(h.state_mut(), END, Modifiers::SHIFT); + let erased_rows: Vec<_> = (280..=320).filter(|&y| alpha(h.state(), 200, y) == 0.0).collect(); + assert_eq!(erased_rows.len(), 16); + assert_eq!(erased_rows[15] - erased_rows[0], 15); + assert!(erased_rows.iter().all(|&y| (100..=300).all(|x| alpha(h.state(), x, y) == 0.0)), "the same mode keeps the whole line"); + let band = block_pixels(h.state(), 80..=320); + if let Some(ordinary) = &ordinary { + assert!(&band == ordinary, "reselecting Block preserves every pixel of the ordinary line"); + } else { + ordinary = Some(band); + } + } +} + +#[test] +fn choosing_a_different_eraser_mode_from_the_canvas_menu_also_forgets_the_endpoint() { + let mut app = document("brush"); + testing::click(&mut app, START, Modifiers::NONE); + testing::secondary_click(&mut app, START, Modifiers::SHIFT); + assert!(app.ui.canvas_tool_menu.is_some(), "Shift-right-click opens the canvas menu"); + brush_mode_menu::choose(&mut app, Item::Eraser("block")); + assert_eq!(app.ui.tool_options.eraser_mode, "block"); + testing::click(&mut app, END, Modifiers::SHIFT); + assert_eq!(alpha(&app, 300, 300), 0.0); + assert_eq!(alpha(&app, 200, 300), 1.0); +} diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index a704025cef..01817fab35 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -30,8 +30,8 @@ mod tests; /// the very stall this avoids. pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { // A smart filter edit re-renders the whole stack: every stage constrains the factor. - let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); - if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom(), doc.size.area()) } + let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::app_factor(app, doc)); + if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom(), crate::proxy::planning_area(app, doc)) } } /// The open adjustment dialog (a plain one or a Smart Filter edit) while its preview shows: its dialog id and what OK @@ -364,11 +364,11 @@ pub(super) fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f3 (st.doc.id, st.revision, st.doc.clone()) }; // Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size). - let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); + let mut k = crate::proxy::app_factor(app, &doc); // Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when // the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen // (none at 50 % and closer). Otherwise the full size would be a CPU composite per change. - let fine = crate::proxy::view_factor(k, zoom, doc.size.area()); + let fine = crate::proxy::view_factor(k, zoom, crate::proxy::planning_area(app, &doc)); if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) { k = fine; } diff --git a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs index 33dca070fe..851a1ee455 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs @@ -14,37 +14,48 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec> { let tile = &doc.tiles[0]; let (device, queue) = (&gpu.rs.device, &gpu.rs.queue); let bpp = texel_bytes(doc.format) as usize; - (0..tile.levels.len()) + // Each level starts after a whole number of padded rows, so each copy offset has + // room for its own texels and meets the copy alignment for both canvas formats. + let mut size = 0; + let levels: Vec<_> = (0..tile.levels.len()) .map(|level| { let (w, h) = ((doc.size[0] >> level).max(1), (doc.size[1] >> level).max(1)); let row = (w as usize * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize); - let buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("mip_test_readback"), - size: (row * h as usize) as u64, - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - let mut encoder = device.create_command_encoder(&Default::default()); - encoder.copy_texture_to_buffer( - wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyBufferInfo { - buffer: &buffer, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, - }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - queue.submit([encoder.finish()]); - buffer.slice(..).map_async(wgpu::MapMode::Read, |result| result.unwrap()); - assert!(gpu.health.wait(device, None)); - let data = buffer.slice(..).get_mapped_range().unwrap(); - let mut pixels = Vec::new(); - for y in 0..h as usize { - for x in 0..w as usize { - let offset = y * row + x * bpp; - pixels.push(texel_to_f32(doc.format, &data[offset..offset + bpp])); - } - } - pixels + let offset = size; + size += row * h as usize; + (w, h, row, offset) + }) + .collect(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mip_test_readback"), + size: size as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + for (level, &(w, h, row, offset)) in levels.iter().enumerate() { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: offset as u64, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + } + let submission = queue.submit([encoder.finish()]); + let slice = buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |result| result.expect("map mip readback")); + assert!(gpu.health.wait_idle(device, Some(submission))); + let data = slice.get_mapped_range().expect("read mip snapshot"); + levels + .into_iter() + .map(|(w, h, row, offset)| { + data[offset..offset + row * h as usize] + .chunks_exact(row) + .flat_map(|line| line[..w as usize * bpp].chunks_exact(bpp)) + .map(|texel| texel_to_f32(doc.format, texel)) + .collect() }) .collect() } @@ -124,40 +135,44 @@ fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) { } fn check_mips(gpu: &GpuCanvas) { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - // 767 × 431 is a single tile (`DEFAULT_TILE`) with odd sides down the chain (767, 383, 191, 95 and 431, - // 215, 107, 53), and its levels 1 and 2 are over `WHOLE_MIP_SIDE` (128), so the patch below redraws two - // levels by their damage (`mip_damage`) before the chain is redrawn whole: the paths 1791 × 1083 took, at - // a sixth of the pixels. The larger driver case stays in `partial_updates_match_a_full_rebuild_at_every_mip_level`. - for (w, h) in [(767, 431), (513, 1), (1, 513)] { - let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]); - // Reusing the key also covers replacing textures after a size or depth change. - gpu.upload_buffer_full(1, &full, depth); - for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { - for pixel in pixels { - assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { - assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - } + use SampleType::{F32, U8, U16}; + // 519 is odd and still gives two damage-redrawn levels above WHOLE_MIP_SIDE + // (259 and 129), followed by whole levels. Both stored formats use this path + // on each backend, and the thin horizontal and vertical cases reach 1 × 1. + // U16 and F32 use the same float texture and mip pipeline for these values. + let depths_and_sizes: &[(SampleType, u32, u32)] = if photocraft_testkit::full_sweep() { + &[(U8, 767, 431), (U8, 513, 1), (U8, 1, 513), (U16, 767, 431), (U16, 513, 1), (U16, 1, 513), (F32, 767, 431), (F32, 513, 1), (F32, 1, 513)] + } else { + &[(U8, 519, 267), (U16, 519, 267), (F32, 1, 513), (U8, 513, 1)] + }; + for &(depth, w, h) in depths_and_sizes { + let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]); + // Reusing the key also covers replacing textures after a size or depth change. + gpu.upload_buffer_full(1, &full, depth); + for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { + for pixel in pixels { + assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); + for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { + assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); } } - let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); - let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); - assert!(gpu.upload_buffer_rect(1, &changed)); - for y in patch.y0..patch.y1 { - for x in patch.x0..patch.x1 { - full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; - } + } + let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); + let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); + assert!(gpu.upload_buffer_rect(1, &changed)); + for y in patch.y0..patch.y1 { + for x in patch.x0..patch.x1 { + full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; } - gpu.upload_buffer_full(2, &full, depth); - let partial = read_mips(gpu, 1); - let rebuilt = read_mips(gpu, 2); - for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { - for (a, b) in actual.iter().zip(expected) { - assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); - for (a, b) in a.iter().zip(b) { - assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); - } + } + gpu.upload_buffer_full(2, &full, depth); + let partial = read_mips(gpu, 1); + let rebuilt = read_mips(gpu, 2); + for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { + for (a, b) in actual.iter().zip(expected) { + assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); + for (a, b) in a.iter().zip(b) { + assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); } } } @@ -177,7 +192,17 @@ fn partial_updates_match_a_full_rebuild_at_every_mip_level() { return; }; let gpu = GpuCanvas::new(&rs); - for (depth, w, h) in [(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] { + let adapter = rs.adapter.get_info(); + // Keep the allocation/layout sweep on physical Vulkan devices, where the + // scissor regression was observed, and in the full sweep. Software adapters + // still exercise both texture formats, whole and partial redraws, and both dabs. + let sizes: &[(SampleType, u32, u32)] = + if photocraft_testkit::full_sweep() || (adapter.backend == wgpu::Backend::Vulkan && adapter.device_type != wgpu::DeviceType::Cpu) { + &[(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] + } else { + &[(SampleType::U8, 255, 255), (SampleType::F32, 519, 267)] + }; + for &(depth, w, h) in sizes { let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.0; 4]); for (i, px) in full.px.iter_mut().enumerate() { let (x, y) = (i as u32 % w, i as u32 / w); @@ -232,8 +257,9 @@ fn background_compositor_switch_preserves_pixels(gpu: &GpuCanvas) { } let second = gpu.refresh(key, &doc, Some(damage), None); assert_eq!(second.kind, "gpu-rect", "{:?}", second.fallback); - let actual = read_mips(gpu, key).remove(0); + let (_, _, actual) = gpu.read_texels(key).expect("read updated canvas"); let expected = photocraft_compose::render(&doc, doc.bounds()); + assert_eq!(actual.len(), expected.px.len()); for (got, want) in actual.iter().zip(expected.px.iter()) { for (g, w) in got.iter().zip(want.iter()) { assert!((g - w).abs() < 0.02, "{got:?} != {want:?}"); diff --git a/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs b/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs new file mode 100644 index 0000000000..15888b21cc --- /dev/null +++ b/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs @@ -0,0 +1,145 @@ +//! #12023 exercises the Hand options and gestures through the application window. + +use craft::ui::canvas::ToolHost; +use egui::accesskit::{Role, Toggled}; +use egui::{Event, Modifiers, PointerButton, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::CanvasHost; +use crate::state::{Tool, ToolOptions}; +use crate::{PhotocraftApp, Services}; + +type Window = Harness<'static, Box>; + +/// Two shown 3000 × 2000 documents, at 100% and 50%, with the second one active. +fn window() -> Window { + let mut window = Harness::builder().with_size(vec2(1400.0, 900.0)).with_pixels_per_point(1.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Services::default()); + app.background_jobs = false; + for name in ["oracle", "second"] { + app.run("file.new", json!({"width": 3000, "height": 2000, "name": name})).unwrap(); + } + app.ui.tool = Tool::Hand; + app.session.prefs.edit(|prefs| { + prefs.tools.enable_flick_panning = false; + prefs.general.animated_zoom = false; + }); + app + }); + window.run_steps(6); + let ctx = window.ctx.clone(); + crate::menus::invoke(window.state_mut(), &ctx, "window.arrange.twoUpVertical", json!({})).unwrap(); + window.run_steps(6); + for (view, zoom) in window.state_mut().ui.views.iter_mut().zip([1.0, 0.5]) { + view.zoom = zoom; + view.center = [1500.0, 1000.0]; + view.clear_pending(); + } + window.run_steps(4); + assert_eq!(window.state().session.active_index(), Some(1)); + assert_eq!(window.ctx.pixels_per_point(), 1.0); + window +} + +fn cameras(window: &Window) -> Vec<(f32, [f32; 2])> { + window.state().ui.views.iter().map(|view| (view.zoom, view.center)).collect() +} + +fn history_lengths(window: &Window) -> Vec { + window.state().session.documents().iter().map(|state| state.history.entries().len()).collect() +} + +fn enable_scroll_all(window: &mut Window) { + let checkbox = window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows"); + assert_eq!(checkbox.accesskit_node().toggled(), Some(Toggled::False)); + checkbox.click(); + window.run_steps(3); + assert!(window.state().ui.tool_options.hand_scroll_all); + assert_eq!(window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows").accesskit_node().toggled(), Some(Toggled::True)); +} + +/// A fixed screen-space gesture, so following a changing camera cannot add a second movement. +fn drag_second(window: &mut Window, modifiers: Modifiers) { + let source = ToolHost::shown_space(&window.ctx, CanvasHost::main(1).canvas_id()).expect("the active tile is shown").view; + let start = source.rect.center(); + let delta = vec2(-100.0, -50.0); + window.event(Event::ModifiersChanged(modifiers)); + window.hover_at(start); + window.run_steps(2); + window.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers }); + window.run_steps(2); + for fraction in [0.25, 0.5, 0.75, 1.0] { + window.event(Event::ModifiersChanged(modifiers)); + window.hover_at(start + delta * fraction); + window.run_steps(1); + } + window.event(Event::PointerButton { pos: start + delta, button: PointerButton::Primary, pressed: false, modifiers }); + window.run_steps(3); + window.event(Event::ModifiersChanged(Modifiers::NONE)); + window.run_steps(1); +} + +fn assert_moved(before: (f32, [f32; 2]), after: (f32, [f32; 2]), expected: Vec2) { + assert_eq!(after.0, before.0, "a Hand drag keeps each view's zoom"); + let delta = vec2(after.1[0] - before.1[0], after.1[1] - before.1[1]); + assert!((delta - expected).length() < 1e-3, "expected {expected:?} document pixels, got {delta:?}"); +} + +#[test] +fn checkbox_is_saved_without_history_and_pans_both_views_in_image_pixels() { + let mut window = window(); + assert!(!window.state().ui.tool_options.hand_scroll_all); + let history = history_lengths(&window); + enable_scroll_all(&mut window); + let saved = serde_json::to_value(&*window.state().ui.tool_options).unwrap(); + let restored: ToolOptions = serde_json::from_value(saved).unwrap(); + assert!(restored.hand_scroll_all, "the option persists with the other tool options"); + assert_eq!(history_lengths(&window), history, "ticking the checkbox adds no history state"); + let before = cameras(&window); + drag_second(&mut window, Modifiers::NONE); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_moved(before[0], after[0], vec2(200.0, 100.0)); + assert_eq!(history_lengths(&window), history, "panning adds no history state"); +} + +#[test] +fn shift_drag_pans_both_views_by_the_same_image_distance() { + let mut window = window(); + let before = cameras(&window); + drag_second(&mut window, Modifiers::SHIFT); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_moved(before[0], after[0], vec2(200.0, 100.0)); + assert!(!window.state().ui.tool_options.hand_scroll_all); +} + +#[test] +fn checkbox_off_without_shift_pans_only_the_dragged_view() { + let mut window = window(); + let before = cameras(&window); + drag_second(&mut window, Modifiers::NONE); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_eq!(after[0], before[0]); +} + +#[test] +fn hand_zoom_buttons_change_only_the_active_view_with_scroll_all_on() { + for label in ["100%", "Fit Screen", "Fill Screen"] { + let mut window = window(); + enable_scroll_all(&mut window); + let before = cameras(&window); + let history = history_lengths(&window); + window.get_by_role_and_label(Role::Button, label).click(); + window.run_steps(5); + let after = cameras(&window); + assert_eq!(after[0], before[0], "{label} leaves the other view unchanged"); + assert_ne!(after[1].0, before[1].0, "{label} changes the active view's zoom"); + assert_eq!(history_lengths(&window), history, "{label} adds no history state"); + assert!(window.state().ui.tool_options.hand_scroll_all); + } +} diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 5d00405adf..6533aee54e 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -867,3 +867,15 @@ pub(crate) fn multiple_color_target(app: &PhotocraftApp) -> bool { && photocraft_engine::mask_view_cmds::current(st).is_none() && photocraft_engine::color_channels::selected(&app.session).is_some_and(|colors| colors.len() > 1) } + +/// A real Eraser mode change starts a new sequence of Shift-click strokes. +pub(crate) fn set_eraser_mode(app: &mut PhotocraftApp, mode: &str) { + if app.ui.tool_options.eraser_mode != mode { + app.ui.tool_options.eraser_mode = mode.into(); + app.last_stroke_end = None; + } +} + +#[cfg(test)] +#[path = "eraser_shift_click_mode_change_tests.rs"] +mod eraser_shift_click_mode_change_tests; diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 1a850582d0..ab817bf6d1 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -97,7 +97,7 @@ pub(crate) fn canvas_picture( if proxy == ProxyPreview::Document && crate::adjust_preview::shown_key(app) == Some(preview_key) && let Some(st) = app.session.documents().get(idx) - && crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)) > 1 + && crate::proxy::app_factor(app, &st.doc) > 1 { (doc, preview_key) = (st.doc.clone(), 0); } diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index f7bee2e456..782b161a50 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -164,6 +164,8 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { }) }), "panels": legacy.get("panels").cloned().unwrap_or_else(|| json!(app.ui.panels)), + // Window › Options (#16795): whether the options bar is on. + "optionsBar": json!({"enabled": app.ui.panels.options_bar}), // The contextual task bar (#10890): Window › Contextual Task Bar, whether it shows now and // where (screen points), and its place (pinned, dragged-to corner). "taskBar": json!({ diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 7558da5ea0..25daf7c2b3 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -17,9 +17,9 @@ use craft::behavior::{EditEvent, EditEvents, Mixed}; use craft::color_ui::ui::gradient::{ColorStop, GradientStops}; use craft::draw::ui::gradient::{GradientGroup, GradientItem, GradientMap, GradientMapEditor, GradientMapOutput}; use craft::imaging::ui::adjust::{ - AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, - ChannelMixerEditor, ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel, - PhotoFilter, PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace, + AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, ChannelMixerEditor, + ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel, PhotoFilter, + PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace, }; use craft::imaging::ui::histogram::{ChannelColor, HistogramData}; use craft::theme::Srgba; @@ -35,6 +35,7 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; +pub(crate) mod black_white_presets; mod session; pub mod values; @@ -320,11 +321,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c let out = editor.show(ui); AdjustOut { tone: Some(out.tone), ..lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) } } - ("blackWhite", AdjustValue::BlackWhite { value }) => { - let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui); - let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; - AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }), tone: None } - } + ("blackWhite", AdjustValue::BlackWhite { value }) => black_white_presets::show(ui, value, context), ("photoFilter", AdjustValue::PhotoFilter { value }) => { let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui); AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }), tone: None } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs b/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs new file mode 100644 index 0000000000..ec3456bc83 --- /dev/null +++ b/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs @@ -0,0 +1,105 @@ +//! Original Black & White recipes for tonal shifts and the effect of color filters. + +use std::sync::Arc; + +use craft::behavior::{EditEvent, EditEvents, Mixed}; +use craft::imaging::ui::adjust::{AdjustContext, AdjustWords, BlackWhite, BlackWhiteEditor}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::form::Field; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Env; +use egui::Ui; + +use super::{AdjustAsk, AdjustOut, AdjustValue}; + +type Mix = [f64; 6]; + +/// The presets change the grayscale mix and keep the layer's tint settings. +fn entries() -> [Entry>; 16] { + [ + Entry::new(Some(BlackWhite::DEFAULT_WEIGHTS), tl!("Default")), + Entry::separator(), + Entry::new(Some([22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), tl!("Darker")), + Entry::new(Some([60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), tl!("Lighter")), + Entry::new(Some([8.0; 6]), tl!("Deep Shadows")), + Entry::new(Some([92.0; 6]), tl!("Bright Highlights")), + Entry::new(Some([48.0; 6]), tl!("Even Color Weights")), + Entry::new(Some([86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), tl!("Red Filter")), + Entry::new(Some([64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), tl!("Yellow Filter")), + Entry::new(Some([28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), tl!("Green Filter")), + Entry::new(Some([24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), tl!("Blue Filter")), + Entry::new(Some([100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), tl!("Strong Red Filter")), + Entry::new(Some([4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), tl!("Strong Blue Filter")), + Entry::new(Some([58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), tl!("Infrared Foliage")), + Entry::separator(), + Entry::new(None, tl!("Custom")), + ] +} + +/// A manual edit can land on exactly the weights of a named recipe. Remember that edit locally +/// so its value still shows as Custom. The Properties inspector scopes this memory to its target. +#[derive(Clone, Copy, PartialEq)] +struct ManualValue { + weights: Mix, + tint: Option<[u8; 3]>, +} + +impl From for ManualValue { + fn from(value: BlackWhite) -> Self { + let [r, g, b, _] = value.tint_color.to_rgba().0; + Self { weights: value.weights, tint: value.tint.then_some([r, g, b]) } + } +} + +fn manual_id(ui: &Ui) -> egui::Id { + ui.make_persistent_id("black-white-manual-value") +} + +pub(crate) fn clear_custom(ui: &Ui) { + ui.data_mut(|d| d.remove::(manual_id(ui))); + ui.ctx().request_repaint(); +} + +/// The Properties host applies accepted Color Picker colors and Auto outside the editor's pass. +pub(super) fn mark_custom(ui: &Ui, value: &AdjustValue) { + if let AdjustValue::BlackWhite { value } = value { + ui.data_mut(|d| d.insert_temp(manual_id(ui), ManualValue::from(*value))); + } +} + +pub(super) fn show(ui: &mut Ui, value: &mut BlackWhite, context: AdjustContext) -> AdjustOut { + let id = manual_id(ui); + let mut manual = ui.data(|d| d.get_temp::(id)); + let entries = entries(); + let shown = (manual != Some((*value).into()) && entries.iter().any(|entry| entry.value() == Some(&Some(value.weights)))).then_some(value.weights); + let label = tl!("Preset"); + let picked = Field::new(label).show(ui, |ui, _| Select::new(label, Bind::given(shown), &entries).show(ui).events.committed().copied()).inner.flatten(); + let mut edit = EditEvents::new(); + if let Some(picked) = picked { + manual = picked.is_none().then(|| (*value).into()); + if let Some(weights) = picked + && weights != value.weights + { + let before = *value; + value.weights = weights; + edit.push(EditEvent::set(Mixed::Same(before), *value, Arc::from(label), None)); + } + } + + let out = BlackWhiteEditor::new("Black & White", Bind::bound(&mut *value)).context(context).show(ui); + if let Some(after) = out.edit.events.committed() { + let words = Env::of(ui).words::(); + let reset = matches!(out.edit.events.ended(), Some(EditEvent::Set { label, .. }) if label.as_ref() == words.default_button.as_str()); + manual = (!reset).then(|| (*after).into()); + } + ui.data_mut(|d| match manual { + Some(value) => { + d.insert_temp(id, value); + } + None => d.remove::(id), + }); + + let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; + edit.extend(out.edit.events); + AdjustOut { ask, edit: edit.map(|value| AdjustValue::BlackWhite { value }), tone: None } +} diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 6fda7a035e..2739288577 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -13,7 +13,7 @@ use photocraft_engine::adjust_params; use serde_json::{Value, json}; use super::values::{self, ValueCx}; -use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, editor, gradient_presets, is_gray, swatches}; +use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, black_white_presets, editor, gradient_presets, is_gray, swatches}; use crate::PhotocraftApp; use crate::color_picker_ui::PickWindow; use crate::theme::Tokens; @@ -192,7 +192,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj // put while it shows this layer, replays included. record.session.track(session_target(doc, id), app.properties_hidden, &committed); } - follow_color_pick(app, id, &mut record, &committed, &vcx); + follow_color_pick(app, ui, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { Some((layer, params)) if *layer == id => values::from_params(kind, params, &vcx).unwrap_or_else(|_| committed.clone()), _ => committed.clone(), @@ -246,7 +246,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj target.extend(weights); } match values::from_params(kind, ¶ms, &vcx) { - Ok(auto) => commit(app, id, &mut record, &committed, &auto, &vcx, None), + Ok(auto) => { + if auto != committed { + black_white_presets::mark_custom(ui, &auto); + } + commit(app, id, &mut record, &committed, &auto, &vcx, None); + } Err(err) => app.ui.status = err, } } @@ -294,7 +299,7 @@ fn commit( /// A colour well's Color Picker while it is open: its colour previews on the layer. Once it /// closed, OK's colour is one edit and Cancel (or OK without a colour) leaves the layer as it was. -fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) { +fn follow_color_pick(app: &mut PhotocraftApp, ui: &egui::Ui, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) { let Some(pick) = record.pick.take() else { return }; match app.framework.dialogs.get_by_id::(pick.dialog).map(ColorPickerDialog::current) { Some(current) => { @@ -310,6 +315,9 @@ fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut Properti Some((key, color)) if key == pick.key && Some(color) != pick.opened => { let mut answered = pick.before; if answer_color(&mut answered, &key, color) { + if answered != *committed { + black_white_presets::mark_custom(ui, &answered); + } commit(app, id, record, committed, &answered, vcx, None); } else { app.live_adjust = None; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index fa23887d65..87493748f5 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -492,3 +492,154 @@ fn black_white_auto_button_sets_the_weights() { assert_ne!(after, before, "the red and blue are told apart"); assert_eq!(history_len(&h), steps + 1); } + +#[track_caller] +fn assert_black_white_preset(h: &Harness<'_, Box>, name: &str) { + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Preset").accesskit_node().value().as_deref(), Some(name)); +} + +#[test] +fn black_white_presets_apply_the_authored_weights_and_keep_tint() { + let mut h = app_harness("blackWhite", "rgb", 8); + // Leave enough vertical space for the complete dropdown to be visible at once. + h.set_size(vec2(1440.0, 1350.0)); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap(); + h.run_steps(4); + let (_, original) = layer(&h); + let Adjustment::BlackWhite { tint: original_tint, .. } = &original else { panic!("{original:?}") }; + + for (name, expected) in [ + ("Darker", [22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), + ("Lighter", [60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), + ("Deep Shadows", [8.0; 6]), + ("Bright Highlights", [92.0; 6]), + ("Even Color Weights", [48.0; 6]), + ("Red Filter", [86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), + ("Yellow Filter", [64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), + ("Green Filter", [28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), + ("Blue Filter", [24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), + ("Strong Red Filter", [100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), + ("Strong Blue Filter", [4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), + ("Infrared Foliage", [58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), + ("Default", [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]), + ] { + let history = history_len(&h); + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, name).click(); + h.run_steps(4); + + let (_, applied) = layer(&h); + let Adjustment::BlackWhite { weights, tint } = applied else { panic!("{applied:?}") }; + assert_eq!(weights, expected, "{name} applies the authored mix"); + assert_black_white_preset(&h, name); + assert_eq!(&tint, original_tint, "{name} preserves Tint"); + assert_eq!(history_len(&h), history + 1, "{name} is one history step"); + assert!(h.state().live_adjust.is_none(), "{name} finishes the preview"); + } + assert_eq!(layer(&h).1, original, "Default restores the original mix"); +} + +#[test] +fn black_white_presets_apply_through_properties_and_undo() { + let mut h = app_harness("blackWhite", "rgb", 8); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap(); + h.run_steps(4); + let (_, before) = layer(&h); + let Adjustment::BlackWhite { weights: original, tint: original_tint } = &before else { panic!("{before:?}") }; + let history = history_len(&h); + let pixel = h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(); + assert_black_white_preset(&h, "Default"); + + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, "Darker").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Darker"); + let (_, after) = layer(&h); + let Adjustment::BlackWhite { weights, tint } = &after else { panic!("{after:?}") }; + assert!(weights.iter().zip(original).all(|(weight, original)| weight < original)); + assert_eq!(tint, original_tint); + assert_ne!(h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(), pixel); + assert_eq!(history_len(&h), history + 1); + assert!(h.state().live_adjust.is_none()); + + let ctx = h.ctx.clone(); + let picker = open_picker(&mut h, "Tint Color"); + show_in_picker(&mut h, picker, "#ad632a"); + h.state_mut().framework.dialogs.cancel_by_id(&ctx, picker); + h.run_steps(4); + assert_black_white_preset(&h, "Darker"); + assert_eq!(layer(&h).1, after); + assert_eq!(history_len(&h), history + 1); + + let picker = open_picker(&mut h, "Tint Color"); + show_in_picker(&mut h, picker, "#ad632a"); + crate::dialogs::confirm(h.state_mut(), &ctx, picker).expect("OK is enabled"); + h.run_steps(4); + assert_black_white_preset(&h, "Custom"); + assert_eq!(history_len(&h), history + 2); + + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(layer(&h).1, after); + assert_black_white_preset(&h, "Darker"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(layer(&h).1, before); + assert_black_white_preset(&h, "Default"); +} + +#[test] +fn black_white_presets_distinguish_manual_edits_from_named_choices() { + let mut h = app_harness("blackWhite", "rgb", 8); + // Opening the dropdown on Custom reveals the last row, so leave room for Default too. + h.set_size(vec2(1440.0, 1350.0)); + let (id, defaults) = layer(&h); + let Adjustment::BlackWhite { weights, .. } = &defaults else { panic!("{defaults:?}") }; + let red = weights[0]; + let type_default = |h: &mut Harness<'_, Box>| { + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "reds": red + 7.0})).unwrap(); + h.run_steps(4); + assert_black_white_preset(h, "Custom"); + h.get_by_role_and_label(Role::SpinButton, "Reds").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(red.to_string())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(4); + assert_eq!(layer(h).1, defaults); + assert_black_white_preset(h, "Custom"); + }; + + type_default(&mut h); + + h.state_mut().run("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap(); + // Layer selection can keep the mask targeted. Return to the adjustment's controls. + h.state_mut().run("channel.target.composite", json!({})).unwrap(); + h.run_steps(4); + assert_black_white_preset(&h, "Custom"); + + let history = history_len(&h); + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, "Default").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + assert_eq!(layer(&h).1, defaults); + assert_eq!(history_len(&h), history); + + type_default(&mut h); + h.get_by_role_and_label(Role::Button, "Reset to defaults").scroll_to_me(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Reset to defaults").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + assert_eq!(layer(&h).1, defaults); +} diff --git a/crates/ui-egui/src/dialogs/adjust_preview.rs b/crates/ui-egui/src/dialogs/adjust_preview.rs index 1011f82cad..dd3269909c 100644 --- a/crates/ui-egui/src/dialogs/adjust_preview.rs +++ b/crates/ui-egui/src/dialogs/adjust_preview.rs @@ -254,7 +254,7 @@ pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str, param fn cheap(app: &PhotocraftApp, doc: &Document) -> bool { match &app.gpu { Some(g) => g.supports(doc), - None => crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app)) <= 1, + None => crate::proxy::app_factor(app, doc) <= 1, } } @@ -426,15 +426,16 @@ pub fn gpu_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option Result pick_and_export(app, f) } -/// Export each selected layer separately, with one destination prompt for the batch. -/// The chosen path names the first file; subsequent files have numbered sibling names. +/// Export each selected layer or group to its own PNG, named after the source. pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result { let st = app.session.active().ok_or("no document")?; let layers = st.selected_layers(); @@ -393,28 +392,56 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result = names.iter().flat_map(|name| [name.to_uppercase(), name.to_lowercase()]).collect(); + let paths = names.iter().map(|name| { + let stem = name.strip_suffix(".png").unwrap_or(name); + unused_export_path(dir, stem, "png", |candidate| reserved.contains(&candidate.to_uppercase()) || reserved.contains(&candidate.to_lowercase())) + .to_string_lossy() + .into_owned() + }); + write_quick_pngs(app, &docs, paths, true) }) } +fn write_quick_pngs(app: &mut PhotocraftApp, docs: &[Document], paths: impl IntoIterator, new_files_only: bool) -> Result { + let mut exported = Vec::new(); + for (doc, path) in docs.iter().zip(paths) { + crate::app::ensure_memory_to_save(doc, &path)?; + let export = app.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(doc, &path, &ExportSettings { xmp_all: false, ..Default::default() })?; + // A file may have appeared at a generated path while the encoder was running. + let write = if new_files_only { + app.services.write_new.as_mut().ok_or("no exclusive export writer configured")? + } else { + app.services.write.as_mut().ok_or("no writer configured")? + }; + write(&path, &bytes)?; + crate::notices::io_warnings(app, &format!("Exported {}", crate::file_open::display_name(&path)), &warnings); + exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})); + } + app.ui.status = format!("Exported {} PNG files", exported.len()); + app.ui.status_error = false; + Ok(json!({"files": exported})) +} + /// The first 80 characters of `name`, each control character and each character a file name /// can't hold (`< > : " / \ | ? *`) turned into `_`. fn file_name_chars(name: &str) -> String { @@ -435,6 +462,26 @@ fn layer_export_name(name: &str) -> String { if name.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { name } } +fn layer_export_suggestion(name: &str, ext: &str) -> String { + generated_export_name(&layer_export_name(&stem_of(name)), ext, None) +} + +/// Leave room within a 255-byte filename component for the atomic writer's temporary suffix. +const MAX_GENERATED_EXPORT_NAME_BYTES: usize = 200; + +fn generated_export_name(stem: &str, ext: &str, number: Option) -> String { + let suffix = number.map_or_else(String::new, |number| format!("-{number}")); + let limit = MAX_GENERATED_EXPORT_NAME_BYTES.saturating_sub(ext.len()).saturating_sub(1 + suffix.len()); + let name_at = |limit| { + let stem = stem.get(..stem.floor_char_boundary(limit)).unwrap_or_default(); + let stem = if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer" } else { stem }; + photocraft_engine::file_cmds::portable_device_name(format!("{stem}{suffix}.{ext}")) + }; + let name = name_at(limit); + // Truncation can expose a Windows device name. Its escape adds one byte. + if name.len() > MAX_GENERATED_EXPORT_NAME_BYTES { name_at(limit.saturating_sub(1)) } else { name } +} + /// The files a multi-layer export writes: the chosen path, then numbered siblings named after /// each layer, in the chosen path's format. fn batch_paths(path: &str, docs: &[Document]) -> Vec { @@ -448,27 +495,36 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec { if i == 0 { return path.to_string(); } - let name = export_name(&doc.name); - let candidate = parent.join(format!("{stem}-{}-{name}.{ext}", i + 1)); + let numbered = format!("{stem}-{}-{}", i + 1, export_name(&doc.name)); // The first file's overwrite is handled by the Save dialog; never overwrite sibling // files silently on desktop. Downloads on the web are named by the browser. #[cfg(not(target_arch = "wasm32"))] - let candidate = { - let mut candidate = candidate; - let mut suffix = 1u64; - // A name any entry occupies is taken, a symlink (even a dangling one) included: the writer - // follows links, so one planted here would redirect the export. - while candidate.symlink_metadata().is_ok() { - candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1)); - suffix = suffix.saturating_add(1); - } - candidate - }; + let candidate = unused_export_path(parent, &numbered, ext, |_| false); + #[cfg(target_arch = "wasm32")] + let candidate = parent.join(format!("{numbered}.{ext}")); candidate.to_string_lossy().into_owned() }) .collect() } +/// Keep existing entries, including links (even dangling ones), when choosing an output path. +#[cfg(not(target_arch = "wasm32"))] +fn unused_export_path(dir: &std::path::Path, stem: &str, ext: &str, reserved: impl Fn(&str) -> bool) -> std::path::PathBuf { + let candidate = dir.join(generated_export_name(stem, ext, None)); + if candidate.symlink_metadata().is_err() { + return candidate; + } + let mut suffix = 1u64; + loop { + let name = generated_export_name(stem, ext, Some(suffix)); + let candidate = dir.join(&name); + if !reserved(&name) && candidate.symlink_metadata().is_err() { + return candidate; + } + suffix = suffix.saturating_add(1); + } +} + /// The document a dialog exports: the whole image, or one layer (`__layer`). fn source_document_from(doc: Arc, f: &Map) -> Result, String> { match f.get("__layer").and_then(Value::as_u64) { @@ -1073,8 +1129,8 @@ fn export_to(app: &mut PhotocraftApp, f: &Map, path: &str) -> Res /// A layer's name may hold characters a file name can't (#14810): `a/b:c*?` suggests `a_b_c__`. fn pick_and_export(app: &mut PhotocraftApp, f: Map) -> Result { let doc = source_document(app, &f)?; - let stem = if f.contains_key("__layer") { layer_export_name(&stem_of(&doc.name)) } else { stem_of(&doc.name) }; - let suggested = format!("{stem}.{}", s_fmt(&f)); + let ext = s_fmt(&f); + let suggested = if f.contains_key("__layer") { layer_export_suggestion(&doc.name, &ext) } else { format!("{}.{ext}", stem_of(&doc.name)) }; app.pick_export(&suggested, move |app, path| export_to(app, &f, &path)) } @@ -1185,7 +1241,7 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result.`, replacing a file of that /// name (#14808). One file is written at `path`; the web downloads each file, the first under -/// `path` and the others named as Quick Export names a selection's files. +/// `path` and the others under numbered names derived from that filename and their layer names. fn export_layers(app: &mut PhotocraftApp, f: &Map, ids: &[LayerId], path: &str) -> Result { let st = app.session.active().ok_or("no document")?; let source_profile = effective_source_profile(app, &st.doc); @@ -1239,7 +1295,7 @@ fn write_layer_file( /// can't hold becomes `_` (`a/b:c*?` → `a_b_c__`), spaces are kept. fn layer_file_stem(name: &str) -> String { let stem: String = name.chars().map(|c| if c.is_control() || "<>:\"/\\|?*".contains(c) { '_' } else { c }).collect(); - if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { stem } + if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { photocraft_engine::file_cmds::portable_device_name(stem) } } /// The names several layers' files get, for `docs` in document order (bottom to top). Equal @@ -1257,10 +1313,10 @@ fn layer_file_names(docs: &[Document], ext: &str) -> Vec { let mut names = vec![String::new(); docs.len()]; for (i, doc) in docs.iter().enumerate().rev() { let stem = layer_file_stem(&doc.name); - let mut name = format!("{stem}.{ext}"); + let mut name = generated_export_name(&stem, ext, None); let mut n = 1u64; while taken(&used, &name) { - name = format!("{stem}-{n}.{ext}"); + name = generated_export_name(&stem, ext, Some(n)); n = n.saturating_add(1); } used.insert(name.to_uppercase()); diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs index 4eaea2e4c3..89e2e91690 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs @@ -70,9 +70,11 @@ fn answer(app: &mut PhotocraftApp, files: &ScriptedFiles, path: &std::path::Path fn quick_export_skips_the_same_layers() { let (mut app, l, written, files) = app(); *app.session.active_mut().unwrap().selection_mut() = vec![l.empty, l.red, l.adjustment, l.blue, l.gone]; + app.services.write_new = app.services.write.take(); + let out = tempfile::tempdir().unwrap(); quick_export_selected_layers_png(&mut app).unwrap(); - answer(&mut app, &files, std::path::Path::new("quick.png")); - assert_eq!(*written.borrow(), ["quick.png", "quick-2-Blue.png"]); + answer(&mut app, &files, out.path()); + assert_eq!(*written.borrow(), [out.path().join("Red.png").to_string_lossy(), out.path().join("Blue.png").to_string_lossy()]); } #[test] diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs index 652adf18c6..96ed42d2c5 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs @@ -89,6 +89,21 @@ mod planted_link { request } + #[test] + fn quick_export_uses_one_folder_and_names_each_file_after_its_layer() { + let out = tempfile::tempdir().unwrap(); + let (mut app, ids, _, written, files) = app(); + app.services.write_new = app.services.write.take(); + app.session.restore_layer_selection(Some(ids[0]), &ids, None).unwrap(); + quick_export_selected_layers_png(&mut app).unwrap(); + assert_eq!(files.requests().last().unwrap().kind, craft::host::PickKind::Folder); + files.answer(Picked::Paths(vec![out.path().to_path_buf()])).unwrap(); + app.poll_file_dialog(); + let written = written.borrow(); + let actual: Vec<_> = written.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_str().unwrap()).collect(); + assert_eq!(actual, ["a_b_c__.png", "Dup-1.png", "Dup.png"]); + } + #[test] fn a_planted_link_is_replaced_not_followed() { let guard = tempfile::tempdir().unwrap(); diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs index d7006361fc..f4ceaad0c2 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs @@ -5,25 +5,45 @@ //! export's `export_name`. use super::*; -use craft::host::ScriptedFiles; +use craft::host::{PickKind, ScriptedFiles}; /// The file name Layer › Quick Export as PNG suggests for a layer named `name` (the Save dialog /// stays open), and the whole save request as text. fn suggested_for(name: &str) -> (String, String) { + suggested_for_selection(name, false) +} + +fn suggested_for_selection(name: &str, include_empty: bool) -> (String, String) { let files = Arc::new(ScriptedFiles::held()); let services = crate::Services { files: Some(files.clone()), ..Default::default() }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); app.run("file.new", json!({"width": 20, "height": 20})).unwrap(); + app.run("layer.new.layer", json!({"name": "Empty"})).unwrap(); + let empty = app.session.active().unwrap().active_layer.unwrap(); app.run("layer.new.layer", json!({"name": name})).unwrap(); app.run("select.rect", json!({"x": 2, "y": 2, "width": 6, "height": 6})).unwrap(); app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); let layer = app.session.active().unwrap().active_layer.unwrap(); - quick_export_layer_png(&mut app, layer).unwrap(); + if include_empty { + app.session.restore_layer_selection(Some(layer), &[empty, layer], None).unwrap(); + } + crate::menus::invoke(&mut app, &egui::Context::default(), "layer.quickExportAsPng", Value::Null).unwrap(); let asked = files.requests(); let [request] = asked.as_slice() else { panic!("one Save dialog: {asked:?}") }; + assert_eq!(request.kind, PickKind::Save); (request.file_name.clone().unwrap_or_default(), format!("{request:?}")) } +#[test] +fn quick_export_suggests_the_same_name_when_an_empty_layer_is_selected() { + for name in ["Hero.v2", "a/b:c*?", "CON", &"界".repeat(100)] { + let (single, _) = suggested_for(name); + let (with_empty, _) = suggested_for_selection(name, true); + assert_eq!(with_empty, single, "{name:?}"); + assert!(single.len() <= MAX_GENERATED_EXPORT_NAME_BYTES); + } +} + #[test] fn a_layer_named_with_illegal_characters_suggests_underscores() { let (file, path) = suggested_for("a/b:c*?"); diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 9c51d2eb22..3bf432812c 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -631,8 +631,8 @@ fn specs(keys: &HashMap, user: &Map, light: f32) .filter_map(|(key, _)| { let kind = EffectKind::from_key(key)?; let mut spec = EffectSpec::photoshop(kind).with_blend_keys(keys); - if kind == EffectKind::OuterGlow { - // #14944: Photoshop groups the Outer Glow rows Structure / Elements / Quality and + if matches!(kind, EffectKind::OuterGlow | EffectKind::InnerGlow) { + // #14944, #14917: Photoshop groups the glow rows Structure / Elements / Quality and // puts Noise right under Opacity. The hosted page draws the spec's rows in order, // so the host moves the row; the group titles belong to the framework's page. if let Some(noise) = spec.fields.iter().position(|f| f.key == "noise") { diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index df36e41c5c..08ade2e29e 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -766,10 +766,10 @@ fn a_new_satin_in_the_dialog_starts_at_the_factory_values() { /// #14944: the Outer Glow page is grouped Photoshop-style - Noise right under Opacity, the rows of /// the Structure, Elements and Quality blocks. The hosted page draws `specs()` rows in order, so /// the page order is pinned here; the group TITLES belong to the framework's page (craft-libs has -/// no header row on an effect page yet) and the other pages keep the framework's order (#14917 is -/// the Inner Glow's own ticket). +/// no header row on an effect page yet). #14917 groups the Inner Glow page the same way; the +/// other pages keep the framework's order. #[test] -fn the_outer_glow_page_rows_group_noise_under_opacity() { +fn the_glow_page_rows_group_noise_under_opacity() { let row_keys = |want: &str| { specs(&blend_keys(), &Map::new(), 120.0) .into_iter() @@ -781,11 +781,7 @@ fn the_outer_glow_page_rows_group_noise_under_opacity() { .collect::>() }; assert_eq!(row_keys("outerGlow"), ["blend", "opacity", "noise", "color", "technique", "spread", "size", "contour", "range"]); - assert_eq!( - row_keys("innerGlow"), - ["blend", "opacity", "color", "technique", "source", "choke", "size", "contour", "range", "noise"], - "the Inner Glow page stays as it is" - ); + assert_eq!(row_keys("innerGlow"), ["blend", "opacity", "noise", "color", "technique", "source", "choke", "size", "contour", "range"]); assert_eq!( row_keys("dropShadow"), ["blend", "color", "opacity", "angle", "useGlobalLight", "distance", "spread", "size", "contour", "noise", "knocksOut"], @@ -818,6 +814,33 @@ fn a_new_outer_glow_opens_at_the_factory_values_and_ok_keeps_them() { assert_eq!(hex(c), "#ffffff", "OK stored the colour"); } +/// #14917: a new Inner Glow opens at the reference application's factory values, and OK stores +/// exactly those. +#[test] +fn a_new_inner_glow_opens_at_the_factory_values_and_ok_keeps_them() { + let mut app = app_with_layer(32); + let id = open(&mut app, Some(EffectKind::InnerGlow.key())).unwrap(); + let glow = first_of(&app, id, EffectKind::InnerGlow); + let style = &draft(&app, id).style; + assert_eq!( + (text(style, glow, "blend").as_deref(), text(style, glow, "technique").as_deref(), text(style, glow, "source").as_deref()), + (Some("Screen"), Some("softer"), Some("edge")) + ); + assert_eq!( + (num(style, glow, "opacity"), num(style, glow, "noise"), num(style, glow, "choke"), num(style, glow, "size"), num(style, glow, "range")), + (Some(35.0), Some(0.0), Some(0.0), Some(7.0), Some(50.0)), + "the page's own seed" + ); + assert_eq!(style.effect(glow).and_then(|e| e.params.bool("antiAlias")), Some(false)); + let Some(StyleValue::Color(c)) = param(style, glow, "color") else { panic!("the colour row loads as a colour") }; + assert_eq!(color_picker_ui::hex(c.to_rgb_array()), "#ffffff", "the page's own colour"); + ok(&mut app, id); + let Effect::InnerGlow(g) = &layer_effects(&app.session)[0] else { panic!("{:?}", layer_effects(&app.session)) }; + assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4 && (g.size - 7.0).abs() < 1e-4, "OK stored {g:?}"); + let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) }; + assert_eq!(hex(c), "#ffffff", "OK stored the colour"); +} + /// #14944: the factory values never reach an Outer Glow the layer already carries: the page shows /// its own values and OK keeps them, as it does for a glow read from a PSD or `.pcraft`. #[test] diff --git a/crates/ui-egui/src/dialogs/new_layer_name_trim_tests.rs b/crates/ui-egui/src/dialogs/new_layer_name_trim_tests.rs new file mode 100644 index 0000000000..78a8f17f86 --- /dev/null +++ b/crates/ui-egui/src/dialogs/new_layer_name_trim_tests.rs @@ -0,0 +1,22 @@ +use super::{COMMAND, testing}; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +#[test] +fn new_layer_dialog_trims_only_its_name() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let ctx = app.ctx().clone(); + + for (typed, expected) in [(" sp a ", Some("sp a")), ("", None), (" ", None)] { + let default = app.session.active().unwrap().doc.next_layer_name("Layer"); + crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap(); + let id = testing::top(&app); + testing::set(&mut app, id, "name", json!(typed)).unwrap(); + crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.last().unwrap().name, expected.unwrap_or(&default)); + } + + app.run(COMMAND, json!({"name": "abc "})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.last().unwrap().name, "abc "); +} diff --git a/crates/ui-egui/src/dialogs/new_layer_ui.rs b/crates/ui-egui/src/dialogs/new_layer_ui.rs index 72aecda8bc..1375f74fe3 100644 --- a/crates/ui-egui/src/dialogs/new_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/new_layer_ui.rs @@ -88,7 +88,7 @@ pub fn params(f: &DialogFields) -> Value { }); // An empty name gets the next "Layer N", as the Layers panel button does. if let Some(name) = f.text("name").filter(|n| !n.trim().is_empty()) { - p["name"] = json!(name); + p["name"] = json!(name.trim_matches(' ')); } p } @@ -130,6 +130,10 @@ pub(crate) mod testing { } } +#[cfg(test)] +#[path = "new_layer_name_trim_tests.rs"] +mod new_layer_name_trim_tests; + #[cfg(test)] mod tests { use serde_json::json; diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index f418ef3923..3caea64f8e 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -241,6 +241,34 @@ impl PhotocraftApp { self.pick_save_in(suggested, true, None, then) } + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn pick_export_folder(&mut self, then: impl FnOnce(&mut Self, String) -> Result + 'static) -> Result { + let doc = self.session.active(); + let document_dir = doc.and_then(|st| { + self.save_dirs + .get(&st.doc.id) + .filter(|dir| folder_exists(dir)) + .cloned() + .or_else(|| st.path.as_deref().and_then(|p| Path::new(p).parent()).map(Path::to_path_buf)) + }); + let doc = doc.map(|st| st.doc.id); + let mut request = PickRequest::folder("export"); + if let Some(dir) = export_start_dir(Some(&self.session.prefs().export.last_folder), document_dir, folder_exists) { + request = request.directory(dir); + } + self.ask_file(request, move |app, picked| { + let path = path_strings(&picked).into_iter().next().ok_or(UNEXPECTED)?; + let exported = then(app, path.clone())?; + if let Some(doc) = doc + && app.session.documents().iter().any(|st| st.doc.id == doc) + { + app.save_dirs.insert(doc, PathBuf::from(&path)); + } + app.session.prefs.edit(|prefs| prefs.export.last_folder = path); + Ok(exported) + }) + } + fn pick_save_in( &mut self, suggested: &str, diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 11edd5f050..3e854efbd2 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -910,6 +910,8 @@ fn convert_to_linked_asks_where_to_write_the_contents() { #[test] fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() { let (mut app, files, written) = app(); + app.services.write_new = app.services.write.take(); + let out = tempfile::tempdir().unwrap(); app.run("layer.new.layer", json!({"name": "Same/name"})).unwrap(); app.run("paint.bucket", json!({"x": 0, "y": 0, "color": "#ff0000"})).unwrap(); app.run("layer.new.layer", json!({"name": "Same/name"})).unwrap(); @@ -932,12 +934,13 @@ fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() { assert_eq!(files.requests().len(), 1, "one destination for the entire selection"); // Selection changes while choosing a destination must not change the captured sources. app.run("layer.select", json!({"layer": selected[0].0})).unwrap(); - answer(&files, chose("selected.png")); + assert_eq!(files.requests()[0].kind, craft::host::PickKind::Folder); + answer(&files, Picked::Paths(vec![out.path().to_path_buf()])); app.poll_file_dialog(); assert_eq!(written.borrow().len(), selected.len()); assert_eq!(sources.borrow().len(), selected.len()); - assert_eq!(written.borrow()[0], "selected.png"); - assert_eq!(written.borrow()[1], "selected-2-Same_name.png"); + assert_eq!(written.borrow()[0], out.path().join("Same_name-1.png").to_string_lossy()); + assert_eq!(written.borrow()[1], out.path().join("Same_name.png").to_string_lossy()); assert_eq!(selected.len(), 2, "Select All Layers leaves the locked Background out"); assert_eq!(app.session.active().unwrap().doc, before); assert!(!app.ui.status_error, "{}", app.ui.status); diff --git a/crates/ui-egui/tests/it/gpu_tests/full_res_preview.rs b/crates/ui-egui/src/gpu_tests/full_res_preview.rs similarity index 59% rename from crates/ui-egui/tests/it/gpu_tests/full_res_preview.rs rename to crates/ui-egui/src/gpu_tests/full_res_preview.rs index 2d0b634651..4997f60fd1 100644 --- a/crates/ui-egui/tests/it/gpu_tests/full_res_preview.rs +++ b/crates/ui-egui/src/gpu_tests/full_res_preview.rs @@ -1,29 +1,32 @@ //! Preferences › Performance › Low Resolution Previews: on (the default) live previews of a large //! document render on a reduced copy, off they render at full resolution. //! -//! A 2502 × 2000 document of 1 px black and white columns: the reduced copy (every 2nd pixel at -//! this size) is all black, so its preview shows a flat colour where the full-size one shows the -//! columns at 100 % (and their mipmapped grey zoomed out). Drives the real app offscreen on wgpu; +//! A document of 1 px black and white columns: the reduced copy (every 2nd pixel) is all black, +//! so its preview shows a flat colour where the full-size one shows the columns at 100 % +//! and their mipmapped grey zoomed out. Drives the real app offscreen on wgpu; //! skips when no GPU adapter exists (like `drag_preview_canvas.rs`). +use crate::PhotocraftApp; +use crate::control::{ControlRequest, handle}; +use craft::behavior::kurbo::Point; use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::{Document, Size}; use photocraft_geom::Rect; -use photocraft_ui_egui::PhotocraftApp; -use photocraft_ui_egui::control::{ControlRequest, handle}; use serde_json::{Value, json}; type Harness = egui_kittest::Harness<'static, Box>; -// Just above the 5 MP proxy threshold; keep the same factor-two reduction. -const W: i32 = 2502; -const H: i32 = 2000; +// Leave room for a visible patch of columns beside the dialogs at 50 % zoom. +const W: i32 = 800; +const H: i32 = 500; +const PREVIEW_AREA_MULTIPLIER: u64 = 13; fn harness() -> Option { let built = std::panic::catch_unwind(|| { egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + app.preview_test_area_multiplier = PREVIEW_AREA_MULTIPLIER; if let Some(rs) = cc.wgpu_render_state.as_ref() { app.set_wgpu(rs.clone()); } @@ -46,32 +49,35 @@ fn control(h: &mut Harness, method: &str, params: Value) { h.run_steps(3); } -fn columns_document() -> Document { - let mut doc = Document::with_background("columns", Size::new(W as u32, H as u32), ColorMode::Rgb, SampleType::U8, Color::WHITE); - assert_eq!(photocraft_ui_egui::proxy::factor(&doc), 2, "the fixture must exercise a reduced preview"); - let s = doc.layers[0].surface_mut().expect("background pixels"); - let row: Vec = (0..W) +fn columns_document(width: i32, height: i32) -> Result { + let mut doc = Document::with_background("columns", Size::new(width as u32, height as u32), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let s = doc.layers.first_mut().and_then(|layer| layer.surface_mut()).ok_or("missing background pixels")?; + let row: Vec = (0..width) .flat_map(|x| { let v = if x % 2 == 0 { 0.0 } else { 1.0 }; [v, v, v, 1.0] }) .collect(); - for y in (0..H).step_by(64) { - let end = (y + 64).min(H); - s.write_region(Rect::new(0, y, W, end), &row.repeat((end - y) as usize)); + for y in (0..height).step_by(64) { + let end = (y + 64).min(height); + s.write_region(Rect::new(0, y, width, end), &row.repeat((end - y) as usize)); } - doc + Ok(doc) } -fn setup(h: &mut Harness, zoom: f32) { +fn setup(h: &mut Harness, zoom: f32) -> Result<(), &'static str> { { let app = h.state_mut(); - app.session.add_document(columns_document(), None); + let doc = columns_document(W, H)?; + assert_eq!(crate::proxy::factor(&doc), 1, "the fixture is below the production threshold"); + assert_eq!(crate::proxy::app_factor(app, &doc), 2, "the test must exercise a twofold reduction"); + app.session.add_document(doc, None); app.sync_views(); app.ui.extras.rulers = false; } control(h, "ui.set", json!({"zoom": zoom, "center": [W / 2, H / 2]})); h.run_steps(4); + Ok(()) } /// Whether the canvas draws on the GPU (the previews under test are the GPU canvas's). @@ -84,27 +90,29 @@ fn on_gpu(h: &mut Harness) -> bool { gpu } -fn low_res(h: &mut Harness, on: bool) { - h.state_mut().run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": on})).expect("prefs.set"); +fn low_res(h: &mut Harness, on: bool) -> Result<(), String> { + h.state_mut().run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": on}))?; h.run_steps(4); + Ok(()) } -/// Luma along a 300 px row near the canvas's top-left corner (clear of centred dialogs). -fn row(h: &mut Harness) -> Vec { +/// Luma along a row inside the visible document, to the left of centred dialogs. +fn row(h: &mut Harness) -> Result, &'static str> { h.run_steps(4); - // The canvas as its last pass showed it: the rectangle the rendered pixels are sampled in. - let canvas = photocraft_ui_egui::canvas::active_view(h.state()).expect("the canvas has been shown").rect; - // egui_kittest waits 10 s for the GPU. Windows CI renders on WARP, a software rasterizer, - // where the first full-resolution composite of this 5 MP document can take longer; the - // submitted work still finishes, so wait for it again instead of failing. - let img = (0..3).find_map(|_| h.render().ok()).expect("render"); - let (x0, y) = (canvas.min.x as u32 + 20, canvas.min.y as u32 + 40); - (x0..x0 + 300) + let view = crate::canvas::active_view(h.state()).ok_or("the canvas has not been shown")?; + let image = egui::Rect::from_two_pos(view.to_screen(Point::ORIGIN), view.to_screen(Point::new(f64::from(W), f64::from(H)))); + let visible = view.rect.intersect(image); + // Windows CI uses a software rasterizer. A render timeout need not drop the submitted work. + let img = (0..3).find_map(|_| h.render().ok()).ok_or("could not render the canvas")?; + let (x0, y) = (visible.min.x.ceil() as u32 + 12, visible.min.y.ceil() as u32 + 12); + let x1 = x0 + 48; + assert!(visible.contains(egui::pos2(x1 as f32, y as f32)), "sample row is inside the visible image"); + Ok((x0..x1) .map(|x| { let p = img.get_pixel(x, y).0; (i32::from(p[0]) * 3 + i32::from(p[1]) * 6 + i32::from(p[2])) / 10 }) - .collect() + .collect()) } /// Fraction of neighbouring screen pixels that differ like black and white. @@ -121,14 +129,14 @@ fn mean(r: &[i32]) -> f32 { /// previews on; zoomed out to 50 % the default drag runs on the reduced copy (only the black columns, inverted), and with /// them off it matches the committed view (the columns' mipmapped grey). #[test] -fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() { +fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() -> Result<(), String> { let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut h) = harness() else { return }; - setup(&mut h, 1.0); + let Some(mut h) = harness() else { return Ok(()) }; + setup(&mut h, 1.0)?; if !on_gpu(&mut h) { - return; + return Ok(()); } - assert!(columns(&row(&mut h)) > 0.9, "the canvas shows the 1 px columns at 100 %"); + assert!(columns(&row(&mut h)?) > 0.9, "the canvas shows the 1 px columns at 100 %"); let layer = { let app = h.state_mut(); app.run("layer.newAdjustmentLayer.invert", json!({})).expect("adjustment layer"); @@ -137,66 +145,70 @@ fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() { app.live_adjust = Some((id, json!({}))); id }; - let at_100 = row(&mut h); + let at_100 = row(&mut h)?; assert!(columns(&at_100) > 0.9, "default at 100 %: the drag is never coarser than the screen ({})", columns(&at_100)); control(&mut h, "ui.set", json!({"zoom": 0.5, "center": [W / 2, H / 2]})); h.state_mut().live_adjust = None; - let committed = mean(&row(&mut h)); - assert!(committed > 60.0, "zoomed out the inverted columns average to grey ({committed})"); + let committed = mean(&row(&mut h)?); + assert!((60.0..220.0).contains(&committed), "zoomed out the inverted columns average to grey ({committed})"); h.state_mut().live_adjust = Some((layer, json!({}))); - let reduced = mean(&row(&mut h)); + let reduced = mean(&row(&mut h)?); assert!(reduced > 225.0, "default at 50 %: the reduced copy keeps only the (inverted) black columns ({reduced})"); - low_res(&mut h, false); + low_res(&mut h, false)?; h.state_mut().live_adjust = Some((layer, json!({}))); - let full = mean(&row(&mut h)); + let full = mean(&row(&mut h)?); assert!((full - committed).abs() < 8.0, "low-res previews off: the drag matches the committed view ({full} vs {committed})"); + Ok(()) } /// A filter dialog's live preview is never coarser than the screen either (#6326): at 100 % every /// column shows with low-resolution previews on; zoomed out to 50 % the default preview runs on /// the reduced copy (only the black columns), and with them off it matches the committed view. #[test] -fn filter_dialog_previews_at_full_resolution_when_low_res_is_off() { +fn filter_dialog_previews_at_full_resolution_when_low_res_is_off() -> Result<(), String> { let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut h) = harness() else { return }; - setup(&mut h, 0.5); + let Some(mut h) = harness() else { return Ok(()) }; + setup(&mut h, 0.5)?; if !on_gpu(&mut h) { - return; + return Ok(()); } - let committed = mean(&row(&mut h)); - assert!(committed > 60.0, "zoomed out the columns average to grey ({committed})"); + let committed = mean(&row(&mut h)?); + assert!((60.0..220.0).contains(&committed), "zoomed out the columns average to grey ({committed})"); control(&mut h, "ui.set", json!({"zoom": 1.0, "center": [W / 2, H / 2]})); // Offset 0, 0 leaves the pixels as they are: any change is the preview's resolution. - let _dialog = photocraft_ui_egui::filter_dialog::open(h.state_mut(), "filter.other.offset").expect("Offset dialog"); - let at_100 = row(&mut h); + let _dialog = crate::filter_dialog::open(h.state_mut(), "filter.other.offset").expect("Offset dialog"); + let at_100 = row(&mut h)?; assert!(columns(&at_100) > 0.9, "default at 100 %: the preview is never coarser than the screen ({})", columns(&at_100)); control(&mut h, "ui.set", json!({"zoom": 0.5, "center": [W / 2, H / 2]})); - let reduced = mean(&row(&mut h)); + let reduced = mean(&row(&mut h)?); assert!(reduced < 30.0, "default at 50 %: the reduced copy keeps only the black columns ({reduced})"); - low_res(&mut h, false); - let full = mean(&row(&mut h)); + low_res(&mut h, false)?; + let full = mean(&row(&mut h)?); assert!((full - committed).abs() < 8.0, "low-res previews off: the preview matches the committed view ({full} vs {committed})"); + Ok(()) } #[test] -fn adjustment_dialog_zoomed_out_skips_the_reduced_copy_when_low_res_is_off() { +fn adjustment_dialog_zoomed_out_skips_the_reduced_copy_when_low_res_is_off() -> Result<(), String> { let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut h) = harness() else { return }; - setup(&mut h, 0.5); + let Some(mut h) = harness() else { return Ok(()) }; + setup(&mut h, 0.5)?; if !on_gpu(&mut h) { - return; + return Ok(()); } - let committed = mean(&row(&mut h)); - assert!(committed > 60.0, "zoomed out the columns average to grey ({committed})"); - let _dialog = photocraft_ui_egui::adjust_dialog::open(h.state_mut(), "image.adjustments.levels").expect("Levels dialog"); + let committed = mean(&row(&mut h)?); + assert!((60.0..220.0).contains(&committed), "zoomed out the columns average to grey ({committed})"); + let _dialog = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.levels").expect("Levels dialog"); h.run_steps(4); - assert!(photocraft_ui_egui::adjust_preview::gpu_proxy(h.state_mut(), 0, 0.5).is_some(), "default: zoomed out on the reduced copy"); - let reduced = mean(&row(&mut h)); + let proxy = crate::adjust_preview::gpu_proxy(h.state_mut(), 0, 0.5).expect("default: zoomed out on the reduced copy"); + assert_eq!(proxy.k, 2); + let reduced = mean(&row(&mut h)?); assert!(reduced < 30.0, "the reduced copy keeps only the black columns ({reduced})"); - low_res(&mut h, false); - assert!(photocraft_ui_egui::adjust_preview::gpu_proxy(h.state_mut(), 0, 0.5).is_none(), "off: no reduced copy"); - let full = mean(&row(&mut h)); + low_res(&mut h, false)?; + assert!(crate::adjust_preview::gpu_proxy(h.state_mut(), 0, 0.5).is_none(), "off: no reduced copy"); + let full = mean(&row(&mut h)?); assert!((full - committed).abs() < 8.0, "off: the preview matches the committed view ({full} vs {committed})"); + Ok(()) } /// Check the encoded texture directly, before canvas painting or adjustment previews. @@ -211,8 +223,11 @@ fn compositor_chunks_keep_their_columns() { return; }; eprintln!("canvas encode adapter {:?}", rs.adapter.get_info()); - let gpu = photocraft_ui_egui::gpu_canvas::GpuCanvas::new(&rs); - let doc = columns_document(); + let gpu = crate::gpu_canvas::GpuCanvas::new(&rs); + // Keep three chunks across and two down, with a partial chunk on both axes. + let width = 2 * photocraft_gpu::CHUNK + 24; + let height = photocraft_gpu::CHUNK + 24; + let doc = columns_document(width as i32, height as i32).expect("columns document"); let refresh = gpu.refresh(doc.id.0, &doc, None, None); assert!(gpu.fault().is_none(), "GPU fault after canvas refresh: {:?}", gpu.fault()); if refresh.kind == "full" { @@ -222,11 +237,11 @@ fn compositor_chunks_keep_their_columns() { assert_eq!(refresh.kind, "gpu-full", "{:?}", refresh.fallback); let (format, size, texels) = gpu.read_texels(doc.id.0).expect("read back the encoded canvas"); assert_eq!(format, eframe::wgpu::TextureFormat::Rgba8Unorm); - assert_eq!(size, [W as u32, H as u32]); - assert_eq!(texels.len(), (W * H) as usize); + assert_eq!(size, [width, height]); + assert_eq!(texels.len(), (width * height) as usize); for (i, pixel) in texels.iter().enumerate() { - let x = i % W as usize; + let x = i % width as usize; let v = (x % 2) as f32; - assert_eq!(*pixel, [v, v, v, 1.0], "canvas pixel ({x}, {})", i / W as usize); + assert_eq!(*pixel, [v, v, v, 1.0], "canvas pixel ({x}, {})", i / width as usize); } } diff --git a/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs b/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs new file mode 100644 index 0000000000..5e033dc469 --- /dev/null +++ b/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs @@ -0,0 +1,64 @@ +//! #18634: with a layer mask targeted, the Classic gradient's Mode list greys Behind, Darker Color, Lighter Color, Hue, +//! Saturation, Color and Luminosity, the modes that need colour or transparency; every other entry stays enabled. With +//! the layer's pixels targeted again, this rule greys nothing. + +use photocraft_doc::BlendMode; +use serde_json::json; + +use super::mode_entries; +use crate::PhotocraftApp; +use crate::state::Tool; + +const GREYED_ON_A_MASK: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60, "background": "white"})).unwrap(); + app.ui.tool = Tool::Gradient; + app.ui.tool_options.gradient_classic = true; + app +} + +/// The greyed entries of the Mode list: `None` is Behind. +fn greyed(app: &PhotocraftApp) -> Vec> { + mode_entries(app).iter().filter(|e| !e.is_enabled()).filter_map(|e| e.value().copied()).collect() +} + +fn expected_on_a_mask() -> Vec> { + let mut v: Vec> = vec![None]; + v.extend(GREYED_ON_A_MASK.map(Some)); + v.sort_by_key(|m| format!("{m:?}")); + v +} + +fn sorted(mut v: Vec>) -> Vec> { + v.sort_by_key(|m| format!("{m:?}")); + v +} + +#[test] +fn a_targeted_layer_mask_greys_the_seven_modes() { + let cases: [(&str, &[(&str, serde_json::Value)]); 3] = [ + ("a pixel layer's mask", &[("layer.new.layer", json!({})), ("layer.layerMask.revealAll", json!({})), ("channel.target", json!({"channel": "mask"}))]), + ("a solid colour fill layer's mask", &[("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("channel.target", json!({"channel": "mask"}))]), + ("a Curves adjustment layer's mask", &[("layer.newAdjustmentLayer.curves", json!({})), ("channel.target", json!({"channel": "mask"}))]), + ]; + for (case, steps) in cases { + let mut app = app(); + for (id, params) in steps { + app.run(id, params.clone()).unwrap_or_else(|e| panic!("{case}: {id}: {e}")); + } + assert_eq!(sorted(greyed(&app)), expected_on_a_mask(), "{case}"); + } +} + +#[test] +fn the_layers_pixels_targeted_again_grey_none_of_them() { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.target", json!({"channel": "mask"})).unwrap(); + app.run("channel.target", json!({"channel": "composite"})).unwrap(); + assert!(greyed(&app).is_empty(), "{:?}", greyed(&app)); +} diff --git a/crates/ui-egui/src/gradient_preview_swatch_opacity_tests.rs b/crates/ui-egui/src/gradient_preview_swatch_opacity_tests.rs new file mode 100644 index 0000000000..9a83b1b17d --- /dev/null +++ b/crates/ui-egui/src/gradient_preview_swatch_opacity_tests.rs @@ -0,0 +1,49 @@ +//! #18644: The Classic gradient swatch follows the options bar's Opacity. + +use craft::theme::Srgba; +use egui::{Color32, Pos2, Rect, Shape, vec2}; +use photocraft_engine::presets::{PresetsExt, gradients::GradientPreset}; +use serde_json::json; + +use crate::{PhotocraftApp, state::Tool}; + +fn mesh_has_color(shape: &Shape, color: Color32) -> bool { + match shape { + Shape::Vec(shapes) => shapes.iter().any(|shape| mesh_has_color(shape, color)), + Shape::PaintChunk(shapes) => shapes.iter().any(|clipped| mesh_has_color(&clipped.shape, color)), + Shape::Mesh(mesh) => mesh.vertices.iter().any(|vertex| vertex.color == color), + _ => false, + } +} + +#[test] +fn classic_gradient_opacity_changes_the_painted_swatch_only_in_classic_mode() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + app.ui.tool = Tool::Gradient; + app.ui.tool_options.gradient_classic = true; + app.session.presets_mut().gradient = GradientPreset::new("Swatch test", &["#ff00ff", "#ff00ff"]); + let ctx = app.ctx().clone(); + PhotocraftApp::setup_context(&ctx, crate::theme::AppTheme::pro()); + + let draw = |app: &mut PhotocraftApp, alpha: f32| { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 180.0)); + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + ui.horizontal(|ui| super::bar(app, ui)); + }); + // This fixture inspects the paint shapes without a renderer. + output.textures_delta.clear(); + let expected = Color32::from(Srgba::new(1.0, 0.0, 1.0, alpha)); + assert!(output.shapes.iter().any(|clipped| mesh_has_color(&clipped.shape, expected)), "the swatch paints at alpha {alpha}"); + }; + + app.ui.tool_options.fill_opacity = 100.0; + draw(&mut app, 1.0); + app.ui.tool_options.fill_opacity = 10.0; + draw(&mut app, 0.1); + + app.session.presets_mut().gradient.opacity = vec![(0.0, 0.5), (1.0, 0.5)]; + draw(&mut app, 0.05); + app.ui.tool_options.gradient_classic = false; + draw(&mut app, 0.5); +} diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f630565fb1..d1c4a07fb1 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -23,6 +23,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")), ("folder-plus", include_bytes!("../../../assets/icons/folder-plus.svg")), + ("gradient-tool", include_bytes!("../../../assets/icons/gradient-tool.svg")), ("grid-2x2", include_bytes!("../../../assets/icons/grid-2x2.svg")), ("history-brush", include_bytes!("../../../assets/icons/history-brush.svg")), ("house", include_bytes!("../../../assets/icons/house.svg")), diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 9af03225bd..c7aa58730f 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -117,7 +117,14 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { (Target::Brush { flow: true }, true) => { let _ = app.run("tools.setBrush", json!({ "brush": { "flow": v.max(0.01) } })); } - (Target::ToolOpacity, false) => app.ui.tool_options.fill_opacity = percent, + // The field starts at 1%. The Paint Bucket's `00` is 100%, as the Brush's is (#17742); the + // Gradient's was not measured, so it keeps the 1% the field can hold. + (Target::ToolOpacity, false) => { + app.ui.tool_options.fill_opacity = match tool { + Tool::PaintBucket if percent <= 0.0 => 100.0, + _ => percent.max(1.0), + } + } // The Tolerance field starts at 1%; `00` (0%) keeps today's value rather than guessing. (Target::BgTolerance, false) if percent >= 1.0 => app.ui.tool_options.bg_tolerance = percent, // The field starts at 1%; an unmeasured 00 keeps its existing value. @@ -137,6 +144,10 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { } } +#[cfg(test)] +#[path = "opacity_keys_bucket_double_zero_tests.rs"] +mod bucket_double_zero_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/input/opacity_keys_bucket_double_zero_tests.rs b/crates/ui-egui/src/input/opacity_keys_bucket_double_zero_tests.rs new file mode 100644 index 0000000000..9bdae5afe1 --- /dev/null +++ b/crates/ui-egui/src/input/opacity_keys_bucket_double_zero_tests.rs @@ -0,0 +1,62 @@ +//! The Paint Bucket's number keys: `0`, `0` typed quickly is 100 %, never the 0 % its Opacity field can't hold (#17742). + +use craft::ui::canvas::OpacityDigit as D; +use serde_json::json; + +use super::fired; +use crate::PhotocraftApp; +use crate::blend_keys::test_fired; +use crate::state::Tool; + +const DIGITS: [D; 10] = [ + D::OpacityZero, + D::OpacityOne, + D::OpacityTwo, + D::OpacityThree, + D::OpacityFour, + D::OpacityFive, + D::OpacitySix, + D::OpacitySeven, + D::OpacityEight, + D::OpacityNine, +]; + +/// The tool's Opacity after typing `digits` 0.1 s apart, from a start of 50 %. +fn typed(tool: Tool, digits: &[usize]) -> f32 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.ui.tool = tool; + app.ui.tool_options.fill_opacity = 50.0; + for (i, d) in digits.iter().enumerate() { + let mut f = test_fired(DIGITS[*d].into()); + f.time = i as f64 * 0.1; + assert!(fired(&mut app, &f), "{tool:?} takes digit {d}"); + } + app.ui.tool_options.fill_opacity +} + +#[test] +fn paint_bucket_double_zero_is_full_opacity() { + assert_eq!(typed(Tool::PaintBucket, &[0, 0]), 100.0); +} + +#[test] +fn no_digits_leave_the_shared_opacity_below_its_minimum() { + // The Gradient shares the Paint Bucket's Opacity field, which starts at 1 %. + for tool in [Tool::PaintBucket, Tool::Gradient] { + for digits in [&[0, 0][..], &[0], &[0, 1], &[1, 0], &[5, 0]] { + let got = typed(tool, digits); + assert!(got >= 1.0, "{tool:?} {digits:?}: {got}"); + } + } +} + +#[test] +fn paint_bucket_other_digits_keep_their_values() { + for d in 1..=9 { + assert_eq!(typed(Tool::PaintBucket, &[d]), d as f32 * 10.0, "{d}"); + } + for (digits, want) in [(&[0][..], 100.0), (&[4, 5], 45.0), (&[0, 5], 5.0)] { + assert_eq!(typed(Tool::PaintBucket, digits), want, "{digits:?}"); + } +} diff --git a/crates/ui-egui/src/input/quick_mask_free_transform_tests.rs b/crates/ui-egui/src/input/quick_mask_free_transform_tests.rs new file mode 100644 index 0000000000..67eaa1272b --- /dev/null +++ b/crates/ui-egui/src/input/quick_mask_free_transform_tests.rs @@ -0,0 +1,35 @@ +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use serde_json::json; + +use super::tests::{app_harness, tap}; +use crate::{PhotocraftApp, Services}; + +type AppHarness = Harness<'static, Box>; + +fn quick_mask(h: &AppHarness) -> bool { + h.state().session.active().unwrap().doc.quick_mask.is_some() +} + +#[test] +fn quick_mask_shortcut_waits_for_free_transform_to_finish() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 120, "height": 100})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap(); + let mut h = app_harness(app); + + for (starts_in_quick_mask, finish) in [(false, Key::Enter), (true, Key::Escape)] { + assert_eq!(quick_mask(&h), starts_in_quick_mask); + tap(&mut h, Key::T, Modifiers::COMMAND); + let transform = h.state().ui.transform.as_ref().expect("Free Transform opens from its shortcut").id; + + tap(&mut h, Key::Q, Modifiers::NONE); + assert_eq!(quick_mask(&h), starts_in_quick_mask, "Q keeps Quick Mask unchanged while Free Transform is live"); + assert_eq!(h.state().ui.transform.as_ref().map(|t| t.id), Some(transform), "the same Free Transform stays live"); + + tap(&mut h, finish, Modifiers::NONE); + assert!(h.state().ui.transform.is_none(), "Enter and Escape close Free Transform"); + tap(&mut h, Key::Q, Modifiers::NONE); + assert_eq!(quick_mask(&h), !starts_in_quick_mask, "Q toggles again when the transform is closed"); + } +} diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index f37a2aca7a..351b3166d2 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -698,6 +698,17 @@ fn pick_tool(app: &mut PhotocraftApp, letter: char, step: PickStep, plain: bool, /// through [`dispatch_as`]. fn run_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Fired) { let id = f.command.id.as_str(); + if f.source == FireSource::Key + && id == crate::panels::QUICK_MASK + && app.ui.transform.as_ref().is_some_and(|transform| { + !transform.selection + && transform.content_aware.is_none() + && transform.session.warp().is_none() + && transform.session.current_mode() == craft::behavior::geometry::TransformMode::Free + }) + { + return; + } // The Magnetic Lasso's bracket keys step its detection width, not the brush (#11688), until an outline is open. if app.ui.tool == Tool::MagneticLasso && !app.canvas_tools.selection.outline_open() { let step = match id { @@ -819,3 +830,7 @@ fn record(ctx: &egui::Context, id: &str, outcome: Outcome) { /// The whole-app key harness the key tests of this module share (`app_harness`, `tap`). #[cfg(test)] pub(crate) mod tests; + +#[cfg(test)] +#[path = "quick_mask_free_transform_tests.rs"] +mod quick_mask_free_transform_tests; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 555ebcc427..99ea81ea48 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -38,6 +38,10 @@ pub mod file_open; pub mod frame_stages; pub mod gpu_memo; pub mod gpu_status; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod gpu_tests { + mod full_res_preview; +} mod history_keys; pub mod home_recent_ui; pub mod i18n; @@ -413,6 +417,9 @@ pub struct PhotocraftApp { control: Option, /// Live (uncommitted) adjustment edit shown on canvas while a slider is dragged. pub live_adjust: Option<(photocraft_doc::LayerId, Value)>, + /// Lets GPU tests use small fixtures while exercising large-document preview decisions. + #[cfg(test)] + preview_test_area_multiplier: u64, /// Frames rendered (for tests and the status bar). pub frame: u64, /// What the notice stack keeps between frames: the pointer rest that gives a fresh auto-hide @@ -1151,6 +1158,8 @@ mod reset_tip_tests; #[cfg(test)] mod rotate_steps_tests; #[cfg(test)] +mod window_options_toggle_tests; +#[cfg(test)] mod zoom_mode_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 479e8e0368..731634301e 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -693,6 +693,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["View"], "100%", Some("Cmd+1"), "view.actualPixels"), (&["View"], "200%", None, "view.twoHundredPercent"), (&["View"], "Print Size", None, "view.printSize"), + (&["View"], "Actual Size", None, "view.actualSize"), (&["View"], "---", None, "---"), (&["View"], "Flip Horizontal", None, "view.flipHorizontal"), (&["View", "Screen Mode"], "Standard Screen Mode", None, "view.screenMode.standard"), diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 7bd46578ce..30b4203b46 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -129,9 +129,47 @@ pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Opti !any } +/// Puppet Warp, Perspective Warp and Content-Aware Scale work on one layer: with two or more +/// layers selected the reference greys them (#18501). Measured on layers at the top of the stack; +/// a group among them, or layers inside a group, keep the engine's own rule. +const ONE_LAYER_DISTORTS: [&str; 3] = ["edit.puppetWarp", "edit.perspectiveWarp", "edit.contentAwareScale"]; + +fn several_layers_block(doc: &Document, selected: &[LayerId], id: &str) -> bool { + ONE_LAYER_DISTORTS.contains(&id) + && selected.len() > 1 + && selected.iter().all(|l| doc.layer(*l).is_some_and(|layer| !layer.is_group()) && doc.layers.index().parent(*l).is_none()) +} + +/// Why a menu item that [`disabled`] greys for the layer selection is refused when it is invoked +/// anyway (a shortcut, the control channel's `ui.menu.invoke`), before any session opens. A +/// control call (`{"ui": …}`) for a Puppet Warp or Perspective Warp already open is not refused: it +/// commits, cancels or edits that session, opened on one layer, whatever is selected since. +pub fn refusal(app: &crate::PhotocraftApp, id: &str, params: &serde_json::Value) -> Option { + let open = match id { + "edit.puppetWarp" => app.distort.puppet.is_some(), + "edit.perspectiveWarp" => app.distort.perspective.is_some(), + _ => false, + }; + if open && params.get("ui").is_some() { + return None; + } + let st = app.session.active()?; + several_layers_block(&st.doc, st.selected_layers(), id).then(|| { + let name = match id { + "edit.puppetWarp" => "Puppet Warp", + "edit.perspectiveWarp" => "Perspective Warp", + _ => "Content-Aware Scale", + }; + format!("{name} works on one layer at a time: select a single layer") + }) +} + pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { let Some(st) = app.session.active() else { return false }; let active = st.active_layer.and_then(|a| st.doc.layer(a)); + if several_layers_block(&st.doc, st.selected_layers(), id) { + return true; + } // The split warps edit the open Warp box's grid: with none they are greyed, also on a smart // object with a stored warp, as the reference greys them there (#12494, #12942). if matches!( @@ -521,3 +559,7 @@ mod tests { #[cfg(test)] #[path = "warp_split_enable_tests.rs"] mod warp_split_enable_tests; + +#[cfg(test)] +#[path = "several_layers_distort_greyed_tests.rs"] +mod several_layers_distort_greyed_tests; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 8515d08a01..1ebbf0be88 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -60,6 +60,7 @@ fn keeps_box_drag(id: &str) -> bool { "view.zoomOut", "view.fitOnScreen", "view.actualPixels", + "view.actualSize", "view.rotateView", "view.resetView", "view.darkenInterface", @@ -86,6 +87,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va if !keeps_box_drag(id) { crate::type_box_preview::end_drag(app); } + // An item the menu greys for the layer selection opens nothing when invoked anyway (#18501). + if let Some(why) = crate::enable_rules::refusal(app, id, ¶ms) { + return Err(why); + } if crate::discard_ui::intercept(app, id, ¶ms) { return Ok(Value::Null); } diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 454f427e9e..117cf2ab86 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -138,6 +138,10 @@ fn find<'a>(rows: &'a mut [Row], id: &str) -> Option<&'a mut Row> { /// A live row shows the chord the runtime's keymap runs its command for (`commands::chord`: overrides included, a /// key another command wins left out); a catalogue row shows its text. fn shortcut_of(app: &PhotocraftApp, id: &str, catalogue: Option<&str>) -> Option { + // Quick Mask has a key binding without a hint in the Select menu. + if id == crate::panels::QUICK_MASK { + return None; + } if is_live(id) { return craft::ui::runtime::commands::chord(app.ctx(), &crate::shortcut_dispatch::keymap_command(id)); } @@ -236,6 +240,14 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { { item.label = "Merge Group".into(); } + // And Merge Clipping Mask with just the base of a clip group selected (#18481). + if let Some(st) = app.session.active() + && st.selected_layers().len() <= 1 + && st.active_layer.is_some_and(|id| photocraft_engine::layer_multi_cmds::merges_clipping_mask(&st.doc, id)) + && let Some(item) = find(&mut rows, "layer.mergeLayers") + { + item.label = "Merge Clipping Mask".into(); + } // Edit › Fade names the step it fades (#13803). if let Some(item) = find(&mut rows, "edit.fade") { item.label = photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session); @@ -473,3 +485,7 @@ fn build(app: &PhotocraftApp) -> Built { #[cfg(test)] #[path = "background_entry_swap_tests.rs"] mod background_entry_swap_tests; + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "quick_mask_shortcut_text_tests.rs"] +mod quick_mask_shortcut_text_tests; diff --git a/crates/ui-egui/src/menus/quick_mask_shortcut_text_tests.rs b/crates/ui-egui/src/menus/quick_mask_shortcut_text_tests.rs new file mode 100644 index 0000000000..0cc512c68e --- /dev/null +++ b/crates/ui-egui/src/menus/quick_mask_shortcut_text_tests.rs @@ -0,0 +1,44 @@ +use egui::{Key, Modifiers}; +use serde_json::{Value, json}; + +use crate::control::{ControlRequest, Reply}; +use crate::input::shortcut_dispatch::tests::{app_harness, tap}; +use crate::panels::QUICK_MASK; +use crate::{PhotocraftApp, Services}; + +fn quick_mask_menu_row(app: &mut PhotocraftApp) -> Option { + let ctx = app.ctx().clone(); + let (request, _reply) = ControlRequest::new("ui.menu.list", json!({})); + let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { return None }; + reply["result"].as_array()?.iter().find(|row| row["id"] == QUICK_MASK && row["path"] == json!(["Select"])).cloned() +} + +fn quick_mask(app: &PhotocraftApp) -> bool { + app.session.active().is_some_and(|state| state.doc.quick_mask.is_some()) +} + +#[test] +fn quick_mask_menu_omits_the_hint_while_q_still_toggles_after_a_shortcut_reset() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let mut h = app_harness(app); + let row = quick_mask_menu_row(h.state_mut()).expect("Quick Mask stays in the Select menu"); + assert!(row["shortcut"].is_null(), "the Select menu does not show a Quick Mask shortcut: {row}"); + + tap(&mut h, Key::Q, Modifiers::NONE); + assert!(quick_mask(h.state()), "Q is bound by default"); + tap(&mut h, Key::Q, Modifiers::NONE); + assert!(!quick_mask(h.state())); + + h.state_mut().run("edit.keyboardShortcuts", json!({"set": {(QUICK_MASK): ""}})).unwrap(); + h.run_steps(2); + tap(&mut h, Key::Q, Modifiers::NONE); + assert!(!quick_mask(h.state()), "the user can remove Q"); + + h.state_mut().run("edit.keyboardShortcuts", json!({"reset": true})).unwrap(); + h.run_steps(2); + tap(&mut h, Key::Q, Modifiers::NONE); + assert!(quick_mask(h.state()), "reset restores Q"); + let row = quick_mask_menu_row(h.state_mut()).expect("Quick Mask stays in the Select menu"); + assert!(row["shortcut"].is_null(), "the Select menu does not show a Quick Mask shortcut: {row}"); +} diff --git a/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs b/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs new file mode 100644 index 0000000000..c04e0efe73 --- /dev/null +++ b/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs @@ -0,0 +1,181 @@ +//! Puppet Warp, Perspective Warp and Content-Aware Scale with several layers selected (#18501): +//! greyed in the Edit menu and in `ui.menu.list`, refused when invoked anyway (no session opens, +//! nothing changes); one pixel layer keeps all three, and the cases not measured keep today's state. + +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply}; + +const THREE: [&str; 3] = ["edit.puppetWarp", "edit.perspectiveWarp", "edit.contentAwareScale"]; + +fn layer_of(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) +} + +/// A 100 × 100 white document with a new pixel layer holding a block of colour, active. +fn painted_layer(app: &mut PhotocraftApp, name: &str, x: i64, color: &str) -> LayerId { + let layer = layer_of(app.run("layer.new.layer", json!({ "name": name })).unwrap()); + app.run("select.rect", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + layer +} + +fn app_with_two_layers() -> (Box, LayerId, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + app.sync_views(); + let a = painted_layer(&mut app, "A", 10, "#ff0000"); + let b = painted_layer(&mut app, "B", 50, "#0000ff"); + (app, a, b) +} + +/// The Edit menu row's state as the menu builds it. +fn in_menu(app: &PhotocraftApp, id: &str) -> bool { + let rows = crate::menus::menu_rows(app); + let row = crate::menus::items::row(&rows, id).map(|r| (r.path.clone(), r.enabled)); + let (path, enabled) = row.unwrap_or_else(|| panic!("{id} is in the menu")); + assert_eq!(path.first().map(String::as_str), Some("Edit"), "{id}"); + enabled +} + +fn control(app: &mut PhotocraftApp, method: &str, params: Value) -> Result { + let ctx = app.ctx().clone(); + let (request, _reply) = ControlRequest::new(method, params); + match crate::control::handle(app, &ctx, &request) { + Reply::Done(reply) if reply["ok"] == true => Ok(reply), + Reply::Done(reply) => Err(reply["error"].as_str().unwrap_or_default().to_owned()), + _ => panic!("expected an immediate reply to {method}"), + } +} + +/// `enabled` of `id` in `ui.menu.list`. +fn listed(app: &mut PhotocraftApp, id: &str) -> bool { + let list = control(app, "ui.menu.list", json!({})).unwrap(); + let row = list["result"].as_array().unwrap().iter().find(|row| row["id"] == id).cloned(); + row.unwrap_or_else(|| panic!("{id} is listed"))["enabled"].as_bool().unwrap() +} + +fn no_session(app: &PhotocraftApp) -> bool { + app.distort.puppet.is_none() && app.distort.perspective.is_none() && app.ui.transform.is_none() +} + +fn history_len(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +#[test] +fn two_selected_pixel_layers_grey_the_three_and_invoking_them_opens_nothing() { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + for id in THREE { + assert!(!in_menu(&app, id), "{id} is greyed in the Edit menu with two layers selected"); + assert!(!listed(&mut app, id), "{id} is disabled in ui.menu.list with two layers selected"); + } + let steps = history_len(&app); + for id in THREE { + let refused = control(&mut app, "ui.menu.invoke", json!({ "id": id })); + let why = refused.expect_err(&format!("{id} is refused with two layers selected")); + assert!(why.contains("one layer at a time"), "{id}: {why}"); + assert!(no_session(&app), "{id} opened a session"); + let ctx = app.ctx().clone(); + assert!(crate::menus::invoke(&mut app, &ctx, id, json!({})).is_err(), "{id} through the menu's own invoke"); + assert!(no_session(&app), "{id} opened a session"); + } + assert_eq!(history_len(&app), steps, "nothing changed"); + assert_eq!(app.session.active().unwrap().selected_layers(), [a, b], "the selection stays"); +} + +#[test] +fn free_transform_and_edit_transform_stay_enabled_with_two_layers() { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + for id in [ + "edit.freeTransform", + "edit.transform.scale", + "edit.transform.rotate", + "edit.transform.skew", + "edit.transform.distort", + "edit.transform.perspective", + "edit.transform.rotate180", + "edit.transform.rotate90Cw", + "edit.transform.rotate90Ccw", + "edit.transform.flipHorizontal", + "edit.transform.flipVertical", + ] { + assert!(in_menu(&app, id), "{id} stays enabled with two layers selected"); + } +} + +#[test] +fn one_pixel_layer_keeps_all_three() { + let (mut app, _, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + for id in THREE { + assert!(in_menu(&app, id), "{id} is enabled for one pixel layer"); + assert!(listed(&mut app, id), "{id} is listed enabled for one pixel layer"); + } + control(&mut app, "ui.menu.invoke", json!({"id": "edit.puppetWarp"})).expect("Puppet Warp opens on one layer"); + assert!(app.distort.puppet.is_some(), "the pin mesh is open"); +} + +#[test] +fn the_cases_not_measured_keep_todays_state() { + // Two layers inside a group. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + app.run("layer.groupLayers", json!({})).unwrap(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + for id in THREE { + assert!(in_menu(&app, id), "{id}: two layers inside a group keep today's state"); + } + + // A group and a layer, the layer active. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": a.0})).unwrap(); + let group = layer_of(app.run("layer.groupLayers", json!({})).unwrap()); + app.run("layer.select", json!({"layers": [group.0, b.0]})).unwrap(); + app.run("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + assert_eq!(app.session.active().unwrap().active_layer, Some(b)); + for id in THREE { + assert!(in_menu(&app, id), "{id}: a group and a layer keep today's state"); + } + + // A linked layer: one layer selected, its partner not. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + app.run("layer.linkLayers", json!({})).unwrap(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + for id in THREE { + assert!(in_menu(&app, id), "{id}: a linked layer keeps today's state"); + } +} + +/// A Puppet Warp or Perspective Warp opened on one layer still takes its control calls (commit, cancel) when two +/// layers are selected afterwards: the refusal is for opening a new session only. +#[test] +fn an_open_warp_still_commits_and_cancels_with_two_layers_selected() { + for (id, how) in [("edit.puppetWarp", "commit"), ("edit.puppetWarp", "cancel"), ("edit.perspectiveWarp", "commit"), ("edit.perspectiveWarp", "cancel")] { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + control(&mut app, "ui.menu.invoke", json!({ "id": id })).unwrap_or_else(|e| panic!("{id} opens on one layer: {e}")); + assert!(!no_session(&app), "{id}: a session is open"); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + let reply = control(&mut app, "ui.menu.invoke", json!({ "id": id, "params": { "ui": { how: true } } })); + reply.unwrap_or_else(|e| panic!("{id} {how} with two layers selected: {e}")); + assert!(no_session(&app), "{id}: {how} closes the session"); + } + // Opening a new session with two layers selected is still refused, also with control params. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + for id in ["edit.puppetWarp", "edit.perspectiveWarp"] { + let refused = control(&mut app, "ui.menu.invoke", json!({ "id": id, "params": { "ui": { "commit": true } } })); + assert!(refused.is_err_and(|why| why.contains("one layer at a time")), "{id}: no session, so it is refused"); + assert!(no_session(&app), "{id} opened a session"); + } +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 864806a2c7..eb0d9ebbe4 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -62,8 +62,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { if let Some(e) = crate::workspace_ui::is_enabled(app, id) { return e; } - if crate::analysis::handles(id) { - return true; + if let Some(enabled) = crate::analysis::enabled(app, id) { + return enabled; } // The view command wrapper otherwise uses the engine's document-level availability. if id == "type.pasteLoremIpsum" { diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 7aed10a946..c166082763 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -13,6 +13,7 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; +mod actual_size; mod arrange; pub(crate) mod dialogs; mod dispatch; @@ -218,3 +219,7 @@ mod save_a_copy_name_tests; #[cfg(test)] #[path = "view_cmds/file_info_title_labels_tests.rs"] mod file_info_title_labels_tests; + +#[cfg(test)] +#[path = "view_cmds/actual_size_tests.rs"] +mod actual_size_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs new file mode 100644 index 0000000000..191c16a003 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -0,0 +1,253 @@ +//! Physical-size viewing. Logical UI scaling is deliberately absent from the PPI calculation. + +use craft::behavior::{canvas::ZoomScheme, kurbo::Size}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; + +pub(super) fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, params: &Value) -> Result { + let physical_ppi = display_ppi(ctx); + apply(app, physical_ppi, params) +} + +pub(super) fn apply(app: &mut PhotocraftApp, physical_ppi: Option, params: &Value) -> Result { + if !params.as_object().is_some_and(|object| object.is_empty()) { + return Err("Actual Size takes an empty parameter object".into()); + } + let index = app.session.active_index().ok_or("Actual Size needs an open document")?; + let doc = &app.session.documents().get(index).ok_or("no document")?.doc; + let document_ppi = f64::from(doc.resolution_dpi); + if !document_ppi.is_finite() || document_ppi <= 0.0 { + return Err("Actual Size needs a positive document resolution".into()); + } + let physical_ppi = physical_ppi.filter(|ppi| ppi.is_finite() && *ppi >= 1.0).map(f64::floor); + let fallback = physical_ppi.is_none(); + let preferred = app.session.prefs().units_and_rulers.screen_resolution; + let screen_ppi = physical_ppi.unwrap_or(if preferred >= 1.0 { preferred.floor() } else { preferred }); + let zoom = screen_ppi / document_ppi; + if !zoom.is_finite() || zoom <= 0.0 { + return Err("Actual Size needs a positive screen resolution".into()); + } + let size = Size::new(f64::from(doc.size.width), f64::from(doc.size.height)); + let zoom = ZoomScheme::PHOTOSHOP.clamp(zoom, size) as f32; + app.sync_views(); + let animate = app.session.prefs().general.animated_zoom; + let view = app.ui.views.get_mut(index).ok_or("no document view")?; + view.request_zoom_animation(animate); + view.clear_pending(); + view.zoom = zoom; + let message = if fallback { + tl!("Actual Size uses Screen Resolution because the display's physical size is unavailable").to_string() + } else { + tl!("Actual Size uses the display's physical resolution").to_string() + }; + app.ui.status = message.clone(); + app.ui.status_error = false; + crate::panels::actions::runner::journal_view(app, "view.actualSize", params.clone()); + Ok(json!({"zoom": zoom, "screenPpi": screen_ppi, "fallback": fallback, "status": message})) +} + +/// Invalid or absent device metrics must use the explicit Screen Resolution fallback. +#[cfg(any(test, target_os = "windows", target_os = "macos", target_os = "linux"))] +pub(super) fn physical_ppi(pixels: f64, millimeters: f64) -> Option { + if !pixels.is_finite() || !millimeters.is_finite() || pixels <= 0.0 || millimeters <= 0.0 { + return None; + } + let ppi = pixels * 25.4 / millimeters; + (ppi.is_finite() && (1.0..=10000.0).contains(&ppi)).then_some(ppi.floor()) +} + +#[cfg(target_os = "windows")] +fn display_ppi(ctx: &egui::Context) -> Option { + use winsafe::{HDC, prelude::*}; + + let rect = ctx.input(|input| input.viewport().outer_rect)?; + let scale = f64::from(ctx.pixels_per_point()); + let window = [f64::from(rect.left()) * scale, f64::from(rect.top()) * scale, f64::from(rect.right()) * scale, f64::from(rect.bottom()) * scale]; + if !window.iter().all(|value| value.is_finite()) { + return None; + } + let mut best = (0.0, None); + HDC::NULL + .EnumDisplayMonitors(None, |monitor, _, rect| { + let width = (window[2].min(f64::from(rect.right)) - window[0].max(f64::from(rect.left))).max(0.0); + let height = (window[3].min(f64::from(rect.bottom)) - window[1].max(f64::from(rect.top))).max(0.0); + let area = width * height; + if area > best.0 { + let ppi = monitor + .GetMonitorInfo() + .ok() + .and_then(|info| windows_monitor_width(&info.szDevice())) + .and_then(|millimeters| physical_ppi(f64::from(rect.right) - f64::from(rect.left), millimeters)); + best = (area, ppi); + } + true + }) + .ok()?; + best.1 +} + +/// GDI's HORZSIZE can be synthesized from 96 DPI on WDDM. Read the monitor's EDID instead. +#[cfg(target_os = "windows")] +fn windows_monitor_width(device: &str) -> Option { + use winsafe::{HKEY, RegistryValue, co}; + + // Without a current orientation, a rotated desktop width cannot be paired with an EDID axis safely. + let mut mode = winsafe::DEVMODE::default(); + if !winsafe::EnumDisplaySettingsEx(Some(device), winsafe::GmidxEnum::Enum(co::ENUM_SETTINGS::CURRENT), &mut mode, co::EDS::default()).ok()? + || !mode.dmFields.has(co::DM::DISPLAYORIENTATION) + { + return None; + } + let mut result = None; + for monitor in winsafe::EnumDisplayDevices(Some(device), Some(co::EDD::GET_DEVICE_INTERFACE_NAME)).take(64) { + let monitor = monitor.ok()?; + let path = monitor_registry_path(&monitor.DeviceID())?; + let key = HKEY::LOCAL_MACHINE.RegOpenKeyEx(Some(&path), co::REG_OPTION::default(), co::KEY::READ).ok()?; + let override_key = key.RegOpenKeyEx(Some("EDID_OVERRIDE"), co::REG_OPTION::default(), co::KEY::READ).ok(); + let value = match override_key.as_ref().map(|override_key| windows_edid_value(override_key, "0")) { + Some(Ok(value)) => value, + Some(Err(error)) if error != co::ERROR::FILE_NOT_FOUND => return None, + _ => windows_edid_value(&key, "EDID").ok()?, + }; + let RegistryValue::Binary(edid) = value else { return None }; + let width = oriented_width(edid_size(&edid)?, mode.dmDisplayOrientation().raw())?; + // Mirrored outputs must agree on physical size before one scale can describe both. + if result.is_some_and(|previous: f64| (previous - width).abs() > 0.5) { + return None; + } + result = Some(width); + } + result +} + +#[cfg(target_os = "windows")] +fn windows_edid_value(key: &winsafe::HKEY, value: &str) -> Result { + // Registry EDIDs are small. Bound the safe binding's allocation before asking for the value. + let mut maximum = 0; + key.RegQueryInfoKey(None, None, None, None, None, None, Some(&mut maximum), None, None)?; + if maximum > 32768 { + return Err(winsafe::co::ERROR::INVALID_DATA); + } + key.RegQueryValueEx(Some(value)) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn monitor_registry_path(interface: &str) -> Option { + let mut parts = interface.strip_prefix(r"\\?\")?.split('#'); + if !parts.next()?.eq_ignore_ascii_case("DISPLAY") { + return None; + } + let model = parts.next()?; + let instance = parts.next()?; + let class = parts.next()?; + if parts.next().is_some() || !class.eq_ignore_ascii_case("{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}") { + return None; + } + let safe_component = + |value: &str| !value.is_empty() && value.len() <= 256 && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'&' | b'_' | b'-')); + if !safe_component(model) || !safe_component(instance) { + return None; + } + Some(format!(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\{model}\{instance}\Device Parameters")) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn edid_size(edid: &[u8]) -> Option<[f64; 2]> { + let base = edid.get(..128)?; + if base.get(..8)? != [0, 255, 255, 255, 255, 255, 255, 0] || base.iter().fold(0u8, |sum, value| sum.wrapping_add(*value)) != 0 { + return None; + } + // EDID detailed timing descriptors carry millimetres, with the high bits shared at byte 14. + for timing in base.get(54..126)?.as_chunks::<18>().0.iter() { + if timing.get(..2)? == [0, 0] { + continue; + } + let width = u16::from(*timing.get(12)?) | (u16::from(*timing.get(14)? & 0xf0) << 4); + let height = u16::from(*timing.get(13)?) | (u16::from(*timing.get(14)? & 0x0f) << 8); + if width > 0 && height > 0 { + return Some([f64::from(width), f64::from(height)]); + } + } + let width = *base.get(21)?; + let height = *base.get(22)?; + (width > 0 && height > 0).then_some([f64::from(width) * 10.0, f64::from(height) * 10.0]) +} + +/// EDID describes the unrotated panel; desktop horizontal pixels follow the current display orientation. +#[cfg(any(test, target_os = "windows"))] +pub(super) fn oriented_width(size: [f64; 2], quarter_turns: u32) -> Option { + if !size.iter().all(|value| value.is_finite() && *value > 0.0) { + return None; + } + match quarter_turns { + 0 | 2 => Some(size[0]), + 1 | 3 => Some(size[1]), + _ => None, + } +} + +/// Missing backing-mode metrics must fall back, rather than substitute a logical display width. +#[cfg(any(test, target_os = "macos"))] +pub(super) fn backing_mode_ppi(width: Option, millimeters: f64) -> Option { + physical_ppi(width? as f64, millimeters) +} + +#[cfg(target_os = "macos")] +fn display_ppi(ctx: &egui::Context) -> Option { + use core_graphics::display::CGDisplay; + + let window = ctx.input(|input| input.viewport().outer_rect)?; + let native = ctx.native_pixels_per_point().filter(|scale| scale.is_finite() && *scale > 0.0)?; + let factor = f64::from(ctx.pixels_per_point() / native); + let mut best = (0.0, None); + for id in CGDisplay::active_displays().ok()? { + let display = CGDisplay::new(id); + let bounds = display.bounds(); + let width = (f64::from(window.right()) * factor).min(bounds.origin.x + bounds.size.width) - (f64::from(window.left()) * factor).max(bounds.origin.x); + let height = (f64::from(window.bottom()) * factor).min(bounds.origin.y + bounds.size.height) - (f64::from(window.top()) * factor).max(bounds.origin.y); + let area = width.max(0.0) * height.max(0.0); + if area > best.0 { + best = (area, backing_mode_ppi(display.display_mode().map(|mode| mode.pixel_width()), display.screen_size().width)); + } + } + best.1 +} + +#[cfg(target_os = "linux")] +fn display_ppi(ctx: &egui::Context) -> Option { + use x11rb::{connection::Connection, protocol::randr::ConnectionExt}; + + // Xwayland's virtual outputs do not describe the native Wayland display's physical size. + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + return None; + } + let window = ctx.input(|input| input.viewport().outer_rect)?; + let factor = f64::from(ctx.pixels_per_point()); + let (connection, screen) = x11rb::connect(None).ok()?; + let root = connection.setup().roots.get(screen)?.root; + let resources = connection.randr_get_screen_resources_current(root).ok()?.reply().ok()?; + let mut best = (0.0, None); + for output in resources.outputs { + let output = connection.randr_get_output_info(output, resources.config_timestamp).ok()?.reply().ok()?; + if output.crtc == 0 { + continue; + } + let crtc = connection.randr_get_crtc_info(output.crtc, resources.config_timestamp).ok()?.reply().ok()?; + let x = f64::from(crtc.x); + let y = f64::from(crtc.y); + let width = (f64::from(window.right()) * factor).min(x + f64::from(crtc.width)) - (f64::from(window.left()) * factor).max(x); + let height = (f64::from(window.bottom()) * factor).min(y + f64::from(crtc.height)) - (f64::from(window.top()) * factor).max(y); + let area = width.max(0.0) * height.max(0.0); + if area > best.0 { + let mode = resources.modes.iter().find(|mode| mode.id == crtc.mode)?; + best = (area, physical_ppi(f64::from(mode.width), f64::from(output.mm_width))); + } + } + best.1 +} + +#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] +fn display_ppi(_ctx: &egui::Context) -> Option { + None +} diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs new file mode 100644 index 0000000000..eff9979c72 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs @@ -0,0 +1,166 @@ +use super::actual_size::{apply, backing_mode_ppi, edid_size, monitor_registry_path, oriented_width, physical_ppi}; +use crate::{PhotocraftApp, Services}; +use photocraft_engine::Session; +use serde_json::json; + +#[test] +fn actual_size_uses_whole_physical_ppi_and_keeps_the_document() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + app.sync_views(); + for (document_ppi, expected) in [(72.0, 95.0 / 72.0), (300.0, 95.0 / 300.0), (150.0, 95.0 / 150.0), (96.0, 95.0 / 96.0), (36.0, 95.0 / 36.0)] { + app.run("image.imageSize", json!({"resolution": document_ppi, "resample": "none"})).unwrap(); + for screen_ppi in [72.0, 96.0] { + app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": screen_ppi})).unwrap(); + app.ui.views[0].center = [126.75, 636.25]; + let before = app.session.active().unwrap().doc.clone(); + let history = app.session.active().unwrap().history.entries().len(); + let dirty = app.session.active().unwrap().is_dirty(); + let result = apply(&mut app, physical_ppi(1920.0, 509.0), &json!({})).unwrap(); + assert!((app.ui.views[0].zoom - expected).abs() < 1e-6); + assert_eq!(app.ui.views[0].center, [126.75, 636.25]); + assert_eq!(result["fallback"], false); + assert_eq!(result["screenPpi"], 95.0); + assert_eq!(app.session.active().unwrap().doc, before); + assert_eq!(app.session.active().unwrap().history.entries().len(), history); + assert_eq!(app.session.active().unwrap().is_dirty(), dirty); + } + } +} + +#[test] +fn actual_size_fallback_is_reported_by_menu_and_automation() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + let ctx = app.ctx().clone(); + assert!(!crate::menus::is_enabled(&app, "view.actualSize")); + assert!(crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).is_err()); + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": 96.5})).unwrap(); + assert!(crate::menus::is_live("view.actualSize")); + assert!(crate::menus::is_enabled(&app, "view.actualSize")); + assert_eq!(super::checked(&app, "view.actualSize"), None); + let result = crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).unwrap(); + assert_eq!(result["fallback"], true, "a headless context has no physical monitor"); + assert_eq!(result["screenPpi"], 96.0); + assert!((app.ui.views[0].zoom - 96.0 / 72.0).abs() < 1e-6); + assert_eq!(result["status"], app.ui.status); + assert!(app.ui.status.contains("Screen Resolution")); + let (request, _receiver) = crate::control::ControlRequest::new("engine.execute", json!({"command": "view.actualSize", "params": {}})); + match crate::control::handle(&mut app, &ctx, &request) { + crate::control::Reply::Done(reply) => { + assert_eq!(reply["result"]["fallback"], true); + assert_eq!(reply["result"]["status"], app.ui.status); + } + _ => panic!("Actual Size should return its fallback result immediately"), + } + let rows = crate::menus::menu_rows(&app); + let positions: Vec<_> = + ["view.printSize", "view.actualSize", "view.flipHorizontal"].map(|id| rows.iter().position(|row| row.command.id == id).unwrap()).into(); + assert!(positions[0] < positions[1] && positions[1] < positions[2]); + let registration = crate::menus::UI_COMMANDS.iter().find(|row| row.0 == "view.actualSize").unwrap(); + assert_eq!(registration.3, None); +} + +#[test] +fn actual_size_rejects_bad_parameters_and_unusable_metrics() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + for params in [json!(null), json!([]), json!({"ppi": 95})] { + assert!(apply(&mut app, Some(95.0), ¶ms).is_err()); + } + for (pixels, mm) in [(0.0, 509.0), (1920.0, 0.0), (f64::NAN, 509.0), (1920.0, f64::INFINITY), (1920.0, 0.001)] { + assert_eq!(physical_ppi(pixels, mm), None); + } + for ppi in [None, Some(f64::NAN), Some(-1.0)] { + assert_eq!(apply(&mut app, ppi, &json!({})).unwrap()["fallback"], true); + } +} + +#[test] +fn actual_size_remains_unsnapped_on_the_canvas_then_uses_the_next_zoom_rung() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + crate::canvas::testing::frame(&mut app); + app.ui.views[0].center = [1500.0, 1000.0]; + apply(&mut app, Some(95.8), &json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert!((app.ui.views[0].zoom - 95.0 / 72.0).abs() < 1e-6); + assert_eq!(app.ui.views[0].center, [1500.0, 1000.0]); + let ctx = app.ctx().clone(); + crate::menus::invoke(&mut app, &ctx, "view.zoomIn", json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert_eq!(app.ui.views[0].zoom, 2.0); +} + +#[test] +fn actual_size_reads_validated_edid_physical_dimensions() { + let mut edid = [0u8; 128]; + edid[..8].copy_from_slice(&[0, 255, 255, 255, 255, 255, 255, 0]); + edid[21] = 51; + edid[22] = 29; + edid[54] = 1; + edid[66] = 253; + edid[67] = 30; + edid[68] = 0x11; + edid[127] = 0u8.wrapping_sub(edid.iter().copied().fold(0u8, u8::wrapping_add)); + assert_eq!(edid_size(&edid), Some([509.0, 286.0])); + assert_eq!(physical_ppi(1920.0, oriented_width(edid_size(&edid).unwrap(), 0).unwrap()), Some(95.0)); + for length in 0..128 { + assert_eq!(edid_size(&edid[..length]), None); + } + edid[54] = 0; + edid[127] = edid[127].wrapping_add(1); + assert_eq!(edid_size(&edid), Some([510.0, 290.0]), "centimetres when detailed dimensions are absent"); + edid[21] = 0; + edid[127] = edid[127].wrapping_add(51); + assert_eq!(edid_size(&edid), None, "an aspect ratio has no physical width"); + edid[1] = 0; + assert_eq!(edid_size(&edid), None, "corrupt headers are unavailable"); +} + +#[test] +fn actual_size_matches_the_edid_axis_to_all_four_windows_orientations() { + let size = [600.0, 337.0]; + for (orientation, pixels, millimeters) in [(0, 1920.0, 600.0), (1, 1080.0, 337.0), (2, 1920.0, 600.0), (3, 1080.0, 337.0)] { + let width = oriented_width(size, orientation).unwrap(); + assert_eq!(width, millimeters); + assert_eq!(physical_ppi(pixels, width), Some(81.0)); + } + assert_eq!(oriented_width(size, 4), None); + for invalid in [[0.0, 337.0], [600.0, f64::NAN], [f64::INFINITY, 337.0]] { + assert_eq!(oriented_width(invalid, 1), None); + } +} + +#[test] +fn actual_size_uses_backing_mode_pixels_and_falls_back_without_a_usable_mode() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 640, "height": 480})).unwrap(); + let physical = backing_mode_ppi(Some(3024), 344.0); + assert_eq!(physical, Some(223.0), "backing width rather than a 1512-point logical mode"); + assert_eq!(physical_ppi(1512.0, 344.0), Some(111.0)); + assert_eq!(apply(&mut app, physical, &json!({})).unwrap()["fallback"], false); + for mode in [None, Some(0)] { + let missing = backing_mode_ppi(mode, 344.0); + assert_eq!(missing, None); + let fallback = apply(&mut app, missing, &json!({})).unwrap(); + assert_eq!(fallback["fallback"], true); + assert!(fallback["status"].as_str().unwrap().contains("Screen Resolution")); + } +} + +#[test] +fn actual_size_maps_only_recognized_monitor_interfaces_to_edid_keys() { + assert_eq!( + monitor_registry_path(r"\\?\DISPLAY#MODEL01#5&0000&0&UID1#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}"), + Some(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\MODEL01\5&0000&0&UID1\Device Parameters".into()) + ); + for interface in [ + "", + r"\\?\DISPLAY#MODEL01", + r"\\?\OTHER#MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + r"\\?\DISPLAY#..\MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + ] { + assert_eq!(monitor_registry_path(interface), None); + } +} diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index 62a94a1277..dbcab116d5 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -44,6 +44,12 @@ fn is_context_task_bar(id: &str) -> bool { matches!(id, "window.panel.contextualTaskBar" | "window.toggle.contextualTaskBar") } +/// The Window item and its shell command for the options bar, which is a bar of the window, not a dock panel +/// (#16795). +fn is_options_bar(id: &str) -> bool { + matches!(id, "window.panel.options" | "window.toggle.options") +} + /// Ids handled here (live menu items). pub fn handles(id: &str) -> bool { if let Some(k) = id.strip_prefix("view.show.") { @@ -69,9 +75,16 @@ pub fn handles(id: &str) -> bool { } PANEL_IDS.contains(&id) || is_context_task_bar(id) + || is_options_bar(id) || matches!( id, - "view.extras" | "view.flipHorizontal" | "view.pixelAspectRatioCorrection" | "view.patternPreview" | "view.pixelArtPreview" | "view.rotateView" + "view.extras" + | "view.flipHorizontal" + | "view.pixelAspectRatioCorrection" + | "view.patternPreview" + | "view.pixelArtPreview" + | "view.rotateView" + | "view.actualSize" ) } @@ -91,7 +104,7 @@ pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabl // Standard again before the next pass (`leave_full_screen_without_document`). "view.screenMode.cycle" | "view.screenMode.cycleBack" => app.ui.text_edit.is_none() && doc, "view.screenMode.fullScreen" | "view.screenMode.fullScreenWithMenuBar" => doc, - "view.rotateView" => doc, + "view.rotateView" | "view.actualSize" => doc, i if i.starts_with("window.arrange.") => arrange_command(&i["window.arrange.".len()..]).is_some_and(|command| { let windows = &app.ui.document_windows; command.arrangement().enabled(app.session.documents().len(), windows.docked.len(), windows.floating.len()) @@ -152,6 +165,9 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { if is_context_task_bar(id) { return Some(app.ui.panels.context_task_bar); } + if is_options_bar(id) { + return Some(app.ui.panels.options_bar); + } if PANEL_IDS.contains(&id) { return Some(crate::panel_docking::toggle_panel(id).is_some_and(|panel| crate::panel_docking::is_checked(app, panel))); } @@ -264,6 +280,9 @@ pub(super) fn no_params(p: &Value) -> bool { /// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when /// `id` isn't ours. pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + if id == "view.actualSize" { + return Some(super::actual_size::invoke(app, ctx, params)); + } if let Some(result) = crate::panel_docking::command(app, id, params) { return Some(result); } @@ -310,6 +329,14 @@ fn run(app: &mut PhotocraftApp, id: &str, p: &Value) -> Result { *bar = flag_param(p, *bar); return Ok(json!(*bar)); } + if is_options_bar(id) { + let show = match p.get("show").or_else(|| p.get("on")) { + None | Some(Value::Null) => !app.ui.panels.options_bar, + Some(value) => value.as_bool().ok_or("show must be a boolean")?, + }; + app.ui.panels.options_bar = show; + return Ok(json!(show)); + } let o = &mut app.ui.view; if let Some(k) = id.strip_prefix("view.show.") { if k == "all" { diff --git a/crates/ui-egui/src/panels/background_row_menu_tests.rs b/crates/ui-egui/src/panels/background_row_menu_tests.rs new file mode 100644 index 0000000000..422082c587 --- /dev/null +++ b/crates/ui-egui/src/panels/background_row_menu_tests.rs @@ -0,0 +1,99 @@ +//! The Background row's context menu starts with Layer from Background… and a separator, the Layer › New entry +//! (#16764); other rows, a locked pixel layer among them, keep the menu they had. + +use craft::layers::ui::panel::{LayersEvent, MenuTarget}; +use craft::layers::ui::tree::LayerRowKey; +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::panels::layers_tree::{PhotoLayers, row_menu}; + +const FROM_BACKGROUND: &str = "layer.new.layerFromBackground"; + +/// A document with its Background and a pixel layer "Ink" above it; "Ink" is active. +fn setup() -> Box { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 24, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Ink"})).unwrap(); + app +} + +fn background(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + st.doc.walk().into_iter().map(|(_, _, l)| l.id).find(|id| st.doc.is_background(*id)) +} + +fn active(app: &PhotocraftApp) -> LayerId { + app.session.active().and_then(|st| st.active_layer).expect("a layer is active") +} + +/// The right-clicked row's menu as (value, enabled); a separator is `None`. +fn menu(app: &PhotocraftApp, id: LayerId) -> Vec> { + let st = app.session.active().unwrap(); + let tree = PhotoLayers::new(app, st, &Default::default(), false, None); + row_menu(app, &tree, &MenuTarget::new(Some(LayerRowKey::Layer(id)))) + .iter() + .map(|e| if e.is_separator() { None } else { e.value().map(|v| (v.clone(), e.is_enabled())) }) + .collect() +} + +fn values(menu: &[Option<(String, bool)>]) -> Vec> { + menu.iter().map(|e| e.as_ref().map(|(v, _)| v.clone())).collect() +} + +fn offers(menu: &[Option<(String, bool)>]) -> bool { + menu.iter().flatten().any(|(v, _)| v == FROM_BACKGROUND) +} + +fn last_step(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.entries().last().cloned() +} + +#[test] +fn the_background_row_starts_with_layer_from_background_and_a_separator() { + let mut app = setup(); + let ink = values(&menu(&app, active(&app))); + let bg = background(&app).expect("the document has a Background"); + // The right-click selects the row it opens on. + app.run("layer.select", json!({"layer": bg.0, "mode": "replace"})).unwrap(); + let m = menu(&app, bg); + assert_eq!(m.first().cloned().flatten(), Some((FROM_BACKGROUND.to_string(), true)), "first and available: {m:?}"); + assert_eq!(m.get(1), Some(&None), "a separator follows: {m:?}"); + assert_eq!(values(&m)[2..], ink[..], "the rest is the menu another pixel layer gets"); +} + +#[test] +fn other_rows_have_no_layer_from_background() { + let mut app = setup(); + let ink = active(&app); + assert!(!offers(&menu(&app, ink)), "a pixel layer"); + // A pixel layer above the Background with its locks: it is not the Background. + app.run("layer.lockLayers", json!({"transparency": true, "position": true})).unwrap(); + let locked = app.session.active().unwrap().doc.layer(ink).unwrap().clone(); + assert!(locked.locks.transparency && locked.locks.position, "the locks took"); + assert!(!offers(&menu(&app, ink)), "a locked pixel layer"); + app.run("layer.groupLayers", json!({"name": "G"})).unwrap(); + assert!(!offers(&menu(&app, active(&app))), "a group"); +} + +/// Picking the entry converts the Background in the same History step as Layer › New › Layer from Background… +#[test] +fn picking_the_entry_converts_the_background_like_the_layer_menu() { + let mut app = setup(); + let bg = background(&app).unwrap(); + app.run("layer.select", json!({"layer": bg.0, "mode": "replace"})).unwrap(); + let ctx = app.ctx().clone(); + let pick = LayersEvent::menu(MenuTarget::new(Some(LayerRowKey::Layer(bg))), FROM_BACKGROUND); + crate::panels::layers_events::apply_layers_events(&mut app, &ctx, vec![pick]); + assert_eq!(background(&app), None, "the Background became a normal layer"); + assert!(!offers(&menu(&app, bg)), "and its row no longer offers the entry"); + + let mut menu_app = setup(); + let menu_bg = background(&menu_app).unwrap(); + menu_app.run("layer.select", json!({"layer": menu_bg.0, "mode": "replace"})).unwrap(); + crate::menus::invoke(&mut menu_app, &ctx, FROM_BACKGROUND, json!({})).unwrap(); + assert_eq!(background(&menu_app), None); + assert_eq!(last_step(&app), last_step(&menu_app), "the same History step as the Layer menu"); +} diff --git a/crates/ui-egui/src/panels/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs index 0d55e1330a..fed63c8cf1 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui.rs @@ -62,6 +62,27 @@ pub(crate) fn layer_count_label(command: &str, multi: bool) -> Option<&'static s Some(if multi { several } else { one }) } +/// The context menu entries for a layer's row: [`entries`], led on the Background's row +/// (`background`, [`photocraft_doc::Document::is_background`]) by Layer from Background… and a +/// separator, the Layer › New entry (#16764). A multi-selection keeps the plain entries. The base of a clip group +/// (`clip_base`, [`photocraft_engine::layer_multi_cmds::merges_clipping_mask`]) reads Merge Clipping Mask in place of +/// Merge Down (#18481). +pub fn row_entries(l: &Layer, multi: bool, has_selection: bool, background: bool, clip_base: bool) -> Vec { + let mut v: Vec = Vec::new(); + if background && !multi { + v.push(Some((tl!("Layer from Background…"), "layer.new.layerFromBackground"))); + v.push(None); + } + v.extend(entries(l, multi, has_selection)); + if clip_base + && !multi + && let Some(merge) = v.iter_mut().flatten().find(|e| e.1 == "layer.mergeDown") + { + *merge = (tl!("Merge Clipping Mask"), "layer.mergeLayers"); + } + v +} + /// The context menu entries for a layer (Photoshop 2026 order, trimmed to the layer kind). pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { let mut v: Vec = vec![Some((tl!("Blending Options…"), "layer.layerStyle.blendingOptions"))]; @@ -185,3 +206,7 @@ mod tests; #[cfg(test)] #[path = "layer_menu_artboard_group_tests.rs"] mod layer_menu_artboard_group_tests; + +#[cfg(test)] +#[path = "background_row_menu_tests.rs"] +mod background_row_menu_tests; diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 961f9e7aa1..756b3ffa83 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -773,7 +773,9 @@ pub(crate) fn row_menu(app: &PhotocraftApp, tree: &PhotoLayers, target: &MenuTar MenuKind::Effects => commands(crate::layer_menu_ui::effects_entries(), false), MenuKind::Layer(id) => { let Some(l) = tree.layer(&id) else { return Vec::new() }; - let mut out = commands(crate::layer_menu_ui::entries(l, target.on_selection, has_selection), target.on_selection); + let background = tree.doc().is_background(id); + let clip_base = photocraft_engine::layer_multi_cmds::merges_clipping_mask(tree.doc(), id); + let mut out = commands(crate::layer_menu_ui::row_entries(l, target.on_selection, has_selection, background, clip_base), target.on_selection); out.push(Entry::separator()); out.push(Entry::new(RENAME.to_string(), tl!("Rename Layer…").to_string())); out diff --git a/crates/ui-egui/src/panels/options_bar/paint.rs b/crates/ui-egui/src/panels/options_bar/paint.rs index e0dbdbeb2a..e7180aa5a1 100644 --- a/crates/ui-egui/src/panels/options_bar/paint.rs +++ b/crates/ui-egui/src/panels/options_bar/paint.rs @@ -305,7 +305,7 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> apply_values(app, tool, &mut brush, &before, &after); crate::brush_panel::commit_keyed(app, &brush_before, &brush, key); } - PaintEvent::EraserMode(mode) => app.ui.tool_options.eraser_mode = eraser_mode_name(mode).into(), + PaintEvent::EraserMode(mode) => crate::canvas::strokes::set_eraser_mode(app, eraser_mode_name(mode)), PaintEvent::MixerLoad => { let result = app.run("brush.mixer.load", json!({})); report(app, result); diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 552d2898f6..0d8fd3e08c 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -16,7 +16,7 @@ use craft::ui::patterns::presets::{ PresetFooterOptions, PresetMenuAction, PresetPanelMenu, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, ThumbFn, ThumbInfo, }; use craft::ui::primitives::textures::TextureCache; -use craft::ui::primitives::{ContentPainterCx, FacePaint}; +use craft::ui::primitives::{ContentPainterCx, FacePaint, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandSet as _, CommandState}; use craft::ui::runtime::env::Env; @@ -834,8 +834,19 @@ fn tool_preset_rows(presets: &&[(String, String)], _: &Env) -> Vec row.accessible_name(crate::i18n::fmt(tl!("{preset}, {tool}"), &[("preset", name), ("tool", tl!(tool.label()))])), + None => row, + } }) .collect() } @@ -1141,3 +1152,7 @@ pub(crate) fn gradient_picker_at(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "tool_presets_row_icon_tests.rs"] +mod tool_presets_row_icon_tests; diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index e49b0666d8..c883be58aa 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -159,6 +159,9 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, let params = crate::adjust_editors::layer_reset(app, id, adj); let _ = app.run("layer.setAdjustment", params); app.live_adjust = None; + if matches!(adj, photocraft_doc::Adjustment::BlackWhite { .. }) { + crate::adjust_editors::black_white_presets::clear_custom(ui); + } } } diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index d70707bee8..429c0a6842 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -63,7 +63,7 @@ pub(crate) enum ToolCommand { BackgroundEraser, #[command(label = "Magic Eraser Tool", icon = "eraser_magic", kind = "tool", group = "E", default = "E", alias = "tools.select.magicEraser")] MagicEraser, - #[command(label = "Gradient Tool", icon = "gradient", kind = "tool", group = "G", default = "G", alias = "tools.select.gradient")] + #[command(label = "Gradient Tool", icon = "gradient-tool", kind = "tool", group = "G", default = "G", alias = "tools.select.gradient")] Gradient, #[command(label = "Paint Bucket Tool", icon = "paint_bucket", kind = "tool", group = "G", default = "G", alias = "tools.select.paintBucket")] PaintBucket, diff --git a/crates/ui-egui/src/panels/tool_presets_row_icon_tests.rs b/crates/ui-egui/src/panels/tool_presets_row_icon_tests.rs new file mode 100644 index 0000000000..3ac8d99c57 --- /dev/null +++ b/crates/ui-egui/src/panels/tool_presets_row_icon_tests.rs @@ -0,0 +1,45 @@ +use egui::{Rect, Shape, TextureId}; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::presets::{PresetsExt, tools::ToolPreset}; +use serde_json::json; + +use crate::input::shortcut_dispatch::tests::app_harness; +use crate::{PhotocraftApp, Services}; + +fn icon_texture(shape: &Shape, row: Rect) -> Option { + match shape { + Shape::Vec(shapes) => shapes.iter().find_map(|shape| icon_texture(shape, row)), + Shape::PaintChunk(shapes) => shapes.iter().find_map(|shape| icon_texture(&shape.shape, row)), + Shape::Mesh(mesh) if mesh.texture_id != TextureId::default() && row.contains(mesh.calc_bounds().center()) => Some(mesh.texture_id), + _ => None, + } +} + +#[test] +fn tool_preset_rows_paint_distinct_tool_glyphs_and_a_fallback() { + let names = ["Test crop preset", "Test brush preset", "Test unknown preset"]; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.session.presets_mut().tool_presets = names + .into_iter() + .zip(["crop", "brush", "unrecognised-test-tool"]) + .map(|(name, tool)| ToolPreset { name: name.into(), tool: tool.into(), options: json!({}) }) + .collect(); + let mut h = app_harness(app); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "window.panel.toolPresets", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "window.panel.window", json!({"panel": "toolPresets", "native": false})).unwrap(); + h.run_steps(6); + + let textures = names.map(|name| { + let row = h.query_by_label_contains(name).expect("the preset is exposed as a row in the panel"); + h.output().shapes.iter().find_map(|shape| icon_texture(&shape.shape, row.rect())).unwrap_or_else(|| panic!("{name} draws an icon in its row")) + }); + assert_ne!(textures[0], textures[1], "different tools draw different icons"); + assert_ne!(textures[0], textures[2], "the unknown tool uses the fallback icon"); + assert_ne!(textures[1], textures[2], "the unknown tool uses the fallback icon"); + for (name, tool) in [(names[0], "Crop Tool"), (names[1], "Brush Tool")] { + let label = h.query_by_label_contains(name).unwrap().accesskit_node().label().unwrap(); + assert!(label.starts_with(name) && label.contains(tool), "the row announces its preset name and tool: {label}"); + } +} diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index e3cf32a56c..5bfdd4983b 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -21,6 +21,9 @@ mod toolbar_docking_tests; #[path = "toolbar_flyout_mark_tests.rs"] mod toolbar_flyout_mark_tests; #[cfg(test)] +#[path = "toolbar_rotate_view_reset_tests.rs"] +mod toolbar_rotate_view_reset_tests; +#[cfg(test)] #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; @@ -318,7 +321,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(tool) = out.select { crate::tool_memory::select(app, tool); } - // A double click on Hand fits the image on screen, on Zoom shows it at 100% (Photoshop); with no document open there + // A double click on Hand fits the image on screen, Rotate View resets its angle, and Zoom shows it at 100%; with no document open there // is nothing to do. The framework reports no double click after a modified click. match out.double_clicked { Some(Tool::Hand) => { @@ -327,6 +330,9 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Some(Tool::Zoom) => { let _ = crate::menus::invoke(app, &ctx, "view.actualPixels", json!({})); } + Some(Tool::RotateView) => { + let _ = crate::menus::invoke(app, &ctx, "view.resetView", json!({})); + } _ => {} } if let Some(next) = &out.last_used { diff --git a/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs b/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs new file mode 100644 index 0000000000..2cc3991808 --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs @@ -0,0 +1,102 @@ +//! Double-clicking the Rotate View icon in the Hand slot runs Reset View (#18744). + +use super::*; +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +/// Use 60 Hz frames so two clicks fall inside the double-click interval. +fn harness(documents: usize) -> Harness<'static, Box> { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 1100.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("prefs.set", json!({"values": {"general.animatedZoom": false}})).expect("disable zoom animation"); + // Home hides the toolbar, so the empty-document case uses the workspace. + app.session.edit_prefs(|prefs| prefs.general.auto_show_home_screen = false); + for _ in 0..documents { + app.run("file.new", json!({"width": 3000, "height": 2000})).expect("new document"); + } + app.ui.tool = Tool::RotateView; + app.ui.remember_group_tool(Tool::RotateView); + app + }); + h.run_steps(4); + h +} + +/// The shown tool's rail button, excluding the options-bar button and the flyout corner. +fn slot(h: &Harness<'static, Box>, label: &str) -> egui::Pos2 { + h.query_all_by_label(label).rfind(|node| node.rect().width() >= 16.0).expect("the toolbar shows the tool").rect().center() +} + +fn click(h: &mut Harness<'static, Box>, at: egui::Pos2) { + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } +} + +#[test] +fn double_click_on_the_rotate_view_slot_resets_only_the_active_angle() { + let mut h = harness(2); + h.state_mut().ui.views[0].rotation = -23.0; + let active = &mut h.state_mut().ui.views[1]; + active.rotation = 37.0; + active.zoom = 0.75; + active.center = [1400.0, 900.0]; + h.run_steps(4); + let before = h.state().ui.views[1].clone(); + let other = h.state().ui.views[0].clone(); + let doc = h.state().session.active().expect("active document").doc.clone(); + let history = h.state().session.active().expect("active document").history.past_len(); + let at = slot(&h, "Rotate View Tool"); + click(&mut h, at); + assert_eq!(h.state().ui.views[1].rotation, 37.0, "one click only selects Rotate View"); + click(&mut h, at); + h.run_steps(4); + let after = &h.state().ui.views[1]; + assert_eq!(after.rotation, 0.0, "the second click runs Reset View"); + assert_eq!((after.zoom, after.center), (before.zoom, before.center)); + assert_eq!(h.state().ui.views[0], other, "the other document keeps its view"); + assert_eq!(h.state().ui.tool, Tool::RotateView); + let session = h.state().session.active().expect("active document"); + assert!(std::sync::Arc::ptr_eq(&session.doc, &doc)); + assert_eq!(session.history.past_len(), history); +} + +#[test] +fn double_click_on_rotate_view_without_a_document_keeps_the_tool_selected() { + let mut h = harness(0); + let at = slot(&h, "Rotate View Tool"); + click(&mut h, at); + click(&mut h, at); + h.run_steps(4); + assert_eq!(h.state().ui.tool, Tool::RotateView); + assert!(h.state().ui.views.is_empty()); + assert!(h.state().session.active().is_none()); +} + +#[test] +fn hand_and_zoom_keep_their_double_click_actions() { + for (tool, label) in [(Tool::Hand, "Hand Tool"), (Tool::Zoom, "Zoom Tool")] { + let mut h = harness(1); + h.state_mut().ui.tool = tool; + h.state_mut().ui.remember_group_tool(tool); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 0.75; + view.center = [1400.0, 900.0]; + h.run_steps(4); + let at = slot(&h, label); + click(&mut h, at); + click(&mut h, at); + h.run_steps(4); + let view = &h.state().ui.views[0]; + if tool == Tool::Hand { + assert!(view.zoom > 0.0 && view.zoom < 0.75, "Hand fits the large document on screen"); + assert_eq!(view.center, [1500.0, 1000.0]); + } else { + assert_eq!(view.zoom, 1.0, "Zoom shows actual pixels"); + } + } +} diff --git a/crates/ui-egui/src/panels/type_panels_ui/style_options.rs b/crates/ui-egui/src/panels/type_panels_ui/style_options.rs index 255a6aeddb..538be23058 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/style_options.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/style_options.rs @@ -7,7 +7,7 @@ use craft::text::ui::character::{ StyleOptionValues, StyleOptionsChange, TextAlign, TextStyleOptions, }; use craft::theme::Rgba; -use photocraft_doc::text::{CharStyle, ParagraphStyle}; +use photocraft_doc::text::{CharStyle, Digits, ParagraphStyle}; use serde_json::{Value, json}; use super::{color_picker, run}; @@ -157,9 +157,28 @@ pub(crate) fn character_values(style: &CharStyle) -> CharacterValues { values.strikethrough = Some(style.strikethrough); values.opentype = opentype; values.language = style.language.clone(); + values.digits = Some(digit_name(style.digits).to_string()); values } +/// The engine's `digits` name of a digit style. +pub(crate) fn digit_name(d: Digits) -> &'static str { + match d { + Digits::AsTyped => "asTyped", + Digits::Western => "western", + Digits::Contextual => "contextual", + Digits::Devanagari => "devanagari", + Digits::Bengali => "bengali", + Digits::Gurmukhi => "gurmukhi", + Digits::Gujarati => "gujarati", + Digits::Odia => "odia", + Digits::Tamil => "tamil", + Digits::Telugu => "telugu", + Digits::Kannada => "kannada", + Digits::Malayalam => "malayalam", + } +} + /// The values the Paragraph controls show for `style`. pub(crate) fn paragraph_values(style: &ParagraphStyle) -> ParagraphValues { use photocraft_doc::text::TextDirection as D; diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 1942c3d1e0..d56107481c 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -87,6 +87,9 @@ fn language_label(ctx: &egui::Context, native: &str, code: &str) -> String { if can_draw { native.to_string() } else { code.to_string() } } +/// The order RAW Defaults lists its color spaces in; a space not named here comes last. +const RAW_SPACE_ORDER: [&str; 4] = ["adobeRgb", "displayP3", "proPhoto", "srgb"]; + /// The rules of every setting from the engine's schema: choices, ranges, colours, hidden settings, the ones read /// at launch, and the labels and groups the window shows. pub(super) fn rules(ctx: &egui::Context) -> Vec { @@ -108,7 +111,10 @@ pub(super) fn rules(ctx: &egui::Context) -> Vec { let refs: Vec<(&str, &str)> = pairs.iter().map(|(id, label)| (id.as_str(), label.as_str())).collect(); tweak(&mut rules, &path, |r| r.choices(&refs)); } else if let Some(options) = prefs::choices(&path) { - let labelled: Vec<(&str, String)> = options.iter().map(|id| (*id, choice_label(id))).collect(); + let mut labelled: Vec<(&str, String)> = options.iter().map(|id| (*id, choice_label(id))).collect(); + if path == "rawDefaults.colorSpace" { + labelled.sort_by_key(|(id, _)| RAW_SPACE_ORDER.iter().position(|o| o == id).unwrap_or(usize::MAX)); + } let refs: Vec<(&str, &str)> = labelled.iter().map(|(id, label)| (*id, label.as_str())).collect(); tweak(&mut rules, &path, |r| r.choices(&refs)); } else if let Some((lo, hi)) = prefs::range(&path) { @@ -231,6 +237,9 @@ fn label_override(key: &str) -> Option<&'static str> { "lowLatencyDrawing" => "Low-Latency Drawing (vsync off, applies at next launch)", "sizeLimitMb" => "Scratch Size Limit (MB, 0 = No Limit)", "gpuMemoryMb" => "GPU Memory (MB, 0 = Automatic)", + "openInCameraRaw" => "Open in RAW Develop", + "openAsSmartObject" => "Open as Smart Object", + "writeXmpSidecars" => "Write XMP sidecars", _ => return None, }) } @@ -255,6 +264,13 @@ pub(super) fn choice_label(v: &str) -> String { "ahd" => "AHD (adaptive homogeneity)".into(), "mhc" => "Malvar–He–Cutler".into(), "cpu" => "CPU (no GPU acceleration)".into(), + // The print dialog's name for this space, so one catalog key covers both. + "adobeRgb" => "Adobe RGB (1998) compatible".into(), + "displayP3" => "Display P3".into(), + "proPhoto" => "ProPhoto RGB".into(), + "srgb" => "sRGB IEC61966-2.1".into(), + "glossy" => "Glossy Paper".into(), + "matte" => "Matte Paper".into(), v => spelled(v), } } @@ -305,3 +321,7 @@ mod language_label_tests { assert!(!rules(&ctx).is_empty()); } } + +#[cfg(test)] +#[path = "../raw_defaults_labels_tests.rs"] +mod raw_defaults_labels_tests; diff --git a/crates/ui-egui/src/prefs/raw_defaults_labels_tests.rs b/crates/ui-egui/src/prefs/raw_defaults_labels_tests.rs new file mode 100644 index 0000000000..758d2fd24f --- /dev/null +++ b/crates/ui-egui/src/prefs/raw_defaults_labels_tests.rs @@ -0,0 +1,46 @@ +//! Preferences > RAW Defaults shows proper names instead of words spelled out from the stored ids (#17770). + +use craft::i18n::Folder; +use craft::i18n::matcher::Matcher; +use craft::ui::patterns::preferences::{PreferencesModel, RowKind, SettingsDocument, row_matches}; +use photocraft_engine::prefs; + +use super::{PrefPages, choice_label, rules, spelled}; + +/// The labels hang on stored ids written as text, so a renamed id would silently fall back to `spelled`. +#[test] +fn raw_choices_have_names_of_their_own() { + for (path, ids) in [("rawDefaults.colorSpace", &["adobeRgb", "displayP3", "proPhoto", "srgb"][..]), ("rawDefaults.sharpenFor", &["glossy", "matte"][..])] { + let offered = prefs::choices(path).expect("a choice setting"); + for id in ids { + assert!(offered.contains(id), "{path} no longer offers {id}"); + assert_ne!(choice_label(id), spelled(id), "{path}: {id}"); + } + } +} + +#[test] +fn preferences_search_finds_the_raw_develop_switch() { + let doc = SettingsDocument::new(PrefPages::default()).expect("the default preferences").rules(rules(&egui::Context::default())); + let matcher = Matcher::new(&Folder::new("en"), "RAW Develop"); + let pages = PreferencesModel::pages(&doc); + let found: Vec<&str> = pages.iter().flat_map(|p| &p.groups).flat_map(|g| &g.rows).filter(|r| row_matches(&matcher, r)).map(|r| r.key).collect(); + assert!(found.contains(&"rawDefaults.openInCameraRaw"), "{found:?}"); +} + +/// The list is reordered for display only: every stored color space is still offered, each under its own id. +#[test] +fn raw_color_spaces_are_reordered_without_losing_one() { + let doc = SettingsDocument::new(PrefPages::default()).expect("the default preferences").rules(rules(&egui::Context::default())); + let pages = PreferencesModel::pages(&doc); + let row = pages.iter().flat_map(|p| &p.groups).flat_map(|g| &g.rows).find(|r| r.key == "rawDefaults.colorSpace").expect("the row"); + let RowKind::Choice { options, .. } = &row.kind else { panic!("not a choice row") }; + let shown: Vec = options.iter().filter_map(|o| o.value().map(|v| v.to_string())).collect(); + let stored: Vec = prefs::choices("rawDefaults.colorSpace").expect("a choice setting").iter().map(|id| id.to_string()).collect(); + assert_ne!(shown, stored, "the stored order is shown"); + let sorted = |mut ids: Vec| { + ids.sort(); + ids + }; + assert_eq!(sorted(shown), sorted(stored)); +} diff --git a/crates/ui-egui/src/proxy.rs b/crates/ui-egui/src/proxy.rs index 52a8b9c203..6ae3da9762 100644 --- a/crates/ui-egui/src/proxy.rs +++ b/crates/ui-egui/src/proxy.rs @@ -5,12 +5,17 @@ use craft::imaging::ui::live_preview::ProxyPlan; use photocraft_doc::Document; +use crate::PhotocraftApp; + /// Target pixel count for previews (fast enough to composite every frame on CPU). pub const PREVIEW_PIXELS: u64 = 2_500_000; /// Downscale factor for a document, or 1 when it's already small. pub fn factor(doc: &Document) -> u32 { - let px = doc.size.area(); + factor_for_area(doc.size.area()) +} + +fn factor_for_area(px: u64) -> u32 { if px <= PREVIEW_PIXELS * 2 { return 1; } @@ -19,7 +24,7 @@ pub fn factor(doc: &Document) -> u32 { /// Whether live previews may run on a reduced copy (Preferences › Performance › Low Resolution /// Previews, on by default). Off, every live preview renders at full resolution. -pub fn reduced_previews(app: &crate::PhotocraftApp) -> bool { +pub fn reduced_previews(app: &PhotocraftApp) -> bool { app.session.prefs().performance.low_resolution_previews } @@ -28,6 +33,19 @@ pub fn preview_factor(doc: &Document, reduced: bool) -> u32 { if reduced { factor(doc) } else { 1 } } +/// Pixel count for choosing preview resolution. Tests can scale the decision's input +/// while the fixture's real dimensions still govern rendering and allocation. +pub(crate) fn planning_area(_app: &PhotocraftApp, doc: &Document) -> u64 { + let area = doc.size.area(); + #[cfg(test)] + let area = area.saturating_mul(_app.preview_test_area_multiplier); + area +} + +pub(crate) fn app_factor(app: &PhotocraftApp, doc: &Document) -> u32 { + if reduced_previews(app) { factor_for_area(planning_area(app, doc)) } else { 1 } +} + /// A live preview's factor `k` capped for a view at `zoom` (physical screen pixels per document /// pixel) of a document of `document_pixels`: never coarser than the screen /// ([`ProxyPlan::factor`]), so a view at 100 % shows full resolution instead of k-pixel blocks while @@ -48,6 +66,10 @@ mod tests { fn factor_scales_with_size() { let small = Document::new("s", Size::new(1000, 1000), ColorMode::Rgb, SampleType::U8); assert_eq!(factor(&small), 1); + let boundary = Document::new("threshold", Size::new(2500, 2000), ColorMode::Rgb, SampleType::U8); + let above = Document::new("above threshold", Size::new(2501, 2000), ColorMode::Rgb, SampleType::U8); + assert_eq!(factor(&boundary), 1); + assert_eq!(factor(&above), 2); let big = Document::new("b", Size::new(6016, 6016), ColorMode::Rgb, SampleType::U8); let k = factor(&big); assert!((3..=5).contains(&k), "{k}"); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 90fbd74f2a..9e621dd6f5 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -540,6 +540,8 @@ pub struct Services { pub file_dialog: Option, /// Write bytes to a path (native) or trigger a download (web). pub write: Option, + /// Publish a new file on the desktop, leaving any occupied destination intact. + pub write_new: Option, /// Size and modification time of a file (native); `None` on the web, where Save never /// writes back to a file. pub file_stamp: Option, diff --git a/crates/ui-egui/src/tools/analysis/menu_enabled_no_doc_tests.rs b/crates/ui-egui/src/tools/analysis/menu_enabled_no_doc_tests.rs new file mode 100644 index 0000000000..5285b01139 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/menu_enabled_no_doc_tests.rs @@ -0,0 +1,33 @@ +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +const DATA_POINTS: &str = "image.analysis.selectDataPoints"; +const RULER: &str = "image.analysis.rulerTool"; +const COUNT: &str = "image.analysis.countTool"; +const SCALE: &str = "image.analysis.setMeasurementScale"; +const RECORD: &str = "image.analysis.recordMeasurements"; +const MARKER: &str = "image.analysis.placeScaleMarker"; + +#[test] +fn analysis_menu_can_select_tools_without_a_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + let ctx = app.ctx().clone(); + + for (id, tool) in [(RULER, Tool::Ruler), (COUNT, Tool::Count)] { + assert!(crate::menus::is_enabled(&app, id), "{id} can select a tool before opening a document"); + crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); + assert_eq!(app.ui.tool, tool); + assert!(!app.session.is_enabled(id), "the headless command still requires a document"); + } + for id in [DATA_POINTS, SCALE, RECORD, MARKER] { + assert!(!crate::menus::is_enabled(&app, id), "{id} is disabled without a document"); + } + assert!(crate::menus::invoke(&mut app, &ctx, DATA_POINTS, json!({})).is_err()); + assert!(app.session.is_enabled(DATA_POINTS), "headless session measurement settings remain available"); + + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + for id in [RULER, COUNT, DATA_POINTS, SCALE, RECORD, MARKER] { + assert!(crate::menus::is_enabled(&app, id), "{id} is enabled with a document"); + } +} diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index a567de1c71..d1cbd264ce 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -24,6 +24,8 @@ pub(crate) mod log_panel; pub(crate) mod note_alerts; pub(crate) mod notes_panel; +#[cfg(test)] +mod menu_enabled_no_doc_tests; #[cfg(test)] mod tests; @@ -111,11 +113,22 @@ impl Default for AnalysisUi { const PANELS: [&str; 2] = ["window.panel.measurementLog", "window.panel.notes"]; -/// Menu ids handled here (live menu items). +/// Menu ids implemented by this module rather than engine command specs. pub fn handles(id: &str) -> bool { PANELS.contains(&id) } +/// Menu state for the Analysis front ends that act differently from their headless commands. +pub(crate) fn enabled(app: &PhotocraftApp, id: &str) -> Option { + match id { + // These menu items choose a tool; their engine counterparts read or edit a document. + "image.analysis.rulerTool" | "image.analysis.countTool" => Some(true), + "image.analysis.selectDataPoints" => Some(app.session.active().is_some()), + _ if handles(id) => Some(true), + _ => None, + } +} + /// The check mark of a menu item of this module. pub fn checked(app: &PhotocraftApp, id: &str) -> Option { match id { @@ -166,7 +179,13 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option dialogs::open(app, dialogs::Kind::DataPoints).map(|_| json!({"dialog": "dataPoints"})), + "image.analysis.selectDataPoints" => { + if app.session.active().is_none() { + Err(tl!("no document open").to_string()) + } else { + dialogs::open(app, dialogs::Kind::DataPoints).map(|_| json!({"dialog": "dataPoints"})) + } + } "image.analysis.placeScaleMarker" => { app.session.active()?; dialogs::open(app, dialogs::Kind::ScaleMarker).map(|_| json!({"dialog": "scaleMarker"})) diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index fb8d4828cf..c1ca38fbd9 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -529,6 +529,9 @@ mod options_bar_tests; #[cfg(test)] mod convert_point_delete_key_tests; +#[cfg(test)] +mod free_transform_points_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select/free_transform_points_tests.rs b/crates/ui-egui/src/tools/direct_select/free_transform_points_tests.rs new file mode 100644 index 0000000000..f917d91ee5 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/free_transform_points_tests.rs @@ -0,0 +1,414 @@ +//! #13209: ⌘T / Edit ▸ Free Transform with anchors selected in Direct Selection frames the box over +//! those anchors and transforms only them (Free Transform Points). Measured on the epic's document: +//! the anchors (300,300) and (100,500) of the closed square selected, the box spans 100,300 to +//! 300,500; W 50 % (linked) and Enter moves them to (250,350) and (150,450) about the centre of the +//! selection, the two unselected anchors of the square stay, and History holds one step "Transform +//! Points". With nothing selected, and in the neighbouring cases the ticket leaves unmeasured, the +//! whole path transforms as it does today. + +use craft::behavior::geometry::quad::BoxState; +use craft::behavior::kurbo::{Point, Vec2}; +use egui::Modifiers; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::state::Tool; + +/// The epic's document: 800 x 600 on white, a layer "Red", and saved path Path 1 holding the closed +/// corner square (100,300) (300,300) (300,500) (100,500) and the open line (400,300)-(700,300), +/// targeted in the Paths panel, Direct Selection on. +fn saved_path_app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.ui.tool = Tool::DirectSelection; + app +} + +/// A square work path whose knot 1 at (120,40) is smooth, with handles at (100,40) and (140,40). +fn work_path_app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::DirectSelection; + let path = json!({"subpaths": [{"closed": true, "knots": [ + [40, 40], + {"anchor": [120, 40], "in": [100, 40], "out": [140, 40], "smooth": true}, + [120, 120], + [40, 120], + ]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app +} + +/// A live rectangle shape layer "Rectangle 1" at 550,50 to 750,200, Direct Selection on. +fn shape_app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.run("shape.create", json!({"kind": "rect", "rect": [550, 50, 200, 150]})).unwrap(); + app.ui.tool = Tool::DirectSelection; + app +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { + testing::click(app, at, mods); +} + +/// The measured two-anchor selection: (300,300) and (100,500) of the square. +fn select_two_corners(app: &mut PhotocraftApp) { + click(app, [300.0, 300.0], Modifiers::NONE); + click(app, [100.0, 500.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [0, 3]], "both corners are selected"); +} + +/// ⌘T / Edit ▸ Free Transform. +fn open_box(app: &mut PhotocraftApp) { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "edit.freeTransform", json!({})).expect("the path is transformable"); + assert!(app.ui.transform.is_some(), "the box opened"); +} + +/// The box's source frame. +fn box_rect(app: &PhotocraftApp) -> [f64; 4] { + app.ui.transform.as_ref().expect("a Free Transform is open").rect_array() +} + +/// What the box will send to `path.transform`. +fn box_params(app: &PhotocraftApp) -> serde_json::Value { + app.ui.transform.as_ref().expect("a Free Transform is open").path.clone().unwrap_or(serde_json::Value::Null) +} + +/// Puts the box on `quad`, as the transform controls do. +fn set_box(app: &mut PhotocraftApp, quad: [[f64; 2]; 4]) { + app.ui.transform.as_mut().unwrap().edit_box(|b| *b = BoxState::new(quad.map(|[x, y]| Point::new(x, y)), b.pivot)); +} + +/// Moves the box and its reference point, as a drag inside the box does. +fn move_box(app: &mut PhotocraftApp, dx: f64, dy: f64) { + app.ui.transform.as_mut().unwrap().edit_box(|b| *b = b.moved(Vec2::new(dx, dy))); +} + +/// OK: commit the open box. +fn commit_box(app: &mut PhotocraftApp) { + crate::transform_tool::commit(app); + assert!(app.ui.transform.is_none(), "the box closed: {}", app.ui.status); +} + +fn path1(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").map(|p| p.path.clone()).expect("Path 1 is there") +} + +fn work_path(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.work_path.clone().expect("the work path is there") +} + +fn anchors(path: &Path, sub: usize) -> Vec<[f64; 2]> { + path.subpaths[sub].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn knot(path: &Path, sub: usize, knot: usize) -> (photocraft_geom::Point, photocraft_geom::Point, photocraft_geom::Point) { + let k = &path.subpaths[sub].knots[knot]; + (k.anchor, k.in_ctrl, k.out_ctrl) +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn last_step(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.undo_label().map(str::to_string) +} + +/// The measured row: the box frames the two selected anchors, not all of Path 1. +#[test] +fn the_box_frames_the_selected_anchors() { + let mut app = saved_path_app(); + select_two_corners(&mut app); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 300.0, 500.0], "the box spans 100,300 to 300,500"); + assert_eq!(box_params(&app), json!({"name": "Path 1", "anchors": [[0, 1], [0, 3]]}), "the box names the selected anchors"); +} + +/// The measured row: W 50 % (linked) and Enter moves the selected anchors about the centre of the +/// selection; the unselected anchors of the square and the other subpath stay where they are. +#[test] +fn a_half_wide_box_moves_only_the_selected_anchors() { + let mut app = saved_path_app(); + select_two_corners(&mut app); + open_box(&mut app); + // Half the width and half the height about the centre (200,400) of the selected anchors. + set_box(&mut app, [[150.0, 350.0], [250.0, 350.0], [250.0, 450.0], [150.0, 450.0]]); + commit_box(&mut app); + let p = path1(&app); + assert_eq!(anchors(&p, 0), vec![[100.0, 300.0], [250.0, 350.0], [300.0, 500.0], [150.0, 450.0]], "only the selected corners moved"); + assert_eq!(anchors(&p, 1), vec![[400.0, 300.0], [700.0, 300.0]], "the other subpath is untouched"); +} + +/// The measured row: one History step, named "Transform Points". +#[test] +fn the_point_transform_is_one_history_step_named_transform_points() { + let mut app = saved_path_app(); + let before = steps(&app); + select_two_corners(&mut app); + assert_eq!(steps(&app), before, "selecting anchors changes nothing"); + open_box(&mut app); + set_box(&mut app, [[150.0, 350.0], [250.0, 350.0], [250.0, 450.0], [150.0, 450.0]]); + commit_box(&mut app); + assert_eq!((steps(&app), last_step(&app).as_deref()), (before + 1, Some("Transform Points")), "{}", app.ui.status); + assert!(app.session.undo(), "the step undoes"); + assert_eq!(anchors(&path1(&app), 0), vec![[100.0, 300.0], [300.0, 300.0], [300.0, 500.0], [100.0, 500.0]], "Undo restores the square"); +} + +/// The Done-when row "with their own handles": a selected smooth anchor's direction handles follow +/// the box; the anchors and knots outside the selection do not move. +#[test] +fn a_selected_anchor_moves_its_own_handles() { + let mut app = work_path_app(); + click(&mut app, [120.0, 40.0], Modifiers::NONE); + click(&mut app, [120.0, 120.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [0, 2]]); + open_box(&mut app); + // The box covers the two anchors and the selected knot's handles: 100,40 to 140,120. + assert_eq!(box_rect(&app), [100.0, 40.0, 140.0, 120.0]); + // Twice as wide: the anchors sit on the box's centre line, so only the handles move in x. + set_box(&mut app, [[80.0, 40.0], [160.0, 40.0], [160.0, 120.0], [80.0, 120.0]]); + commit_box(&mut app); + let p = work_path(&app); + let (anchor, handle_in, handle_out) = knot(&p, 0, 1); + assert_eq!([anchor.x, anchor.y], [120.0, 40.0]); + assert_eq!([handle_in.x, handle_in.y], [80.0, 40.0], "the in handle followed the box"); + assert_eq!([handle_out.x, handle_out.y], [160.0, 40.0], "the out handle followed the box"); + assert_eq!(anchors(&p, 0), vec![[40.0, 40.0], [120.0, 40.0], [120.0, 120.0], [40.0, 120.0]], "the unselected anchors stayed"); + let (corner, corner_in, corner_out) = knot(&p, 0, 0); + assert_eq!([(corner.x, corner.y), (corner_in.x, corner_in.y), (corner_out.x, corner_out.y)], [(40.0, 40.0), (40.0, 40.0), (40.0, 40.0)]); + assert!(app.session.undo(), "one Undo takes the point transform back"); + let (anchor, handle_in, handle_out) = knot(&work_path(&app), 0, 1); + assert_eq!( + [(anchor.x, anchor.y), (handle_in.x, handle_in.y), (handle_out.x, handle_out.y)], + [(120.0, 40.0), (100.0, 40.0), (140.0, 40.0)], + "Undo restores the anchor and both handles" + ); +} + +/// Neighbour: with nothing selected, ⌘T keeps today's whole-path transform and today's step name. +#[test] +fn nothing_selected_transforms_the_whole_path() { + let mut app = saved_path_app(); + let before = steps(&app); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "the box frames all of Path 1"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "no anchors are named"); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!((steps(&app), last_step(&app).as_deref()), (before + 1, Some("Transform Path"))); + let p = path1(&app); + assert_eq!(anchors(&p, 0), vec![[250.0, 300.0], [350.0, 300.0], [350.0, 500.0], [250.0, 500.0]], "the whole square moved"); + assert_eq!(anchors(&p, 1), vec![[400.0, 300.0], [550.0, 300.0]], "and the line with it"); +} + +/// Neighbour: Path Selection is untouched by the point decision, even with a path targeted. +#[test] +fn path_selection_transforms_the_whole_path() { + let mut app = saved_path_app(); + app.ui.tool = Tool::PathSelection; + let before = steps(&app); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0]); + assert_eq!(box_params(&app), json!({"name": "Path 1"})); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!((steps(&app), last_step(&app).as_deref()), (before + 1, Some("Transform Path"))); + assert_eq!(anchors(&path1(&app), 0), vec![[250.0, 300.0], [350.0, 300.0], [350.0, 500.0], [250.0, 500.0]]); +} + +/// Neighbour the ticket leaves unmeasured: anchors on several subpaths keep today's whole-path +/// transform. +#[test] +fn anchors_on_two_subpaths_keep_the_whole_path() { + let mut app = saved_path_app(); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + click(&mut app, [400.0, 300.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [1, 0]], "one anchor in each subpath"); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "the box still frames the whole path"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "no anchors are named"); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!(last_step(&app).as_deref(), Some("Transform Path")); + assert_eq!(anchors(&path1(&app), 0), vec![[250.0, 300.0], [350.0, 300.0], [350.0, 500.0], [250.0, 500.0]]); + assert_eq!(anchors(&path1(&app), 1), vec![[400.0, 300.0], [550.0, 300.0]]); +} + +/// Neighbour the ticket leaves unmeasured: a segment selected on its own keeps today's whole-path +/// transform. +#[test] +fn a_segment_selection_keeps_the_whole_path() { + let mut app = saved_path_app(); + click(&mut app, [200.0, 300.0], Modifiers::NONE); + assert!(app.ui.direct_selection.anchors.is_empty(), "a segment click selects no anchor"); + assert_eq!(app.ui.direct_selection.segment, Some([0, 0]), "the segment between knots 0 and 1"); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0]); + assert_eq!(box_params(&app), json!({"name": "Path 1"})); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!(anchors(&path1(&app), 0), vec![[250.0, 300.0], [350.0, 300.0], [350.0, 500.0], [250.0, 500.0]]); +} + +/// Neighbour: the box keeps the anchor selection while it is open and leaves it, as a path transform +/// does today, when it commits. Same for the whole-path transform of the unmeasured multi-subpath +/// selection, so the point decision changes nothing there. +#[test] +fn the_transform_leaves_the_anchor_selection_as_a_path_transform_does() { + let mut app = saved_path_app(); + select_two_corners(&mut app); + open_box(&mut app); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [0, 3]], "the selection stands while the box is open"); + set_box(&mut app, [[150.0, 350.0], [250.0, 350.0], [250.0, 450.0], [150.0, 450.0]]); + commit_box(&mut app); + assert_eq!(app.ui.direct_selection.anchors, Vec::<[usize; 2]>::new(), "the box ends the selection, as a path transform does"); + + let mut app = saved_path_app(); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + click(&mut app, [400.0, 300.0], Modifiers::SHIFT); + open_box(&mut app); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!(app.ui.direct_selection.anchors, Vec::<[usize; 2]>::new(), "and the same with the whole-path transform"); +} + +/// The command on its own: `path.transform` with `anchors` pivots numeric scaling on the centre of +/// the anchors it names, which is how the measured box move comes out. +#[test] +fn the_command_transforms_named_anchors_about_their_own_centre() { + let mut app = saved_path_app(); + app.run("path.transform", json!({"name": "Path 1", "anchors": [[0, 1], [0, 3]], "scaleX": 0.5, "scaleY": 0.5})).expect("the anchors scale"); + let p = path1(&app); + assert_eq!(anchors(&p, 0), vec![[100.0, 300.0], [250.0, 350.0], [300.0, 500.0], [150.0, 450.0]]); + assert_eq!(anchors(&p, 1), vec![[400.0, 300.0], [700.0, 300.0]], "the unlisted subpath is untouched"); + assert_eq!(last_step(&app).as_deref(), Some("Transform Points")); +} + +/// Hostile params: an anchor list the path does not have is an error, never a whole-path transform +/// and never a panic. +#[test] +fn anchors_off_the_path_are_an_error() { + let mut app = saved_path_app(); + let (before, n) = (path1(&app), steps(&app)); + for bad in [ + json!({"name": "Path 1", "anchors": [[9, 0]], "matrix": [1, 0, 0, 1, 5, 0]}), + json!({"name": "Path 1", "anchors": [[0, 9]], "matrix": [1, 0, 0, 1, 5, 0]}), + json!({"name": "Path 1", "anchors": [], "matrix": [1, 0, 0, 1, 5, 0]}), + json!({"name": "Path 1", "anchors": [[0]], "matrix": [1, 0, 0, 1, 5, 0]}), + json!({"name": "Path 1", "anchors": "0,1", "matrix": [1, 0, 0, 1, 5, 0]}), + ] { + assert!(app.run("path.transform", bad.clone()).is_err(), "{bad} is refused"); + } + assert_eq!(path1(&app), before, "nothing moved"); + assert_eq!(steps(&app), n, "and no step was added"); +} + +/// The box needs an area to work in: one straight anchor spans none, so that selection keeps today's +/// whole-path transform. The reference application was not measured with a frame-less selection. +#[test] +fn one_anchor_selected_keeps_the_whole_path() { + let mut app = saved_path_app(); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "one straight anchor is selected"); + let before = steps(&app); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "the box frames the whole path"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "no anchors are named"); + // Drag the box 20 right and 20 down, OK: every anchor of Path 1 follows. + move_box(&mut app, 20.0, 20.0); + commit_box(&mut app); + assert_eq!((steps(&app), last_step(&app).as_deref()), (before + 1, Some("Transform Path"))); + assert_eq!(anchors(&path1(&app), 0), vec![[120.0, 320.0], [320.0, 320.0], [320.0, 520.0], [120.0, 520.0]]); + assert_eq!(anchors(&path1(&app), 1), vec![[420.0, 320.0], [720.0, 320.0]], "the line moved with it"); +} + +/// Two anchors on one line span an area of nothing either: the same whole-path transform. +#[test] +fn collinear_anchors_keep_the_whole_path() { + let mut app = saved_path_app(); + click(&mut app, [100.0, 300.0], Modifiers::NONE); + click(&mut app, [300.0, 300.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 0], [0, 1]], "both top corners"); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "the box frames the whole path"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "no anchors are named"); + set_box(&mut app, [[250.0, 300.0], [550.0, 300.0], [550.0, 500.0], [250.0, 500.0]]); + commit_box(&mut app); + assert_eq!(last_step(&app).as_deref(), Some("Transform Path")); + assert_eq!(anchors(&path1(&app), 0), vec![[250.0, 300.0], [350.0, 300.0], [350.0, 500.0], [250.0, 500.0]]); + assert_eq!(anchors(&path1(&app), 1), vec![[400.0, 300.0], [550.0, 300.0]]); +} + +/// Path Selection's component pick fills the same anchor list; the tool is checked first, so Ctrl+T +/// keeps the whole-path transform. +#[test] +fn a_path_selection_component_pick_keeps_the_whole_path() { + let mut app = saved_path_app(); + app.ui.tool = Tool::PathSelection; + click(&mut app, [200.0, 400.0], Modifiers::NONE); + assert!(!app.ui.direct_selection.anchors.is_empty(), "the component pick writes the anchors it covers"); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "the box frames the whole path"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "no anchors are named"); + move_box(&mut app, 20.0, 20.0); + commit_box(&mut app); + assert_eq!(last_step(&app).as_deref(), Some("Transform Path")); + assert_eq!(anchors(&path1(&app), 0), vec![[120.0, 320.0], [320.0, 320.0], [320.0, 520.0], [120.0, 520.0]]); + assert_eq!(anchors(&path1(&app), 1), vec![[420.0, 320.0], [720.0, 320.0]]); +} + +/// #13284 makes Path Selection with Ctrl held act as Direct Selection, and the anchor it presses ends +/// up in that same list. The free-transform entry reads the tool in hand, so this keeps today's +/// whole-path transform; asked on the issue whether the held tool should decide instead. +#[test] +fn path_selection_with_ctrl_held_keeps_the_whole_path() { + let mut app = saved_path_app(); + app.ui.tool = Tool::PathSelection; + click(&mut app, [300.0, 300.0], Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "the Ctrl press selected the anchor"); + open_box(&mut app); + assert_eq!(box_rect(&app), [100.0, 300.0, 700.0, 500.0], "today: the box frames the whole path"); + assert_eq!(box_params(&app), json!({"name": "Path 1"}), "today: no anchors are named"); +} + +/// Neighbour the ticket leaves unmeasured: anchors selected on a shape layer's path keep today's +/// whole-path box, params and step name. +#[test] +fn anchors_on_a_shape_layer_keep_the_whole_path() { + let mut app = shape_app(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + click(&mut app, [750.0, 50.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(crate::direct_select::PathRef::Layer(layer.0)), "the shape path is targeted"); + let selected = app.ui.direct_selection.anchors.clone(); + assert_eq!(selected.len(), 1, "the corner anchor is selected"); + let before = steps(&app); + open_box(&mut app); + assert_eq!(box_rect(&app), [550.0, 50.0, 750.0, 200.0], "the box frames the whole shape path"); + assert_eq!(box_params(&app), json!({"name": "layer", "layer": layer.0}), "no anchors are named"); + move_box(&mut app, 20.0, 20.0); + commit_box(&mut app); + assert_eq!((steps(&app), last_step(&app).as_deref()), (before + 1, Some("Transform Path")), "{}", app.ui.status); + let shape = app.session.active().unwrap().doc.layer(layer).and_then(|l| match &l.content { + photocraft_doc::LayerContent::Shape(sh) => Some(sh.path.clone()), + _ => None, + }); + let p = shape.expect("the layer is still a shape"); + let mut moved: Vec<[f64; 2]> = p.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + moved.sort_by(|a, b| a[0].partial_cmp(&b[0]).unwrap().then(a[1].partial_cmp(&b[1]).unwrap())); + assert_eq!(moved, vec![[570.0, 70.0], [570.0, 220.0], [770.0, 70.0], [770.0, 220.0]], "the whole rect moved"); +} diff --git a/crates/ui-egui/src/tools/gradient_ui/bar.rs b/crates/ui-egui/src/tools/gradient_ui/bar.rs index d7d5fa912d..a971b1de93 100644 --- a/crates/ui-egui/src/tools/gradient_ui/bar.rs +++ b/crates/ui-egui/src/tools/gradient_ui/bar.rs @@ -3,6 +3,7 @@ //! and Dither. use craft::behavior::IconId; +use craft::color_ui::ui::gradient::GradientStops; use craft::draw::ui::gradient::{GradientFillWords, GradientStyle, GradientSwatch}; use craft::ui::buttons::IconButton; use craft::ui::choice::{Checkbox, Segmented}; @@ -21,12 +22,18 @@ use super::{fill_layer_active, options_changed, stops}; use crate::state::Tool; use crate::{PhotocraftApp, panel_docking}; +/// The modes a layer mask has no use for: they need colour (#18634). The reference greys them, with Behind, while a +/// layer mask is the target. +const COLOUR_MODES: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + /// The modes the Classic gradient lists, with a rule above each group: `None` is Behind, third /// after Normal and Dissolve, and greyed where `behind_enabled` is false (the Background, as the -/// Paint Bucket's). The list has no Clear (#12011). -fn blend_modes(behind_enabled: bool) -> Vec>> { - static CACHE: crate::i18n::LangCache>>> = crate::i18n::LangCache::new(); - CACHE.get_or_build(behind_enabled, || { +/// Paint Bucket's). The list has no Clear (#12011). With `on_mask` (a layer mask targeted) the +/// [`COLOUR_MODES`] are greyed too. +fn blend_modes(behind_enabled: bool, on_mask: bool) -> Vec>> { + static CACHE: crate::i18n::LangCache<(bool, bool), Vec>>> = crate::i18n::LangCache::new(); + CACHE.get_or_build((behind_enabled, on_mask), || { let mut keys: Vec>> = crate::blend_keys::tool_modes(Tool::Gradient) .unwrap_or_default() .into_iter() @@ -37,11 +44,23 @@ fn blend_modes(behind_enabled: bool) -> Vec>> { keys.insert(at, BlendKeyEntry::behind(None)); blend_entries(&keys, |entry| Label::from(tl!(entry.key.map_or("Behind", BlendMode::label)).to_string())) .into_iter() - .map(|entry| if entry.value() == Some(&None) { entry.enabled(behind_enabled) } else { entry }) + .map(|entry| match entry.value().copied() { + Some(None) => entry.enabled(behind_enabled), + Some(Some(mode)) if on_mask && COLOUR_MODES.contains(&mode) => entry.enabled(false), + _ => entry, + }) .collect() }) } +/// The Classic gradient's Mode list for the current target. +pub(crate) fn mode_entries(app: &PhotocraftApp) -> Vec>> { + // Behind paints under a layer's pixels: greyed on a mask, a channel or Quick Mask, as the engine refuses it there. + let target = crate::canvas::paint_target(app); + let pixels = target == serde_json::json!("pixels"); + blend_modes(pixels && crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), target == serde_json::json!("mask")) +} + /// `add` captioned `label` as a field of the bar. fn labelled(ui: &mut egui::Ui, label: &str, mut add: impl FnMut(&mut egui::Ui)) { Field::new(label.to_owned()).show(ui, |ui, _| add(ui)); @@ -55,13 +74,12 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let locked_live = fill_layer_active(app); let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); let tool_stops = stops::of_preset(&app.session.presets().gradient, fg, bg); - let sampler = stops::sampler(fg, bg); + let sample = stops::sampler(fg, bg); let words = Env::of(ui).words::(); let styles: Vec> = GradientStyle::ALL.iter().map(|style| Entry::new(*style, style.label(&words)).icon(style.icon())).collect(); let modes = [Entry::new(false, tl!("Gradient").to_owned()), Entry::new(true, tl!("Classic gradient").to_owned())]; - // Behind paints under a layer's pixels: greyed on a mask, a channel or Quick Mask, as the engine refuses it there. let pixels = crate::canvas::paint_target(app) == serde_json::json!("pixels"); - let blends = blend_modes(pixels && crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind)); + let blends = mode_entries(app); let open_editor; let presets; { @@ -72,6 +90,11 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if !locked_live && classic != app.ui.tool_options.gradient_classic { app.ui.tool_options.gradient_classic = classic; } + let opacity = if classic { app.ui.tool_options.fill_opacity.clamp(0.0, 100.0) / 100.0 } else { 1.0 }; + let sampler = move |stops: &GradientStops, at| { + let color = sample(stops, at); + color.with_alpha(color.a * opacity) + }; let swatch = GradientSwatch::new(tl!("Gradient picker").to_string(), &tool_stops).sampler(&sampler).show(ui); open_editor = swatch.clicked; presets = preset_arrow(ui, swatch.response.rect); @@ -117,9 +140,17 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(at) = presets { preset_picker(app, ui, at); } + if before.fill_opacity != app.ui.tool_options.fill_opacity { + // The swatch painted before the Opacity field accepted the edit. + craft::ui::runtime::frame::request_repaint(ui.ctx()); + } options_changed(app, &before); } +#[cfg(test)] +#[path = "../../gradient_preview_swatch_opacity_tests.rs"] +mod gradient_preview_swatch_opacity_tests; + /// The gradient preset picker's open state between passes, kept in egui's memory: it is the bar's popup, not a setting. #[derive(Clone, Copy, Default)] struct PresetPopup { @@ -171,3 +202,7 @@ fn preset_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Pos2) { keep_popup(ui, PresetPopup { open: false, ..popup }); } } + +#[cfg(test)] +#[path = "../../gradient_mask_target_greyed_modes_tests.rs"] +mod gradient_mask_target_greyed_modes_tests; diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 6033d2622e..9443ee4497 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -128,6 +128,9 @@ pub struct OpenPreview { tool: Tool, /// Free Transform Path: the path as it was, drawn through the box instead of pixels. path: Option, + /// Free Transform Points (#13209): the anchors of that path the box moves, `[subpath, knot]`. + /// Set, the outline follows the box only there and the rest of the path stays put. + path_points: Option>, /// A layer's session keeps `doc` and `opacity` up to date with edits made while the box is /// open ([`follow_edits`]); `None` for a lone mask or channel and Transform Selection. follow: Option, @@ -159,6 +162,7 @@ impl OpenPreview { warp_grid: warp::GridSelection::default(), tool, path: None, + path_points: None, follow: None, committing: None, content_aware: None, diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index a6a3bf7bba..5ab3a0206f 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -619,8 +619,12 @@ fn begin_lone( /// Edit › Free Transform Path: the box frames the path's anchors and handles and draws the /// path through it; OK commits one `path.transform` step. +/// +/// Free Transform Points (#13209): the params can name anchors, in which case the box frames those +/// anchors and OK transforms only them. fn begin_path(app: &mut PhotocraftApp, params: serde_json::Value, path: photocraft_doc::vector::Path) -> Result<(), String> { - let (x0, y0, x1, y1) = path.control_bounds().ok_or("the path has no points to transform")?; + let (x0, y0, x1, y1) = + crate::vector_ui::free_transform_point_bounds(¶ms, &path).or_else(|| path.control_bounds()).ok_or("the path has no points to transform")?; let st = app.session.active().ok_or("no document")?; let doc = st.doc.clone(); let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?; @@ -633,7 +637,11 @@ fn begin_path(app: &mut PhotocraftApp, params: serde_json::Value, path: photocra format!("transform-{session}"), PreviewPixels::new(egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]), ); - app.transform_preview = Some(OpenPreview { path: Some(path), ..OpenPreview::new(session, doc, textures, app.ui.tool) }); + app.transform_preview = Some(OpenPreview { + path: Some(path), + path_points: crate::vector_ui::free_transform_point_anchors(¶ms), + ..OpenPreview::new(session, doc, textures, app.ui.tool) + }); app.ui.transform = Some(FreeTransform { session: open_session(app, rect, BoxAllow::default(), true), id: session, diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 71356fd576..76b9fb11e1 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -321,10 +321,36 @@ fn path_outline(t: &FreeTransform, pv: &OpenPreview) -> Option { (Box::new(move |p| h.apply_in_front(p, rect)), false) } }; + // Free Transform Points (#13209): the box carries only the anchors it was opened on, so those + // points go through its map here and the outline of the whole path is drawn where it then stands. + let (source, map, bends) = match pv.path_points.as_deref() { + Some(anchors) => (points_through_box(source, anchors, &*map), Box::new(stays_where_it_is) as Box Option>, false), + None => (source, map, bends), + }; let subpaths = source.subpaths.iter().flat_map(|sub| mapped_runs(&flatten(sub, bends), sub.closed, &*map)).collect(); Some(EditPath::new(source.key, subpaths).colored(source.color)) } +/// The map of a point transform's outline: the points it leaves alone keep their place. +fn stays_where_it_is(p: Point) -> Option { + Some(p) +} + +/// Free Transform Points (#13209): `source` with the knots `anchors` names put where the box puts +/// them — each named knot's anchor and its own handles follow the map, every other point of the path +/// stays exactly where it is. A point the map sends behind a Distort's horizon keeps its place. +fn points_through_box(mut source: EditPath, anchors: &[[usize; 2]], map: &dyn Fn(Point) -> Option) -> EditPath { + for &[sub, knot] in anchors { + let Some(node) = source.subpaths.get_mut(sub).and_then(|sub| sub.knots.get_mut(knot)) else { continue }; + for p in [&mut node.anchor, &mut node.in_ctrl, &mut node.out_ctrl] { + if let Some(q) = map(*p) { + *p = q; + } + } + } + source +} + /// `sub`'s outline as points: each segment's start, and for a curved segment (or any segment when /// `bends`, since the map then bends a straight one) points along it. An open subpath ends with /// its last anchor. diff --git a/crates/ui-egui/src/tools/type_tool/character_panel_digits_tests.rs b/crates/ui-egui/src/tools/type_tool/character_panel_digits_tests.rs new file mode 100644 index 0000000000..1e35edee68 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/character_panel_digits_tests.rs @@ -0,0 +1,68 @@ +//! The Character panel's Digits select (#10996): it shows the selected layer's digit style, and a pick restyles the +//! selected type layer's digits through the type command, in one history step. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use photocraft_doc::LayerId; +use photocraft_doc::text::Digits; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::BuildApp; + +const SELECT: &str = "Digits"; + +/// One selected type layer with digits in its text. +fn one_layer() -> (Box, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Type; + let made = app.run("type.create", json!({"text": "Room 42", "font": "Inter", "size": 24, "x": 40, "y": 80})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + (app, id) +} + +fn harness(app: Box) -> Harness<'static, Box> { + // Wait for the font scan: while it runs the panels repaint every 100 ms and `Harness::run` gives up. + let _ = photocraft_text::shared(); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(760.0, 1200.0)).with_max_steps(16).build_app( + move |ui, app: &mut PhotocraftApp| { + ui.set_width(340.0); + super::character_panel(app, ui, false); + }, + app, + ); + h.run_steps(4); + h +} + +fn digits(app: &PhotocraftApp, id: LayerId) -> Vec { + let text = super::super::text_layer(&app.session.active().unwrap().doc, id).unwrap(); + text.char_runs().into_iter().map(|r| r.style.digits).collect() +} + +fn shown(h: &Harness<'static, Box>) -> String { + h.get_by_role_and_label(Role::ComboBox, SELECT).value().unwrap_or_default() +} + +#[test] +fn a_digits_pick_restyles_the_selected_layer_in_one_history_step() { + let (app, id) = one_layer(); + let before = digits(&app, id); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = harness(app); + let was = shown(&h); + h.get_by_role_and_label(Role::ComboBox, SELECT).click(); + h.run(); + h.get_by_role_and_label(Role::ListBoxOption, "Devanagari").click(); + h.run(); + let after = digits(h.state(), id); + assert_ne!(after, before, "the pick changed the layer's digits"); + assert!(after.iter().all(|d| *d == Digits::Devanagari), "every run takes the picked style: {after:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1, "one history step"); + assert_ne!(shown(&h), was, "the select shows the new style"); +} diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 06b1678265..568d2cad6c 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -240,6 +240,8 @@ pub(super) fn apply(app: &mut PhotocraftApp, props: serde_json::Value, coalesce: if insertion_style::set_font(app, &props) { return; } + // A font chosen at the caret and not yet typed outlives another character change there (#10996). + let kept = insertion_style::pending(app).cloned(); app.ui.type_insertion_style = None; let Some(mut p) = formatting_params(app) else { apply_defaults(app, &props); @@ -253,7 +255,11 @@ pub(super) fn apply(app: &mut PhotocraftApp, props: serde_json::Value, coalesce: if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()).or(coalesce) { p["coalesce"] = json!(key); } - let _ = app.run("type.setStyle", p); + if app.run("type.setStyle", p).is_ok() + && let Some(kept) = kept + { + insertion_style::rebase(app, kept, &props); + } } /// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index 9d1c96e054..81fa78c371 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -385,3 +385,52 @@ fn an_existing_empty_layer_keeps_its_font_when_committed() { assert_eq!(families(&saved(&h, id)), [FONTS[1]]); } } + +/// A font chosen at the caret survives a Digits change there before typing (#10996): the typed digit takes the +/// chosen font and the picked digit style. +#[test] +fn a_digits_change_at_the_caret_keeps_the_chosen_typing_font() { + let (mut h, id) = fixture(0, "abcdef"); + select(&mut h, [3, 3]); + h.run(); + choose(&mut h, FONTS[1], "enter"); + assert!(super::insertion_style::pending(h.state()).is_some(), "a pending font at the caret"); + super::apply(h.state_mut(), json!({"digits": "devanagari"}), None); + assert!(super::insertion_style::pending(h.state()).is_some(), "the Digits change keeps the pending font"); + super::host::type_text(h.state_mut(), "5"); + h.run(); + assert_eq!(families(&saved(&h, id))[3], FONTS[1], "the typed digit takes the chosen font"); + let t = layer(&h.state().session.active().unwrap().doc, id); + let mut offset = 0; + let digits = t.char_runs().into_iter().find_map(|r| { + offset += r.len; + (offset > 3).then_some(r.style.digits) + }); + assert_eq!(digits, Some(photocraft_doc::text::Digits::Devanagari), "the typed digit takes the picked digit style"); +} + +/// An axis change at the caret after a font was chosen there wins over the chosen font's saved axes; the axes it does +/// not set keep their chosen values. +#[test] +fn an_axis_change_at_the_caret_keeps_its_value_with_the_chosen_typing_font() { + let (mut h, id) = fixture(0, "abcdef"); + h.state_mut().run("type.setStyle", json!({"layer": id.0, "variations": {"wght": 650, "wdth": 95}})).unwrap(); + select(&mut h, [3, 3]); + h.run(); + choose(&mut h, FONTS[1], "enter"); + super::apply(h.state_mut(), json!({"variations": {"wdth": 110}}), None); + super::host::type_text(h.state_mut(), "X"); + h.run(); + assert_eq!(families(&saved(&h, id))[3], FONTS[1], "the typed letter takes the chosen font"); + let mut offset = 0; + let axes = layer(&h.state().session.active().unwrap().doc, id) + .char_runs() + .into_iter() + .find_map(|r| { + offset += r.len; + (offset > 3).then_some(r.style.variations) + }) + .unwrap(); + assert!(axes.iter().any(|v| v.axis == "wdth" && v.value == 110.0), "the changed axis holds: {axes:?}"); + assert!(axes.iter().any(|v| v.axis == "wght" && v.value == 650.0), "an axis the change left keeps its value: {axes:?}"); +} diff --git a/crates/ui-egui/src/tools/type_tool/insertion_style.rs b/crates/ui-egui/src/tools/type_tool/insertion_style.rs index 05a2624c99..aa6e023bd0 100644 --- a/crates/ui-egui/src/tools/type_tool/insertion_style.rs +++ b/crates/ui-egui/src/tools/type_tool/insertion_style.rs @@ -49,6 +49,33 @@ pub(super) fn set_font(app: &mut PhotocraftApp, props: &serde_json::Value) -> bo true } +/// Keeps the caret's pending font `kept` after another character change at the same caret: the style the command +/// stored there (in the layer's own units) with the chosen font on it, for the new revision, so the next typed text +/// still takes the chosen font and the change. +pub(super) fn rebase(app: &mut PhotocraftApp, mut kept: TypeInsertionStyle, props: &serde_json::Value) { + let Some((mut style, _)) = styles_at(app) else { return }; + let Some(st) = app.session.active() else { return }; + let chosen = &kept.style; + style.font_family.clone_from(&chosen.font_family); + style.weight = chosen.weight; + style.italic = chosen.italic; + style.postscript_name.clone_from(&chosen.postscript_name); + style.variations.clone_from(&chosen.variations); + // An axis the change set itself wins over the chosen font's saved value; the others stay as chosen. + if let Some(axes) = props.get("variations").and_then(serde_json::Value::as_object) { + for (axis, value) in axes { + let Some(value) = value.as_f64() else { continue }; + match style.variations.iter_mut().find(|v| v.axis == *axis) { + Some(v) => v.value = value as f32, + None => style.variations.push(photocraft_doc::text::FontVariation { axis: axis.clone(), value: value as f32 }), + } + } + } + kept.style = style; + kept.revision = st.revision; + app.ui.type_insertion_style = Some(kept); +} + /// How many characters `text` adds once the engine stores it: a CRLF pair becomes one `\n` (a lone CR is one /// character either way), so a pasted Windows line break moves the caret by one, not two. pub(super) fn stored_chars(text: &str) -> usize { diff --git a/crates/ui-egui/src/tools/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs index e9eb1a7d1f..32cb870607 100644 --- a/crates/ui-egui/src/tools/type_tool/panel.rs +++ b/crates/ui-egui/src/tools/type_tool/panel.rs @@ -78,7 +78,8 @@ fn character_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, unit: DocUnit, let styles = values::style_names(app, &shown); let face = values::face_axes(app); let mut font_state = fonts::font_state(app); - let mut controls = CharacterControls::new(tl!("Character"), &shown, &families, &styles).unit(unit); + let digits = values::digit_entries(); + let mut controls = CharacterControls::new(tl!("Character"), &shown, &families, &styles).unit(unit).digits(&digits); controls = controls.font_picker(font_state.source()); if let Some(face) = &face { controls = controls.axes(face.view()); @@ -147,6 +148,10 @@ fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } +#[cfg(test)] +#[path = "character_panel_digits_tests.rs"] +mod character_panel_digits_tests; + #[cfg(test)] #[path = "character_panel_anti_alias_tests.rs"] mod character_panel_anti_alias_tests; diff --git a/crates/ui-egui/src/tools/type_tool/values.rs b/crates/ui-egui/src/tools/type_tool/values.rs index c9bdb4fe9e..6653f9db7d 100644 --- a/crates/ui-egui/src/tools/type_tool/values.rs +++ b/crates/ui-egui/src/tools/type_tool/values.rs @@ -16,14 +16,14 @@ use craft::text::ui::character::{ use craft::text::ui::type_bar::TypeBarChange; use craft::text::ui::type_options::{TextAntiAlias, TextOrientation}; use craft::ui::runtime::env::UnitKind; -use photocraft_doc::text::{CharStyle, ParagraphStyle}; +use photocraft_doc::text::{CharStyle, Digits, ParagraphStyle}; use super::defaults::{apply, default_styles, formatting_params, open_color_picker, shown_scale, target, target_doc, target_text}; use super::fonts; use super::options_bar::{kerning_at, styles_at}; use super::panel::{OPENTYPE_BUTTONS, toggle_opentype}; use super::{LayerId, PhotocraftApp, byte_of, json, text_layer}; -use crate::panels::type_panels_ui::style_options::{character_values as style_character_values, paragraph_values as style_paragraph_values}; +use crate::panels::type_panels_ui::style_options::{character_values as style_character_values, digit_name, paragraph_values as style_paragraph_values}; /// The unit the type controls show lengths in (Preferences ▸ Units & Rulers ▸ Type); pixels follow the document's /// resolution. Values stay in points. @@ -93,6 +93,27 @@ fn runs_at_target(app: &PhotocraftApp) -> Option<(Vec, Vec Vec<(String, String)> { + [ + (Digits::AsTyped, tl!("As Typed")), + (Digits::Western, tl!("Western")), + (Digits::Contextual, tl!("Contextual")), + (Digits::Devanagari, tl!("Devanagari")), + (Digits::Bengali, tl!("Bengali")), + (Digits::Gurmukhi, tl!("Gurmukhi")), + (Digits::Gujarati, tl!("Gujarati")), + (Digits::Odia, tl!("Odia")), + (Digits::Tamil, tl!("Tamil")), + (Digits::Telugu, tl!("Telugu")), + (Digits::Kannada, tl!("Kannada")), + (Digits::Malayalam, tl!("Malayalam")), + ] + .into_iter() + .map(|(d, label)| (digit_name(d).to_string(), label.to_string())) + .collect() +} + /// The character values at the target: equal values shown, differing ones mixed. Sizes show as the layer appears /// (a 12 pt layer scaled 200 % reads 24 pt). pub(crate) fn character_values(app: &PhotocraftApp) -> CharacterValues { @@ -305,6 +326,7 @@ fn character_step(change: &CharacterChange) -> Option { CharacterChange::Strikethrough(on) => json!({"strikethrough": on}), CharacterChange::OpenType { tag, on, .. } => return Some(Step::OpenType { tag, on: *on }), CharacterChange::Language(tag) => json!({"language": tag}), + CharacterChange::Digits(tag) => json!({"digits": tag}), CharacterChange::Axes(axes) => { let map: serde_json::Map = axes.iter().map(|(tag, v)| (String::from_utf8_lossy(tag).trim().to_string(), json!(v))).collect(); diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 8907a7acd5..7f33f0094f 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -39,8 +39,8 @@ pub use path_ops::{ active_path_name, make_shape, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path, }; pub(crate) use path_ops::{ - active_shape_path, active_type_path, delete_key_edits_path, deselect_loaded_path, edit_path, free_transform_path, saved_path_components_selected, - targeted_vector_mask, work_path_shown, + active_shape_path, active_type_path, delete_key_edits_path, deselect_loaded_path, edit_path, free_transform_path, free_transform_point_anchors, + free_transform_point_bounds, saved_path_components_selected, targeted_vector_mask, work_path_shown, }; pub use paths_panel::{PathEntry, PathRow, path_rows, paths_panel}; #[cfg(test)] diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index 44a66ca2d6..74be4164c7 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -349,13 +349,93 @@ pub(crate) fn edit_path(path: &Path, key: u64) -> EditPath { /// Edit › Free Transform Path (⌘T with Path Selection or Direct Selection): the path the /// box transforms (the one Path Selection edits) and `path.transform`'s params that name it. +/// +/// Free Transform Points (#13209): when Direct Selection has anchors selected on that same path, the +/// params name those anchors as well, so the box transforms only them, and +/// [`free_transform_point_bounds`] is the frame they span. The reference application was measured on +/// a work or saved path with every selected anchor in one subpath, no segment selected and a frame +/// that has an area; a shape layer's path, a vector mask, anchors across subpaths, a segment on its +/// own, a selection spanning no area (one straight anchor, anchors on one line) and no selection keep +/// today's whole-path transform. pub(crate) fn free_transform_path(app: &PhotocraftApp) -> Option<(Value, Path)> { if !matches!(app.ui.tool, Tool::PathSelection | Tool::DirectSelection) { return None; } let (target, path) = target_path(app)?; path.control_bounds()?; - Some((target.params(app), path)) + let mut params = target.params(app); + if let Some(anchors) = free_transform_anchor_selection(app, target, &path) { + params.as_object_mut()?.insert("anchors".into(), json!(anchors)); + } + Some((params, path)) +} + +/// The anchors Free Transform Points acts on: the tool's own anchor selection of the path the box +/// transforms, in the configuration the reference application was measured in. `None` keeps the +/// whole-path transform. Every index addresses a knot of `path` and the selection is still the one +/// this document and revision made, so a selection left over from elsewhere cannot name a point that +/// is not there. +fn free_transform_anchor_selection(app: &PhotocraftApp, target: PathRef, path: &Path) -> Option> { + if app.ui.tool != Tool::DirectSelection || !matches!(target, PathRef::Work | PathRef::Saved(_)) { + return None; + } + let ds = &app.ui.direct_selection; + if ds.editing.is_some() || ds.segment.is_some() || ds.target != Some(target) || !crate::direct_select::still_valid(app, ds) { + return None; + } + let anchors = &ds.anchors; + let [sub, _] = *anchors.first()?; + let mut out = Vec::with_capacity(anchors.len()); + for a in anchors { + let [s, k] = *a; + // Anchors on several subpaths were not measured: that selection keeps the whole path. + if s != sub { + return None; + } + path.subpaths.get(s)?.knots.get(k)?; + out.push([s, k]); + } + // A box needs an area to work in: one straight anchor, or anchors on one line, span none, and the + // session then has no map to move them by. That was not measured, so it keeps the whole path. + let (x0, y0, x1, y1) = point_frame(path, &out)?; + (x1 > x0 && y1 > y0).then_some(out) +} + +/// The anchors Free Transform Points params name (`[subpath, knot]`, as `path.moveAnchors` names +/// them); `None` when the params transform the whole path (#13209). +pub(crate) fn free_transform_point_anchors(params: &Value) -> Option> { + let list = params.get("anchors")?.as_array()?; + let mut out = Vec::with_capacity(list.len()); + for a in list { + let pair = a.as_array().filter(|pair| pair.len() == 2)?; + let (Some(s), Some(k)) = (pair[0].as_u64(), pair[1].as_u64()) else { return None }; + let (Ok(s), Ok(k)) = (usize::try_from(s), usize::try_from(k)) else { return None }; + out.push([s, k]); + } + (!out.is_empty()).then_some(out) +} + +/// The frame the Free Transform box opens over: the bounds of the anchors and their own handles the +/// params name (Free Transform Points, #13209), so the options bar reads the selection's X, Y, W and +/// H. `None` when the params name no anchors: the whole path's control bounds then frame the box. +pub(crate) fn free_transform_point_bounds(params: &Value, path: &Path) -> Option<(f64, f64, f64, f64)> { + point_frame(path, &free_transform_point_anchors(params)?) +} + +/// The bounds the knots `anchors` span: their anchors and their own handles, the same measure +/// [`Path::control_bounds`] is for the whole path. `None` when an index is not a knot of `path`. +fn point_frame(path: &Path, anchors: &[[usize; 2]]) -> Option<(f64, f64, f64, f64)> { + let mut frame: Option<(f64, f64, f64, f64)> = None; + for &[s, k] in anchors { + let node = path.subpaths.get(s)?.knots.get(k)?; + for p in [node.anchor, node.in_ctrl, node.out_ctrl] { + frame = Some(match frame { + Some((x0, y0, x1, y1)) => (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)), + None => (p.x, p.y, p.x, p.y), + }); + } + } + frame } fn point_in_subpath(sp: &photocraft_doc::vector::Subpath, pt: [f64; 2]) -> bool { diff --git a/crates/ui-egui/src/window_options_toggle_tests.rs b/crates/ui-egui/src/window_options_toggle_tests.rs new file mode 100644 index 0000000000..9152f0c614 --- /dev/null +++ b/crates/ui-egui/src/window_options_toggle_tests.rs @@ -0,0 +1,77 @@ +//! #16795: Window › Options shows and hides the options bar, its check mark follows the bar, and the +//! control channel drives it like the other Window toggles. + +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply, handle}; + +/// An app with a document open, so the options bar has a tool to show. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app +} + +/// The control channel's whole reply to `method` with `params`. +fn control(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = app.ctx().clone(); + let (request, _reply) = ControlRequest::new(method, params); + let Reply::Done(reply) = handle(app, &ctx, &request) else { panic!("{method} should reply at once") }; + reply +} + +/// Chooses menu item `id` through the control channel with the command's `params`, as a click on it does; its +/// result. +fn invoke(app: &mut PhotocraftApp, id: &str, params: Value) -> Value { + let reply = control(app, "ui.menu.invoke", json!({"id": id, "params": params})); + assert_eq!(reply["ok"], true, "{id}: {reply}"); + reply["result"].clone() +} + +/// Whether the menu shows `id` checked, as `ui.menu.list` reports it. +fn checked(app: &mut PhotocraftApp, id: &str) -> Value { + let list = control(app, "ui.menu.list", json!({})); + let rows = list["result"].as_array().cloned().unwrap_or_default(); + rows.into_iter().find(|row| row["id"] == id).map_or(Value::Null, |row| row["checked"].clone()) +} + +/// Whether the options bar is on (Window › Options), as `ui.inspect` reports it. +fn bar_shown(app: &mut PhotocraftApp) -> Value { + control(app, "ui.inspect", json!({}))["result"]["optionsBar"]["enabled"].clone() +} + +#[test] +fn window_options_hides_and_shows_the_options_bar_with_its_check_mark() { + let mut app = app(); + assert_eq!((checked(&mut app, "window.panel.options"), bar_shown(&mut app)), (json!(true), json!(true)), "checked while the bar shows"); + invoke(&mut app, "window.panel.options", json!({})); + assert_eq!((checked(&mut app, "window.panel.options"), bar_shown(&mut app)), (json!(false), json!(false)), "choosing it hides the bar and unchecks it"); + assert!(!app.ui.status.contains("unknown command"), "no error in the status bar: {}", app.ui.status); + invoke(&mut app, "window.panel.options", json!({})); + assert_eq!((checked(&mut app, "window.panel.options"), bar_shown(&mut app)), (json!(true), json!(true)), "choosing it again brings the bar back"); +} + +#[test] +fn the_control_channel_shows_or_hides_the_options_bar_with_show() { + let mut app = app(); + for (show, want) in [(false, false), (false, false), (true, true), (true, true)] { + invoke(&mut app, "window.panel.options", json!({"show": show})); + assert_eq!(bar_shown(&mut app), json!(want), "show: {show} sets the bar rather than toggling it"); + } + let reply = control(&mut app, "ui.menu.invoke", json!({"id": "window.panel.options", "params": {"show": "no"}})); + assert_eq!(reply["ok"], false, "a show that isn't true or false is refused: {reply}"); + assert_eq!(bar_shown(&mut app), json!(true), "and changes nothing"); +} + +/// Neighbours: the other Window bars beside Options keep toggling on their own. +#[test] +fn window_tools_and_contextual_task_bar_keep_their_own_toggles() { + let mut app = app(); + let tools = checked(&mut app, "window.panel.tools"); + invoke(&mut app, "window.panel.tools", json!({})); + assert_ne!(checked(&mut app, "window.panel.tools"), tools, "Window › Tools toggles the toolbar"); + invoke(&mut app, "window.panel.contextualTaskBar", json!({})); + assert_eq!(checked(&mut app, "window.panel.contextualTaskBar"), json!(false), "Window › Contextual Task Bar toggles its bar"); + assert_eq!(bar_shown(&mut app), json!(true), "neither touches the options bar"); +} diff --git a/crates/ui-egui/tests/it/camera_raw_histogram.rs b/crates/ui-egui/tests/it/camera_raw_histogram.rs index f90da8ef97..e6c2af6106 100644 --- a/crates/ui-egui/tests/it/camera_raw_histogram.rs +++ b/crates/ui-egui/tests/it/camera_raw_histogram.rs @@ -11,13 +11,13 @@ fn described(h: &Harness<'_, Box>) -> Value { /// Runs the app's frames until the develop of the settings in force has landed, and returns the dialog's /// description. The develop waits on the framework's queue until a request finishes it, as the agent entry /// point's `waitPreview` does. -fn settled(h: &mut Harness<'_, Box>) -> Value { - h.run_steps(2); +fn settled(h: &mut Harness<'_, Box>, previous_revision: u64) -> Value { for _ in 0..2000 { craft::ui::runtime::pending::finish_jobs(&h.ctx, std::time::Duration::from_secs(30)); h.run_steps(1); let now = described(h); - if now["previewPending"] == false && !now["histogram"].is_null() { + let advanced = now["previewRevision"].as_u64().is_some_and(|revision| revision > previous_revision); + if advanced && now["previewPending"] == false && !now["histogram"].is_null() { return now; } std::thread::sleep(std::time::Duration::from_millis(5)); @@ -25,35 +25,32 @@ fn settled(h: &mut Harness<'_, Box>) -> Value { panic!("the Camera Raw preview never finished"); } -/// A control request, then the develop it asks for. -fn request(h: &mut Harness<'_, Box>, params: Value) -> Value { +fn request(h: &mut Harness<'_, Box>, params: Value) { let ctx = h.ctx.clone(); - let reply = camera_raw_ui::menu(h.state_mut(), &ctx, "filter.cameraRaw", ¶ms).unwrap().unwrap(); - if described(h).is_null() { - return reply; - } - settled(h) + camera_raw_ui::menu(h.state_mut(), &ctx, "filter.cameraRaw", ¶ms).unwrap().unwrap(); } #[test] fn histogram_matches_visible_preview_at_all_supported_depths_and_cancel_commit_are_reversible() { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); + PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()) + }); for mode in ["rgb", "grayscale"] { for depth in [8, 16, 32] { - let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - app - }); - h.run_steps(3); + let app = h.state_mut(); + app.run("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + h.run_steps(1); let original = h.state().session.active().unwrap().doc.clone(); let steps = h.state().session.active().unwrap().history.past_len(); - let initial = request(&mut h, json!({})); + request(&mut h, json!({})); + let initial = settled(&mut h, 0); assert_eq!(initial["histogram"]["samples"], 128); - let changed = request(&mut h, json!({"ui": {"set": {"exposure": 1.0}}})); - assert_ne!(changed["histogram"]["red"], initial["histogram"]["red"]); + request(&mut h, json!({"ui": {"set": {"exposure": 1.0}}})); + let changed = settled(&mut h, initial["previewRevision"].as_u64().unwrap()); + assert_ne!(changed["histogram"]["red"], initial["histogram"]["red"], "{mode}/{depth}: exposure must change the histogram"); assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); request(&mut h, json!({"ui": {"cancel": true}})); assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original), "Cancel leaves the document alone"); @@ -62,8 +59,13 @@ fn histogram_matches_visible_preview_at_all_supported_depths_and_cancel_commit_a h.state_mut().run("edit.undo", json!({})).unwrap(); assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); h.state_mut().run("edit.redo", json!({})).unwrap(); - let committed = request(&mut h, json!({})); + request(&mut h, json!({})); + let committed = settled(&mut h, 0); assert_eq!(committed["histogram"]["red"], changed["histogram"]["red"], "{mode}/{depth}: graph and committed pixels disagree"); + request(&mut h, json!({"ui": {"cancel": true}})); + assert!(described(&h).is_null(), "{mode}/{depth}: Camera Raw must close"); + h.state_mut().run("file.close", json!({"discard": true})).unwrap(); + assert!(h.state().session.active().is_none(), "{mode}/{depth}: the next case needs a fresh document"); } } } diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index f5890874b7..050549e99c 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -90,12 +90,14 @@ fn button(h: &mut Harness, at: Pos2, pressed: bool) { h.step(); } -/// The rendered frame's RGB at document point `(x, y)`. -fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { - let p = screen(h, x, y); +/// Sample all points in the same rendered frame. +fn rgb_at(h: &mut Harness, points: [[f64; 2]; N]) -> [[u8; 3]; N] { + let points = points.map(|[x, y]| screen(h, x, y)); let img = h.render().expect("render"); - let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); - [px[0], px[1], px[2]] + points.map(|p| { + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] + }) } fn is_red(c: [u8; 3]) -> bool { @@ -110,11 +112,12 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness(gpu_canvas) else { return }; setup(&mut h); - assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + let [before] = rgb_at(&mut h, [[150.5, 150.5]]); + assert!(is_red(before), "the layer shows before the transform"); control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); assert!(h.state().ui.transform.is_some(), "Free Transform is open"); - let inside = rgb_at(&mut h, 150.5, 150.5); + let [inside] = rgb_at(&mut h, [[150.5, 150.5]]); assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the @@ -125,12 +128,11 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { for i in 1..=6 { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, vacated] = rgb_at(&mut h, [[230.5, 130.5], [120.5, 130.5]]); assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); - let vacated = rgb_at(&mut h, 120.5, 130.5); assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); button(&mut h, to, false); - let released = rgb_at(&mut h, 230.5, 130.5); + let [released] = rgb_at(&mut h, [[230.5, 130.5]]); assert!(is_red(released), "the moved square still shows after the release: {released:?}"); } @@ -158,14 +160,14 @@ fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } button(&mut h, to, false); - assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square"); + let [before] = rgb_at(&mut h, [[230.5, 130.5]]); + assert!(is_red(before), "the box moved the square"); h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.step(); assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform"); - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, back] = rgb_at(&mut h, [[230.5, 130.5], [150.5, 130.5]]); assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}"); - let back = rgb_at(&mut h, 150.5, 130.5); assert!(is_red(back), "the square is back in its place: {back:?}"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs index f8f56bb371..43790c4a40 100644 --- a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs @@ -162,15 +162,22 @@ fn pm(p: &[f32; 4]) -> [f32; 4] { [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] } -fn diffs(a: &[[f32; 4]], b: &[[f32; 4]]) -> Vec { - a.iter().zip(b).map(|(x, y)| (0..4).map(|c| (pm(x)[c] - pm(y)[c]).abs()).fold(0.0, f32::max)).collect() -} - /// Largest difference, ignoring up to `skip` outliers. fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 { - let mut d = diffs(a, b); - d.sort_by(|x, y| y.total_cmp(x)); - d.get(skip).copied().unwrap_or(0.0) + assert_eq!(a.len(), b.len()); + let diffs = a.iter().zip(b).map(|(x, y)| { + let (x, y) = (pm(x), pm(y)); + x.into_iter().zip(y).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) + }); + if skip == 0 { + diffs.fold(0.0, f32::max) + } else { + let mut diffs = diffs.collect::>(); + if skip >= diffs.len() { + return 0.0; + } + *diffs.select_nth_unstable_by(skip, |x, y| y.total_cmp(x)).1 + } } #[test] @@ -181,11 +188,18 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { // command's CPU result (adds the command's rounding to the layer depth). let (tol_gpu, tol_cmd) = (2.0 / 255.0, 2.5 / 255.0); let mut worst = 0.0f32; + let full_sweep = photocraft_testkit::full_sweep(); for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (depth_index, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { for selection in [false, true] { let (doc, target) = document(mode, depth, selection); - for kind in photocraft_ui_egui::adjust_editors::KINDS { + for (kind_index, kind) in photocraft_ui_egui::adjust_editors::KINDS.into_iter().enumerate() { + // Keep every shader at every mode and depth, sampling both mask + // paths. The CPU test preview_composite_matches_the_destructive_command + // already compares all combinations; the full GPU sweep keeps them too. + if !full_sweep && selection != (kind_index + depth_index).is_multiple_of(2) { + continue; + } let params = sample(kind); let preview = match preview_document(&doc, target, kind, ¶ms) { Ok(p) => p, @@ -209,7 +223,7 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { let mut s = photocraft_engine::Session::new(); s.add_document(doc.clone(), None); s.select_layer(target).unwrap(); - s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap(); + s.execute(&format!("image.adjustments.{kind}"), params).unwrap(); let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px(); let d = max_diff(&on_gpu, &cmd, skip); worst = worst.max(d); @@ -284,7 +298,7 @@ fn proxy_preview_composites_on_the_gpu() { let (doc, target) = document(ColorMode::Rgb, SampleType::U8, selection); let proxy = proxy_base(&base_document(&doc, target).unwrap(), 2); // Render the full document too, so both share the compositor's resident textures. - render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).unwrap(); + comp.render(&device, &queue, &doc, doc.bounds(), |_, _| {}).unwrap(); for kind in photocraft_ui_egui::adjust_editors::KINDS { let p = proxy_with_settings(&proxy, kind, &sample(kind)).unwrap(); let on_gpu = render_to_vec(&mut comp, &device, &queue, &p, p.bounds()).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs index 97ad7528ac..88d506e010 100644 --- a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs +++ b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs @@ -39,22 +39,29 @@ fn harness() -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) -> Value { +fn request(h: &mut Harness, method: &str, params: Value) -> Value { let ctx = h.ctx.clone(); let (req, _rx) = ControlRequest::new(method, params); let Reply::Done(value) = handle(h.state_mut(), &ctx, &req) else { panic!("{method} did not finish") }; assert_eq!(value["ok"], true, "{method}: {value}"); - h.run_steps(4); value["result"].clone() } +fn control(h: &mut Harness, method: &str, params: Value) -> Value { + let result = request(h, method, params); + h.run_steps(4); + result +} + fn setup(h: &mut Harness, width: u32, height: u32, zoom: f32, center: [f32; 2]) { + // Settle once after the document is filled and positioned. The fixture does not + // need a canvas frame for the old tab, the empty editor or the temporary white fill. while h.state().session.active().is_some() { - control(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); + request(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); } - control(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); - control(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); - control(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); + request(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); + request(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); + request(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); control(h, "ui.set", json!({"zoom":zoom,"center":center})); assert!(h.state().perf.gpu, "the fixture must use the GPU canvas"); } @@ -129,18 +136,18 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { setup(&mut h, width, height, zoom, center); assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor); let id = open_previewing(&mut h); - let source = blue(&mut h, &format!("{width}x{height}-{degrees}-zero")).0; - assert!(source > 5_000, "the unrotated blue image must be visible outside the dialog"); angle(&mut h, &id, degrees); h.get_by_label("Preview").click(); h.run_steps(4); assert!(!preview_on(&h)); - assert!(blue(&mut h, &format!("{width}x{height}-{degrees}-off")).0 > 5_000, "Preview off shows the original image"); + let (original, original_top, original_bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-off")); + assert!(original > 5_000, "Preview off shows the original image"); h.get_by_label("Preview").click(); h.run_steps(4); assert!(preview_on(&h)); let (count, top, bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-on")); assert!(count > 5_000, "{width}x{height}, {degrees}°, factor {factor}: rotated blue pixels disappeared ({count} remain)"); + assert!(bottom - top > original_bottom - original_top, "{degrees}°: the rotated preview should be taller"); let rect = photocraft_ui_egui::canvas::active_view(h.state()).expect("a shown view").rect; let expected_y = rect.center().y + (height as f32 / 2.0 - center[1]) * zoom; let actual_y = (top + bottom) as f32 / 2.0; diff --git a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs index fcdd436f7d..8193a546e6 100644 --- a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs +++ b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs @@ -227,9 +227,10 @@ fn screens(cases: Vec>) -> Option> { } harness.run_steps(6); let img = harness.render().expect("render"); - let out = std::env::temp_dir().join(name); - let _ = img.save(&out); - eprintln!("screen: {}", out.display()); + if let Some(dir) = std::env::var_os("PHOTOCRAFT_CANVAS_16F_EVIDENCE_DIR") { + std::fs::create_dir_all(&dir).expect("evidence directory"); + img.save(std::path::Path::new(&dir).join(name)).expect("save UI frame"); + } shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() }); if let Some((doc, setup, name)) = cases.next() { harness.state_mut().session.open_document(doc, None); @@ -252,7 +253,9 @@ fn screen_levels(img: &Screen, y: u32, x0: u32, x1: u32) -> (usize, i32) { fn sixteen_bit_gradient_on_screen() { let _gpu = gpu_lock(); // A 16-bit ramp drawn by the app's canvas: smooth, monotonic, no visible steps. - let doc = gradient(SampleType::U16, 2048, 1024, 0.0, 1.0); + // The document still fits down to the same viewport and has more source levels than + // the screen can display. The extra source pixels aren't needed to spot banding. + let doc = gradient(SampleType::U16, 1024, 512, 0.0, 1.0); let Some(img) = screen(doc, &[], "photocraft-canvas-16f-gradient.png") else { return }; let (n, step) = screen_levels(&img, img.h / 2, 150, 600); assert!(n > 100 && step <= 3, "{n} levels, max step {step}"); @@ -263,7 +266,7 @@ fn thirty_two_bit_preview_exposes_values_above_one() { let _gpu = gpu_lock(); // A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit // canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth. - let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0); + let doc = gradient(SampleType::F32, 1024, 512, 0.0, 1.0 / 16.0); // Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0 // at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8). let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32); diff --git a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs index e3708e4592..ae99576baa 100644 --- a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs @@ -1,13 +1,17 @@ -//! The transparency checker is made of 8 screen pixel cells (the Medium preference) at every zoom, +//! The transparency checker is made of 8 screen point cells (the Medium preference) at every zoom, //! anchored to the document's top-left corner so the pattern moves with the image. The pixel grid shows above 500% zoom, //! over pixels with content only, never over empty checker. //! //! These tests render the real app offscreen and read pixels back. They skip when no GPU adapter //! is available. The CPU canvas (no wgpu handed to the app) has its own pixel grid tests at the end. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, Size}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; use photocraft_ui_egui::PhotocraftApp; -use photocraft_ui_egui::control::{ControlRequest, handle}; -use serde_json::{Value, json}; +use photocraft_ui_egui::control::{ControlRequest, Reply, handle}; +use serde_json::json; type Harness = egui_kittest::Harness<'static, Box>; @@ -24,8 +28,18 @@ fn harness_with(gpu: bool) -> Option { } fn harness_with_scale(gpu: bool, ppp: f32) -> Option { + // At 2× the same document pixels take half as many points. Keep the samples + // inside the viewport without reading back a 2800 × 1600 frame. + let size = if ppp > 1.0 { + egui::vec2(820.0, 570.0) + } else if photocraft_testkit::full_sweep() { + // The full sweep also samples a 730 px wide document at 1×. + egui::vec2(1400.0, 800.0) + } else { + egui::vec2(900.0, 640.0) + }; let built = std::panic::catch_unwind(|| { - egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 800.0)).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { + egui_kittest::Harness::builder().with_size(size).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if let Some(rs) = cc.wgpu_render_state.as_ref().filter(|_| gpu) { @@ -43,10 +57,11 @@ fn harness_with_scale(gpu: bool, ppp: f32) -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) { +fn set_view(h: &mut Harness, zoom: f32, center: [f32; 2]) { let ctx = h.ctx.clone(); - let (req, _rx) = ControlRequest::new(method, params); - handle(h.state_mut(), &ctx, &req); + let (req, _rx) = ControlRequest::new("ui.set", json!({"zoom": zoom, "center": center})); + let Reply::Done(reply) = handle(h.state_mut(), &ctx, &req) else { panic!("setting the view did not finish") }; + assert_eq!(reply["ok"], true, "{reply}"); h.run_steps(4); } @@ -87,30 +102,23 @@ impl Shot { } } -/// Opens a `doc` px square document at `zoom` (transparent, or filled black when `black`), renders -/// it with the pixel grid on or off, and returns the screenshot with the document's left and top -/// screen edge and its width in screen pixels. -fn render(h: &mut Harness, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - render_on(h, true, zoom, doc, black, grid) +fn open_document(h: &mut Harness, doc: u32, black: bool, grid: bool) { + let app = h.state_mut(); + while app.session.active().is_some() { + app.run("file.close", json!({"discard": true})).expect("close"); + } + let background = if black { "white" } else { "transparent" }; + app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); + if black { + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + } + app.sync_views(); + app.ui.view.show.pixel_grid = grid; } -/// [`render`] on the GPU canvas (`gpu`) or the CPU canvas. -fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - let background = if black { "white" } else { "transparent" }; - app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); - if black { - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - } - app.sync_views(); - app.ui.view.show.pixel_grid = grid; - } - control(h, "ui.set", json!({"zoom": zoom, "center": [doc as f32 / 2.0, doc as f32 / 2.0]})); - h.run_steps(3); +/// Zooms the current document and returns the screenshot and the document's physical-pixel bounds. +fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool) -> (Shot, u32, u32, u32) { + set_view(h, zoom, [doc as f32 / 2.0; 2]); assert_eq!(h.state().perf.gpu, gpu, "zoom {zoom}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); let rendered = h.render().expect("render"); let (width, height) = (rendered.width(), rendered.height()); @@ -122,7 +130,8 @@ fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: return (img, origin.x.round() as u32, origin.y.round() as u32, (doc as f32 * zoom).round() as u32); } let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); + let center = r.center() * h.ctx.pixels_per_point(); + let (cx, cy) = (center.x as u32, center.y as u32); let (x0, w) = longest_run((0..width).map(|x| is_checker_grey(img.at(x, cy)))); let (y0, hgt) = longest_run((0..height).map(|y| is_checker_grey(img.at(cx, y)))); let doc_px = (doc as f32 * zoom).round() as i64; @@ -135,14 +144,33 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // The 8 px cell never changes with the zoom. - for (zoom, doc) in [(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] { - let (img, x0, y0, _) = render(&mut h, zoom, doc, false, false); - let n = ((doc as f32 * zoom) / 8.0) as u32; + // The checker draws in screen points, independent of the document zoom. + // Sample reduced, 1:1, fractional and magnified views, including 2× displays. + let zooms_1x: &[(f32, u32)] = if photocraft_testkit::full_sweep() { + &[(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] + } else { + &[(0.5, 64), (1.0, 64), (1.1, 64)] + }; + let zooms_2x = [(8.0, 32), (32.0, 12)]; + let cases = zooms_1x.iter().map(|&(zoom, doc)| (1.0, zoom, doc)).chain(zooms_2x.into_iter().map(|(zoom, doc)| (2.0, zoom, doc))); + let mut current_size = 0; + for (ppp, zoom, doc) in cases { + if h.ctx.pixels_per_point() != ppp { + h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT).expect("root viewport").native_pixels_per_point = Some(ppp); + h.run_steps(4); + } + assert_eq!(h.ctx.pixels_per_point(), ppp); + if current_size != doc { + open_document(&mut h, doc, false, false); + current_size = doc; + } + let (img, x0, y0, _) = render_on(&mut h, true, zoom, doc, false); + let cell = (8.0 * ppp) as u32; + let n = (doc as f32 * zoom) as u32 / cell; assert!(n >= 2, "zoom {zoom}: test needs at least two cells"); for row in 0..n.min(4) { for col in 0..n.min(6) { - let (sx, sy) = (x0 + col * 8 + 4, y0 + row * 8 + 4); + let (sx, sy) = (x0 + col * cell + cell / 2, y0 + row * cell + cell / 2); let got = img.at(sx, sy); let want = if (col + row) % 2 == 0 { LIGHT } else { DARK }; assert!( @@ -152,8 +180,8 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { } } // Crisp: every pixel of the row is exactly one of the two greys, no blended edges. - let y = y0 + 4; - for x in x0..x0 + (n * 8).min(48) { + let y = y0 + cell / 2; + for x in x0..x0 + n.min(6) * cell { let v = img.at(x, y)[0]; assert!(v == LIGHT || v == DARK, "zoom {zoom}: blended pixel {v} at ({x}, {y})"); } @@ -170,10 +198,11 @@ fn pixel_grid_shows_above_500_percent_and_lightens_a_dark_pixel_by_about_a_quart let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render(&mut h, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, true, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, true); let lit = lit_columns(&img, x0, y0 + (zoom * 3.5) as u32, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "zoom {zoom}: grid columns {lit:?}"); assert!(lit.windows(2).all(|p| p[1] - p[0] == zoom as u32), "zoom {zoom}: spacing of {lit:?}"); @@ -187,8 +216,9 @@ fn pixel_grid_is_not_drawn_over_empty_checker() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); + open_document(&mut h, 24, false, true); for zoom in [8.0f32, 16.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 24, false, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, false); for y in y0..y0 + 64 { for x in x0..x0 + 64 { let v = img.at(x, y)[0]; @@ -204,10 +234,11 @@ fn cpu_pixel_grid_shows_above_500_percent_over_content() { for ppp in [1.0, 2.0] { let Some(mut h) = harness_with_scale(false, ppp) else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render_on(&mut h, false, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, false, zoom, 24, true); let y = y0 + (zoom * 3.5) as u32; let lit = lit_columns(&img, x0, y, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "scale {ppp}, zoom {zoom}: one physical pixel per line, columns {lit:?}"); @@ -224,9 +255,12 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { let Some(mut h) = harness_with(false) else { return }; h.run_steps(4); // The CPU checker has soft cell edges of its own, so compare with and without the grid. + open_document(&mut h, 24, false, false); for zoom in [8.0f32, 16.0] { - let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false, false); - let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false, true); + h.state_mut().ui.view.show.pixel_grid = false; + let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false); + h.state_mut().ui.view.show.pixel_grid = true; + let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false); assert_eq!((x0, y0), (x1, y1), "zoom {zoom}: the document moved"); for y in y0..y0 + 64 { for x in x0..x0 + 64 { @@ -236,56 +270,48 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { } } -/// The pixel grid over a flat `grey` document at 800%: the largest difference, in 8-bit levels, -/// between a grid line and the pixel interior beside it. -fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("file.new", json!({"width": 48, "height": 48, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": format!("#{grey:02x}{grey:02x}{grey:02x}")})).expect("fill"); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - } - control(h, "ui.set", json!({"zoom": 8.0, "center": [24.0, 24.0]})); - h.run_steps(3); - assert!(h.state().perf.gpu, "expected the GPU canvas"); - let rendered = h.render().expect("render"); - let img = Shot { w: rendered.width(), px: rendered.into_raw() }; - let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); - // The median of an 8 px block is a pixel interior whichever line the block straddles. - let mut block: Vec = (0..64).map(|i| img.at(cx + i % 8, cy + i / 8)[0] as i32).collect(); - block.sort_unstable(); - let interior = block[32]; - // Walk out to the document edge: the pasteboard is far darker than any grid line. - let near = |x: u32, y: u32| (img.at(x, y)[0] as i32 - interior).abs() < 50; - let x0 = (0..=cx).rev().take_while(|x| near(*x, cy)).last().unwrap_or(cx); - let y0 = (0..=cy).rev().take_while(|y| near(cx, *y)).last().unwrap_or(cy); - // Pixel (col, row) owns the grid line on its left and top edge, 8 screen px apart. - let y = y0 + 8 * 3 + 4; - (2..6).map(|col| (img.at(x0 + 8 * col, y)[0] as i32 - img.at(x0 + 8 * col + 4, y)[0] as i32).abs()).max().unwrap_or(0) -} - #[test] fn pixel_grid_does_not_flip_colour_across_mid_tones() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white - // line to a full black one. Both now give a faint line, so neighbouring cells match. - for grey in [0x87u8, 0x90] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c <= 14, "grey {grey:#04x}: grid line differs from its pixel by {c} levels, want a faint line"); + // Put both sides of the old luma cutoff and the stronger dark/light lines in one frame. + // Sample inside each swatch so an edge between swatches cannot pass as a grid line. + let greys = [0x87u8, 0x90, 0x60, 0xd0, 0xff]; + let mut doc = Document::new("grid midtones", Size::new(40, 16), ColorMode::Rgb, SampleType::U8); + let mut surface = Surface::new(doc.pixel_format()); + for (i, grey) in greys.into_iter().enumerate() { + let x = i as i32 * 8; + let v = f32::from(grey) / 255.0; + surface.fill_rect(Rect::new(x, 0, x + 8, 16), &[v, v, v, 1.0]); } - // The fade must not remove the grid where it is needed: dark and light pixels keep a clear - // line (white over 0x60, black over 0xd0 and white; black itself is in the unit tests, as the - // dark pasteboard defeats this walk to the document edge). - for grey in [0x60u8, 0xd0, 0xff] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {c} levels"); + doc.layers.push(Layer::new("swatches", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + set_view(&mut h, 8.0, [20.0, 8.0]); + assert!(h.state().perf.gpu); + let img = h.render().expect("render swatches"); + let center = h.state().last_canvas_rect.center(); + let x0 = (center.x - 20.0 * 8.0).round() as u32; + let y = (center.y + 3.5 * 8.0).round() as u32; + for (i, grey) in greys.into_iter().enumerate() { + let x = x0 + i as u32 * 64; + let contrast = (2..6) + .map(|col| { + let edge = x + 8 * col; + let inside = img.get_pixel(edge + 4, y)[0]; + assert!(inside.abs_diff(grey) <= 1, "wrong swatch at {edge}: {inside} vs {grey}"); + (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, y)[0].abs_diff(inside)).max().expect("grid line") + }) + .max() + .expect("swatch columns"); + if i < 2 { + assert!(contrast <= 14, "grey {grey:#04x}: grid line differs from its pixel by {contrast} levels, want a faint line"); + } else { + assert!(contrast >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {contrast} levels"); + } } } @@ -296,8 +322,7 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() { /// it, which the `inside` assertion reads: on the GPU canvas its texture (`Rgba8Unorm` for 8-bit, `Rgba16Float` for /// 16/32-bit, see `canvas_16f.rs`). So every canvas and scale runs 8-bit, and the GPU canvas adds 16-bit at 1x and /// 32-bit at 2x. -fn grid_depths(gpu: bool, ppp: f32) -> Vec { - use photocraft_color::SampleType; +fn grid_depths(gpu: bool, ppp: f32) -> Vec { match (gpu, ppp > 1.0) { (true, false) => vec![SampleType::U8, SampleType::U16], (true, true) => vec![SampleType::U8, SampleType::F32], @@ -307,36 +332,49 @@ fn grid_depths(gpu: bool, ppp: f32) -> Vec { fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) { let _gpu = photocraft_testkit::gpu_lock(); - use photocraft_color::{ColorMode, PixelFormat}; - use photocraft_doc::{Document, Layer, LayerContent, Size}; - use photocraft_geom::Rect; - use photocraft_raster::Surface; let Some(mut h) = harness_with_scale(gpu, ppp) else { return }; for depth in grid_depths(gpu, ppp) { - for v in [0.0, 1.0] { - let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth); - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true)); - surface.fill_rect(Rect::new(0, 0, 32, 16), &[v, v, v, 1.0]); - doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); - let app = h.state_mut(); - app.session.add_document(doc, None); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - for zoom in [7.119, 8.0, 22.825] { - control(&mut h, "ui.set", json!({"zoom": zoom, "center": [16.0, 8.0]})); - assert_eq!(h.state().perf.gpu, gpu); - let img = h.render().expect("render opaque grid"); - let center = h.state().last_canvas_rect.center() * ppp; - let x0 = center.x - 16.0 * zoom; - let y = (center.y + 3.25 * zoom).floor() as u32; + let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth); + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true)); + // Both neutral fills take the same grid draw path, with opposite line contrast. + // Separate rows let them share one readback at each depth and zoom. + surface.fill_rect(Rect::new(0, 0, 32, 8), &[0.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(0, 8, 32, 16), &[1.0; 4]); + doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + // Keep the 500% cutoff at each scale. Across the two scales, sample both + // fractional and integer grid alignment, including the largest zoom. + let visible_zooms: &[f32] = if photocraft_testkit::full_sweep() { + &[7.119, 8.0, 22.825] + } else if ppp == 1.0 { + &[7.119] + } else { + &[8.0, 22.825] + }; + for zoom in (depth == SampleType::U8).then_some(5.0).into_iter().chain(visible_zooms.iter().copied()) { + set_view(&mut h, zoom, [16.0, 8.0]); + assert_eq!(h.state().perf.gpu, gpu); + assert_eq!(h.ctx.pixels_per_point(), ppp); + let img = h.render().expect("render opaque grid"); + let center = h.state().last_canvas_rect.center() * ppp; + let x0 = center.x - 16.0 * zoom; + for (v, dy) in [(0, -2.75), (255, 3.25)] { + let y = (center.y + dy * zoom).floor() as u32; for x in 2..30 { let edge = (x0 + x as f32 * zoom).floor() as u32; for sy in y..y + 3 { let inside = img.get_pixel((x0 + (x as f32 + 0.5) * zoom).floor() as u32, sy)[0]; - assert_eq!(inside, (v * 255.0) as u8); + assert_eq!(inside, v); let contrast = (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, sy)[0].abs_diff(inside)).max().expect("line"); - assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + if zoom == 5.0 { + assert_eq!(contrast, 0, "grid visible at 500%, {gpu:?}/{depth:?}, scale {ppp}, fill {v}"); + } else { + assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + } } } } diff --git a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs index 208dac9e95..03030efc62 100644 --- a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs @@ -197,17 +197,22 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { // which the marquee tool paints through `ToolContext::marching_ants`). White on white (#253) hid the light ants // and black would hide the dark ones; over grey the test sees both inks at once, so an outline missing either // colour fails here as it failed on one of the two documents. (The name is the one CI's slow-test order lists.) - // One harness for both scales: the app derives its scale from the window's native one every frame - // (`prefs_ui/appearance.rs` `interface_zoom`), so the 2x pass sets that, as a move to a HiDPI display does. + // Both shapes paint through the same scale-aware marching-ants painter. + // Sample the rectangle at 1× and the curve at 2× by default; the full + // sweep also covers each shape at the other scale. + let full_sweep = photocraft_testkit::full_sweep(); let Some(mut h) = harness(1.0) else { return }; h.run_steps(4); - for ppp in [1.0f32, 2.0] { + for (ppp, primary) in [(1.0f32, "rectMarquee"), (2.0, "ellipseMarquee")] { if let Some(root) = h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT) { root.native_pixels_per_point = Some(ppp); } h.run_steps(4); assert_eq!(h.ctx.pixels_per_point(), ppp, "the harness runs at {ppp}x"); for tool in ["rectMarquee", "ellipseMarquee"] { + if tool != primary && !full_sweep { + continue; + } setup(&mut h, GREY, tool); let (a, b) = ([100.0, 80.0], [300.0, 220.0]); let before = render(&mut h); @@ -246,8 +251,8 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { } // Each move's frame shows the outline where the pointer is now (no stale frame). pointer_move(&mut h, 340.0, 250.0); - let img = render(&mut h); if tool == "rectMarquee" { + let img = render(&mut h); let [top, right, ..] = edges(&h, a, [340.0, 250.0]); for (ink, test) in inks() { assert!(coverage(&img, ppp, top.0, top.1, test) > 0.3, "{tool} @{ppp}x: top edge follows the pointer ({ink})"); diff --git a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs index 1556fb0e04..bf92a75c03 100644 --- a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs @@ -141,7 +141,6 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The smoothing tool option syncs on the first frame with the Brush: set it after. h.state_mut().session.tools.brush.smoothing.amount = c.smoothing; let canvas = |h: &mut Harness| { - h.run_steps(3); let r = h.state().last_canvas_rect.shrink(4.0); let img = h.render().expect("render"); let mut px = Vec::new(); @@ -152,10 +151,13 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { } px }; + h.run_steps(3); let before = canvas(h); let pressure = |t: f64| if c.pressure { 0.3 + 0.7 * t } else { 1.0 }; control(h, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100, "pressure": pressure(0.0)}]})); - let n = 14; + // Keep the whole curved path and both ends of the pressure ramp. The full + // sweep also exercises the original denser sequence of pointer events. + let n = if photocraft_testkit::full_sweep() { 14 } else { 8 }; let mut last = (100.0, 100.0); for i in 1..=n { let t = f64::from(i) / f64::from(n); @@ -168,11 +170,12 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The pointer stays held at its last point, as a mouse held still repeats its position. let held = |h: &mut Harness| { control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]})); - canvas(h) + h.run_steps(3); }; - let drawing = settled(h, held); + let drawing = settled(h, held, canvas); let gpu = h.state().perf.gpu && !c.flip; control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]})); + h.run_steps(3); let done = canvas(h); (before, drawing, done, gpu) } @@ -180,22 +183,28 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { /// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own /// thread and a frame waits only a few real ms for it, so on a slow machine its newest step /// arrives late, and only a later pointer event shows it; release would then paint the rest. -/// `picture` holds the pointer still and takes a picture, with short real waits between them, -/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove -/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails -/// instead of hanging or comparing an unsettled picture. -fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { +/// Keep feeding the held pointer until the stroke is idle and three pictures in a row match. +/// A busy stroke can't be stable, so advance those frames without a GPU readback. +fn settled(h: &mut Harness, held: impl Fn(&mut Harness), picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { const TRIES: usize = 80; - let mut last = picture(h); + let mut last = None; let mut unchanged = 0; - for _ in 0..TRIES { - std::thread::sleep(std::time::Duration::from_millis(25)); - let next = picture(h); - unchanged = if next == last { unchanged + 1 } else { 0 }; - last = next; - if unchanged >= 2 && !h.state().live_stroke_busy() { - return last; + for attempt in 0..=TRIES { + if attempt != 0 { + std::thread::sleep(std::time::Duration::from_millis(25)); } + held(h); + if h.state().live_stroke_busy() { + last = None; + unchanged = 0; + continue; + } + let next = picture(h); + unchanged = if last.as_ref() == Some(&next) { unchanged + 1 } else { 0 }; + if unchanged >= 2 { + return next; + } + last = Some(next); } panic!("the live stroke did not settle before release"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs index c661370ea6..3ff626b86c 100644 --- a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs @@ -86,26 +86,20 @@ fn assert_document_size_is_physical(gpu: bool) { let Some(mut h) = harness(gpu) else { return }; h.run_steps(4); const DOC: u32 = 60; + let app = h.state_mut(); + app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + app.sync_views(); // A fractional and an integer UI scale: the canvas sees the scale only as `pixels_per_point` (device px per doc px // = zoom x ppp), and its sampling branches on that product being below 1, whole (or 2 and up) or fractional // (`gpu_canvas::callback::filter_mode`). 125% gives 1.25 and 2.5 at the two zooms, as 150% would; 200% gives 2 and // 4, covering 100%'s 1 and 2, where a dropped ppp could not show anyway (#15652). for ui_scale in ["125", "200"] { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); - app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - app.sync_views(); - } + h.state_mut().run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); h.run_steps(6); assert_eq!(h.state().perf.gpu, gpu, "UI Scale {ui_scale}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); for zoom in [1.0f32, 2.0] { control(&mut h, "ui.set", json!({"zoom": zoom, "center": [DOC as f32 / 2.0, DOC as f32 / 2.0]})); - h.run_steps(4); let (w, hgt) = document_physical_size(&mut h); let want = (DOC as f32 * zoom).round() as i64; assert!( diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d00eeeff3d..d920f1962a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -60,7 +60,6 @@ mod gpu_tests { mod color_managed_canvas; mod display_shadows; mod drag_preview_canvas; - mod full_res_preview; mod live_stroke_canvas; mod pattern_preview_canvas; mod ui_scale_canvas; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a3a766a182..b815713606 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -813,9 +813,12 @@ else}` is Photoshop's Insert Conditional as a step: it tests the document or act (`always`, `landscape`, `modeIsRGB`, `hasLayers`, `isBackground`, `hasPixelMask`… see its params) and plays the matching action by name, failing the caller when that action fails. -Layer-panel **Quick Export as PNG** exports every selected layer as a separate PNG. A single -Save dialog chooses the first filename; remaining files are numbered siblings with sanitized -layer names. Selection is captured before opening the dialog; an unselected layer is excluded. +Layer-panel **Quick Export as PNG** exports each selected layer or group with exportable pixels +as a separate PNG. Each PNG uses its source name with unsafe filename characters replaced. +For several outputs, desktop asks for one folder and the web downloads each file. Duplicate +names get numbered alternatives, as do occupied filenames on desktop. A single output uses +a Save dialog that lets you confirm replacing an existing file. +Multiple selected sources are captured before opening the picker. ## Shared panel docking diff --git a/docs/scorecard.md b/docs/scorecard.md index 016cab7ceb..e3bc83e3aa 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -262,7 +262,7 @@ Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace. | TYPE-218-9 | Distort/Perspective/Warp on live type as in Photoshop (was: offer 'Rasterize and continue?'; Photoshop doesn't prompt) | done | [#218](https://github.com/storytold/photocraft/issues/218) | Photoshop 2026 prompts for none of these: Edit › Transform › Warp on live type stays enabled with no rasterize prompt and offers only the warp styles (the mesh can't be dragged), so the type stays editable; Distort, Perspective and the split warps are greyed. PhotoCraft does the same: Warp on type commits the layer's Warp Text in one step (transform_tool.rs enter_type_warp, warp_cmds.rs warp_type_layer, #3004; warp_on_type_takes_a_style_and_keeps_the_type_editable), Distort/Perspective greyed (enable_rules.rs, #2701) | | TYPE-218-10 | Area type: Type tool click inside a closed path or shape wraps text inside it, holes and dents included, PSD round trip | partial | [#218](https://github.com/storytold/photocraft/issues/218) | TextShape::Area (doc text.rs) laid out line by line into the spans the path leaves (text area.rs, layout.rs break_area), type.fillPath (engine type_area_cmds.rs), released to box text by type.detachFromPath, area/path cursors and click-to-place (ui-egui type_tool.rs path_target), .pcraft round trip. Missing: PSD area type (saves as paragraph text over the path's bounds, with an export warning); mixed type sizes in one area paragraph space at its largest line; area type takes paths of at most 4096 anchors: beyond that a Type tool click makes point text (the pointer shows the plain I-beam), and type.fillPath refuses the path with "the path has too many anchor points" (type.attachToPath still takes a subpath of up to 100,000 anchors); a word too wide for every span in the shape overflows its span (box text breaks it at the edge, #6694); the first line starts about 0.24 em lower than in a text box of the same size; Photoshop area type in a PSD opens as box text; the area path has no handles to edit it after the type is placed | | TYPE-10996-2 | Font menu filter by script, with the Indic scripts (Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) beside Latin, East Asian, Japanese and Thai | done | [#10996](https://github.com/storytold/photocraft/issues/10996) | The font pickers (options bar, Character panel, Style Options) offer the script row (ui-egui type_tool fonts.rs); coverage is read from the cmap in craft-font-manager. Arabic and Hebrew are not offered yet | -| TYPE-10996-1 | Digit style: digits drawn as typed, Western, by the script of the letters before them, or in an Indic script (Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) | partial | [#10996](https://github.com/storytold/photocraft/issues/10996) | CharStyle `digits` (doc text.rs), drawn in shaping (text digits.rs) while the layer text keeps the typed digits; set through the type commands' `digits` key. No Character panel control yet (needs the shared panel in craft-libs); Arabic and Persian digits are #6685; not saved in PSD | +| TYPE-10996-1 | Digit style: digits drawn as typed, Western, by the script of the letters before them, or in an Indic script (Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) | partial | [#10996](https://github.com/storytold/photocraft/issues/10996) | CharStyle `digits` (doc text.rs), drawn in shaping (text digits.rs) while the layer text keeps the typed digits; set through the type commands' `digits` key. The Character panel's Digits select sets it; Arabic and Persian digits are #6685; not saved in PSD | ## Automation diff --git a/scorecard/type.toml b/scorecard/type.toml index df80105c4f..6a0c910199 100644 --- a/scorecard/type.toml +++ b/scorecard/type.toml @@ -86,4 +86,4 @@ id = "TYPE-10996-1" target = "Digit style: digits drawn as typed, Western, by the script of the letters before them, or in an Indic script (Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam)" status = "partial" issue = 10996 -note = "CharStyle `digits` (doc text.rs), drawn in shaping (text digits.rs) while the layer text keeps the typed digits; set through the type commands' `digits` key. No Character panel control yet (needs the shared panel in craft-libs); Arabic and Persian digits are #6685; not saved in PSD" +note = "CharStyle `digits` (doc text.rs), drawn in shaping (text digits.rs) while the layer text keeps the typed digits; set through the type commands' `digits` key. The Character panel's Digits select sets it; Arabic and Persian digits are #6685; not saved in PSD"