diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index e29549e3a7a..628b8e77305 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -142,6 +142,11 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { for v in [&mut ia, &mut ib] { v.as_object_mut().unwrap().remove("name"); v["snapshots"][0].as_object_mut().unwrap().remove("name"); + // The History Brush's default source names the open snapshot, which carries the document's + // own name as well (#12845); its shape still has to match. + if let Some(source) = v["historySource"].as_object_mut() { + source.remove("name"); + } } assert_eq!(ia, ib); let (pa, pb) = (d.join("a.png"), d.join("b.png")); diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index a6021bbccc5..f6af7d88ca5 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -55,7 +55,7 @@ use distance::{ use paint::dissolves; pub use paint::{ aa_shift, anti_aliased_contour, bevel_contour_lut, glow_gradient_gain, glow_lut, glow_paint_lut, gradient_t, gradient_units, hash_noise, ranged_lut, - sample_gradient, satin_lut, spread_split, + sample_gradient, satin_aa_shift, satin_lut, spread_split, }; #[cfg(test)] use paint::{glow_map, lut_at, noise, offset, shadow_map}; @@ -265,6 +265,8 @@ mod tests; #[cfg(test)] mod outer_glow_range_one_tests; +#[cfg(test)] +mod satin_anti_alias_tests; #[cfg(test)] mod satin_invert_contour_tests; #[cfg(test)] diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs index 0aecebe4d9f..d1fe2bea844 100644 --- a/crates/compose/src/effects/bevel.rs +++ b/crates/compose/src/effects/bevel.rs @@ -270,8 +270,12 @@ pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { pub(super) fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { let (dx, dy) = offset(s.angle, satin_distance(s)); - let mut a = shape.shifted(dx, dy, 0.0); - let mut b = shape.shifted(-dx, -dy, 0.0); + // #14984: an Anti-aliased Satin takes both copies from the shape a third of a pixel towards + // the top-left (`satin_aa_shift`): the pattern moves, its Distance does not. The final clip + // below stays on the layer's own shape. + let aa = super::paint::satin_aa_shift(s.anti_alias, &s.contour, s.size); + let mut a = shape.shifted(dx + aa, dy + aa, 0.0); + let mut b = shape.shifted(-dx + aa, -dy + aa, 0.0); if s.size == 1.0 { // #14983: the measured edge has one quarter-strength pixel on either side. super::blur::size_one_blur(&mut a); diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 84dd4d8fea3..d7d3291f5e8 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -355,6 +355,19 @@ pub fn aa_shift(on: bool, c: &Contour, size: f32, spread: f32) -> f32 { if on && anti_aliased_contour(c) && anti_aliased_geometry(size, spread) { -1.0 / 3.0 } else { 0.0 } } +/// The sub-pixel offset an Anti-aliased Satin builds both of its shifted copies from (#14984): +/// the same third of a pixel towards the top-left as `aa_shift`, which moves the whole satin +/// pattern while keeping its Distance. The reference application was measured with the Gaussian +/// and the Ring contour (both bands move up: the top band lighter at its inner end, the bottom band +/// darker) and with Linear (no change at all, which `satin_lut`'s identity makes a non-event +/// anyway, so it keeps today's map bit-for-bit); every other contour, and a Size whose blur is the +/// identity (`anti_aliased_geometry` with no spread: Size 0, and Size 1, which has its own measured +/// kernel, #14983), keeps today's map. Public because the GPU satin builder asks the same rule. +pub fn satin_aa_shift(on: bool, c: &Contour, size: f32) -> f32 { + let measured = matches!(c, Contour::Custom { name, .. } if name.eq_ignore_ascii_case("Gaussian") || name.eq_ignore_ascii_case("Ring")); + if on && measured && anti_aliased_geometry(size, 0.0) { -1.0 / 3.0 } else { 0.0 } +} + /// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and /// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { diff --git a/crates/compose/src/effects/satin_anti_alias_tests.rs b/crates/compose/src/effects/satin_anti_alias_tests.rs new file mode 100644 index 00000000000..742372a3ecc --- /dev/null +++ b/crates/compose/src/effects/satin_anti_alias_tests.rs @@ -0,0 +1,299 @@ +//! #14984 - BUG-LAYER-STYLE-SATIN-ANTI-ALIASED-IGNORED. +//! +//! Measured on the issue's test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, a +//! pixel layer with an orange (255, 128, 0) rectangle at x 100..=299, y 75..=224. Black Satin, +//! Normal, Opacity 100 %, Angle 90, Distance 20, Size 10, Invert off. The tables are the G channel +//! of the flattened image down column x 200 from y 75 to y 224 (128 = no satin, 0 = full black +//! satin), written as the issue writes them: `0x11` is the value 0 eleven times in a row. +//! +//! On main `satin_map` never read `Satin::anti_alias`, so a Gaussian or Ring Satin gave one map +//! both ways. In the reference application Anti-aliased moves both bands of the column upwards: +//! the top band gets lighter at its inner end and the bottom band darker. One sub-pixel source +//! offset reproduces both bands for both contours - the third of a pixel towards the top-left the +//! Inner Shadow (#14934) and Drop Shadow (#14881) measured - applied to both shifted copies of the +//! shape, so the satin's own Distance is unchanged and the whole pattern moves. + +use super::*; +use photocraft_doc::Satin; + +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 +} + +fn curve(name: &str, pts: &[(f32, f32)]) -> Contour { + Contour::Custom { + name: name.into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + // Every inner point of a built-in preset is a corner (the Contour picker stores it that + // way), so the curve is its polyline. + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + } +} + +/// The Gaussian contour as the built-in preset carries it (`layer_style::CONTOURS`). +fn gaussian() -> Contour { + curve( + "Gaussian", + &[ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ], + ) +} + +/// The Ring contour as the built-in preset carries it (`layer_style::CONTOURS`). +fn ring() -> Contour { + curve( + "Ring", + &[ + (0.0, 0.0), + (0.031, 0.078), + (0.039, 0.117), + (0.117, 0.383), + (0.172, 0.609), + (0.195, 0.734), + (0.266, 0.953), + (0.305, 1.0), + (0.344, 0.992), + (0.383, 0.922), + (0.43, 0.805), + (0.477, 0.641), + (0.57, 0.281), + (0.617, 0.141), + (0.664, 0.055), + (0.703, 0.016), + (0.742, 0.016), + (0.773, 0.062), + (0.836, 0.234), + (0.859, 0.344), + (0.891, 0.445), + (0.914, 0.547), + (0.945, 0.734), + (0.977, 0.875), + (1.0, 1.0), + ], + ) +} + +/// A built-in preset the issue did not measure with Anti-aliased. +fn cone() -> Contour { + curve( + "Cone", + &[ + (0.0, 0.0), + (0.172, 0.477), + (0.195, 0.555), + (0.266, 0.711), + (0.383, 0.922), + (0.43, 0.969), + (0.477, 0.992), + (0.523, 0.992), + (0.57, 0.969), + (0.664, 0.859), + (0.703, 0.789), + (0.742, 0.711), + (0.836, 0.477), + (0.859, 0.398), + (0.914, 0.266), + (0.945, 0.156), + (0.977, 0.078), + (1.0, 0.0), + ], + ) +} + +fn satin(size: f32, distance: f32, angle: f32, contour: Contour, anti_aliased: bool, invert: bool) -> Satin { + Satin { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle, + distance, + size, + contour, + anti_alias: anti_aliased, + invert, + } +} + +fn map(size: f32, distance: f32, angle: f32, contour: Contour, anti_aliased: bool) -> Map { + satin_map(&document_shape(), &satin(size, distance, angle, contour, anti_aliased, false)) +} + +/// The issue's document: Angle 90, Distance 20, Size 10. +fn issue_map(contour: Contour, anti_aliased: bool) -> Map { + map(10.0, 20.0, 90.0, contour, anti_aliased) +} + +/// The G channel of column x 200 from y 75 to y 224 under a black Normal satin, rounded to the +/// 8-bit levels the issue reads from the flattened image. +fn column(m: &Map) -> Vec { + (75..=224).map(|y| (128.0 * (1.0 - m.get(200, y))).round()).collect() +} + +/// The issue's run-length notation: `0x11` is 0 eleven times, a bare number is one value. +fn expand(spec: &str) -> Vec { + let mut out = Vec::new(); + for t in spec.split_whitespace() { + let (v, n) = t.split_once('x').unwrap_or((t, "1")); + let (v, n): (f32, usize) = (v.parse().unwrap(), n.parse().unwrap()); + out.extend(std::iter::repeat_n(v, n)); + } + out +} + +/// A top half followed by its mirror image ("the bottom half mirrors the top half"). +fn mirrored(top: &str) -> Vec { + let mut v = expand(top); + let mut bottom = v.clone(); + bottom.reverse(); + v.extend(bottom); + v +} + +/// Assert the column against `want` within `tol` levels, with per-row exceptions `(y, tol)`. +fn assert_column(m: &Map, want: &[f32], tol: f32, exceptions: &[(usize, f32)], what: &str) { + assert_eq!(want.len(), 150, "{what}: the measured column has 150 rows"); + for (i, (got, want)) in column(m).iter().zip(want).enumerate() { + let y = 75 + i; + let tol = exceptions.iter().find(|(ey, _)| *ey == y).map_or(tol, |(_, t)| *t); + assert!((got - want).abs() <= tol, "{what}, y {y}: G {got} vs measured {want} (within {tol})"); + } +} + +/// 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 +} + +const GAUSSIAN_OFF: &str = "0x11 1x3 3 6 13 26 46 71 93 107 116 121 124 125 126 127 128x47"; +const GAUSSIAN_ON: &str = "0x10 1x3 2 4 8 16 32 55 79 98 110 117 122 124 126 127x2 128x94 127 126 125 123 119 113 103 86 63 39 21 10 5 2 1x3 0x11"; +const RING_OFF: &str = "0x11 4 12 25 43 69 102 126 124 94 46 12 1 13 37 64 89 108 121 128x46"; +const RING_ON: &str = "0x10 1 7 16 30 51 80 112 127 115 78 34 6 3 20 46 72 95 113 124 128x91 126 117 102 81 55 28 8 3 22 62 105 126 120 91 60 37 21 10 3 0x11"; + +/// Done when: Gaussian with Anti-aliased gives the measured column within 3 levels. +#[test] +fn anti_aliased_gaussian_gives_the_measured_column() { + assert_column(&issue_map(gaussian(), true), &expand(GAUSSIAN_ON), 3.0, &[], "Gaussian, Anti-aliased"); +} + +/// Done when: Ring with Anti-aliased gives the measured column within 3 levels. One row is the +/// exception: at y 100 the Ring's off path on main already sits 3 levels from the measured +/// Anti-aliased-off column (61 against 64, `without_anti_alias_the_columns_stay_as_today`), and the +/// same row lands 4 levels off with the flag on (68 against 72). That residue is the off path's, +/// not the offset's; every other row of the column lands within 3. +#[test] +fn anti_aliased_ring_gives_the_measured_column() { + assert_column(&issue_map(ring(), true), &expand(RING_ON), 3.0, &[(100, 4.0)], "Ring, Anti-aliased"); +} + +/// The flag moves both bands, so neither column can be met by the off path: the measured +/// difference is what the change adds, not slack in the tolerance. +#[test] +fn anti_aliased_moves_both_bands() { + for (name, contour) in [("Gaussian", gaussian()), ("Ring", ring())] { + let (on, off) = (column(&issue_map(contour.clone(), true)), column(&issue_map(contour, false))); + let top = (0..40).map(|i| (on[i] - off[i]).abs()).fold(0.0, f32::max); + let bottom = (110..150).map(|i| (on[i] - off[i]).abs()).fold(0.0, f32::max); + assert!(top > 3.0 && bottom > 3.0, "{name}: Anti-aliased moved the top band by {top:.1} and the bottom band by {bottom:.1} levels"); + } +} + +/// Done when: without Anti-aliased the columns stay as today. The whole maps keep the hashes they +/// had on main 610c86b969, and the columns sit within 3 levels of the issue's measured +/// Anti-aliased-off tables. The row y 150 stays 128 and the layer centre stays uncovered in every +/// case, as measured. +#[test] +fn without_anti_alias_the_columns_stay_as_today() { + let gauss = issue_map(gaussian(), false); + assert_eq!(bit_hash(&gauss), 0x287f_b22f_d709_0159, "the Gaussian Satin map (Anti-aliased off) moved"); + assert_column(&gauss, &mirrored(GAUSSIAN_OFF), 3.0, &[], "Gaussian, Anti-aliased off"); + let ring_off = issue_map(ring(), false); + assert_eq!(bit_hash(&ring_off), 0x6581_1338_3ebc_56d5, "the Ring Satin map (Anti-aliased off) moved"); + assert_column(&ring_off, &mirrored(RING_OFF), 3.0, &[], "Ring, Anti-aliased off"); + for contour in [Contour::Linear, gaussian(), ring()] { + for aa in [false, true] { + let m = issue_map(contour.clone(), aa); + assert_eq!(m.get(200, 150), 0.0, "the layer centre gained satin ({contour:?}, Anti-aliased {aa})"); + for x in 100..=299 { + assert!(m.get(x, 150) < 0.5 / 128.0, "row y 150 is not 128 at x {x} ({contour:?}, Anti-aliased {aa})"); + } + } + } +} + +/// Done when: with Linear, Anti-aliased on gives a pixel-identical image to Anti-aliased off. +/// Contours the issue did not measure with Anti-aliased (Cone here) keep today's map too. +#[test] +fn linear_and_unmeasured_contours_ignore_anti_alias() { + for size in [3.0, 10.0, 30.0] { + assert_eq!(bit_hash(&map(size, 20.0, 90.0, Contour::Linear, true)), bit_hash(&map(size, 20.0, 90.0, Contour::Linear, false)), "Linear Size {size}"); + } + assert_eq!(bit_hash(&issue_map(Contour::Linear, true)), 0xbc2c_550d_40a1_6091, "the Linear Satin map moved"); + assert_eq!(bit_hash(&issue_map(cone(), true)), bit_hash(&issue_map(cone(), false)), "a Cone Satin moved with Anti-aliased"); +} + +/// The gate shared with the shadows (`anti_aliased_geometry` at no spread): Size 0 and Size 1 are +/// not a blur wider than the identity (Size 1 is its own measured kernel, #14983), so the offset +/// would be the whole edge; neither was measured with Anti-aliased and both keep today's map. +#[test] +fn identity_blur_sizes_keep_todays_map() { + for size in [0.0, 1.0] { + for contour in [gaussian(), ring()] { + assert_eq!(bit_hash(&map(size, 20.0, 90.0, contour.clone(), true)), bit_hash(&map(size, 20.0, 90.0, contour, false)), "Size {size}"); + } + } + assert_eq!(bit_hash(&map(1.0, 20.0, 90.0, gaussian(), false)), 0x7746_6f79_0561_5215, "the Size 1 Gaussian Satin map moved"); +} + +/// Guard: the rule is in the inputs, not keyed to the measured document. Other Sizes, Distances +/// and Angles take the offset too; with the flag off they keep the maps they had on main. +#[test] +fn the_offset_follows_the_inputs() { + for (size, distance, angle) in [(3.0, 20.0, 90.0), (30.0, 20.0, 90.0), (10.0, 50.0, 45.0)] { + assert_ne!( + bit_hash(&map(size, distance, angle, gaussian(), true)), + bit_hash(&map(size, distance, angle, gaussian(), false)), + "Anti-aliased did nothing at Size {size}, Distance {distance}, Angle {angle}" + ); + } + assert_eq!(bit_hash(&map(3.0, 20.0, 90.0, gaussian(), false)), 0xc2d9_f2ff_2e28_b5e5, "Size 3 Gaussian off"); + assert_eq!(bit_hash(&map(30.0, 20.0, 90.0, gaussian(), false)), 0x34f9_ed94_4796_b7cd, "Size 30 Gaussian off"); + assert_eq!(bit_hash(&map(10.0, 50.0, 45.0, gaussian(), false)), 0x251b_da84_c855_0df1, "Distance 50 Angle 45 Gaussian off"); +} + +/// Invert flips the result after the contour (#14981), so an inverted Anti-aliased Satin is the +/// exact opposite of the same Satin without Invert; the flag off keeps main's inverted map. +#[test] +fn invert_stays_the_opposite_with_anti_alias() { + let shape = document_shape(); + let off = satin_map(&shape, &satin(10.0, 20.0, 90.0, gaussian(), false, true)); + assert_eq!(bit_hash(&off), 0x9bd6_7f2d_bcb2_1e9d, "the inverted Gaussian Satin map (Anti-aliased off) moved"); + let plain = satin_map(&shape, &satin(10.0, 20.0, 90.0, gaussian(), true, false)); + let inverted = satin_map(&shape, &satin(10.0, 20.0, 90.0, gaussian(), true, true)); + for ((p, i), a) in plain.v.iter().zip(&inverted.v).zip(&shape.v) { + assert!((p + i - a).abs() < 1e-6, "Invert is not the opposite of the Anti-aliased Satin: {p} + {i} vs {a}"); + } +} diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index ed7ac850d07..415c00da7b1 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -66,6 +66,8 @@ pub mod fx_visibility_cmds; pub mod gallery_cmds; pub mod gradient_fill_cmds; pub mod group_view_cmds; +#[cfg(test)] +mod history_brush_default_source_tests; pub mod history_cmds; pub mod history_menu_cmds; pub mod history_options_cmds; diff --git a/crates/engine-core/src/cmd/adjust_cmds.rs b/crates/engine-core/src/cmd/adjust_cmds.rs index 3d310b703a3..3888cf7186d 100644 --- a/crates/engine-core/src/cmd/adjust_cmds.rs +++ b/crates/engine-core/src/cmd/adjust_cmds.rs @@ -103,9 +103,11 @@ pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result) -> Result { const CMD: &str = "colorLookup"; let (mut name, mut lut, mut size, mut tetrahedral, mut dither, mut source) = match base { @@ -118,6 +120,15 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result Ok(None), + Some("rgb") => Ok(Some(false)), + Some("bgr") => Ok(Some(true)), + Some(o) => Err(bad(CMD, format!("`{key}` must be \"rgb\" or \"bgr\", not `{o}`"))), + }; + // Data Order BGR reverses each table line; Table Order RGB (not the standard BGR) makes red the slowest index. + let swap_out = order("dataOrder")?.unwrap_or(false); + let swap_in = !order("tableOrder")?.unwrap_or(true); let format = match opt_str(CMD, p, "lutFormat")? { None | Some("auto") => None, Some("cube") => Some(craft_cms::lutfile::Format::Cube), @@ -169,7 +180,8 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result) -> Result bool { + let utf16 = |rest: &[u8], from: fn([u8; 2]) -> u16| String::from_utf16_lossy(&rest.as_chunks::<2>().0.iter().map(|&c| from(c)).collect::>()); + let text = match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, u16::from_le_bytes), + [0xFE, 0xFF, rest @ ..] => utf16(rest, u16::from_be_bytes), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => String::from_utf8_lossy(bytes).into_owned(), + }; + text.lines().any(|line| line.split('#').next().unwrap_or("").split_whitespace().next() == Some("LUT_3D_SIZE")) +} + +/// A standard `n`³ table (red index fastest, lines R G B) re-read in the reference application's other orders: +/// `swap_in` (Table Order RGB) reads the file with the red index slowest, `swap_out` (Data Order BGR) reads each +/// line as B G R. Both are red/blue swaps, of the input axes and of the outputs. The same rule PR #9218 applies to a +/// PSD's stored `tableOrder` / `dataOrder`. A short table reads its missing nodes as black (the parser has +/// already checked the length). +fn cube_in_order(data: &[f32], n: usize, swap_in: bool, swap_out: bool) -> Vec { + let mut out = Vec::with_capacity(data.len()); + for b in 0..n { + for g in 0..n { + for r in 0..n { + let node = if swap_in { (r * n + g) * n + b } else { (b * n + g) * n + r }; + let mut c: [f32; 3] = node.checked_mul(3).and_then(|at| data.get(at..at + 3)).and_then(|s| s.try_into().ok()).unwrap_or_default(); + if swap_out { + c.reverse(); + } + out.extend(c); + } + } + } + out +} + /// A Color Lookup smart filter's `recorded` params with the interpolation and dither it renders with written out: /// a key it never recorded runs as trilinear without dither (`lookup_from_params` with no base), and the legacy /// `tetrahedral` flag, which wins over `interpolation`, becomes `interpolation`. Its editor opens on these rather than @@ -927,6 +974,10 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests; +#[cfg(test)] +#[path = "color_lookup_order_tests.rs"] +mod color_lookup_order_tests; + #[cfg(test)] #[path = "color_lookup_defaults_tests.rs"] mod color_lookup_defaults_tests; diff --git a/crates/engine-core/src/cmd/color_lookup_order_tests.rs b/crates/engine-core/src/cmd/color_lookup_order_tests.rs new file mode 100644 index 00000000000..b3fea274a38 --- /dev/null +++ b/crates/engine-core/src/cmd/color_lookup_order_tests.rs @@ -0,0 +1,197 @@ +//! Color Lookup's Data Order and Table Order for `.cube` files (#14423), measured in the reference +//! application with `swap2.cube` (2x2x2, out = (b, g, r)) over gray strips and six colour strips. + +use super::*; + +/// The issue's strips: grays, then (200,50,50) (50,200,50) (50,50,200) (255,128,0) (30,60,90) (128,128,128). +const STRIPS: [[u8; 3]; 10] = + [[0, 0, 0], [64, 64, 64], [192, 192, 192], [255, 255, 255], [200, 50, 50], [50, 200, 50], [50, 50, 200], [255, 128, 0], [30, 60, 90], [128, 128, 128]]; + +const DEPTHS: [u64; 3] = [8, 16, 32]; + +/// `swap2.cube`: a 2³ table in the standard layout (red index fastest) whose output is (b, g, r). +fn swap2() -> String { + let mut cube = String::from("TITLE \"swap2\"\nLUT_3D_SIZE 2\n"); + for b in 0..2 { + for g in 0..2 { + for r in 0..2 { + cube.push_str(&format!("{b} {g} {r}\n")); + } + } + } + cube +} + +/// A one-row document with one pixel per strip at `depth`. +fn strips(depth: u64) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": STRIPS.len(), "height": 1, "depth": depth, "mode": "rgb"})).unwrap(); + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for c in STRIPS { + data.extend(photocraft_raster::from_rgba(&fmt, [0, 1, 2, 3].map(|i| c.get(i).map_or(1.0, |v| f32::from(*v) / 255.0)))); + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + s +} + +/// The strips as 0..255 levels. +fn levels(s: &Session) -> Vec<[f32; 3]> { + let d = s.active().unwrap(); + let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(); + (0..STRIPS.len() as i32).map(|x| surf.rgba(x, 0)).map(|p| [p[0] * 255.0, p[1] * 255.0, p[2] * 255.0]).collect() +} + +fn swapped(c: [u8; 3]) -> [u8; 3] { + [c[2], c[1], c[0]] +} + +fn assert_strips(got: &[[f32; 3]], want: impl Fn([u8; 3]) -> [u8; 3], what: &str) { + for (strip, px) in STRIPS.iter().zip(got) { + let w = want(*strip); + for c in 0..3 { + assert!((px[c] - f32::from(w[c])).abs() <= 0.5, "{what}: strip {strip:?} gave {px:?}, want {w:?}"); + } + } +} + +/// The issue's truth table: the defaults apply the file as written; BGR data or RGB table order +/// alone undo the swap; both together swap again. +#[test] +fn the_four_orders_give_the_measured_swap2_results() { + let cases: [(Option<&str>, Option<&str>, bool); 5] = [ + (None, None, true), + (Some("rgb"), Some("bgr"), true), + (Some("bgr"), Some("bgr"), false), + (Some("rgb"), Some("rgb"), false), + (Some("bgr"), Some("rgb"), true), + ]; + for depth in DEPTHS { + for (data, table, swaps) in cases { + let mut s = strips(depth); + let mut p = json!({"data": swap2(), "fileName": "swap2.cube", "dither": false}); + if let Some(o) = data { + p["dataOrder"] = json!(o); + } + if let Some(o) = table { + p["tableOrder"] = json!(o); + } + s.execute("image.adjustments.colorLookup", p).unwrap(); + let what = format!("{depth} bit, data {data:?}, table {table:?}"); + assert_strips(&levels(&s), if swaps { swapped } else { |c| c }, &what); + } + } +} + +/// Table Order RGB transposes the grid (blue index fastest), so a table that is not symmetric +/// in its axes reads different nodes: out = (r, 0.25 + 0.5g, 0.125 + 0.25b) as in #9126. +#[test] +fn table_order_moves_nodes_and_data_order_reverses_each_line() { + let f = |r: f32, g: f32, b: f32| [r, 0.25 + 0.5 * g, 0.125 + 0.25 * b]; + let mut cube = String::from("LUT_3D_SIZE 2\n"); + for i in 0..8 { + let [r, g, b] = f((i & 1) as f32, (i >> 1 & 1) as f32, (i >> 2 & 1) as f32); + cube.push_str(&format!("{r} {g} {b}\n")); + } + // Input pure red (255, 0, 0) for each order, as PR #9218 reads a PSD's stored orders. + let cases = [("rgb", "bgr", f(1.0, 0.0, 0.0)), ("bgr", "bgr", [0.125, 0.25, 1.0]), ("rgb", "rgb", f(0.0, 0.0, 1.0)), ("bgr", "rgb", [0.375, 0.25, 0.0])]; + for (data, table, want) in cases { + let mut one = crate::session(); + one.execute("file.new", json!({"width": 1, "height": 1, "depth": 16, "mode": "rgb", "background": "backgroundColor", "backgroundColor": [1, 0, 0]})) + .unwrap(); + one.execute("image.adjustments.colorLookup", json!({"data": cube, "fileName": "f.cube", "dataOrder": data, "tableOrder": table, "dither": false})) + .unwrap(); + let d = one.active().unwrap(); + let px = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(0, 0); + for c in 0..3 { + assert!((px[c] - want[c]).abs() < 1e-3, "data {data}, table {table}: {px:?}, want {want:?}"); + } + } +} + +/// `.3dl` and `.look` files ignore both orders: Lustre tables have their own layout. +#[test] +fn other_formats_ignore_the_orders() { + let mut lut = String::from("0 1023\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + // Out = (b, g, r), blue fastest as `.3dl` files are. + lut.push_str(&format!("{} {} {}\n", b * 1023, g * 1023, r * 1023)); + } + } + } + let mut plain = strips(8); + plain.execute("image.adjustments.colorLookup", json!({"data": lut, "fileName": "swap2.3dl", "dither": false})).unwrap(); + let mut ordered = strips(8); + ordered + .execute("image.adjustments.colorLookup", json!({"data": lut, "fileName": "swap2.3dl", "dataOrder": "bgr", "tableOrder": "rgb", "dither": false})) + .unwrap(); + assert_eq!(levels(&plain), levels(&ordered)); + assert_ne!(levels(&plain), levels(&strips(8)), "the .3dl applied"); +} + +/// Not measured for 1D `.cube` files (`LUT_1D_SIZE`): they keep today's result whatever the orders. +#[test] +fn a_1d_cube_ignores_the_orders() { + let cube = "LUT_1D_SIZE 2\n0 0 0\n0.5 1 0.25\n"; + let mut plain = strips(8); + plain.execute("image.adjustments.colorLookup", json!({"data": cube, "fileName": "ramp.cube", "dither": false})).unwrap(); + let mut ordered = strips(8); + ordered + .execute("image.adjustments.colorLookup", json!({"data": cube, "fileName": "ramp.cube", "dataOrder": "bgr", "tableOrder": "rgb", "dither": false})) + .unwrap(); + assert_eq!(levels(&plain), levels(&ordered)); +} + +/// A smart filter records the orders with its params, so a re-run (here: an edit of the smart +/// object's contents being re-rendered through the filter) gives the same pixels. +#[test] +fn a_smart_filter_keeps_both_orders() { + for depth in DEPTHS { + let mut s = strips(depth); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let p = json!({"data": swap2(), "fileName": "swap2.cube", "dataOrder": "bgr", "tableOrder": "bgr", "dither": false}); + s.execute("image.adjustments.colorLookup", p).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + let sf = sm.smart_filters.last().unwrap(); + assert_eq!(sf.params["dataOrder"], "bgr"); + assert_eq!(sf.params["tableOrder"], "bgr"); + // The filter re-runs from its recorded params: BGR data + BGR table undoes the file's swap. + let flat = photocraft_compose::flatten(&d.doc).into_px(); + let got: Vec<[f32; 3]> = flat.iter().take(STRIPS.len()).map(|p| [p[0] * 255.0, p[1] * 255.0, p[2] * 255.0]).collect(); + assert_strips(&got, |c| c, &format!("smart filter, {depth} bit")); + } +} + +/// Wrong values are refused with the key named, and nothing is applied. +#[test] +fn bad_order_values_are_errors_not_panics() { + for (key, value) in [ + ("dataOrder", json!("grb")), + ("dataOrder", json!("")), + ("dataOrder", json!(1)), + ("dataOrder", json!(true)), + ("tableOrder", json!("RGBA")), + ("tableOrder", json!(0.5)), + ("tableOrder", json!(["rgb"])), + ("tableOrder", json!({"order": "rgb"})), + ] { + let mut s = strips(8); + let before = levels(&s); + let mut p = json!({"data": swap2(), "fileName": "swap2.cube"}); + p[key] = value.clone(); + let e = s.execute("image.adjustments.colorLookup", p).unwrap_err(); + assert!(e.to_string().contains(key), "{key}={value}: {e}"); + assert_eq!(levels(&s), before, "{key}={value} changed pixels"); + // Without a LUT the value is still checked. + assert!(s.execute("image.adjustments.colorLookup", json!({key: value})).is_err(), "{key}={value} without a LUT"); + } +} diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs b/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs index 8f84de4fe72..768d0a2dcea 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs @@ -40,6 +40,9 @@ pub(super) fn purge(s: &mut Session, what: &str) -> Result { if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { for st in &mut s.docs { st.history.clear(); + // The state source went back to the default with the states (#2966), so the + // engine's record of that choice goes with it (#12845). + st.source_state_id = None; st.coalesce = None; } freed += b; diff --git a/crates/engine-core/src/cmd/history_brush_default_source_tests.rs b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs new file mode 100644 index 00000000000..8b1b5a28b20 --- /dev/null +++ b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs @@ -0,0 +1,121 @@ +//! #12845 (EPIC-HISTORY-BRUSH #12618): the History Brush's default source is the open snapshot, +//! the document as opened, not the oldest state held. `historySource` therefore reports +//! `{snapshot, name}` with the document's name on a new or opened document, the default survives +//! the history filling up, deleting the open snapshot leaves no source, and with History Options › +//! Automatically Create First Snapshot off the default stays the oldest state. + +use serde_json::{Value, json}; + +use crate::Session; + +/// The active document's History Brush source, as `historySource` in `doc_inspect` reports it. +fn source(s: &Session) -> Value { + crate::inspect::document(s.active().unwrap())["historySource"].clone() +} + +/// The name of the active document's first snapshot row. +fn opened_name(s: &Session) -> String { + s.active().unwrap().snapshots()[0].name.clone() +} + +#[test] +fn the_default_source_is_the_open_snapshot_named_after_the_document() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)})); + assert_eq!(s.active().unwrap().doc.name, opened_name(&s), "the open snapshot is named after the document"); + // Edits move the oldest state's label but not the default. + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)})); +} + +#[test] +fn the_default_open_snapshot_survives_a_full_history() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let expected = source(&s); + s.active_mut().unwrap().history.max_states = 2; + for _ in 0..6 { + s.execute("layer.new.layer", json!({})).unwrap(); + } + let st = s.active().unwrap(); + assert_eq!(st.history.past_len(), 2, "the history filled up and older states fell off"); + assert!(st.history.entries().first().is_some_and(|label| label != "New"), "the opening state is gone from row 0: {:?}", st.history.entries()); + assert_eq!(source(&s), expected, "the default still names the document as opened"); + assert_eq!(st.snapshots().len(), 1, "the open snapshot is not a state and is never trimmed"); +} + +#[test] +fn deleting_the_open_snapshot_leaves_no_source() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert!(source(&s).is_null(), "no source until one is set"); + // An explicit state source still works after that. + s.execute("history.setSource", json!({"state": 0})).unwrap(); + assert_eq!(source(&s)["state"], 0); +} + +#[test] +fn the_default_follows_automatically_create_first_snapshot() { + // Each session starts from the default and carries its own preferences: the option is set on + // the session that then opens the document. + for first in [false, true] { + let mut s = crate::session(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": first})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + if first { + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)}), "the open snapshot"); + } else { + // Not measured: no open snapshot exists, so today's default (the oldest state) stays. + assert_eq!(source(&s), json!({"state": 0, "label": "New"}), "the oldest state held"); + } + } +} + +/// A state set in the panel is still the source once the open snapshot is gone: the default does +/// not overwrite an explicit choice. +#[test] +fn an_explicit_state_source_survives_deleting_the_open_snapshot() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(source(&s), json!({"state": 1, "label": "New Layer"})); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(source(&s), json!({"state": 1, "label": "New Layer"}), "explicit sources are untouched"); +} + +/// With Automatically Create First Snapshot off, deleting states down to one and setting a state +/// source keep working exactly as today (the oldest-state default). +#[test] +fn without_an_open_snapshot_the_oldest_state_default_remains() { + let mut s = crate::session(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + // The current state is a redo row now; the default is still row 0. + assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(source(&s)["label"], "New Layer"); +} + +/// `history.newSnapshot` with `replaceExisting` drops a snapshot of that name, so taking the +/// document's own name removes the open snapshot. Snapshot ids are never reused, so the new row is +/// not the open snapshot, and the default source is gone with it (#12845). +#[test] +fn a_replacement_named_after_the_document_takes_the_default_source_away() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let name = s.active().unwrap().doc.name.clone(); + s.execute("layer.new.layer", json!({})).unwrap(); + let fresh = s.execute("history.newSnapshot", json!({"name": name, "replaceExisting": true})).unwrap()["snapshot"].as_u64().unwrap(); + assert_ne!(fresh, 0, "the new row takes a fresh id"); + assert!(source(&s).is_null(), "no open snapshot, so no default source"); + // A snapshot or a state picked by hand still works. + s.execute("history.setSource", json!({"snapshot": fresh})).unwrap(); + assert_eq!(source(&s)["snapshot"], json!(fresh)); + s.execute("history.setSource", json!({"state": 0})).unwrap(); + assert_eq!(source(&s)["state"], 0); +} diff --git a/crates/engine-core/src/cmd/history_source_cmds.rs b/crates/engine-core/src/cmd/history_source_cmds.rs index 192b5ad045b..2b5ee6c5c20 100644 --- a/crates/engine-core/src/cmd/history_source_cmds.rs +++ b/crates/engine-core/src/cmd/history_source_cmds.rs @@ -1,7 +1,9 @@ //! The History Brush's source (#2966): the History panel's source column, at the left of every //! state and snapshot, sets what the History Brush (and Fill › History) restores from. Exactly one -//! source per document; by default the oldest state held (Photoshop's default is the first -//! snapshot, the document as opened, which that state is until it falls off the history). +//! source per document; by default the open snapshot, the first History panel snapshot (the +//! document as opened, named after it; #12845), which outlives the states (#12618). With History +//! Options › Automatically Create First Snapshot off there is no open snapshot, and the default +//! stays the oldest state held; deleting the open snapshot also leaves no source until one is set. //! //! A state source is kept by state, not by index ([`photocraft_ops::History::set_brush_source`]), //! so it stays on its state while older states fall off, and that state is kept when it would fall @@ -41,14 +43,38 @@ pub enum HistorySource { Snapshot(u64), } -/// The document's History Brush source, `None` once the source state or snapshot is gone. +/// The document's History Brush source, `None` once the source state or snapshot is gone. With no +/// source set it is the open snapshot (the document as opened, #12845); when no open snapshot was +/// taken (History Options › Automatically Create First Snapshot off) it is the oldest state held, +/// as before. pub fn source(st: &DocState) -> Option { - match st.source_snapshot.or_else(|| st.history.brush_source_snapshot()) { - Some(id) => st.snapshots().iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)), + if let Some(id) = st.source_snapshot.or_else(|| st.history.brush_source_snapshot()) { + return st.snapshots().iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)); + } + // A state set in the panel is kept by its state id: it stays the source while older states fall + // off and is gone once it is deleted or discarded (#2966). ops' + // [`photocraft_ops::History::brush_source`] reads row 0 both for such a set state and for "none + // set", so the choice is recorded here in `source_state_id` (#12845). While a state source is + // set, ops keeps the answer: Clear History holds it back until its undo, and an action folding + // its steps can rename the row (#3536). + if let Some(id) = st.source_state_id { + return st.history.row_of(id).or_else(|| st.history.brush_source()).map(HistorySource::State); + } + match st.open_snapshot { + // The document as opened outlives the states, so a click still restores it (#12618). + // Deleting this snapshot leaves no source, as for any deleted source. + Some(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| HistorySource::Snapshot(s.id)), + // Not measured (Automatically Create First Snapshot off): today's default. None => st.history.brush_source().map(HistorySource::State), } } +/// Whether `src` is the document's open snapshot, the History panel's first row (the document as +/// opened): the History Brush's default source (#12845). +pub fn is_open_snapshot(st: &DocState, src: HistorySource) -> bool { + matches!(src, HistorySource::Snapshot(id) if st.open_snapshot == Some(id)) +} + pub fn source_of(st: &DocState, src: HistorySource) -> Option> { match src { HistorySource::State(i) => st.history.row_doc(i, &st.doc), @@ -90,11 +116,15 @@ fn set_source(s: &mut Session, p: &Value) -> Result { if !st.history.set_brush_source(i) { return Err(bad(format!("no history state {i}"))); } + // Kept by state id as well, so the open-snapshot default can tell this choice from + // ops' never-set default (#12845). + st.source_state_id = st.history.row_id(i); st.source_snapshot = None; } Some(HistorySource::Snapshot(id)) => { // No state is the source now, so none is kept past its time. st.history.reset_brush_source(); + st.source_state_id = None; st.source_snapshot = Some(id); } } diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index d17d29feab9..4a91a2c9673 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -1382,6 +1382,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "document": index, "name": name })) } +/// `image.duplicate` with the History Brush source its copy starts on (#12845). `add_document` took +/// an open snapshot holding the document the copy was made from, so the open-snapshot default names +/// that row; the copy's own baseline is the "Duplicate Image" state, so that state is its source. +/// A wrapper, so the pin stays out of `duplicate`: main's #14680 fix ends that function, and a line +/// inside it would conflict when main is merged in. +fn duplicate_with_source(s: &mut Session, p: &Value) -> Result { + let out = duplicate(s, p)?; + if let Some(st) = s.active_mut() { + st.source_state_id = st.history.row_id(0); + } + Ok(out) +} + macro_rules! spec { ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } @@ -1458,7 +1471,7 @@ pub fn specs() -> Vec { spec!("image.mode.bits8", "8 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U8)), spec!("image.mode.bits16", "16 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U16)), spec!("image.mode.bits32", "32 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::F32)), - spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate), + spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate_with_source), ] } diff --git a/crates/engine-core/src/cmd/new_document_history_name_tests.rs b/crates/engine-core/src/cmd/new_document_history_name_tests.rs index 7cd855830cd..7824f1bbb37 100644 --- a/crates/engine-core/src/cmd/new_document_history_name_tests.rs +++ b/crates/engine-core/src/cmd/new_document_history_name_tests.rs @@ -50,18 +50,20 @@ fn every_background_and_mode_of_file_new_gives_new() { } #[test] -fn the_first_state_stays_new_through_undo_and_redo_and_is_the_default_brush_source() { +fn the_first_state_stays_new_through_undo_and_redo_while_the_default_source_is_the_open_snapshot() { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let source = |s: &Session| crate::inspect::document(s.active().unwrap())["historySource"].clone(); - assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + // The default source is the open snapshot (#12845); the "New" state stays the opening state. + let opened = |s: &Session| crate::inspect::document(s.active().unwrap())["snapshots"][0]["name"].as_str().unwrap().to_string(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened(&s)})); s.execute("layer.new.layer", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New", "New Layer"])); s.execute("edit.undo", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New"])); s.execute("edit.redo", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New", "New Layer"])); - assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened(&s)})); } #[test] diff --git a/crates/engine-core/src/cmd/table/image/adjustments.rs b/crates/engine-core/src/cmd/table/image/adjustments.rs index 9cbd3cbe08d..15f23f9c39c 100644 --- a/crates/engine-core/src/cmd/table/image/adjustments.rs +++ b/crates/engine-core/src/cmd/table/image/adjustments.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { ( "colorLookup", "Color Lookup…", - r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it)"##, + r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"dataOrder":"rgb|bgr"="rgb","tableOrder":"rgb|bgr"="bgr","interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it; dataOrder/tableOrder: how a 3D .cube's lines and nodes are ordered, ignored for other files)"##, ), ]; /// Composed layer options (`path`, `opacity`, `name`, `mode`, `clipToPrevious`) belong immediately diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 8ac2581f79e..26f8b0d9321 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -68,8 +68,18 @@ pub struct DocState { /// When Saving), so saving an unchanged document again doesn't add a duplicate row. pub(crate) save_snapshot: Option, /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: - /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). + /// the source is a state ([`DocState::source_state_id`]) or the default + /// ([`crate::history_source_cmds::source`]). pub(crate) source_snapshot: Option, + /// The state id chosen as the History Brush's source (`history.setSource {state}`, or the state + /// `image.duplicate` starts its copy on, which is not the document as opened); `None`: no state + /// was set, so the default applies (#12845). The history keeps the state it names past its + /// own time; Edit › Purge › Histories clears it along with the states it removed. + pub(crate) source_state_id: Option, + /// The snapshot holding the document as opened (`DocState::new`), `None` when History Options › + /// Automatically Create First Snapshot was off when the document was admitted. It is the + /// History Brush's default source (#12845); deleting that snapshot leaves the default empty. + pub(crate) open_snapshot: Option, /// Names the user gave layers (Rename Layer, Duplicate Layer's Name, `type.edit`'s name): a /// type layer keeps such a name although it looks like a copy's ("Title copy 2"), while a /// name Duplicate Layer made still follows the text (#9023). Kept for the session only. @@ -134,7 +144,8 @@ impl DocState { }; let doc = Arc::new(doc); // Photoshop's first snapshot: the document as opened, named after it, so the History - // panel's top row can always bring it back (#2966). + // panel's top row can always bring it back (#2966). It is also the History Brush's default + // source (#12845). let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { inputs: DocStateInputs { doc, active_layer, selected_layers: active_layer.into_iter().collect() }, @@ -164,6 +175,10 @@ impl DocState { next_snapshot: 1, save_snapshot: None, source_snapshot: None, + source_state_id: None, + // The id `DocState::new` gives the document-as-opened snapshot above; session's + // `add_document` clears it when Automatically Create First Snapshot is off. + open_snapshot: Some(0), typed_names: Default::default(), pixel_revision: 0, } diff --git a/crates/engine-core/src/session/documents.rs b/crates/engine-core/src/session/documents.rs index 8c358493a96..c3739cbe544 100644 --- a/crates/engine-core/src/session/documents.rs +++ b/crates/engine-core/src/session/documents.rs @@ -225,9 +225,11 @@ impl Session { st.history.max_bytes = self.prefs.get().performance.history_cap_bytes(); st.history.non_linear = self.prefs.get().history_options.allow_non_linear_history; // History Options › Automatically Create First Snapshot off: no snapshot of the document - // as opened, so the History panel starts at the opening state (#2966). + // as opened, so the History panel starts at the opening state (#2966) and the History + // Brush's default stays the oldest state held (#12845). if !self.prefs.get().history_options.automatically_create_first_snapshot { st.snapshots_mut().clear(); + st.open_snapshot = None; } self.pcraft_caches.insert(st.doc.id, Default::default()); self.docs.push(craft_tracked::Tracked::new(st)); diff --git a/crates/engine-paint/src/cmd/fill_cmds/tests.rs b/crates/engine-paint/src/cmd/fill_cmds/tests.rs index 4d5169f7073..9923e1ed197 100644 --- a/crates/engine-paint/src/cmd/fill_cmds/tests.rs +++ b/crates/engine-paint/src/cmd/fill_cmds/tests.rs @@ -167,7 +167,7 @@ fn history_pattern_and_content_aware() { // History: back to state 1 (after the white fill). s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); assert_eq!(px(&s, 5, 5), [1.0; 4]); - // The default source is the oldest state: the empty layer. + // The default source is the open snapshot, the document as opened (the empty layer; #12845). s.execute(CMD, json!({"contents": "history"})).unwrap(); assert_eq!(px(&s, 5, 5)[3], 0.0); assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); diff --git a/crates/engine-paint/src/cmd/fill_key_cmds.rs b/crates/engine-paint/src/cmd/fill_key_cmds.rs index 4fcd5c64dc8..9ca5e9fab26 100644 --- a/crates/engine-paint/src/cmd/fill_key_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_key_cmds.rs @@ -1,6 +1,7 @@ //! Photoshop's fill keys (#249): ⌥⌫ fills the selection (or the whole layer) with the foreground //! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. ⌘⌥⌫ fills -//! from history: the History Brush's source state (the oldest state still held). Photoshop +//! from history: the History Brush's source (by default its open snapshot, the document as +//! opened; #12845). Photoshop //! has no menu item for them; here they are ordinary commands with default shortcuts, so they //! appear in Edit › Keyboard Shortcuts (Tools) and can be rebound, recorded and driven by agents. //! @@ -156,7 +157,7 @@ pub fn specs() -> Vec { label: "Fill from History", menu: &[], shortcut: Some("Cmd+Alt+Backspace"), - params: r##"{"state":n? (default: the History Brush's source, the oldest state still held),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##, + params: r##"{"state":n? (default: the History Brush's source, by default its open snapshot - the document as opened),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##, enabled: fill_enabled, run: fill_history, journal: true, @@ -262,7 +263,8 @@ mod tests { s.execute("edit.fillForeground", json!({})).unwrap(); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 6})).unwrap(); s.execute("edit.fillHistory", json!({})).unwrap(); - // The oldest state (the new, transparent layer) comes back inside the selection only. + // The open snapshot (the new, transparent document; #12845) comes back inside the + // selection only. assert_eq!(px(&s, 1, 1)[3], 0.0); assert_eq!(px(&s, 6, 1), [1.0, 0.0, 0.0, 1.0]); // A named state, and refused ones change nothing. diff --git a/crates/engine/tests/it/actions_single_history.rs b/crates/engine/tests/it/actions_single_history.rs index 0b66eb00ac4..50282a6c806 100644 --- a/crates/engine/tests/it/actions_single_history.rs +++ b/crates/engine/tests/it/actions_single_history.rs @@ -238,6 +238,25 @@ fn in_action_undo_clear_restores_history_and_keeps_grouped_image_undo() { } } +/// A source set on the row that is current when a play folds its steps into one state: the play +/// moves that row, and Fill › History must still paint its exact pixels (#12845, review round two). +#[test] +fn source_on_the_current_row_survives_the_play_folding_its_steps() { + for single_state in [false, true] { + let mut s = history_control_session(single_state); + // `history_control_session` set the source on the row current then: the green document. + let green = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(green, [0.0, 1.0, 0.0, 1.0], "the source row is the green fill"); + s.actions_mut().list = only("Fill blue", vec![("edit.fill".into(), json!({"color": "#0000ff"}))]); + let result = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "singleState={single_state}: {result}"); + let after_the_play = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(after_the_play, [0.0, 0.0, 1.0, 1.0], "singleState={single_state}: the play filled blue"); + s.execute("edit.fill", json!({"contents": "history"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0), green, "singleState={single_state}: the source row still paints"); + } +} + /// A source held by Clear History becomes active on Undo Clear, with no additional image Undo row. #[test] fn cleared_intermediate_source_restores_exact_pixels_after_undo_redo() { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 652e368a46e..64f7dc28248 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -129,6 +129,7 @@ mod paint_in_fx_view_cmds; mod paint_in_fx_visibility_cmds; mod paint_in_gradient_fill_cmds; mod paint_in_hidden_target; +mod paint_in_history_brush_default_source; mod paint_in_history_cmds; mod paint_in_history_menu_cmds; mod paint_in_history_options_cmds; diff --git a/crates/engine/tests/it/paint_in_history_brush_default_source.rs b/crates/engine/tests/it/paint_in_history_brush_default_source.rs new file mode 100644 index 00000000000..10a14677933 --- /dev/null +++ b/crates/engine/tests/it/paint_in_history_brush_default_source.rs @@ -0,0 +1,163 @@ +//! #12845 (EPIC-HISTORY-BRUSH #12618): the History Brush's default source is the open snapshot, so +//! a click paints the pixels the document had when it opened, even after the history filled up and +//! the opening state fell off. The opened pixels are read from the open snapshot itself, so the +//! comparison is against the state captured at open, not a hand-written colour. + +use photocraft_engine::Session; +use serde_json::{Value, json}; + +/// A white 8×8 document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap(); + s +} + +fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layers[0].surface().unwrap().rgba(x, y) +} + +/// The pixel (3, 3) of the document as opened, as the History panel holds it (snapshot 0). +fn opened_pixel(s: &Session) -> [f32; 4] { + s.active().unwrap().snapshots()[0].doc.layers[0].surface().unwrap().rgba(3, 3) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) +} + +fn paint(s: &mut Session, extra: Value) -> photocraft_engine::Result { + let mut p = json!({"points": [[3, 3]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.historyBrush", p) +} + +#[test] +fn default_source_reports_the_open_snapshot() { + let s = session(); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); +} + +#[test] +fn the_default_brush_paints_the_pixels_the_document_opened_with() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + assert!(rgba(&s, 3, 3)[0] > 0.9 && rgba(&s, 3, 3)[1] < 0.1, "the stroke painted red"); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the default source restores the opened pixel: {:?} vs {at_open:?}", rgba(&s, 3, 3)); +} + +#[test] +fn a_default_brush_click_still_paints_the_opened_image_after_the_history_fills_up() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff", "#ff00ff"] { + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": colour})).unwrap(); + } + let st = s.active().unwrap(); + assert!(st.history.entries()[0] != "New", "the opening state fell off row 0: {:?}", st.history.entries()); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "a click still restores the opened image: {:?} vs {at_open:?}", rgba(&s, 3, 3)); +} + +#[test] +fn deleting_the_open_snapshot_leaves_the_default_without_a_source() { + let mut s = session(); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"].is_null()); + let before = rgba(&s, 3, 3); + let e = paint(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("source was deleted"), "{e}"); + assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); + // Setting a source makes it paint again: a snapshot of the red document, taken before the + // canvas turns blue so a paint that did nothing cannot pass by leaving the red in place. + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let red = rgba(&s, 3, 3); + let snap = s.execute("history.newSnapshot", json!({"name": "Red"})).unwrap()["snapshot"].clone(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + assert!(!close(rgba(&s, 3, 3), red), "the canvas holds the blue fill before the click"); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), red), "the click restored the snapshot's red: {:?}", rgba(&s, 3, 3)); +} + +/// With Automatically Create First Snapshot off there is no open snapshot: the default keeps +/// today's behaviour and paints the oldest state held. +#[test] +fn without_the_open_snapshot_the_default_still_paints_the_oldest_state() { + let mut s = Session::new(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap(); + // Tidy-up only: preferences belong to the session, so this does not reach other tests; it + // leaves the option as the default it started from. + let restore = |s: &mut Session| s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": true})).unwrap(); + assert!(s.active().unwrap().snapshots().is_empty()); + let opened = rgba(&s, 3, 3); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), opened), "the oldest state (the opening state) is the source"); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "New"})); + restore(&mut s); +} + +/// The Art History Brush shares the document's one source, so its default is the open snapshot too. +/// The history has filled up here, so the oldest state held would paint a colour instead. (The +/// brush itself is 8-bit only, so this document is 8-bit.) +#[test] +fn the_art_history_brush_default_source_is_the_open_snapshot() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 8, "background": "white"})).unwrap(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": colour})).unwrap(); + } + assert!(!close(rgba(&s, 3, 3), at_open), "the canvas holds the last stroke"); + s.execute("paint.artHistoryBrush", json!({"points": [[3, 3]], "size": 40, "hardness": 100})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the open snapshot, not the trimmed row 0: {:?}", rgba(&s, 3, 3)); +} + +/// Fill > History reads the same source: with the history full its default fills the opened image +/// back, where the oldest state held would fill a colour. +#[test] +fn fill_from_history_uses_the_open_snapshot_after_the_history_fills_up() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("edit.fill", json!({"color": colour})).unwrap(); + } + let st = s.active().unwrap(); + assert!(st.history.entries().first().is_some_and(|label| label == "Fill"), "row 0 is a fill state: {:?}", st.history.entries()); + s.execute("edit.fill", json!({"contents": "history"})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the opened image comes back: {:?}", rgba(&s, 3, 3)); +} + +/// `history.newSnapshot` with `replaceExisting` drops the open snapshot by name, and snapshot ids +/// are never reused: the default is left empty and the brush refuses, as after a delete (#12845). +#[test] +fn a_replacement_snapshot_named_after_the_document_leaves_the_brush_without_a_source() { + let mut s = session(); + let name = s.active().unwrap().doc.name.clone(); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + let fresh = s.execute("history.newSnapshot", json!({"name": name, "replaceExisting": true})).unwrap()["snapshot"].as_u64().unwrap(); + assert_ne!(fresh, 0, "a fresh id, so the new row is not the open snapshot"); + assert!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"].is_null()); + let before = rgba(&s, 3, 3); + let e = paint(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("source was deleted"), "{e}"); + assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); + // Picking that snapshot as the source paints again: turn the canvas blue first, so a paint + // that did nothing cannot pass by leaving the red stroke in place. + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + assert!(!close(rgba(&s, 3, 3), before), "the canvas holds the blue fill before the click"); + s.execute("history.setSource", json!({"snapshot": fresh})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), before), "the picked snapshot holds the red stroke: {:?}", rgba(&s, 3, 3)); +} diff --git a/crates/engine/tests/it/paint_in_history_source_cmds.rs b/crates/engine/tests/it/paint_in_history_source_cmds.rs index 900e00eb6e8..62bc48a16ff 100644 --- a/crates/engine/tests/it/paint_in_history_source_cmds.rs +++ b/crates/engine/tests/it/paint_in_history_source_cmds.rs @@ -31,9 +31,11 @@ fn close(a: [f32; 3], b: [f32; 3]) -> bool { } #[test] -fn default_source_is_the_oldest_state() { +fn default_source_is_the_open_snapshot() { let mut s = session(); - assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "New"})); + // #12845: the default is the document as opened, not the oldest state held. + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); brush(&mut s, json!({})); assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "{:?}", rgb(&s)); } @@ -105,15 +107,17 @@ fn deleting_the_source_state_leaves_no_source() { } /// Edit › Purge › Histories clears the states: the source goes back to the default instead of -/// leaving every document without one (#3536 review). +/// leaving every document without one (#3536 review). Since #12845 that default is the open +/// snapshot, which Purge keeps, so the brush paints the document as opened. #[test] fn purging_histories_resets_a_state_source() { let mut s = session(); s.execute("history.setSource", json!({"state": 1})).unwrap(); s.execute("edit.purge.histories", json!({})).unwrap(); - assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "Fill"})); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); brush(&mut s, json!({})); - assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "the only state left: {:?}", rgb(&s)); + assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "the open snapshot Purge kept: {:?}", rgb(&s)); s.execute("edit.fill", json!({"contents": "history"})).unwrap(); } diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index 6b51c792117..5085b9dc115 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -90,9 +90,11 @@ impl B { // satin_map let (dx, dy) = offset(s.angle, fx::satin_distance(s)); let kernel = if s.size == 1.0 { fx::size_one_kernel() } else { fx::tent_kernel(s.size) }; - let a = self.shift(In::Shape, dx, dy, 0.0, false); + // #14984: the CPU's Anti-aliased sub-pixel offset on both copies, on the CPU's gate. + let aa = fx::satin_aa_shift(s.anti_alias, &s.contour, s.size); + let a = self.shift(In::Shape, dx + aa, dy + aa, 0.0, false); let a = self.conv(a, kernel.clone()); - let c = self.shift(In::Shape, -dx, -dy, 0.0, false); + let c = self.shift(In::Shape, -dx + aa, -dy + aa, 0.0, false); let c = self.conv(c, kernel); self.finish_lut(a, Some(c), s.invert, fx::satin_lut(&s.contour), true, 0); 1 diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index 897f6a58cf3..00a1369fecb 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -586,3 +586,53 @@ fn anti_aliased_inner_shadow_stage_follows_the_measured_geometry() { assert_eq!(far_choke_on.0.len(), 2, "Choke 50 % at Distance 5 shifts the source and the distance field"); assert_eq!(far_choke_on, far_choke_off, "the Choke 50 % program at Distance 5 stayed whole-pixel: on {:?}, off {:?}", far_choke_on.0, far_choke_off.0); } + +/// #14984: the GPU's Satin program takes the CPU's Anti-aliased sub-pixel offset on both of its +/// shifted copies (`satin_aa_shift`), so the pattern moves while the Distance stays. Linear, +/// unmeasured contours and Size 1 keep today's program, key and all. +#[test] +fn anti_aliased_satin_shifts_both_copies() { + use photocraft_doc::{Contour, Satin}; + let named = |name: &str| Contour::Custom { + name: name.into(), + points: [(0.0, 0.0), (0.383, 0.414), (1.0, 1.0)] + .iter() + .map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }) + .collect(), + corners: vec![false, true, false], + }; + let satin = |size: f32, contour: Contour, anti_aliased: bool| Satin { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 90.0, + distance: 20.0, + size, + contour, + anti_alias: anti_aliased, + invert: false, + }; + let shifts = |s: Satin| -> (Vec<[f32; 4]>, u64) { + let p = program(&Effect::Satin(s), &GlobalLight::default(), false); + (p.stages.iter().filter(|s| s.kernel == Kernel::MShift).map(|s| s.p0).collect(), p.key) + }; + let aa = photocraft_compose::effects::satin_aa_shift(true, &named("Gaussian"), 10.0); + assert_eq!(aa, -1.0 / 3.0, "the CPU offset the GPU has to copy"); + // Angle 90, Distance 20: the copies sit at (0, ±20) (`offset` rounds; -0.0 for the x of the first). + let off = shifts(satin(10.0, named("Gaussian"), false)); + assert_eq!(off.0.len(), 2, "a Satin shifts the shape twice"); + for name in ["Gaussian", "Ring"] { + let on = shifts(satin(10.0, named(name), true)); + assert_eq!(on.0.len(), 2, "{name}: still two shifts"); + for (o, f) in on.0.iter().zip(&off.0) { + assert_eq!([o[0], o[1], o[2], o[3]], [f[0] + aa, f[1] + aa, f[2], f[3]], "{name}: each copy carries the sub-pixel offset"); + } + assert_ne!(on.1, off.1, "{name}: the flag has to invalidate the cached program"); + } + for (s, what) in + [(satin(10.0, Contour::Linear, true), "Linear"), (satin(10.0, named("Cone"), true), "Cone"), (satin(1.0, named("Gaussian"), true), "Size 1")] + { + let mut flag_off = s.clone(); + flag_off.anti_alias = false; + assert_eq!(shifts(s), shifts(flag_off), "the {what} Satin program moved with Anti-aliased"); + } +} diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 1843c30e8bb..3393997f03a 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -3670,6 +3670,98 @@ fn sibling_compositors_have_independent_residency_and_configuration() { assert_ne!(g.comp.resident_budget(), sibling.resident_budget()); } +// --------------------------------------------------------------------------------------------- +// #14984: the Satin's Anti-aliased checkbox has to reach the GPU map program too. + +/// The Ring contour as the built-in preset carries it - one of the two contours #14984 measures. +fn ring_contour() -> Contour { + let pts: [(f32, f32); 25] = [ + (0.0, 0.0), + (0.031, 0.078), + (0.039, 0.117), + (0.117, 0.383), + (0.172, 0.609), + (0.195, 0.734), + (0.266, 0.953), + (0.305, 1.0), + (0.344, 0.992), + (0.383, 0.922), + (0.43, 0.805), + (0.477, 0.641), + (0.57, 0.281), + (0.617, 0.141), + (0.664, 0.055), + (0.703, 0.016), + (0.742, 0.016), + (0.773, 0.062), + (0.836, 0.234), + (0.859, 0.344), + (0.891, 0.445), + (0.914, 0.547), + (0.945, 0.734), + (0.977, 0.875), + (1.0, 1.0), + ]; + Contour::Custom { + name: "Ring".into(), + points: pts.iter().map(|(input, output)| Cp { input: *input, output: *output }).collect(), + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + } +} + +/// The #14984 test document: the #14934 canvas and orange rectangle under a black Normal Satin +/// (Opacity 100 %, Invert off) with the Angle, Distance, Size, contour and Anti-aliased as given. +fn satin_doc(angle: f32, distance: f32, size: f32, contour: Contour, anti_aliased: bool) -> Document { + let mut d = inner_shadow_doc(10.0, 0.0, 0.0, false); + if let Some(px) = d.layers.get_mut(1) { + px.effects.items = vec![Effect::Satin(Satin { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: Color::BLACK, + angle, + distance, + size, + contour, + anti_alias: anti_aliased, + invert: false, + })]; + } + d +} + +/// Done when (#14984): CPU and GPU agree on the issue's document with Gaussian and Ring, Anti-aliased +/// on and off (whole-texture and paged 256 px compositors), and the GPU's column x 200 lands on the +/// issue's tables within 3 levels at y 91, a row the flag moves: Gaussian 16 on and 13 off, Ring +/// 112 on and 102 off. +#[test] +fn anti_aliased_satin_matches_the_cpu() { + let Some(mut g) = gpu() else { return }; + for (name, contour, on, off) in [("Gaussian", gaussian_contour(), 16.0, 13.0), ("Ring", ring_contour(), 112.0, 102.0)] { + for (aa, want) in [(true, on), (false, off)] { + let px = check_full(&mut g, &satin_doc(90.0, 20.0, 10.0, contour.clone(), aa), &format!("#14984 satin, {name}, Anti-aliased {aa}")).whole; + let got = px[91 * 400 + 200][1] * 255.0; + assert!((got - want).abs() <= 3.0, "GPU {name} satin, Anti-aliased {aa}, at (200, 91): G {got:.1} vs measured {want}"); + } + } +} + +/// The gate's neighbours (#14984): Linear and Size 1 take no offset, other Sizes, Distances and +/// Angles take it; both compositors must agree on each, plain and paged. +#[test] +fn anti_aliased_satin_neighbours_match_the_cpu() { + let Some(mut g) = gpu() else { return }; + let shape = Rect::new(96, 71, 304, 229); + for (angle, distance, size, contour, what) in [ + (90.0, 20.0, 10.0, Contour::Linear, "Linear"), + (90.0, 20.0, 1.0, gaussian_contour(), "Size 1 Gaussian"), + (90.0, 20.0, 3.0, gaussian_contour(), "Size 3 Gaussian"), + (45.0, 50.0, 10.0, ring_contour(), "Angle 45 Distance 50 Ring"), + (-30.0, 7.0, 25.0, gaussian_contour(), "Angle -30 Distance 7 Size 25 Gaussian"), + ] { + diff_rect(&mut g, &satin_doc(angle, distance, size, contour, true), shape, &format!("#14984 satin, {what}, Anti-aliased")) + .unwrap_or_else(|e| panic!("{e}")); + } +} + // --------------------------------------------------------------------------------------------- // #14934: the Inner Shadow's Anti-aliased checkbox has to reach the GPU map program too. diff --git a/crates/paint/src/brush_texture_depth_fade_tests.rs b/crates/paint/src/brush_texture_depth_fade_tests.rs new file mode 100644 index 00000000000..0c336203589 --- /dev/null +++ b/crates/paint/src/brush_texture_depth_fade_tests.rs @@ -0,0 +1,98 @@ +//! Texture Depth Fade rises into the pattern; the other Fade controls still fade out. + +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +use crate::dynamics::{DabBuilder, StepInput}; +use crate::rng::{rand01, stream}; +use crate::{ + BrushSettings, Control, Dab, Dynamic, GrayTile, MaskMode, Pattern, ShapeDynamics, Smoothing, Stroke, StrokePoint, Texture, Transfer, dabs, render_stroke, +}; + +fn brush() -> BrushSettings { + BrushSettings { + size: 60.0, + hardness: 1.0, + spacing: 1.5, + smoothing: Smoothing { enabled: false, ..Default::default() }, + texture: Texture { + enabled: true, + each_tip: true, + mode: MaskMode::Subtract, + depth: 1.0, + pattern: Pattern::Tile(GrayTile::from_fn(16, 16, |x, _| if x < 8 { 64.0 / 255.0 } else { 192.0 / 255.0 })), + depth_jitter: Dynamic { control: Control::Fade, fade_steps: 10, ..Default::default() }, + ..Default::default() + }, + ..Default::default() + } +} + +fn steps(brush: &BrushSettings, count: u64) -> Vec { + let mut builder = DabBuilder::new(brush); + let mut out = Vec::new(); + for step in 0..count { + builder.build(&StepInput { point: StrokePoint::new(100.0 + step as f64 * 90.0, 100.0, 1.0), direction: 0.0, initial_direction: 0.0, step }, &mut out); + } + out +} + +#[test] +fn texture_depth_fade_rises_from_minimum_and_holds() { + for (depth, minimum, fade_steps) in [(1.0, 0.0, 10), (0.8, 0.25, 10), (1.0, 0.0, 0)] { + let mut b = brush(); + b.texture.depth = depth; + b.texture.depth_jitter.minimum = minimum; + b.texture.depth_jitter.fade_steps = fade_steps; + let dabs = steps(&b, 14); + for (i, dab) in dabs.iter().enumerate() { + let ramp = (i as f32 / fade_steps.max(1) as f32).min(1.0); + let expected = depth * (minimum + (1.0 - minimum) * ramp); + assert!((dab.depth - expected).abs() < 1e-6, "step {i}, minimum {minimum}, fade {fade_steps}: {} != {expected}", dab.depth); + } + b.texture.each_tip = false; + assert!(steps(&b, 14).iter().all(|dab| dab.depth == depth)); + } +} + +#[test] +fn texture_depth_fade_subtract_stripes_start_solid_and_gain_texture() { + let b = brush(); + let points = vec![StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(1270.0, 100.0, 1.0)]; + let dabs = dabs(&Stroke { brush: b.clone(), points: points.clone() }); + assert!(dabs.len() >= 14); + let mut surface = Surface::new(PixelFormat::RGBA32F); + render_stroke(&mut surface, &b, &points, None, false, 1.0); + for (i, dab) in dabs.iter().take(14).enumerate() { + let ramp = (i as f32 / 10.0).min(1.0); + assert!((dab.depth - ramp).abs() < 1e-6, "dab {i}: {}", dab.depth); + for (offset, pattern_level) in [(0, 64.0), (8, 192.0)] { + // Sample the middle of each document-aligned stripe, safely inside the hard tip. + let x = (dab.center.x as i32).div_euclid(16) * 16 + offset + 4; + let rgba = surface.rgba(x, 100); + let composite_grey = (1.0 - rgba[3]) * 255.0; + let expected = pattern_level * ramp; + assert!((composite_grey - expected).abs() <= 2.0, "dab {i}, stripe {pattern_level}: {composite_grey} != {expected}"); + assert_eq!(rgba[0], 0.0, "the stroke remains black"); + } + } +} + +#[test] +fn texture_jitter_without_fade_and_other_fade_controls_stay_unchanged() { + let mut b = brush(); + b.texture.depth = 0.8; + b.texture.depth_jitter = Dynamic { jitter: 0.75, minimum: 0.25, ..Default::default() }; + b.shape_dynamics = + ShapeDynamics { enabled: true, size: Dynamic { control: Control::Fade, fade_steps: 10, minimum: 0.2, ..Default::default() }, ..Default::default() }; + b.transfer = Transfer { enabled: true, opacity: Dynamic { control: Control::Fade, fade_steps: 4, ..Default::default() }, ..Default::default() }; + let dabs = steps(&b, 14); + assert_eq!(dabs, steps(&b, 14), "jitter replays exactly"); + for (i, dab) in dabs.iter().enumerate() { + let expected_depth = 0.8 * (1.0 - 0.75 * rand01(b.seed, i as u64, stream::DEPTH)).max(0.25); + assert!((dab.depth - expected_depth).abs() < 1e-6, "jitter-only depth at {i}: {}", dab.depth); + let expected_radius = 30.0 * (0.2 + 0.8 * (1.0 - (i as f32 / 10.0).min(1.0))); + assert!((dab.radius - expected_radius).abs() < 1e-5, "size Fade at {i}: {}", dab.radius); + assert!((dab.opacity - (1.0 - (i as f32 / 4.0).min(1.0))).abs() < 1e-6, "opacity Fade at {i}: {}", dab.opacity); + } +} diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 59b337ecd33..1d15eb85295 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -749,8 +749,18 @@ impl DabBuilder { }; // Texture depth (per tip). let tx = &b.texture; - let depth = - if tx.enabled && tx.each_tip { tx.depth.clamp(0.0, 1.0) * scalar(&tx.depth_jitter, s, r(stream::DEPTH)) } else { tx.depth.clamp(0.0, 1.0) }; + let depth = if tx.enabled && tx.each_tip { + // Texture Fade grows from Minimum Depth to Depth, unlike the other Fade controls. + // Reverse only its step so scalar keeps the same response curve, floor and jitter. + let depth_step = if tx.depth_jitter.control == Control::Fade { + StepInput { step: u64::from(tx.depth_jitter.fade_steps.max(1)).saturating_sub(s.step), ..*s } + } else { + *s + }; + tx.depth.clamp(0.0, 1.0) * scalar(&tx.depth_jitter, &depth_step, r(stream::DEPTH)) + } else { + tx.depth.clamp(0.0, 1.0) + }; out.push(Dab { center: c, radius, diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 80b7163cb33..5f7838d3257 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -489,6 +489,9 @@ mod mixer_load_supply_tests; #[cfg(test)] mod smoothing_catch_up_default_tests; +#[cfg(test)] +mod brush_texture_depth_fade_tests; + #[cfg(test)] mod brush_spacing_elliptic_tip_tests; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1c7a0413a77..057910f752b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -452,6 +452,7 @@ pub(crate) const PROMPTS: &[PromptRow] = &[ disk_change_prompt::answer, rasterize_prompt::answer, live_shape_prompt::answer, + replace_layer_mask_prompt::answer, assign_profile_layers_alert::answer, preset_group_prompt::answer, open_prompt::answer_prompt, @@ -682,13 +683,14 @@ const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE /// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not /// by the shape of the value. -fn dont_show_again_keys() -> [&'static str; 5] { +fn dont_show_again_keys() -> [&'static str; 6] { [ delete_layer_prompt::PREF, live_shape_prompt::PREF, assign_profile_layers_alert::PREF, crate::analysis::note_alerts::DELETE_NOTE_PREF, crate::retouch_ui::CAM_NO_PIXELS_PREF, + replace_layer_mask_prompt::PREF, ] } @@ -806,6 +808,8 @@ pub mod channel_options_ui; #[cfg(test)] mod color_lookup_no_remember_tests; #[cfg(test)] +mod color_lookup_order_ui_tests; +#[cfg(test)] mod color_lookup_smart_edit_tests; pub(crate) mod color_picker_preview; pub mod color_picker_ui; @@ -863,6 +867,7 @@ mod paths_export_document_bounds_tests; pub(crate) mod pattern_fill_ui; pub mod preset_group_prompt; pub mod rasterize_prompt; +pub(crate) mod replace_layer_mask_prompt; #[cfg(test)] mod rotate_canvas_layout_tests; pub(crate) mod rotate_canvas_ui; diff --git a/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs b/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs index 9f29624e960..c725ffa1658 100644 --- a/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs +++ b/crates/ui-egui/src/dialogs/apply_image_mask_group_tests.rs @@ -23,6 +23,8 @@ fn mask_channel_key(index: usize) -> String { use crate::PhotocraftApp; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::ParamKind; +use egui::accesskit::Role; +use egui_kittest::{Harness, kittest::Queryable}; use serde_json::{Value, json}; const APPLY: &str = "image.applyImage"; @@ -172,6 +174,63 @@ fn mask_channel_lists_gray_the_colours_and_the_alpha_channels() { assert_eq!(ids(&mut app, &mask_channel_key(target))[0], "RGB"); } +type MaskHarness = Harness<'static, Box>; + +fn mask_menu_harness() -> (MaskHarness, DialogId) { + let (app, ctx) = five_documents(); + let mut h = Harness::builder().with_context(ctx.clone()).with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(move |_| app); + h.run_steps(3); + let dialog = open(h.state_mut(), &ctx); + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, MASK_ON, json!(true)).unwrap(); + h.run_steps(4); + (h, dialog) +} + +fn change_mask_source(h: &mut MaskHarness, dialog: DialogId, name: &str) { + let source = index_of(h.state(), name).to_string(); + let ctx = h.ctx.clone(); + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, MASK_SOURCE, json!(source)).unwrap(); + h.run_steps(3); +} + +/// A separator occupies its own row in the popup. Read the positions of the selectable entries on either side. +fn mask_option_positions(h: &mut MaskHarness, label: &str, options: [&str; N]) -> [f32; N] { + // The mask's dropdown is below the source dropdown with the same label. + h.get_all_by_role_and_label(Role::ComboBox, label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).expect("the mask dropdown").click(); + h.run_steps(3); + let positions = options.map(|option| h.get_by_role_and_label(Role::ListBoxOption, option).rect().center().y); + h.key_press(egui::Key::Escape); + h.run_steps(2); + positions +} + +#[test] +fn mask_layer_menu_separates_merged_from_the_layers() { + let (mut h, dialog) = mask_menu_harness(); + mask_option_positions(&mut h, "Layer", ["Background"]); + change_mask_source(&mut h, dialog, "target"); + + let [merged, masked, top, background] = mask_option_positions(&mut h, "Layer", ["Merged", "Masked", "Top", "Background"]); + let step = background - top; + assert!((top - masked - step).abs() < 0.5, "the individual layers are consecutive"); + assert!(masked - merged > step + 1.0, "the Mask Layer menu separates Merged from the individual layers"); +} + +#[test] +fn mask_channel_menu_separates_the_alpha_channels_from_the_colour_channels() { + let (mut h, dialog) = mask_menu_harness(); + mask_option_positions(&mut h, "Channel", ["Gray"]); + change_mask_source(&mut h, dialog, "source"); + let [gray, red, green, blue] = mask_option_positions(&mut h, "Channel", ["Gray", "Red", "Green", "Blue"]); + assert!((red - gray - (green - red)).abs() < 0.5 && (blue - green - (green - red)).abs() < 0.5, "a list without alpha channels is consecutive"); + + change_mask_source(&mut h, dialog, "target"); + let [gray, red, green, blue, alpha] = mask_option_positions(&mut h, "Channel", ["Gray", "Red", "Green", "Blue", "Alpha 1"]); + let step = blue - green; + assert!((red - gray - step).abs() < 0.5 && (green - red - step).abs() < 0.5, "the composite and colour channels are consecutive"); + assert!(alpha - blue > step + 1.0, "the Mask Channel menu separates Blue from the alpha channels"); +} + #[test] fn ok_applies_through_the_chosen_mask_and_its_invert() { let (mut app, ctx) = five_documents(); diff --git a/crates/ui-egui/src/dialogs/color_lookup_order_ui_tests.rs b/crates/ui-egui/src/dialogs/color_lookup_order_ui_tests.rs new file mode 100644 index 00000000000..172ccc99532 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_lookup_order_ui_tests.rs @@ -0,0 +1,276 @@ +//! #14423: Image › Adjustments › Color Lookup shows Data Order and Table Order only while a `.cube` +//! file is the LUT, and OK applies the chosen orders. + +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::dialogs::filter_dialog::open; + +const COLOR_LOOKUP: &str = "image.adjustments.colorLookup"; + +/// `swap2.cube`: out = (b, g, r), red index fastest. +const SWAP2: &str = "LUT_3D_SIZE 2\n0 0 0\n0 0 1\n0 1 0\n0 1 1\n1 0 0\n1 0 1\n1 1 0\n1 1 1\n"; + +fn app_with_doc() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 4, "height": 4, "background": "#c83232"})).unwrap(); + app +} + +fn fields_of(app: &PhotocraftApp, id: DialogId) -> DialogFields { + app.framework.dialogs.get_by_id::(id).expect("open dialog").fields().clone() +} + +fn try_set(app: &mut PhotocraftApp, id: DialogId, key: &str, value: Value) -> Result<(), String> { + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, key, value) +} + +fn passes(app: &mut PhotocraftApp, n: usize) { + let ctx = app.ctx().clone(); + for _ in 0..n { + crate::testing::run_ui(&ctx, Default::default(), |ui| crate::dialogs::run(app, ui)); + } +} + +fn ok(app: &mut PhotocraftApp, id: DialogId) { + let ctx = app.ctx().clone(); + let _ = crate::dialogs::confirm(app, &ctx, id); + passes(app, 3); + assert!(app.framework.dialogs.get_by_id::(id).is_none(), "OK closes the dialog"); +} + +fn shown(app: &PhotocraftApp, id: DialogId) -> bool { + fields_of(app, id).bool("lutCube") == Some(true) +} + +fn pixel(app: &PhotocraftApp) -> [u8; 3] { + let px = app.session.active().unwrap().doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 1, 1)); + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +/// Hidden with no LUT, a built-in look or a `.3dl` from the LUT folder; shown for a `.cube` from the folder and +/// for a loaded LUT; and while hidden, the rows refuse values. +#[test] +fn the_orders_show_only_for_a_cube() { + let tmp = tempfile::tempdir().unwrap(); + let cube = tmp.path().join("swap2.cube"); + std::fs::write(&cube, SWAP2).unwrap(); + let threedl = tmp.path().join("ramp.3dl"); + std::fs::write(&threedl, "0 1023\n0 0 0\n0 0 1023\n0 1023 0\n0 1023 1023\n1023 0 0\n1023 0 1023\n1023 1023 0\n1023 1023 1023\n").unwrap(); + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + passes(&mut app, 2); + assert!(!shown(&app, id), "no LUT"); + assert!(try_set(&mut app, id, "dataOrder", json!("bgr")).is_err(), "a hidden row takes no value"); + let fields = fields_of(&app, id); + assert_eq!((fields.text("dataOrder"), fields.text("tableOrder")), (Some("rgb"), Some("bgr")), "the defaults"); + + try_set(&mut app, id, "lut", json!("warm")).unwrap(); + passes(&mut app, 2); + assert!(!shown(&app, id), "a built-in look"); + + try_set(&mut app, id, "file", json!(threedl.to_str().unwrap())).unwrap(); + passes(&mut app, 2); + assert!(!shown(&app, id), "a .3dl file"); + + try_set(&mut app, id, "file", json!(cube.to_str().unwrap())).unwrap(); + passes(&mut app, 2); + assert!(shown(&app, id), "a .cube file"); + try_set(&mut app, id, "dataOrder", json!("bgr")).unwrap(); + assert!(try_set(&mut app, id, "tableOrder", json!("grb")).is_err(), "only RGB and BGR"); +} + +/// OK with a `.cube` and Data Order BGR (Table Order left at BGR) applies the file's table read as B G R: the +/// swap2 table becomes the identity, as measured. With the defaults the file's swap applies. +#[test] +fn ok_applies_the_chosen_orders() { + let tmp = tempfile::tempdir().unwrap(); + let cube = tmp.path().join("swap2.cube"); + std::fs::write(&cube, SWAP2).unwrap(); + for (data_order, want) in [("rgb", [50, 50, 200]), ("bgr", [200, 50, 50])] { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + try_set(&mut app, id, "file", json!(cube.to_str().unwrap())).unwrap(); + passes(&mut app, 2); + try_set(&mut app, id, "dataOrder", json!(data_order)).unwrap(); + try_set(&mut app, id, "dither", json!(false)).unwrap(); + ok(&mut app, id); + assert_eq!(pixel(&app), want, "data order {data_order}"); + } +} + +/// `swap2` as a `.3dl` (blue index fastest, 12-bit codes) and as a `.look` (hex float32 RGB, red fastest): both +/// give out = (b, g, r), like the `.cube`. +fn swap2_other_formats() -> [(&'static str, String); 2] { + let mut threedl = String::from("0 1023\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + threedl.push_str(&format!("{} {} {}\n", b * 4095, g * 4095, r * 4095)); + } + } + } + let mut hex = String::new(); + for b in 0..2u8 { + for g in 0..2u8 { + for r in 0..2u8 { + for v in [b, g, r] { + hex.extend(f32::from(v).to_le_bytes().iter().map(|byte| format!("{byte:02x}"))); + } + } + } + } + [("swap2.3dl", threedl), ("swap2.look", format!("2{hex}"))] +} + +/// Load 3D LUT… hands the row a parsed table, which it holds as `.cube` text: a `.3dl` or `.look` loaded that way +/// must not show the orders (CodeRabbit on #16628). +#[test] +fn a_loaded_3dl_or_look_hides_the_orders() { + for (name, text) in swap2_other_formats() { + let lut = craft::cms::lutfile::parse(name, text.as_bytes()).unwrap(); + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + passes(&mut app, 2); + load(&mut app, id, &lut); + passes(&mut app, 2); + assert!(!shown(&app, id), "{name} loaded through Load 3D LUT…"); + assert!(try_set(&mut app, id, "dataOrder", json!("bgr")).is_err(), "{name}: a hidden row takes no value"); + } +} + +/// Orders picked for a `.cube` and kept while hidden don't reach the command once a `.3dl` or `.look` is loaded: +/// the result is the file's own swap, whatever the orders were. +#[test] +fn a_loaded_3dl_or_look_ignores_orders_left_from_a_cube() { + let tmp = tempfile::tempdir().unwrap(); + let cube = tmp.path().join("swap2.cube"); + std::fs::write(&cube, SWAP2).unwrap(); + for (name, text) in swap2_other_formats() { + let lut = craft::cms::lutfile::parse(name, text.as_bytes()).unwrap(); + for (data_order, table_order) in [("rgb", "bgr"), ("bgr", "bgr"), ("rgb", "rgb"), ("bgr", "rgb")] { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + try_set(&mut app, id, "file", json!(cube.to_str().unwrap())).unwrap(); + passes(&mut app, 2); + try_set(&mut app, id, "dataOrder", json!(data_order)).unwrap(); + try_set(&mut app, id, "tableOrder", json!(table_order)).unwrap(); + load(&mut app, id, &lut); + passes(&mut app, 2); + try_set(&mut app, id, "dither", json!(false)).unwrap(); + ok(&mut app, id); + assert_eq!(pixel(&app), [50, 50, 200], "{name} with data order {data_order}, table order {table_order}"); + } + } +} + +/// What Load 3D LUT… does to the open dialog once the picker has read `lut`. +fn load(app: &mut PhotocraftApp, id: DialogId, lut: &craft::cms::lutfile::LutFile) { + let before = fields_of(app, id); + let mut after = before.clone(); + crate::dialogs::filter_dialog::rows::take_loaded_lut(&mut after, lut); + let dialog = app.framework.dialogs.get_mut_by_id::(id).expect("open dialog"); + for (key, _) in before.iter().filter(|(key, _)| !after.contains(key)) { + dialog.clear_field(key); + } + for (key, value) in after.iter() { + dialog.set_field(key, value.clone()); + } +} + +/// An explicit LUT Format decides whether the LUT is a `.cube`, as it does for the command: `swap2.cube` text named +/// `swap2.txt` and read as Cube shows the orders and OK applies them (CodeRabbit on #16628). +#[test] +fn an_explicit_cube_format_shows_and_applies_the_orders() { + let tmp = tempfile::tempdir().unwrap(); + let txt = tmp.path().join("swap2.txt"); + std::fs::write(&txt, SWAP2).unwrap(); + for (source, data_order, want) in + [("file", "rgb", [50, 50, 200]), ("file", "bgr", [200, 50, 50]), ("data", "rgb", [50, 50, 200]), ("data", "bgr", [200, 50, 50])] + { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + passes(&mut app, 2); + if source == "file" { + try_set(&mut app, id, "file", json!(txt.to_str().unwrap())).unwrap(); + } else { + try_set(&mut app, id, "data", json!(SWAP2)).unwrap(); + try_set(&mut app, id, "fileName", json!("swap2.txt")).unwrap(); + } + try_set(&mut app, id, "lutFormat", json!("cube")).unwrap(); + passes(&mut app, 2); + assert!(shown(&app, id), "{source}: a .txt read as Cube"); + try_set(&mut app, id, "dataOrder", json!(data_order)).unwrap(); + try_set(&mut app, id, "dither", json!(false)).unwrap(); + ok(&mut app, id); + assert_eq!(pixel(&app), want, "{source}: data order {data_order}"); + } +} + +/// An explicit `.3dl` or `.look` format is no `.cube`, whatever the file is named: `swap2` in those formats, saved +/// as `swap2.cube`, hides the orders and ignores those left from a real `.cube`. +#[test] +fn an_explicit_other_format_hides_the_orders_of_a_cube_name() { + let tmp = tempfile::tempdir().unwrap(); + let cube = tmp.path().join("real.cube"); + std::fs::write(&cube, SWAP2).unwrap(); + for (name, text) in swap2_other_formats() { + let format = name.rsplit('.').next().unwrap(); + let named_cube = tmp.path().join(format!("{format}.cube")); + std::fs::write(&named_cube, &text).unwrap(); + for source in ["file", "data"] { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + try_set(&mut app, id, "file", json!(cube.to_str().unwrap())).unwrap(); + passes(&mut app, 2); + try_set(&mut app, id, "dataOrder", json!("bgr")).unwrap(); + try_set(&mut app, id, "lutFormat", json!(format)).unwrap(); + if source == "file" { + try_set(&mut app, id, "file", json!(named_cube.to_str().unwrap())).unwrap(); + } else { + try_set(&mut app, id, "file", json!("")).unwrap(); + try_set(&mut app, id, "data", json!(text)).unwrap(); + try_set(&mut app, id, "fileName", json!("swap2.cube")).unwrap(); + } + passes(&mut app, 2); + assert!(!shown(&app, id), "{format} named .cube, from {source}"); + try_set(&mut app, id, "dither", json!(false)).unwrap(); + ok(&mut app, id); + assert_eq!(pixel(&app), [50, 50, 200], "{format} named .cube, from {source}"); + } + } +} + +/// `.cube` text given as `data` with no file name is read as `lut.cube` under Auto and under an explicit Cube format, +/// so the orders show and OK applies them; an explicit `.3dl` or `.look` format still hides them (CodeRabbit on +/// #16628). +#[test] +fn inline_cube_data_without_a_file_name_shows_and_applies_the_orders() { + for (format, data_order, want) in + [("auto", "rgb", [50, 50, 200]), ("auto", "bgr", [200, 50, 50]), ("cube", "rgb", [50, 50, 200]), ("cube", "bgr", [200, 50, 50])] + { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + passes(&mut app, 2); + try_set(&mut app, id, "data", json!(SWAP2)).unwrap(); + try_set(&mut app, id, "lutFormat", json!(format)).unwrap(); + passes(&mut app, 2); + assert!(shown(&app, id), "{format}: inline .cube text"); + try_set(&mut app, id, "dataOrder", json!(data_order)).unwrap(); + try_set(&mut app, id, "dither", json!(false)).unwrap(); + ok(&mut app, id); + assert_eq!(pixel(&app), want, "{format}: data order {data_order}"); + } + for format in ["3dl", "look"] { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + passes(&mut app, 2); + try_set(&mut app, id, "data", json!(SWAP2)).unwrap(); + try_set(&mut app, id, "lutFormat", json!(format)).unwrap(); + passes(&mut app, 2); + assert!(!shown(&app, id), "{format}: an explicit other format"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 34f944bb4c2..2a8c33ef3e1 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -27,7 +27,7 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; mod color_settings_presets; -mod rows; +pub(crate) mod rows; pub(crate) use color_settings_presets::reconcile as reconcile_color_settings; pub(crate) use rows::{REPLACE_COLOR, replace_color_sample}; @@ -722,6 +722,11 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value { if command == "image.adjustments.colorLookup" && map.get("data").and_then(Value::as_str).is_some_and(str::is_empty) { map.remove("data"); } + // Data Order and Table Order belong to a `.cube` (#14423): values kept from one are not sent for another LUT. + if command == "image.adjustments.colorLookup" && !rows::lut_is_cube(fields) { + map.remove("dataOrder"); + map.remove("tableOrder"); + } if command == "image.mode.indexedColor" { // The matte colour row belongs to the "custom" choice, which the command takes as the colour itself. let color = map.remove(rows::MATTE_COLOR); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs index cda4b8792c2..dda20b709c5 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs @@ -6,7 +6,7 @@ //! blur row. //! //! These rows keep values under keys no command parameter has (`matteColor`, `sampleTool`, `resultPicked`, -//! `lutSize`, `lutError`) and Lens Blur's `channel:N` sources and Match Color's textual +//! `lutSize`, `lutError`, `lutCube`, `lutPicked`) and Lens Blur's `channel:N` sources and Match Color's textual //! `source`; the family's `command_params` (dialogs-w24) maps them back and leaves the private ones out. use photocraft_engine::color_cmds::ColorExt; @@ -55,6 +55,11 @@ const RESULT_PICKED: &str = "resultPicked"; /// The size and name of the LUT Load 3D LUT… embedded, and why one could not be read. const LUT_SIZE: &str = "lutSize"; const LUT_ERROR: &str = "lutError"; +/// Whether the chosen LUT is a `.cube` table: Data Order and Table Order show only then (#14423). +const LUT_CUBE: &str = "lutCube"; +/// A LUT Load 3D LUT… read. The picker hands over the parsed table, not the file's format, so the row can't tell a +/// `.cube` from a `.3dl` or `.look`: such a LUT takes no Data Order or Table Order, as before #14423. +const LUT_PICKED: &str = "lutPicked"; /// Builds the rows `command`'s dialog shows from the rows `params` the spec parser made. pub(crate) fn custom_rows(app: &mut PhotocraftApp, command: &str, params: &mut Vec) { @@ -295,6 +300,47 @@ fn lut_choice(fields: &DialogFields) -> LutChoice { photocraft_engine::adjust_cmds::LOOKS.iter().find(|(known, _)| *known == look).map_or(LutChoice::None, |(known, _)| LutChoice::Builtin(known)) } +/// Whether the chosen LUT is a `.cube` file, which Data Order and Table Order apply to: a LUT folder file or given +/// text that the command reads as Cube. An explicit LUT Format decides that, as it does for the command; under Auto +/// the file name does, and given text with no file name is read as `lut.cube`, as the command reads it. Built-in +/// looks are no files and have no orders, and a LUT Load 3D LUT… read has no known format ([`LUT_PICKED`]). +pub(crate) fn lut_is_cube(fields: &DialogFields) -> bool { + let named_cube = |name: &str, bytes: &[u8]| match fields.text("lutFormat") { + Some("cube") => true, + Some("3dl" | "look") => false, + _ => { + matches!(craft::cms::lutfile::Format::detect(name, bytes), craft::cms::lutfile::Format::Cube) + && std::path::Path::new(name).extension().is_some_and(|ext| ext.eq_ignore_ascii_case("cube")) + } + }; + // Given text, which the command reads before a built-in look, under its file name or, with none, as `lut.cube`; + // under Auto the command still tells a `.look` by its text. + let given = || { + let data = fields.text("data").filter(|data| !data.is_empty())?; + let name = fields.text("fileName").filter(|name| !name.is_empty()).unwrap_or("lut.cube"); + Some(named_cube(name, data.as_bytes())) + }; + match lut_choice(fields) { + LutChoice::Folder(path) => named_cube(&path.to_string_lossy(), b""), + _ => fields.bool(LUT_PICKED) != Some(true) && given().unwrap_or(false), + } +} + +/// Keeps [`LUT_CUBE`] in step with the chosen LUT; written only when it changes. +fn sync_lut_cube(fields: &mut DialogFields) { + let cube = lut_is_cube(fields); + if fields.bool(LUT_CUBE) != Some(cube) { + fields.set(LUT_CUBE, cube); + } +} + +/// Data Order and Table Order (#14423): a pair of radio buttons each, shown only while a `.cube` is the LUT, as +/// the reference application does. Not remembered, so every opening starts at its defaults (RGB, BGR). +fn order_row(key: &str, label: Label, default: &str) -> Param { + let options = vec![("rgb".to_owned(), Label::from(tl!("RGB"))), ("bgr".to_owned(), Label::from(tl!("BGR")))]; + Param::new(key, label, ParamKind::radio(options, Some(default.to_owned()))).visible_when(LUT_CUBE, true).not_remembered() +} + /// Writes a picked choice as the command's `lut` / `file` parameters; the loaded LUT already held is no pick. fn set_lut_choice(fields: &mut DialogFields, choice: &LutChoice) { let clear = |fields: &mut DialogFields, keys: &[&str]| keys.iter().for_each(|key| drop(fields.remove(key))); @@ -302,21 +348,31 @@ fn set_lut_choice(fields: &mut DialogFields, choice: &LutChoice) { match choice { LutChoice::None => { fields.set("lut", "none"); - clear(fields, &["file", "data", "fileName", LUT_SIZE]); + clear(fields, &["file", "data", "fileName", LUT_SIZE, LUT_PICKED]); } LutChoice::Builtin(id) => { fields.set("lut", *id); - clear(fields, &["file", "data", "fileName", LUT_SIZE]); + clear(fields, &["file", "data", "fileName", LUT_SIZE, LUT_PICKED]); } LutChoice::Folder(path) => { fields.set("lut", "none"); fields.set("file", path.to_string_lossy().into_owned()); - clear(fields, &["data", "fileName", LUT_SIZE]); + clear(fields, &["data", "fileName", LUT_SIZE, LUT_PICKED]); } _ => {} } } +/// Holds the LUT Load 3D LUT… read as the row's loaded LUT: its table as `.cube` text, which the command embeds, +/// marked [`LUT_PICKED`] because the file's own format is not known. +pub(crate) fn take_loaded_lut(fields: &mut DialogFields, lut: &craft::cms::lutfile::LutFile) { + set_lut_choice(fields, &LutChoice::None); + fields.set("data", write_cube(lut)); + fields.set("fileName", format!("{}.cube", lut.title)); + fields.set(LUT_SIZE, i64::try_from(lut.size).unwrap_or(0)); + fields.set(LUT_PICKED, true); +} + /// Color Lookup's 3D LUT menu lists the LUT folder's files after the built-in looks (#9754), as the adjustment /// layer's Properties do: one picker row over the command's `lut`, `file` and, for a LUT loaded from a file, /// `data` and `fileName`. @@ -342,15 +398,11 @@ fn color_lookup(app: &PhotocraftApp, params: &mut Vec) { } } match out.loaded { - Some(Ok(lut)) => { - set_lut_choice(fields, &LutChoice::None); - fields.set("data", write_cube(&lut)); - fields.set("fileName", format!("{}.cube", lut.title)); - fields.set(LUT_SIZE, i64::try_from(lut.size).unwrap_or(0)); - } + Some(Ok(lut)) => take_loaded_lut(fields, &lut), Some(Err(error)) => fields.set(LUT_ERROR, error.0), None => {} } + sync_lut_cube(fields); if let Some(error) = fields.text(LUT_ERROR) { ui.colored_label(ui.visuals().error_fg_color, error); } @@ -358,6 +410,11 @@ fn color_lookup(app: &PhotocraftApp, params: &mut Vec) { }) .companions(["file", "data", "fileName"]); params.insert(at.min(params.len()), row); + for (key, label, default) in [("dataOrder", Label::from(tl!("Data Order")), "rgb"), ("tableOrder", Label::from(tl!("Table Order")), "bgr")] { + if let Some(p) = params.iter_mut().find(|p| p.key == key) { + *p = order_row(key, label, default); + } + } } // --- Match Color ----------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/src/dialogs/replace_layer_mask_prompt.rs b/crates/ui-egui/src/dialogs/replace_layer_mask_prompt.rs new file mode 100644 index 00000000000..ff395b32181 --- /dev/null +++ b/crates/ui-egui/src/dialogs/replace_layer_mask_prompt.rs @@ -0,0 +1,89 @@ +//! A layer mask dragged (or Alt-dragged) in the Layers panel onto a layer that already has a layer +//! mask asks "Replace Layer Mask?" first, as in Photoshop (#16787): Yes (the default) moves the mask +//! there, or copies it with Alt, replacing the mask in one undo step; No changes nothing. A ticked +//! "Don't show again" (kept with the other dialog preferences under [`PREF`]) makes later drops +//! replace without asking. +//! +//! Groups and adjustment layers that have a mask still refuse the drop: what Photoshop does there was +//! not measured. + +use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt}; +use photocraft_doc::{Layer, LayerContent, LayerId}; +use serde_json::{Value, json}; + +use super::alerts; +use crate::PhotocraftApp; + +/// Its "Don't show again", under `Preferences::dialogs`. +pub const PREF: &str = "layer.layerMask.replace"; + +const COMMAND: &str = "layer.layerMask.moveTo"; + +/// What the question asked about: the mask of `from` going to `to` (a copy when `copy`), in this +/// `revision` of `document`. An edit or another document meanwhile makes the answer replace nothing. +pub(crate) struct ReplaceMask { + document: u64, + revision: u64, + from: LayerId, + to: LayerId, + copy: bool, +} + +/// Whether a layer mask dropped on `target` replaces its mask after the question: it has a layer +/// mask and is neither a group nor an adjustment layer. +pub(crate) fn asks_before_replacing(target: &Layer) -> bool { + target.mask.is_some() && !matches!(target.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) +} + +/// The `layer.layerMask.moveTo` step that moves (or with `copy` copies) the mask of `from` onto +/// `to`, replacing a mask there when `replace`. +pub(crate) fn move_action(from: LayerId, to: LayerId, copy: bool, replace: bool) -> (String, Value) { + let mut params = json!({"layer": from.0, "to": to.0, "copy": copy}); + if replace { + params["replace"] = json!(true); + } + (COMMAND.into(), params) +} + +/// A layer mask dropped from `from` onto `to`, which already has one. `Some` step to run at once when +/// "Don't show again" was ticked before; otherwise opens the question and returns `None`. +pub(crate) fn ask(app: &mut PhotocraftApp, from: LayerId, to: LayerId, copy: bool) -> Option<(String, Value)> { + if alerts::dismissed(app, PREF) { + return Some(move_action(from, to, copy, true)); + } + let (document, revision) = app.session.active().map(|st| (st.doc.id.0, st.revision))?; + let prompt = StandardPrompt::custom(tl!("Replace Layer Mask?").to_owned()) + .title(tl!("PhotoCraft").to_owned()) + .button(PromptChoice::Proceed, tl!("Yes").to_owned()) + .button(PromptChoice::Cancel, tl!("No").to_owned()) + .dont_show_again() + .tag(ReplaceMask { document, revision, from, to, copy }); + // An `Err` is another question already open: the drop waits for nothing and changes nothing. + let _ = alerts::open_prompt(app, prompt); + None +} + +/// The `PROMPTS` entry: Yes replaces the mask in one step and keeps a ticked "Don't show again"; No +/// changes nothing. `false` for another family's answer. +pub(crate) fn answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool { + let Some(ask) = answer.take_tag::() else { return false }; + if answer.choice != PromptChoice::Proceed { + return true; + } + match confirm(app, &ask) { + Ok(_) if answer.skip => alerts::remember_skip(app, PREF), + Ok(_) => {} + Err(error) => alerts::report_error(app, error), + } + true +} + +/// Runs the replacement when the document is still the one, in the revision, the question was asked in. +fn confirm(app: &mut PhotocraftApp, ask: &ReplaceMask) -> Result { + let current = app.session.active().map(|st| (st.doc.id.0, st.revision)); + if current != Some((ask.document, ask.revision)) { + return Err(tl!("The document changed. Drag the mask again to replace it.").into()); + } + let (command, params) = move_action(ask.from, ask.to, ask.copy, true); + app.run(&command, params) +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 59a2def794d..84d7cf6527c 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -879,25 +879,30 @@ fn apply_image_layers(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, /// The mask Channel list of a source document and its default (#14489): its composite, read as luminosity and so named /// Gray, the colour channels of a colour document, then its alpha channels (and Selection while it has one). A colour -/// document starts at its first colour channel, a one-channel document at Gray. The reference draws a rule before the -/// alpha channels; the hosted choice row takes no separators. -fn apply_image_mask_channels(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) { +/// document starts at its first colour channel and separates the alpha channels with a rule. A one-channel document +/// starts at Gray. +fn apply_image_mask_channel_row(key: &str, doc: &photocraft_doc::Document) -> Param { let mode = doc.pixel_format().mode; + let colour = mode.color_channels() > 1; let composite = photocraft_engine::channel_cmds::composite_name(mode).to_string(); let mut list = vec![(composite.clone(), Label::from(tl!("Gray")))]; let mut default = composite; - if mode.color_channels() > 1 { + if colour { let colors = photocraft_engine::channel_cmds::color_names(mode); if let Some(first) = colors.first() { default = (*first).to_string(); } list.extend(colors.iter().map(|n| (n.to_string(), Label::from(n.to_string())))); } - list.extend(apply_image_alpha_options(doc)); + let alpha_start = list.len(); + let alphas = apply_image_alpha_options(doc); + let separate_alpha = colour && !alphas.is_empty(); + list.extend(alphas); if doc.selection.is_some() { list.extend(channels(&["selection".to_string()])); } - (list, default) + let row = choice(key, tl!("Channel"), list, &default); + if separate_alpha { row.separated_at(alpha_start) } else { row } } /// Apply Image's Mask... checkbox and the group it opens (#14489): Source (the documents of [`apply_image_documents`], @@ -910,9 +915,8 @@ fn apply_image_mask_rows(app: &PhotocraftApp) -> Vec { let mut rows = vec![Param::new(MASK_ON, tl!("Mask…"), ParamKind::bool(false)), shown(choice(MASK_SOURCE, tl!("Source"), names, &first))]; for (i, doc) in documents { let (layers, layer) = apply_image_layers(doc); - let (list, channel) = apply_image_mask_channels(doc); - rows.push(choice(&mask_layer_key(i), tl!("Layer"), layers, &layer).visible_when(mask_shown_key(i), true)); - rows.push(choice(&mask_channel_key(i), tl!("Channel"), list, &channel).visible_when(mask_shown_key(i), true)); + rows.push(choice(&mask_layer_key(i), tl!("Layer"), layers, &layer).separated_at(1).visible_when(mask_shown_key(i), true)); + rows.push(apply_image_mask_channel_row(&mask_channel_key(i), doc).visible_when(mask_shown_key(i), true)); } rows.push(shown(Param::new(MASK_INVERT, tl!("Invert"), ParamKind::bool(false)))); rows diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index bea440a6d59..2f0be138166 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -172,3 +172,6 @@ mod mask_properties_tests; #[cfg(test)] mod history_panel_select_tests; + +#[cfg(test)] +mod layers_replace_mask_tests; diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 420ae5de8b0..38f47e0f23e 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -58,8 +58,8 @@ fn current_key(app: &PhotocraftApp) -> Option { st.history.row_id(st.history.past_len()).map(HistoryKey::State) } -/// The row that is the History Brush's source. -fn source_key(st: &photocraft_engine::DocState) -> Option { +/// The row that is the History Brush's source: the open snapshot by default (#12845). +pub(crate) fn source_key(st: &photocraft_engine::DocState) -> Option { match photocraft_engine::history_source_cmds::source(st)? { HistorySource::State(row) => st.history.row_id(row).map(HistoryKey::State), HistorySource::Snapshot(id) => Some(HistoryKey::Snapshot(id)), diff --git a/crates/ui-egui/src/panels/history_panel_select_tests.rs b/crates/ui-egui/src/panels/history_panel_select_tests.rs index 443a3d1f869..dcdbd9bb376 100644 --- a/crates/ui-egui/src/panels/history_panel_select_tests.rs +++ b/crates/ui-egui/src/panels/history_panel_select_tests.rs @@ -417,6 +417,43 @@ fn the_first_snapshot_row_follows_the_option() { } } +/// #12845: the source column marks the open snapshot row by default, still when the states have +/// filled up and fallen off, and nothing once that row is deleted. +#[test] +fn the_source_icon_starts_on_the_open_snapshot_row() { + let mut app = app(); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::Snapshot(0))), "the open snapshot row"); + app.session.active_mut().unwrap().history.max_states = 2; + for _ in 0..4 { + app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); + } + let st = app.session.active().unwrap(); + assert!(st.history.entries().first().is_some_and(|label| label != "New"), "older states fell off: {:?}", st.history.entries()); + assert!(matches!(history::source_key(st), Some(HistoryKey::Snapshot(0))), "still the open snapshot row"); + assert!(rows(st).iter().any(|r| matches!(r.key, HistoryKey::Snapshot(0))), "the row is listed"); + // Deleting that row leaves the panel with no source icon at all. + app.run("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(history::source_key(app.session.active().unwrap()), None, "no source until one is set"); + app.run("history.setSource", json!({"state": 0})).unwrap(); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "a state row again"); +} + +/// #12845: the source column answers a click. Clicking a snapshot row's source box sends +/// `history.setSource {snapshot}` and the panel marks that row; a state row wins again when it is +/// clicked. +#[test] +fn a_click_on_a_snapshot_source_box_makes_it_the_source() { + let mut app = app(); + let state_row = state_key(&app, 1); + apply(&mut app, HistoryEvent::SetSource(state_row)); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "a state row first"); + apply(&mut app, HistoryEvent::SetSource(HistoryKey::Snapshot(0))); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::Snapshot(0))), "the open snapshot row"); + let current_row = current_key(&app); + apply(&mut app, HistoryEvent::SetSource(current_row)); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "the current state row"); +} + /// Snapshot thumbnails belong to the snapshot's document (#6087): a document reopened with the same id (a /// `.pcraft` keeps it) gets fresh ones rather than the closed document's, even before the views are synced. #[test] diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index bd7d9d6d3de..b59a65493f1 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -262,7 +262,14 @@ fn map_event(app: &mut PhotocraftApp, ctx: &egui::Context, event: LayersEvent { - actions.push(("layer.layerMask.moveTo".into(), json!({"layer": mv.layer.0, "to": mv.to.0, "copy": mv.copy}))); + use crate::dialogs::replace_layer_mask_prompt as replace; + let target = doc.layer(mv.to); + if target.is_some_and(replace::asks_before_replacing) { + // Asks "Replace Layer Mask?" first, unless "Don't show again" was ticked (#16787). + actions.extend(replace::ask(app, mv.layer, mv.to, mv.copy)); + } else if target.is_some_and(|l| l.mask.is_none()) { + actions.push(replace::move_action(mv.layer, mv.to, mv.copy, false)); + } } _ => {} } @@ -576,6 +583,17 @@ fn menu_pick(app: &mut PhotocraftApp, ctx: &egui::Context, row: &Option>; + +fn harness(s: Session) -> H { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}})); + crate::control::handle(h.state_mut(), &ctx, &r); + h.run_steps(8); + h +} + +/// 64 x 48 with "Source" (a mask revealing 8,8 24x16) under "Target" (a mask hiding all). +fn masked_pair() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Source"})).unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 16})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Target"})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s +} + +fn mask(h: &H, name: &str) -> Option { + h.state().session.active().unwrap().doc.layer(layer_id(h.state(), name)).unwrap().mask.clone() +} + +fn steps(h: &H) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn drag_mask(h: &mut H, from: &str, to: &str, mods: Modifiers) { + let at = thumb(h, from, LayerPart::LayerMask).center(); + let target = name_point(h, to); + drag(h, at, target, mods); +} + +fn question(h: &H) -> Option { + alerts::prompt_tagged::(h.state()) +} + +/// Presses the question's default button, ticking "Don't show again" when `skip`. +fn answer_default(h: &mut H, id: DialogId, skip: bool) { + let ctx = h.ctx.clone(); + if skip { + h.state_mut().framework.dialogs.set_json_field(&ctx, id, "skip", json!(true)).unwrap(); + } + crate::dialogs::confirm(h.state_mut(), &ctx, id).unwrap(); + h.run_steps(3); +} + +fn answer_no(h: &mut H, id: DialogId) { + let ctx = h.ctx.clone(); + h.state_mut().framework.dialogs.set_json_field(&ctx, id, "choice", json!("cancel")).unwrap(); + crate::dialogs::confirm(h.state_mut(), &ctx, id).unwrap(); + h.run_steps(3); +} + +#[test] +fn a_drop_on_a_masked_layer_asks_replace_layer_mask_with_yes_no_and_an_unticked_box() { + for mods in [Modifiers::NONE, Modifiers::ALT] { + let mut h = harness(masked_pair()); + let (source, target, n) = (mask(&h, "Source"), mask(&h, "Target"), steps(&h)); + drag_mask(&mut h, "Source", "Target", mods); + assert!(question(&h).is_some(), "{mods:?}: the drop asks"); + let prompt = h.state().framework.dialogs.get::().unwrap(); + assert_eq!(prompt.json_fields().unwrap()["skip"], json!(false), "{mods:?}: Don't show again starts unticked"); + h.run_steps(3); + for label in ["Replace Layer Mask?", "Yes", "No", "Don't show again"] { + assert!(h.query_by_label(label).is_some(), "{mods:?}: the alert shows {label:?}"); + } + assert_eq!((mask(&h, "Source"), mask(&h, "Target"), steps(&h)), (source, target, n), "{mods:?}: nothing changes before the answer"); + } +} + +#[test] +fn no_leaves_both_layers_and_the_history_alone() { + for mods in [Modifiers::NONE, Modifiers::ALT] { + let mut h = harness(masked_pair()); + let (source, target, n) = (mask(&h, "Source"), mask(&h, "Target"), steps(&h)); + drag_mask(&mut h, "Source", "Target", mods); + let id = question(&h).expect("the question"); + answer_no(&mut h, id); + assert!(question(&h).is_none()); + assert_eq!((mask(&h, "Source"), mask(&h, "Target"), steps(&h)), (source, target, n), "{mods:?}"); + } +} + +#[test] +fn yes_the_default_moves_the_mask_in_one_undo_step() { + let mut h = harness(masked_pair()); + let (source, target, n) = (mask(&h, "Source"), mask(&h, "Target"), steps(&h)); + assert_ne!(source, target); + drag_mask(&mut h, "Source", "Target", Modifiers::NONE); + let id = question(&h).expect("the question"); + answer_default(&mut h, id, false); + assert_eq!(mask(&h, "Source"), None, "the mask left its layer"); + assert_eq!(mask(&h, "Target").map(|m| m.surface), source.clone().map(|m| m.surface), "and replaced the target's"); + assert_eq!(steps(&h), n + 1, "one step"); + assert!(h.state_mut().session.undo()); + assert_eq!((mask(&h, "Source"), mask(&h, "Target")), (source, target), "one undo puts both back"); +} + +#[test] +fn yes_after_an_alt_drag_copies_the_mask_in_one_undo_step() { + let mut h = harness(masked_pair()); + let (source, target, n) = (mask(&h, "Source"), mask(&h, "Target"), steps(&h)); + drag_mask(&mut h, "Source", "Target", Modifiers::ALT); + let id = question(&h).expect("the question"); + answer_default(&mut h, id, false); + assert_eq!(mask(&h, "Source"), source, "the original stays"); + assert_eq!(mask(&h, "Target").map(|m| m.surface), source.clone().map(|m| m.surface), "a copy replaced the target's"); + assert_eq!(steps(&h), n + 1, "one step"); + assert!(h.state_mut().session.undo()); + assert_eq!((mask(&h, "Source"), mask(&h, "Target")), (source, target)); +} + +#[test] +fn a_ticked_dont_show_again_replaces_at_once_next_time() { + let mut h = harness(masked_pair()); + let source = mask(&h, "Source"); + drag_mask(&mut h, "Source", "Target", Modifiers::ALT); + let id = question(&h).expect("the question"); + answer_default(&mut h, id, true); + assert!(alerts::dismissed(h.state(), PREF), "the box is remembered"); + // Give Target its own mask again, then drop once more: no question, the mask is replaced. + let target = layer_id(h.state(), "Target").0; + h.state_mut().run("layer.layerMask.delete", json!({"layer": target})).unwrap(); + h.state_mut().run("layer.layerMask.hideAll", json!({"layer": target})).unwrap(); + h.run_steps(3); + let n = steps(&h); + drag_mask(&mut h, "Source", "Target", Modifiers::NONE); + assert!(question(&h).is_none(), "no question"); + assert_eq!(mask(&h, "Source"), None, "the mask moved"); + assert_eq!(mask(&h, "Target").map(|m| m.surface), source.map(|m| m.surface)); + assert_eq!(steps(&h), n + 1, "in one step"); +} + +#[test] +fn an_edit_before_yes_replaces_nothing() { + let mut h = harness(masked_pair()); + drag_mask(&mut h, "Source", "Target", Modifiers::NONE); + let id = question(&h).expect("the question"); + let target = layer_id(h.state(), "Target").0; + h.state_mut().run("layer.layerMask.enabled", json!({"layer": target, "enabled": false})).unwrap(); + let (source, masked) = (mask(&h, "Source"), mask(&h, "Target")); + answer_default(&mut h, id, false); + assert_eq!((mask(&h, "Source"), mask(&h, "Target")), (source, masked), "the stale answer changes nothing"); + assert!(h.state().ui.status_error, "and says why"); +} + +#[test] +fn a_drop_on_a_layer_without_a_mask_still_moves_without_asking() { + let mut s = masked_pair(); + s.execute("layer.new.layer", json!({"name": "Plain"})).unwrap(); + let mut h = harness(s); + let (source, n) = (mask(&h, "Source"), steps(&h)); + drag_mask(&mut h, "Source", "Plain", Modifiers::NONE); + assert!(question(&h).is_none()); + assert_eq!(mask(&h, "Plain"), source); + assert_eq!(steps(&h), n + 1); +} + +#[test] +fn the_own_layer_a_vector_mask_a_masked_group_and_a_masked_adjustment_still_refuse() { + let mut s = masked_pair(); + s.execute("layer.vectorMask.revealAll", json!({})).unwrap(); + s.execute("layer.newAdjustmentLayer.brightnessContrast", json!({"name": "Tone", "brightness": 12})).unwrap(); + s.execute("layer.new.group", json!({"name": "Folder"})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + let mut h = harness(s); + assert!(mask(&h, "Tone").is_some() && mask(&h, "Folder").is_some(), "both have a mask"); + let snapshot = |h: &H| ["Source", "Target", "Tone", "Folder"].map(|name| mask(h, name)); + let (before, n) = (snapshot(&h), steps(&h)); + for to in ["Source", "Tone", "Folder"] { + drag_mask(&mut h, "Source", to, Modifiers::NONE); + assert!(question(&h).is_none(), "onto {to}: no question"); + } + let vector = thumb(&h, "Target", LayerPart::VectorMask).center(); + let source = name_point(&h, "Source"); + drag(&mut h, vector, source, Modifiers::NONE); + assert!(question(&h).is_none(), "a vector mask: no question"); + assert_eq!((snapshot(&h), steps(&h)), (before, n), "nothing changed"); +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 38a11a32ba0..358b9131252 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -550,8 +550,10 @@ impl LayerTree for PhotoLayers { } fn accepts_mask_drop(&self, from: &LayerId, part: LayerPart, to: &LayerId) -> bool { - // The engine moves layer masks only. - part == LayerPart::LayerMask && from != to && self.layer(to).is_some_and(|l| l.mask.is_none()) + // The engine moves layer masks only. A layer that has one asks "Replace Layer Mask?" first (#16787). + part == LayerPart::LayerMask + && from != to + && self.layer(to).is_some_and(|l| l.mask.is_none() || crate::dialogs::replace_layer_mask_prompt::asks_before_replacing(l)) } fn label_colors_in_menu(&self, target: &MenuTarget) -> bool { @@ -575,6 +577,8 @@ enum MenuKind { Effects, /// The layer menu. Layer(LayerId), + /// A vector mask's thumbnail (#16781). + VectorMask(LayerId), /// No menu. None, } @@ -594,6 +598,13 @@ fn menu_kind(tree: &PhotoLayers, target: &MenuTarget) -> MenuKind { let measured_state = l.visible && !l.clipped && unlocked; let short_menu_today = matches!(l.content, LayerContent::Raster(_)) && !background; match target.part { + // #16781 measured the vector mask menu on pixel layers only: shape, group and adjustment + // layers keep no menu until measured. + Some(LayerPart::VectorMask) + if l.vector_mask.is_some() && !l.is_group() && !matches!(l.content, LayerContent::Shape(_) | LayerContent::Adjustment(_)) => + { + MenuKind::VectorMask(*id) + } Some(LayerPart::LayerMask) if l.mask.is_some() => MenuKind::Mask(*id), // A thumbnail opens the short menu for every kind (#16777). Frames, artboards and the // hidden, locked or clipped rows the issue did not measure keep today's menu. @@ -606,6 +617,11 @@ fn menu_kind(tree: &PhotoLayers, target: &MenuTarget) -> MenuKind { } } +/// The vector mask thumbnail menu's first entry: what a pick does to the mask. +fn vector_mask_toggle_label(enabled: bool) -> &'static str { + if enabled { tl!("Disable Vector Mask") } else { tl!("Enable Vector Mask") } +} + /// The four thumbnail sizes, in menu order. fn thumbnail_sizes() -> [(ThumbSize, &'static str); 4] { [ @@ -618,6 +634,8 @@ fn thumbnail_sizes() -> [(ThumbSize, &'static str); 4] { /// Menu values that are no engine command: the panel handles them (`layers_events`). pub(crate) const RENAME: &str = "layersPanel:rename"; +/// A vector mask thumbnail's entries: the engine command after the prefix, run on the clicked layer. +pub(crate) const VECTOR_MASK: &str = "layersPanel:vectorMask:"; pub(crate) const THUMB_SIZE: &str = "layersPanel:thumbs:"; pub(crate) const CLIP_THUMBS: &str = "layersPanel:clip:"; pub(crate) const SELECT_PIXELS: &str = "layersPanel:selectPixels"; @@ -736,6 +754,17 @@ pub(crate) fn row_menu(app: &PhotocraftApp, tree: &PhotoLayers, target: &MenuTar out.push(Entry::new(MASK_OPTIONS.to_string(), tl!("Mask Options…").to_string())); out } + MenuKind::VectorMask(id) => { + let Some(mask) = tree.layer(&id).and_then(|l| l.vector_mask.as_ref()) else { return Vec::new() }; + let entry = |command: &str, label: &str| Entry::new(format!("{VECTOR_MASK}{command}"), label.to_string()); + vec![ + entry("layer.vectorMask.enabled", vector_mask_toggle_label(mask.enabled)), + Entry::separator(), + entry("layer.vectorMask.delete", tl!("Delete Vector Mask")), + // Greyed while the mask is disabled, as in the reference. + entry("layer.rasterize.vectorMask", tl!("Rasterize Vector Mask")).enabled(mask.enabled), + ] + } MenuKind::Effects => commands(crate::layer_menu_ui::effects_entries(), false), MenuKind::Layer(id) => { let Some(l) = tree.layer(&id) else { return Vec::new() }; @@ -857,6 +886,10 @@ pub(crate) fn select_pixels(layer: LayerId) -> Value { json!({"channel": "transparency", "layer": layer.0, "operation": "new"}) } +#[cfg(test)] +#[path = "layers_vector_mask_menu_tests.rs"] +mod layers_vector_mask_menu_tests; + #[cfg(test)] #[path = "indexed_background_name_tests.rs"] mod indexed_background_name_tests; diff --git a/crates/ui-egui/src/panels/layers_vector_mask_menu_tests.rs b/crates/ui-egui/src/panels/layers_vector_mask_menu_tests.rs new file mode 100644 index 00000000000..d5ef76efbf2 --- /dev/null +++ b/crates/ui-egui/src/panels/layers_vector_mask_menu_tests.rs @@ -0,0 +1,155 @@ +//! A vector mask thumbnail's right-click menu (#16781): Disable Vector Mask ― Delete Vector Mask · +//! Rasterize Vector Mask, as in the reference application; a disabled mask reads Enable Vector Mask +//! and greys Rasterize. Each entry acts on the clicked layer in one history step. + +use craft::layers::ui::panel::{LayersEvent, MenuTarget}; +use craft::layers::ui::tree::{LayerPart, LayerRowKey}; +use photocraft_doc::{Layer, LayerId}; +use photocraft_engine::Session; +use serde_json::json; + +use super::{PhotoLayers, VECTOR_MASK, row_menu}; +use crate::PhotocraftApp; + +/// A pixel layer "Masked" with a vector mask below a plain layer "Top", which is active. +fn setup() -> (Box, LayerId) { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Masked"})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 10, "width": 60, "height": 40})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.vectorMask.revealAll", json!({})).unwrap(); + let masked = active_id(&app); + app.run("layer.new.layer", json!({"name": "Top"})).unwrap(); + (app, masked) +} + +fn active_id(app: &PhotocraftApp) -> LayerId { + app.session.active().unwrap().active_layer.unwrap() +} + +fn layer(app: &PhotocraftApp, id: LayerId) -> Layer { + app.session.active().unwrap().doc.layer(id).unwrap().clone() +} + +fn steps(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries().to_vec() +} + +fn target(id: LayerId) -> MenuTarget { + let mut t = MenuTarget::new(Some(LayerRowKey::Layer(id))); + t.part = Some(LayerPart::VectorMask); + t +} + +/// The menu as (command, label, enabled) rows, `None` for a separator. +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, &target(id)) + .iter() + .map(|e| e.value().map(|v| (v.strip_prefix(VECTOR_MASK).unwrap_or(v).to_string(), e.label().as_str().to_string(), e.is_enabled()))) + .collect() +} + +fn row(command: &str, label: &str, enabled: bool) -> Option<(String, String, bool)> { + Some((command.to_string(), label.to_string(), enabled)) +} + +fn pick(app: &mut PhotocraftApp, id: LayerId, command: &str) { + let ctx = app.ctx().clone(); + let event = LayersEvent::menu(target(id), format!("{VECTOR_MASK}{command}")); + crate::panels::layers_events::apply_layers_events(app, &ctx, vec![event]); +} + +#[test] +fn an_enabled_vector_mask_offers_disable_delete_and_rasterize() { + let (app, masked) = setup(); + assert_eq!( + menu(&app, masked), + [ + row("layer.vectorMask.enabled", "Disable Vector Mask", true), + None, + row("layer.vectorMask.delete", "Delete Vector Mask", true), + row("layer.rasterize.vectorMask", "Rasterize Vector Mask", true), + ] + ); +} + +#[test] +fn a_disabled_vector_mask_reads_enable_and_greys_rasterize() { + let (mut app, masked) = setup(); + app.run("layer.vectorMask.enabled", json!({"layer": masked.0, "enabled": false})).unwrap(); + assert_eq!( + menu(&app, masked), + [ + row("layer.vectorMask.enabled", "Enable Vector Mask", true), + None, + row("layer.vectorMask.delete", "Delete Vector Mask", true), + row("layer.rasterize.vectorMask", "Rasterize Vector Mask", false), + ] + ); +} + +#[test] +fn the_toggle_acts_on_the_clicked_layer_in_one_named_step() { + let (mut app, masked) = setup(); + let top = active_id(&app); + let before = steps(&app).len(); + pick(&mut app, masked, "layer.vectorMask.enabled"); + assert!(!layer(&app, masked).vector_mask.unwrap().enabled, "the clicked layer's mask is disabled"); + assert_eq!(active_id(&app), top, "the pick itself selects nothing"); + let after = steps(&app); + assert_eq!(after.len(), before + 1); + assert_eq!(after.last().map(String::as_str), Some("Disable Vector Mask")); + pick(&mut app, masked, "layer.vectorMask.enabled"); + assert!(layer(&app, masked).vector_mask.unwrap().enabled, "a second pick enables it again"); + assert_eq!(steps(&app).last().map(String::as_str), Some("Enable Vector Mask")); +} + +#[test] +fn delete_and_rasterize_act_on_the_clicked_layer_in_one_step_each() { + let (mut app, masked) = setup(); + let before = steps(&app).len(); + pick(&mut app, masked, "layer.rasterize.vectorMask"); + let l = layer(&app, masked); + assert!(l.vector_mask.is_none() && l.mask.is_some(), "rasterized into a layer mask"); + assert_eq!(steps(&app).len(), before + 1); + + let (mut app, masked) = setup(); + let before = steps(&app).len(); + pick(&mut app, masked, "layer.vectorMask.delete"); + let l = layer(&app, masked); + assert!(l.vector_mask.is_none() && l.mask.is_none(), "deleted, nothing rasterized"); + assert_eq!(steps(&app).len(), before + 1); +} + +/// The issue did not measure a vector mask on a group or an adjustment layer: they keep no menu. +#[test] +fn unmeasured_layer_kinds_keep_no_menu() { + let (mut app, _) = setup(); + app.run("layer.groupLayers", json!({"name": "G"})).unwrap(); + let group = active_id(&app); + app.run("layer.vectorMask.revealAll", json!({"layer": group.0})).unwrap(); + assert!(layer(&app, group).vector_mask.is_some()); + assert!(menu(&app, group).is_empty(), "a group's vector mask"); + + app.run("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let adjustment = active_id(&app); + app.run("layer.vectorMask.revealAll", json!({"layer": adjustment.0})).unwrap(); + assert!(layer(&app, adjustment).vector_mask.is_some()); + assert!(menu(&app, adjustment).is_empty(), "an adjustment layer's vector mask"); +} + +/// A pick on a layer whose vector mask is gone (or a layer that is gone) changes nothing and does not panic. +#[test] +fn a_stale_pick_changes_nothing() { + let (mut app, masked) = setup(); + app.run("layer.vectorMask.delete", json!({"layer": masked.0})).unwrap(); + assert!(menu(&app, masked).is_empty(), "no vector mask, no menu"); + let before = steps(&app); + pick(&mut app, masked, "layer.vectorMask.enabled"); + pick(&mut app, LayerId(9999), "layer.vectorMask.enabled"); + assert_eq!(steps(&app), before); +} diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs index de5b6cd2ecf..95e820141cb 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs @@ -28,10 +28,18 @@ pub(crate) enum SourceCaption { /// The History Brush's source as the bar names it. pub(crate) fn source_caption(app: &PhotocraftApp) -> SourceCaption { - use photocraft_engine::history_source_cmds::{HistorySource, source}; + use photocraft_engine::history_source_cmds::{HistorySource, is_open_snapshot, source}; let Some(st) = app.session.active() else { return SourceCaption::Deleted }; let named = || match source(st)? { - HistorySource::Snapshot(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())), + // The default source, the open snapshot (#12845), keeps the bar's opening-state wording; + // any other snapshot is named. + src @ HistorySource::Snapshot(id) => { + if is_open_snapshot(st, src) { + Some(SourceCaption::Opening) + } else { + st.snapshots().iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())) + } + } HistorySource::State(idx) => { let entries = st.history.entries(); let name = if idx < entries.len() { entries.get(idx).cloned() } else { st.history.redo_labels().nth(idx - entries.len()).map(str::to_string) }?;