From e8c30125539f4f3fe75cc9335a21b729d2c85f48 Mon Sep 17 00:00:00 2001 From: admiralronton Date: Sat, 31 Oct 2026 10:46:53 -0700 Subject: [PATCH 01/38] Bevel gloss contour: split at the unmapped sin(altitude) (#594) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A gloss contour maps the bevel's shading n·L. Highlight and shadow then split around a neutral. Since #7360 that neutral was the contour-mapped flat shading lut(sin(altitude)). Photoshop keeps the unmapped sin(altitude). The two agree only when the contour leaves the flat value in place, so: - High light, descending contour: Rolling Slope - Descending at altitude 69 maps the flat 0.93 to 0.16. Every slope pixel above 0.16 took the full highlight and bevelled type rendered white. Photoshop only glints where n·L comes within ~0.015 of 0 (measured per pixel). - A contour that moves the flat value lights or darkens the flat face in Photoshop. Cone - Inverted (#594) and the ramp-peak and double-ring oracles all show this, and the old neutral left those faces at the fill. The fix changes one expression on the CPU (bevel_maps) and the same one on the GPU (bevel_part). Linear is unchanged. Photoshop oracle_diff, max error / bad pixels: - #594 Bevel.psd: 0.749 / 7.58 % -> 0.020 / 0.91 % - bevel-inner-gloss-ramp-peak: 0.504 / 31.8 % -> 0.042 / 1.2 % - bevel-inner-gloss-double-ring-aa: 0.503 / 32.3 % -> 0.212 / 15.7 % - the other 25 bevel oracles: unchanged Tests: - New: the high-altitude slope case. - New: the ramp-peak and double-ring flat faces. - New: a red shape that stays red at 8, 16 and 32 bit. - New: a GPU parity case at altitude 69. - The #7360 test now expects the small lift Rolling Slope gives a flat face (Photoshop's composite of that repro is 151-161, not exactly the fill). Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/effects/bevel.rs | 16 ++++--- crates/compose/src/effects/tests.rs | 58 ++++++++++++++++++++++++ crates/compose/src/tests.rs | 69 ++++++++++++++++++++++++++--- crates/gpu/src/compose.wgsl | 5 ++- crates/gpu/tests/it/parity.rs | 5 +++ 5 files changed, 140 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs index ea07fbd709..2ea6d4db62 100644 --- a/crates/compose/src/effects/bevel.rs +++ b/crates/compose/src/effects/bevel.rs @@ -193,11 +193,15 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text let on_bevel = |x: i64, y: i64| { hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) }; - // The gloss contour remaps the shading `n · light` before it splits into highlight (above - // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts - // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light - // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop - // leaves it at the layer's colour. The Linear contour changes nothing either way. + // The gloss contour remaps the shading `n · light` before it splits into highlight (above a + // flat face's own, unmapped `sin(altitude)`) and shadow (below it). Applied to the highlight + // and shadow amounts instead, a contour that starts high (Rolling Slope - Descending) lit + // every pixel the light missed (#7360). With the mapped `lut(sin(altitude))` as the neutral, + // a high light washed out whole faces: at altitude 69 that contour maps the flat 0.93 to + // 0.16, so every slope above 0.16 took the full highlight where Photoshop only glints where + // the shading nears 0. A contour that moves the flat shading lights or darkens the flat face + // too, as Photoshop does (oracles bevel-inner-gloss-ramp-peak / -double-ring-aa: faces at + // the full highlight and a 0.69 shadow). The Linear contour changes nothing either way. let gloss = contour_lut(&b.gloss_contour); let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); @@ -219,7 +223,7 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); + let k = gloss.as_ref().map_or(shade, |l| lut_at(l, shade)) - se; if k > 0.0 { hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; } else { diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 4aea00004f..c8d8bc72f9 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -199,6 +199,64 @@ fn smooth_inner_bevel_lights_the_top_edge_inside_only() { assert!(at(&maps[0], 20, 15) < 0.05); } +/// A gloss contour from Photoshop's 0–255 contour editor points. +fn gloss_of(points: &[(f32, f32)]) -> Contour { + Contour::Custom { + name: "gloss".into(), + points: points.iter().map(|&(i, o)| photocraft_doc::adjust::CurvePoint { input: i / 255.0, output: o / 255.0 }).collect(), + corners: vec![], + } +} + +/// Smooth inner bevel highlight and shadow maps of `shape` with `gloss`, light from `angle` at +/// `altitude`. +fn gloss_maps(shape: &Map, gloss: Contour, angle: f32, altitude: f32, size: f32, depth: f32) -> Vec { + let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); + (b.angle, b.altitude, b.size, b.depth, b.gloss_contour) = (angle, altitude, size, depth, gloss); + bevel_maps(shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 +} + +/// The gloss contour maps the shading, and the flat face's own unmapped shading `sin(altitude)` +/// stays the neutral. Photoshop's own composite of a purchased style pack's type (Rolling Slope - +/// Descending at altitude 69, 16 px smooth inner bevel at 358 %): the face stays at its colour, with white +/// glints only where the shading is within ~0.015 of zero (measured per pixel against this +/// bevel's shading). With the mapped `lut(sin 69°)` = 0.16 as the neutral, every slope pixel +/// whose mapped shading came out above it took the full highlight, and the type rendered white. +#[test] +fn high_altitude_descending_gloss_only_glints_where_the_light_misses() { + let n = 80; + let mut shape = Map::new(n, n, 0.0); + for y in 10..70 { + for x in 20..60 { + shape.v[y * n + x] = 1.0; + } + } + let rolling = gloss_of(&[(2.0, 255.0), (53.0, 100.0), (97.0, 107.0), (179.0, 153.0), (252.0, 0.0)]); + // Light from the left: the bar's right slope faces away from it. + let maps = gloss_maps(&shape, rolling, 180.0, 69.0, 16.0, 3.58); + let row: Vec = (20..60).map(|x| maps[0].v[40 * n + x]).collect(); + let lit = row.iter().filter(|v| **v > 0.05).count(); + assert!(lit <= 8, "only a few glint pixels, not the whole face: {row:?}"); + assert!(row[..20].iter().all(|v| *v < 0.05), "no highlight on the slope facing the light: {row:?}"); + assert!(row[20..].iter().any(|v| *v > 0.9), "a full glint where the slope faces away: {row:?}"); +} + +/// Photoshop 27.11 oracles (corpus `bevel-inner-gloss-ramp-peak` / `-double-ring-aa`: 12 px +/// smooth inner bevel at altitude 30, Screen white and Multiply black at 75 % over (90, 120, +/// 170)): a contour that maps the flat shading 0.5 above or below 0.5 lights or darkens the flat +/// face too. Ramp-peak (0,0)(128,255)(255,0) paints the face (214, 221, 234), the full +/// highlight; double-ring (…, (128, 40), …) paints it (44, 58, 83), a 0.69 shadow. +#[test] +fn a_gloss_contour_lights_or_darkens_the_flat_face_around_the_unmapped_neutral() { + let shape = square(40, 5, 35); + let face = |m: &Map| m.v[20 * 40 + 20]; + let peak = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (128.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0); + assert!(face(&peak[0]) > 0.99 && face(&peak[1]) == 0.0, "ramp-peak: full highlight, {} / {}", face(&peak[0]), face(&peak[1])); + let ring = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (64.0, 255.0), (128.0, 40.0), (192.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0); + // (0.5 − 40/255) / 0.5: 90 × (1 − 0.75 × 0.686) = 43.7. + assert!(face(&ring[0]) == 0.0 && (face(&ring[1]) - 0.686).abs() < 0.02, "double-ring: shadow {}", face(&ring[1])); +} + /// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top /// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the /// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 917192f44a..4208e08333 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1803,10 +1803,12 @@ fn satin_and_bevel_stay_inside_shape() { /// #7360: a gloss contour that starts high (Rolling Slope - Descending, as the reporter's PSD /// uses) left a bevelled shape's flat face at the full Overlay highlight, (255, 40, 42) on a -/// (151, 22, 23) fill, where Photoshop leaves the face at the fill colour. The contour maps the -/// shading, so the flat face stays neutral and only the slopes are shaded. +/// (151, 22, 23) fill. The contour maps the shading, with the unmapped flat shading +/// `sin(altitude)` as the neutral, so the face only takes what the contour moves 0.5 by: +/// Rolling Slope maps it to 0.55, a 0.09 highlight, (161, 24, 25). Photoshop's own composite of +/// the reporter's repro has the glyph's face at 151–161 in red, not the exact fill. #[test] -fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() { +fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_near_its_fill() { let fill = [151.0 / 255.0, 22.0 / 255.0, 23.0 / 255.0, 1.0]; let rolling = photocraft_doc::Contour::Custom { name: "Rolling Slope - Descending".into(), @@ -1844,14 +1846,71 @@ fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() { }; let d = render(rolling); for (x, y) in [(20, 20), (16, 22), (24, 16)] { - let p = px(&d, x, y); - assert!(close4(p, fill), "flat face ({x},{y}) keeps the fill: {:?}", p.map(|v| (v * 255.0).round())); + let p = px(&d, x, y).map(|v| (v * 255.0).round()); + assert!((158.0..=164.0).contains(&p[0]) && (22.0..=26.0).contains(&p[1]), "flat face ({x},{y}) near the fill: {p:?}"); } let linear = render(photocraft_doc::Contour::Linear); assert!(close4(px(&linear, 20, 20), fill), "Linear leaves the flat face too"); assert!(!close4(px(&d, 20, 11), fill), "the slopes are still shaded"); } +/// A deep bevel under a high light with a descending gloss contour (altitude 69, 358 %, Rolling +/// Slope - Descending, Screen white 78 %) keeps a red shape red at every depth: the slopes are +/// shaded around the unmapped `sin(altitude)`, so only the steepest pixels facing away glint. +/// Mapped through the contour, that neutral fell to 0.16 and the whole shape rendered white. +#[test] +fn a_high_light_descending_gloss_keeps_the_face_its_colour_at_every_depth() { + let red = [0.6, 0.0, 0.0, 1.0]; + let rolling = photocraft_doc::Contour::Custom { + name: "Rolling Slope - Descending".into(), + points: [(0.0078, 1.0), (0.2078, 0.3922), (0.3804, 0.4196), (0.7020, 0.6), (0.9882, 0.0)] + .iter() + .map(|&(input, output)| CurvePoint { input, output }) + .collect(), + corners: vec![], + }; + let mut first: Option> = None; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut d = Document::with_background("t", Size::new(80, 80), ColorMode::Rgb, depth, Color::BLACK); + let mut l = Layer::raster("bar", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(20, 10, 60, 70), &red); + l.effects.items = vec![Effect::BevelEmboss(photocraft_doc::Bevel { + enabled: true, + style: photocraft_doc::BevelStyle::InnerBevel, + technique: photocraft_doc::BevelTechnique::Smooth, + depth: 3.58, + up: true, + size: 16.0, + soften: 0.0, + angle: 180.0, + altitude: 69.0, + use_global_light: false, + gloss_contour: rolling.clone(), + gloss_anti_alias: false, + highlight: FxCommon::new(photocraft_color::BlendMode::Screen, 0.78), + highlight_color: Color::WHITE, + shadow: FxCommon::new(photocraft_color::BlendMode::Multiply, 0.09), + shadow_color: Color::BLACK, + contour: None, + texture: None, + })]; + d.layers.push(l); + // The slope facing the light, the middle, and a slope pixel facing away short of its glint. + let got: Vec<[f32; 4]> = [(23, 40), (30, 40), (40, 40), (50, 40)].iter().map(|&(x, y)| px(&d, x, y)).collect(); + for (p, at) in got.iter().zip([23, 30, 40, 50]) { + assert!(p[0] > 0.5 && p[1] < 0.05 && p[2] < 0.05, "{depth:?} x={at}: still red, not washed white: {p:?}"); + } + match &first { + None => first = Some(got), + Some(f) => { + for (a, b) in f.iter().zip(&got) { + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 3.0 / 255.0), "{depth:?} agrees with 8-bit: {a:?} vs {b:?}"); + } + } + } + } +} + #[test] fn clipped_layer_effects_are_clipped_to_base() { let mut d = doc_white(40, 40); diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 09dd4cc415..6204a94a90 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1542,8 +1542,9 @@ fn bevel_part(p: vec2, depth: f32, region: f32) -> f32 { let shade = (n.x * op.p0.x + n.y * op.p0.y + n.z * op.p0.z) / len; let se = op.p0.w; var k = shade - se; - // effects::bevel_maps: the gloss contour maps the shading, a flat face's as the neutral (#7360). - if (op.p1.w > 0.5) { k = lut(0, shade) - lut(0, se); } + // effects::bevel_maps: the gloss contour maps the shading; a flat face's unmapped shading + // stays the neutral (#7360). + if (op.p1.w > 0.5) { k = lut(0, shade) - se; } var v = 0.0; if (op.p1.z > 0.5) { if (k <= 0.0) { v = clamp(-k / max(se, 1e-3), 0.0, 1.0) * region; } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index d22a4515d1..05c6365401 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -1673,6 +1673,10 @@ fn effect_cases() -> Vec<(&'static str, Vec)> { points: vec![Cp { input: 0.0, output: 1.0 }, Cp { input: 0.4, output: 0.4 }, Cp { input: 1.0, output: 0.0 }], corners: vec![], }; + // The same contour under a high light, deep (altitude 69, 358 %): the unmapped flat shading + // stays the neutral, so only the slope facing away glints, on both renderers. + let mut bevel_gloss_high_alt = bevel_gloss_high.clone(); + (bevel_gloss_high_alt.use_global_light, bevel_gloss_high_alt.angle, bevel_gloss_high_alt.altitude, bevel_gloss_high_alt.depth) = (false, 146.0, 69.0, 3.58); vec![ ("drop shadow", vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.75, 120.0, 6.0, 8.0, 0.0))]), ("drop shadow spread contour", vec![Effect::DropShadow(ds_contour)]), @@ -1763,6 +1767,7 @@ fn effect_cases() -> Vec<(&'static str, Vec)> { ), ("bevel contour own light", vec![Effect::BevelEmboss(bevel_contour)]), ("bevel gloss starting high", vec![Effect::BevelEmboss(bevel_gloss_high)]), + ("bevel gloss starting high, high light", vec![Effect::BevelEmboss(bevel_gloss_high_alt)]), ("satin", vec![Effect::Satin(satin)]), ("satin inverted contour", vec![Effect::Satin(satin_inv)]), ("stroke outside colour", vec![Effect::Stroke(stroke(4.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.95, 0.85, 0.1))))]), From c6c562b3a11a6615c94b70d3a7d71b78cb1f918c Mon Sep 17 00:00:00 2001 From: Omar Saidahmed Date: Wed, 28 Oct 2026 18:57:08 -0400 Subject: [PATCH 02/38] split the core command table into per-menu modules --- crates/engine/src/cmd.rs | 1330 +++----------------------- crates/engine/src/cmd/adjustments.rs | 147 +++ crates/engine/src/cmd/edit_menu.rs | 62 ++ crates/engine/src/cmd/file_menu.rs | 94 ++ crates/engine/src/cmd/image_menu.rs | 44 + crates/engine/src/cmd/layer_menu.rs | 578 +++++++++++ crates/engine/src/cmd/paint.rs | 55 ++ crates/engine/src/cmd/queries.rs | 122 +++ crates/engine/src/cmd/select_menu.rs | 112 +++ 9 files changed, 1349 insertions(+), 1195 deletions(-) create mode 100644 crates/engine/src/cmd/adjustments.rs create mode 100644 crates/engine/src/cmd/edit_menu.rs create mode 100644 crates/engine/src/cmd/file_menu.rs create mode 100644 crates/engine/src/cmd/image_menu.rs create mode 100644 crates/engine/src/cmd/layer_menu.rs create mode 100644 crates/engine/src/cmd/paint.rs create mode 100644 crates/engine/src/cmd/queries.rs create mode 100644 crates/engine/src/cmd/select_menu.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a17fdec405..76b34e70f3 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -53,6 +53,7 @@ pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; mod adjust_params; +mod adjustments; pub mod align_cmds; pub mod analysis_cmds; pub mod artboard_cmds; @@ -77,6 +78,7 @@ pub mod cutout_cmds; pub mod distort_cmds; pub mod document_preset_cmds; pub mod edit_cmds; +mod edit_menu; pub mod edit_menu_cmds; mod enabled; pub mod eraser_cmds; @@ -85,6 +87,7 @@ pub mod exr_cmds; pub mod extra_cmds; pub mod face_cmds; pub mod file_cmds; +mod file_menu; pub mod fill_cmds; pub mod fill_key_cmds; pub mod float_cmds; @@ -101,11 +104,13 @@ pub mod history_options_cmds; pub mod history_select_cmds; pub mod history_source_cmds; pub mod image_cmds; +mod image_menu; pub mod layer_copy_cmds; pub mod layer_css_cmds; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; +mod layer_menu; pub mod layer_menu_cmds; pub mod layer_multi_cmds; pub mod layer_nav_cmds; @@ -122,6 +127,7 @@ pub mod notes_cmds; #[cfg(test)] mod notes_stored_values_tests; mod ops; +mod paint; pub mod paint_cmds; mod params; pub(super) mod path_edit_cmds; @@ -133,6 +139,7 @@ pub mod pick_cmds; pub mod plugin_cmds; pub mod preset_import_cmds; pub mod print_cmds; +mod queries; pub mod rasterize_style_cmds; pub mod redeye_cmds; pub mod render_cmds; @@ -142,6 +149,7 @@ pub mod sample_cmds; mod sample_zoom_box_tests; pub mod sampler_cmds; pub mod select_extra_cmds; +mod select_menu; pub mod selection_cmds; pub mod slice_cmds; pub mod smart_cmds; @@ -261,1204 +269,136 @@ fn registry() -> &'static Registry { #[allow(clippy::too_many_lines)] /// Register the core file, edit, layer and document commands. -fn build() -> Vec { - let mut v = vec![ - // File - cmd!( - "file.new", - "New…", - ["File"], - Some("Cmd+N"), - r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|backgroundColor|transparent|#rrggbb"="white","backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str,"artboard":bool=false (one artboard over the canvas, its background the chosen one, holding an empty Layer 1; no Background layer),"profile":"working"|built-in id|path to an .icc file="working" (the colour profile it is tagged with; it must suit the mode)}"##, - always, - |s, p| { - use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type}; - crate::document_preset_cmds::validate_new_params(s, p)?; - // A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254). - let px = |k: &str, d: u32| match p.get(k) { - Some(v) => v - .as_u64() - .map(|n| n.clamp(1, MAX_DIMENSION as u64) as u32) - .or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round().clamp(1.0, MAX_DIMENSION as f64) as u32)) - .unwrap_or(d), - None => d, - }; - let (w, h) = (px("width", 1920), px("height", 1080)); - let mode = color_mode(p.get("mode").and_then(Value::as_str).unwrap_or("rgb")).unwrap_or(ColorMode::Rgb); - let depth = sample_type(p.get("depth").and_then(Value::as_u64).unwrap_or(8)).unwrap_or(SampleType::U8); - let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string(); - let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, MAX_RESOLUTION) as f32; - // The background colour; `None` for Transparent. - let background = match p.get("background").and_then(Value::as_str).unwrap_or("white") { - "backgroundColor" => { - let bgc = background_color(p, s.tools.background, "file.new")?; - Some(Color::rgba(bgc[0], bgc[1], bgc[2], 1.0)) - } - "transparent" => None, - "black" => Some(Color::BLACK), - other => { - let c = parse_hex(other).unwrap_or([1.0; 4]); - Some(Color::rgba(c[0], c[1], c[2], c[3])) - } - }; - let mut doc = if p.get("artboard").and_then(Value::as_bool).unwrap_or(false) { - crate::artboard_cmds::new_artboard_document(name, Size::new(w, h), mode, depth, background) - } else if let Some(c) = background { - Document::with_background(name, Size::new(w, h), mode, depth, c) - } else { - let mut d = Document::new(name, Size::new(w, h), mode, depth); - d.layers.push(Layer::raster("Layer 1", d.pixel_format())); - d - }; - doc.resolution_dpi = res; - // Photoshop's New Document › Color Profile: tag the document with another profile - // than the working space (#321). Checked before the document opens. - if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) { - let prof = s.color.resolve(spec, Some(&doc), None)?; - if prof.color_space != crate::color_cmds::mode_space(doc.mode) { - return Err(EngineError::BadParams { - cmd: "file.new".into(), - msg: format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode), - }); - } - doc.icc_profile = Some(prof.to_bytes()); - } - let i = s.add_document(doc, None); - Ok(json!({ "document": i })) - } - ), - cmd!( - "file.close", - "Close", - ["File"], - Some("Cmd+W"), - r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, - has_doc, - |s, p| { - let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; - match p.get("save").filter(|v| !v.is_null()) { - Some(v) if v == "ask" => { - if s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() { - return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); - } - } - // `false` (don't save) is the older spelling of discard. - Some(Value::Bool(false)) => {} - Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), - _ => {} - } - s.close(i).ok_or(EngineError::NoDocument)?; - Ok(Value::Null) - } - ), - // Edit - cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), - cmd!( - "edit.fill", - "Fill…", - ["Edit"], - Some("Shift+F5"), - r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, - has_pixel_or_channel, - crate::fill_cmds::fill - ), - cmd!( - "edit.clear", - "Clear", - ["Edit"], - Some("Delete"), - r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, - has_pixel_or_channel, - |s, p| { - let bg = s.tools.background; - // A targeted alpha channel or Quick Mask is filled instead (#2734). - let channel = if crate::channel_cmds::is_channel_target(p) { - Some(p.clone()) - } else if p.get("target").is_none() { - crate::channel_cmds::targeted_channel(s) - } else { - None - }; - if let Some(t) = channel { - s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; - return Ok(Value::Null); - } - let id = layer_param(s, p)?; - if is_mask_target(p) { - s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; - return Ok(Value::Null); - } - // A targeted colour channel clears that channel only (#2720). - if let Some(colors) = crate::color_channels::target(s, p)? { - s.edit("Clear", |doc, _| { - for k in colors.indices() { - crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; - } - Ok(()) - })?; - return Ok(Value::Null); - } - s.edit("Clear", |doc, _| { - let sel = doc.selection.clone(); - let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); - crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) - })?; - Ok(Value::Null) - } - ), - // Select - cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| { - s.edit("Select All", |doc, _| { - let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); - m.fill_rect(doc.bounds(), &[1.0]); - doc.selection = Some(m); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("select.deselect", "Deselect", ["Select"], Some("Cmd+D"), "{}", has_selection, |s, _| { - // Nothing selected: nothing to do and no history step, as in Photoshop (#6744). - if s.active().is_none_or(|d| d.doc.selection.is_none()) { - return Ok(Value::Null); - } - s.edit("Deselect", |doc, _| { - doc.selection = None; - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("select.inverse", "Inverse", ["Select"], Some("Cmd+Shift+I"), "{}", has_selection, |s, _| { - s.edit("Inverse", |doc, _| { - let old = doc.selection.take().unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8)); - doc.selection = Some(photocraft_algo::selection::inverse_surface(&old, doc.bounds())); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "select.rect", - "Rectangular Selection", - [], - None, - r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"line":"row|column"?,"antiAlias":bool=true,"feather":px=0}"##, - has_doc, - |s, p| { - let get = |k: &str| int_i32("select.rect", p, k).and_then(|v| v.ok_or_else(|| bad("select.rect", format!("missing `{k}`")))); - let r = Rect::from_xywh(get("x")?, get("y")?, get("width")?.max(0) as u32, get("height")?.max(0) as u32); - let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string(); - let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false); - // The History step is named after the tool: the Single Row / Single Column - // Marquee send `line` (Photoshop). - let step = match p.get("line").and_then(Value::as_str) { - Some("row") => "Single Row Marquee", - Some("column") => "Single Column Marquee", - Some(other) => return Err(bad("select.rect", format!("unknown `line` {other:?} (row|column)"))), - None if ellipse => "Elliptical Marquee", - None => "Rectangular Marquee", - }; - // Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only). - let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); - let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32; - s.edit(step, |doc, _| { - let area = doc.bounds(); - // A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse - // keeps the dragged shape and is only cut there. - use photocraft_algo::selection as sel; - let shape = if ellipse { - sel::ellipse_surface(r, area, aa) - } else { - let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8); - s.fill_rect(r.intersect(&area), &[1.0]); - s - }; - if feather > 0.0 { - let window = selection_cmds::feather_window(r, area, feather); - let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); - doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); - return Ok(()); - } - let old = doc.selection.take(); - let combined = match (mode.as_str(), old) { - ("add", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a.max(b)), - ("subtract", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a * (1.0 - b)), - ("intersect", Some(o)) => sel::combine_surfaces(&o, &shape, area, |a, b| a.min(b)), - // With no existing selection, neither operation can select new pixels. - ("subtract" | "intersect", None) => Surface::new(photocraft_color::PixelFormat::GRAY8), - _ => shape, - }; - // Sparse Add/Subtract keeps untouched pixels outside the canvas. Only pixels - // inside the document count when deciding whether a selection remains. - let has_on_canvas_pixels = (combined.default_bytes().first().copied().unwrap_or(0) != 0 && { - let canvas_tiles = u64::from(area.width().div_ceil(TILE_SIZE as u32)) * u64::from(area.height().div_ceil(TILE_SIZE as u32)); - let stored = combined.tiles().filter(|(coord, _)| !coord.rect().intersect(&area).is_empty()).count() as u64; - stored < canvas_tiles - }) || combined.tiles().any(|(coord, tile)| { - let tile_rect = coord.rect(); - let overlap = tile_rect.intersect(&area); - if overlap.is_empty() { - return false; - } - let x0 = (overlap.x0 - tile_rect.x0) as usize; - let x1 = (overlap.x1 - tile_rect.x0) as usize; - (overlap.y0 - tile_rect.y0..overlap.y1 - tile_rect.y0).any(|y| { - let row_start = y as usize * TILE_SIZE as usize; - let start = row_start + x0; - tile.bytes().get(start..row_start + x1).is_some_and(|row| row.iter().any(|&v| v != 0)) - }) - }); - doc.selection = has_on_canvas_pixels.then_some(combined); - Ok(()) - })?; - Ok(Value::Null) - } - ), - // Layer - cmd!( - "layer.new.layer", - "Layer…", - ["Layer", "New"], - Some("Cmd+Shift+N"), - r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##, - has_doc, - crate::new_layer::run - ), - cmd!( - "layer.new.group", - "Group…", - ["Layer", "New"], - None, - r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, - has_doc, - |s, p| { - let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; - let below = crate::group_options::below("layer.new.group", p)?; - let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; - let id = s.edit("New Group", |doc, active| { - let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); - let mut group = Layer::group(name, vec![]); - opts.apply(&mut group); - let bg = crate::background_cmds::background_id(doc); - let id = crate::layer_place::insert_new(doc, *active, group, place); - crate::background_cmds::keep_background_at_bottom(bg, doc)?; - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.groupLayers", - "Group Layers", - ["Layer"], - Some("Cmd+G"), - r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, - has_layer, - crate::layer_multi_cmds::group_layers - ), - cmd!( - "layer.duplicate", - "Duplicate Layer…", - ["Layer"], - None, - r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##, - has_layer, - |s, p| { - if let Some(d) = p.get("document") { - if d.as_str() == Some("new") { - return crate::layer_copy_cmds::duplicate_to_new_document(s, p); - } - let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64)); - if !same { - return Err(EngineError::BadParams { - cmd: "layer.duplicate".into(), - msg: if d.as_u64().is_some() { - "the destination is another open document (use layer.copyToDocument)".into() - } else { - "`document` must be a document index or \"new\"".into() - }, - }); - } - } - let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false); - let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); - if crate::layer_multi_cmds::multi(s, p) { - return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); - } - let id = layer_param(s, p)?; - let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); - // The dialog offers Duplicate Layer's own name: only a different one was typed (#9023). - let mut typed = None; - let mut shift = (0, 0); - let nid = s.edit("Duplicate Layer", |doc, active| { - let mut dup = layer_copy(doc, id, add_copy)?; - if let Some(name) = name.as_ref().filter(|n| **n != dup.name) { - dup.name.clone_from(name); - typed = Some(name.clone()); - } - let nid = doc.insert_above(Some(id), dup); - // A lone copy joins its original's link group, as in the reference application (#11217). - crate::layer_multi_cmds::relink_copies(doc, &[nid])?; - if !in_place { - shift = crate::artboard_cmds::place_copy(doc, nid)?; - } - *active = Some(nid); - Ok(nid) - })?; - crate::artboard_cmds::follow_shift(s, shift); - if let Some(name) = typed { - crate::type_cmds::note_typed_name(s, nid, &name); - } - Ok(json!({ "layer": nid.0 })) - } - ), - cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| { - if crate::layer_multi_cmds::multi(s, p) { - return crate::layer_multi_cmds::delete_selected(s); - } - let id = layer_param(s, p)?; - s.edit("Delete Layer", |doc, active| { - let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id); - let before = crate::clip_group::Before::read(doc, &[id]); - doc.remove(id).ok_or(EngineError::NoLayer(id))?; - crate::clip_group::settle(doc, &[], &before, false); - if doc.layers.is_empty() { - return Err(EngineError::Other("a document must keep at least one layer".into())); - } - if active.is_some_and(|current| doc.layer(current).is_none()) { - *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); - } - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "layer.select", - "Select Layer", - [], - None, - r##"{"layer":id|str|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"} | "name":str,"occurrence":index?,"mode":"replace|toggle|range|add|remove"="replace"} (typed references use the recorded full layer stack; name occurrence: zero-based document walk order; required for duplicate names; toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##, - has_doc, - crate::layer_multi_cmds::select - ), - cmd!( - "layer.setProps", - "Layer Properties", - [], - None, - r##"{"layer":id?,"layers":[id,…]? (the same change to each, one step: the Layers panel's controls with several layers selected),"name":str? (one layer only),"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?,"channels":[bool,…]? (Advanced Blending: which colour channels blend, R G B / C M Y K / L a b)}"##, - has_layer, - |s, p| { - // Several layers at once (the Layers panel with several selected, as in Photoshop), - // else the given or active one. - let ids: Vec = match p.get("layers") { - None | Some(Value::Null) => vec![layer_param(s, p)?], - Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let mut ids = Vec::with_capacity(a.len()); - for v in a { - let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; - if doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - if !ids.contains(&id) { - ids.push(id); - } - } - ids - } - Some(v) => return Err(bad("layer.setProps", format!("`layers` is a non-empty list of layer ids, got {v}"))), - }; - if ids.len() > 1 && p.get("name").is_some() { - return Err(bad("layer.setProps", "`name` renames one layer, not several")); - } - // Opacity and Fill are fractions here, while the Layer Style commands take - // percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242). - let unit = |key: &str| -> Result> { - let Some(v) = p.get(key) else { return Ok(None) }; - match v.as_f64() { - Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)), - _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))), - } - }; - let (opacity, fill) = (unit("opacity")?, unit("fill")?); - // Photoshop's History names for a single kind of change; a mix is "Layer Properties". - let changed: Vec<&str> = p - .as_object() - .map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "layers" | "coalesce")).collect()) - .unwrap_or_default(); - let label = match changed.as_slice() { - ["visible"] => "Layer Visibility", - ["opacity"] => "Opacity Change", - ["fill"] => "Fill Opacity Change", - ["blend"] => "Blending Change", - ["name"] => "Rename Layer", - _ => "Layer Properties", - }; - // The eye: a history state only with History Options › Make Layer Visibility - // Changes Undoable. - let only_visibility = changed.as_slice() == ["visible"]; - let record = !only_visibility || s.visibility_undoable(); - s.edit_with(label, record, |doc, _| { - // The Background has no opacity, fill or blend mode: like Photoshop, setting - // one that changes its look turns it into a normal layer ("Layer 0") first. - let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); - let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal); - for &id in &ids { - if num("opacity") || num("fill") || blends { - crate::extra_cmds::background_to_layer(doc, id); - } - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if let Some(v) = p.get("name").and_then(Value::as_str) { - l.name = v.to_string(); - } - if let Some(v) = p.get("visible").and_then(Value::as_bool) { - l.visible = v; - } - if let Some(v) = opacity { - l.opacity = v; - } - if let Some(v) = fill { - l.fill_opacity = v; - } - if let Some(v) = p.get("blend").and_then(Value::as_str) { - let b = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; - // Pass Through is a group's mode only, as in Photoshop. - if b == photocraft_color::BlendMode::PassThrough && !l.is_group() { - return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0))); - } - l.blend = b; - } - if let Some(v) = p.get("clipped").and_then(Value::as_bool) { - l.clipped = v; - } - if let Some(v) = p.get("locked").and_then(Value::as_bool) { - l.locks.all = v; - } - if let Some(Value::Array(ch)) = p.get("channels") { - // Blending Options › Advanced Blending › Channels: unchecked = left out. - l.excluded_channels = ch.iter().take(32).enumerate().filter(|(_, v)| v.as_bool() == Some(false)).fold(0, |m, (i, _)| m | 1 << i); - } - if let Some(Value::Object(m)) = p.get("locks") { - for (k, v) in m { - let v = v.as_bool().unwrap_or(false); - if !l.locks.set(k, v) { - return Err(bad("layer.setProps", format!("unknown lock `{k}`"))); - } - } - } - } - Ok(()) - })?; - // The Layers panel's in-place rename: a name the user typed (#9023). - if let (Some(name), [id]) = (p.get("name").and_then(Value::as_str), ids.as_slice()) { - crate::type_cmds::note_typed_name(s, *id, name); - } - Ok(Value::Null) - } - ), - cmd!("layer.arrange.bringForward", "Bring Forward", ["Layer", "Arrange"], Some("Cmd+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, 1)), - cmd!("layer.arrange.sendBackward", "Send Backward", ["Layer", "Arrange"], Some("Cmd+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, -1)), - cmd!("layer.arrange.bringToFront", "Bring to Front", ["Layer", "Arrange"], Some("Cmd+Shift+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange( - s, - p, - i32::MAX - )), - cmd!("layer.arrange.sendToBack", "Send to Back", ["Layer", "Arrange"], Some("Cmd+Shift+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange( - s, - p, - i32::MIN - )), - cmd!( - "layer.createClippingMask", - "Create Clipping Mask", - ["Layer"], - Some("Cmd+Alt+G"), - r##"{"layer":id?} (no layer: every selected layer but the lowest clips to the layer below it)"##, - has_layer, - |s, p| set_clipped(s, p, true) - ), - cmd!( - "layer.releaseClippingMask", - "Release Clipping Mask", - ["Layer"], - None, - r##"{"layer":id?} (no layer: every selected layer)"##, - has_layer, - |s, p| set_clipped(s, p, false) - ), - cmd!( - "layer.layerMask.revealAll", - "Reveal All", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_layer, - |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::reveal_all())) - ), - cmd!( - "layer.layerMask.hideAll", - "Hide All", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_layer, - |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::hide_all())) - ), - cmd!( - "layer.layerMask.revealSelection", - "Reveal Selection", - ["Layer", "Layer Mask"], - None, - r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, - has_selection, - |s, p| { - let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?; - let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() }; - // The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a - // following Invert (⌘I) on the targeted mask then inverts all of it, not just the - // part inside the old selection. Same undo step as the mask. - set_mask_and_deselect(s, p, "Add Layer Mask", mask) - } - ), - cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask( - s, - p, - "Delete Layer Mask", - None - )), - cmd!( - "layer.layerMask.moveTo", - "Move Layer Mask", - [], - None, - r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, - has_layer, - move_mask - ), - cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { - let id = layer_param(s, p)?; - s.edit("Merge Down", |doc, active| { - let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; - let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) }; - if idx == 0 { - return Err(EngineError::Other("no layer below to merge into".into())); - } - let mut below = parent.to_vec(); - below.push(idx - 1); - let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone(); - let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); - let merged = pixels::merge_down(doc, &lower, &upper); - doc.remove(id); - *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged; - *active = Some(lower.id); - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!("layer.mergeGroup", "Merge Group", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { - let id = layer_param(s, p)?; - if !s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { - return Err(EngineError::Other("Merge Group needs a group".into())); - } - merge_group(s, id) - }), - cmd!("layer.flattenImage", "Flatten Image", ["Layer"], None, "{}", has_doc, |s, _| { - s.edit("Flatten Image", |doc, active| { - let fmt = doc.pixel_format(); - let mut bg = Layer::raster("Background", fmt); - bg.locks.transparency = true; - bg.locks.position = true; - *crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0])); - *active = Some(bg.id); - doc.layers = vec![bg]; - Ok(()) - })?; - Ok(Value::Null) - }), - cmd!( - "layer.newFillLayer.solidColor", - "Solid Color…", - ["Layer", "New Fill Layer"], - None, - r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, - has_doc, - |s, p| { - let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; - // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead - // of what its sRGB stand-in converts back to through the document profile (#8568). - let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { - Some(k) => Some(k), - None => s.tools.picked_cmyk([c[0], c[1], c[2]]), - }; - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - let id = s.edit("New Color Fill Layer", |doc, active| { - let fill = match inks { - Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), - _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), - }; - let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.newFillLayer.gradient", - "Gradient…", - ["Layer", "New Fill Layer"], - None, - r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, - has_doc, - |s, p| { - let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; - let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; - let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; - let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); - let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - // The rest of a recorded Gradient Fill (a loaded action's Make): applied as - // `gradient.fill.set` would, in the same step. - let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] - .iter() - .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) - .collect(); - let (fg, bg) = (s.tools.foreground, s.tools.background); - let id = s.edit("New Gradient Fill Layer", |doc, active| { - let mut fill = Fill::gradient( - vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], - angle, - 1.0, - style, - reverse, - ); - if !rest.is_empty() { - let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); - fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; - } - let fill = fill.in_mode(doc.mode); - let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.setAdjustment", - "Adjustment Properties", - [], - None, - r##"{"layer":id?, …params of that adjustment kind} (Levels, Curves: "eyedropper":{"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1} = the Properties panel's Set Black/Neutral Gray/White Point, sampling the image below the layer, RGB and Grayscale (no gray) only)"##, - has_layer, - |s, p| { - let id = layer_param(s, p)?; - let eyedropped = crate::adjust_params::layer_eyedropper(s, id, p)?; - s.edit("Modify Adjustment", |doc, _| { - let mode = doc.mode; - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) }; - if matches!(adj, Adjustment::Unsupported { .. }) { - return Err(EngineError::Other("this adjustment can't be edited (kept as imported)".into())); - } - let kind = adjustment_kind(adj); - // No params resets to the defaults; otherwise params merge over the current values. - *adj = if let Some(eyedropped) = eyedropped { - eyedropped - } else if crate::adjust_params::user_keys(p).is_empty() { - crate::adjust_params::default_for(kind, mode)? - } else { - crate::adjust_params::from_params(kind, p, Some(adj), mode)? - }; - Ok(()) - })?; - Ok(Value::Null) - } - ), - cmd!( - "layer.moveTo", - "Reorder Layer", - [], - None, - r##"{"layer":id|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"}?| "layers":[id,…]?, "target":id|name|{"index":uint},"targetOccurrence":n? (which of several layers named `target`, in document order),"position":"above|below|into"="above","copy":bool=false} (typed target: pre-move recorded stack boundary, omit position; layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row; recorded typed references retain their form)"##, - has_layer, - crate::layer_multi_cmds::move_to - ), - cmd!( - "layer.translate", - "Move Layer", - [], - None, - r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false,"wrap":bool=false,"nest":bool=false} → null | {nested:[id]} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step; wrap: View › Pattern Preview, pixels that leave the canvas come back on the opposite edge so the tile stays seamless; nest: auto-nesting as the Move tool does it, a layer whose bounds centre lands on another artboard joins it and one whose centre is off every artboard leaves for the top level; a clipping base takes the layers clipped to it along and a clipped layer goes only where its base goes; artboards, the Background, empty layers, layers whose board doesn't change, groups that would nest too deep and layers locked with Prevent Auto-Nesting (on the layer, a group around it or the destination board) stay put, with their whole clipping group; nested lists the layers that changed board)"##, - has_layer, - crate::layer_multi_cmds::translate - ), - // Image - cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal) - }), - cmd!("image.imageRotation.flipCanvasVertical", "Flip Canvas Vertical", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Flip Canvas Vertical", crate::canvas_geom::Turn::FlipVertical) - }), - cmd!("image.imageRotation.180", "180°", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Rotate180) - }), - cmd!("image.imageRotation.90cw", "90° Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Cw90) - }), - cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { - turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) - }), - cmd!( - "image.adjustments.desaturate", - "Desaturate", - ["Image", "Adjustments"], - Some("Cmd+Shift+U"), - r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, - has_pixel_layer, - |s, p| { - destructive_adjust( - s, - "Desaturate", - Adjustment::HueSaturation { - hue: 0.0, - saturation: -100.0, - lightness: 0.0, - colorize: false, - ranges: photocraft_doc::adjust::HueRange::defaults(), - }, - p, - ) - } - ), - // Paint - cmd!( - "paint.stroke", - "Brush Stroke", - [], - None, - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - has_paintable, - crate::brush_cmds::paint_stroke - ), - cmd!( - "tools.setColors", - "Set Colors", - [], - None, - r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##, - always, - |s, p| { - let cmyk = |key: &str| cmyk_param("tools.setColors", p, key); - let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?); - let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?; - let background = color_param("tools.setColors", p, "background", s.tools.background)?; - s.tools.foreground = foreground; - s.tools.background = background; - if let Some(k) = fg_cmyk { - let [r, g, b, _] = s.tools.foreground; - s.tools.remember_cmyk([r, g, b], k); - } - if let Some(k) = bg_cmyk { - let [r, g, b, _] = s.tools.background; - s.tools.remember_cmyk([r, g, b], k); - } - Ok(Value::Null) - } - ), - cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| { - std::mem::swap(&mut s.tools.foreground, &mut s.tools.background); - Ok(Value::Null) - }), - cmd!("tools.defaultColors", "Default Foreground and Background Colors", [], Some("D"), "{}", always, |s, _| { - if s.tools.mask_targeted { - s.tools.foreground = crate::ToolState::MASK_COLORS[0]; - s.tools.background = crate::ToolState::MASK_COLORS[1]; - } else { - s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - s.tools.background = [1.0, 1.0, 1.0, 1.0]; - } - Ok(Value::Null) - }), - // Queries (not journaled) - CommandSpec { - id: "session.inspect", - label: "Inspect Session", - menu: &[], - shortcut: None, - params: "{}", - enabled: always, - run: |s, _| Ok(inspect::session(s)), - journal: false, - }, - CommandSpec { - id: "document.inspect", - label: "Inspect Document", - menu: &[], - shortcut: None, - params: r##"{"document":index?}"##, - enabled: has_doc, - run: |s, p| { - let d = match p.get("document") { - Some(v) => { - let i = v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.inspect", "`document` must be an index"))?; - s.documents().get(i).ok_or_else(|| EngineError::Other(format!("no document at index {i}")))? - } - None => s.active().ok_or(EngineError::NoDocument)?, - }; - Ok(inspect::document(d)) - }, - journal: false, - }, - CommandSpec { - id: "document.activate", - label: "Activate Document", - menu: &[], - shortcut: None, - params: r##"{"document":index|{"index":uint}} or {"offset":int} (numeric document: zero-based tab index; typed index: one-based opening order; offset: places after the active document in opening order, before it when negative) → {document}"##, - enabled: has_doc, - run: |s, p| { - // A null key counts as omitted. - let given = |k: &str| p.get(k).filter(|v| !v.is_null()); - let idx = match (given("document"), given("offset")) { - (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")), - (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")), - // Recorded offsets wrap in opening order, independently of dragged tabs. - (None, Some(o)) => { - let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?; - s.document_at_offset(o)? - } - (Some(d), None) => { - if let Some(selector) = d.as_object() { - let index = selector - .get("index") - .filter(|_| selector.len() == 1) - .and_then(Value::as_u64) - .ok_or_else(|| bad("document.activate", "document reference needs one non-negative index"))?; - return s - .document_at_index(index) - .and_then(|idx| if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::NoDocument) }); - } - let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?; - usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))? - } - }; - if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) } - }, - journal: true, - }, - CommandSpec { - id: "document.move", - label: "Move Document", - menu: &[], - shortcut: None, - params: r##"{"document":index?,"to":index}"##, - enabled: has_doc, - run: |s, p| { - let index = |key: &str| { - p.get(key) - .map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index")))) - }; - let from = match index("document") { - Some(i) => i?, - None => s.active_index().ok_or(EngineError::NoDocument)?, - }; - let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??; - let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?; - Ok(json!({"document": to})) - }, - journal: false, - }, - CommandSpec { - id: "command.list", - label: "List Commands", - menu: &[], - shortcut: None, - params: "{}", - enabled: always, - run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())), - journal: false, - }, - CommandSpec { - id: "document.pixel", - label: "Read Composite Pixel", - menu: &[], - shortcut: None, - params: r##"{"x":i32,"y":i32}"##, - enabled: has_doc, - run: |s, p| { - let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits"))); - let (x, y) = (coord("x")?, coord("y")?); - let d = s.active().ok_or(EngineError::NoDocument)?; - // At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent. - let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default(); - Ok(json!(px)) - }, - journal: false, - }, - ]; +const SPECS: &[fn() -> Vec] = &[ + file_menu::specs, + edit_menu::specs, + select_menu::specs, + layer_menu::specs, + image_menu::specs, + paint::specs, + queries::specs, + adjustments::specs, + crate::layer_style::specs, + crate::contour_lib_cmds::specs, + crate::layer_list_cmds::specs, + crate::filters::specs, + crate::filters_ext::specs, + crate::color_to_alpha_cmds::specs, + crate::gallery_cmds::specs, + crate::gradient_fill_cmds::specs, + crate::solid_fill_cmds::specs, + crate::pattern_fill_cmds::specs, + crate::type_cmds::specs, + crate::type_mask_cmds::specs, + crate::transform_cmds::specs, + crate::float_cmds::specs, + crate::vector_cmds::specs, + crate::path_edit_cmds::specs, + crate::smartselect_cmds::specs, + crate::cutout_cmds::specs, + crate::symmetry_cmds::specs, + crate::edit_cmds::specs, + crate::smart_svg_cmds::specs, + crate::color_cmds::specs, + crate::brush_cmds::specs, + crate::brush_preset_cmds::specs, + crate::eraser_cmds::specs, + crate::preset_import_cmds::specs, + crate::style_asl_cmds::specs, + crate::atn_cmds::specs, + crate::actions_edit_cmds::specs, + crate::swatch_cmds::specs, + crate::retouch_cmds::specs, + crate::redeye_cmds::specs, + crate::image_cmds::specs, + crate::perspective_crop_cmds::specs, + crate::selection_cmds::specs, + crate::magnetic_cmds::specs, + crate::select_extra_cmds::specs, + crate::paint_cmds::specs, + crate::extra_cmds::specs, + crate::background_cmds::specs, + crate::file_cmds::specs, + crate::exr_cmds::specs, + crate::type_extra_cmds::specs, + crate::type_area_cmds::specs, + crate::type_styles_cmds::specs, + crate::type_spell_cmds::specs, + crate::type_caret_cmds::specs, + crate::smart_cmds::specs, + crate::layer_multi_cmds::specs, + crate::layer_copy_cmds::specs, + crate::prefs::specs, + crate::updates_cmds::specs, + crate::edit_menu_cmds::specs, + crate::fill_key_cmds::specs, + crate::sample_cmds::specs, + crate::face_cmds::specs, + crate::sampler_cmds::specs, + crate::brush_key_cmds::specs, + crate::stamp_cmds::specs, + crate::align_cmds::specs, + crate::photo_cmds::specs, + crate::lens_cmds::specs, + crate::vp_cmds::specs, + crate::channel_cmds::specs, + crate::adjust_cmds::specs, + crate::layer_menu_cmds::specs, + crate::layer_label_cmds::specs, + crate::layer_css_cmds::specs, + crate::layer_xmp_cmds::specs, + crate::mode_cmds::specs, + crate::multichannel_cmds::specs, + crate::pattern_cmds::specs, + crate::warp_cmds::specs, + crate::comps_cmds::specs, + crate::artboard_cmds::specs, + crate::distort_cmds::specs, + crate::analysis_cmds::specs, + crate::notes_cmds::specs, + crate::font_library_cmds::specs, + crate::history_cmds::specs, + crate::history_options_cmds::specs, + crate::history_menu_cmds::specs, + crate::history_source_cmds::specs, + crate::history_select_cmds::specs, + crate::proof_sim::specs, + crate::presets::specs, + crate::document_preset_cmds::specs, + crate::export_preset_cmds::specs, + crate::render_cmds::specs, + crate::slice_cmds::specs, + crate::web_cmds::specs, + crate::automate_cmds::specs, + crate::print_cmds::specs, + crate::installed_profiles::specs, + crate::pick_cmds::specs, + crate::layer_nav_cmds::specs, + crate::frame_cmds::specs, + crate::migrate_cmds::specs, + crate::trap_cmds::specs, + crate::timeline_cmds::specs, + crate::video_cmds::specs, + crate::jobs::specs, + crate::wia_cmds::specs, + crate::rasterize_style_cmds::specs, + crate::variables_cmds::specs, + crate::plugin_cmds::specs, + crate::group_view_cmds::specs, + crate::fx_view_cmds::specs, + crate::fx_visibility_cmds::specs, + crate::mask_view_cmds::specs, + crate::layer_mask_props_cmds::specs, + crate::actions_cmds::specs, +]; - // Adjustment layers + destructive adjustments, generated from one list. - // Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale), - // cyan/magenta/yellow/black (CMYK), lightness/a/b (Lab); see `adjust_params`. - const ADJ: &[(&str, &str, &str)] = &[ - ("brightnessContrast", "Brightness/Contrast…", r##"{"brightness":-150..150=0,"contrast":-50..100=0,"legacy":bool=false}"##), - ( - "levels", - "Levels…", - r##"{"inBlack":0..253=0,"gamma":0.01..9.99=1,"inWhite":2..255=255,"outBlack":0..255=0,"outWhite":0..255=255,"red":json,"green":json,"blue":json,"eyedropper":json} (top level = composite; per channel {"inBlack","gamma","inWhite","outBlack","outWhite"} under red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}: black/white set each channel's input black/white to the sample, gray each channel's gamma so the sample turns neutral at its luma; colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given levels)"##, - ), - ( - "curves", - "Curves…", - r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}, colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given curves)"##, - ), - ("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##), - ("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##), - ( - "hueSaturation", - "Hue/Saturation…", - r##"{"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"colorize":bool=false,"reds":json,"yellows":json,"greens":json,"cyans":json,"blues":json,"magentas":json} (per range {"hue","saturation","lightness","range":[4 hue degrees]}; colorize: hue 0..360, saturation 0..100)"##, - ), - ( - "colorBalance", - "Color Balance…", - r##"{"shadows":json,"midtones":json,"highlights":json,"preserveLuminosity":bool=true} (each tone [cyan-red, magenta-green, yellow-blue] in -100..100)"##, - ), - ( - "blackWhite", - "Black & White…", - r##"{"reds":-200..300=40,"yellows":-200..300=60,"greens":-200..300=40,"cyans":-200..300=60,"blues":-200..300=20,"magentas":-200..300=80,"tint":bool=false,"tintColor":"#rrggbb"}"##, - ), - ( - "photoFilter", - "Photo Filter…", - r##"{"filter":"warming85|warmingLBA|warming81|cooling80|coolingLBB|cooling82|red|orange|yellow|green|cyan|blue|violet|magenta|sepia|deepRed|deepBlue|deepEmerald|deepYellow|underwater","color":"#rrggbb","density":0..100=25,"preserveLuminosity":bool=true}"##, - ), - ( - "channelMixer", - "Channel Mixer…", - r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##, - ), - ("invert", "Invert", "{}"), - ("posterize", "Posterize…", r##"{"levels":2..255=4}"##), - ("threshold", "Threshold…", r##"{"level":1..255=128}"##), - ("gradientMap", "Gradient Map…", r##"{"stops":json,"reverse":bool=false,"dither":bool=false} (stops [[location 0..1, "#rrggbb"], …], 2..64)"##), - ( - "selectiveColor", - "Selective Color…", - r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##, - ), - ( - "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)"##, - ), - ]; - for &(kind, label, params) in ADJ { - let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str()); - let image_id: &'static str = Box::leak(format!("image.adjustments.{kind}").into_boxed_str()); - v.push(CommandSpec { - id: layer_id, - label, - menu: &["Layer", "New Adjustment Layer"], - shortcut: None, - params: Box::leak(format!(r#"{params} + {{{NEW_LAYER_PATH},"opacity":0..1=1,"name":str?=the adjustment's name + number,"mode":blend mode name="normal" (not Pass Through),"clipToPrevious":bool=false}}"#).into_boxed_str()), - enabled: has_doc, - run: |s, p| { - let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); - let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::eyedropper_from_params(s, &kind, p)? } else { None }; - let adj = match eyedropped { - Some(adj) => adj, - None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?, - }; - new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}")) - }, - journal: true, - }); - v.push(CommandSpec { - id: image_id, - label, - menu: &["Image", "Adjustments"], - shortcut: match kind { - "levels" => Some("Cmd+L"), - "curves" => Some("Cmd+M"), - "hueSaturation" => Some("Cmd+U"), - "colorBalance" => Some("Cmd+B"), - "invert" => Some("Cmd+I"), - "blackWhite" => Some("Cmd+Alt+Shift+B"), - _ => None, - }, - params, - enabled: crate::adjust_cmds::has_adjustable, - run: |s, p| { - let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); - if matches!(kind.as_str(), "levels" | "curves") { - crate::channel_cmds::resolve_tone_target(s, false, p)?; - } - let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::destructive_eyedropper(s, &kind, p)? } else { None }; - // A smart filter re-runs its params, so it records what an eyedropper resolved - // to, not the sample (#3127). - let recorded = eyedropped.as_ref().map(|adj| { - let mut q = p.clone(); - if let (Value::Object(q), Value::Object(resolved)) = (&mut q, crate::adjust_params::to_params(adj)) { - q.remove("eyedropper"); - q.extend(resolved); - } - q - }); - let adj = match eyedropped { - Some(adj) => adj, - None => { - // A gray plane target keeps the neutral tone space even over params - // carrying RGB, Lab or CMYK records (#5335). - let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { - if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() } - } else { - p.clone() - }; - crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))? - } - }; - let adj = if matches!(kind.as_str(), "levels" | "curves") - && let Some(colors) = crate::color_channels::target(s, p)? - { - crate::color_channels::tone_adjustment(&kind, p, adj, doc_mode(s), colors)? - } else { - adj - }; - let label = adj.label().to_string(); - // A smart object records the adjustment as a smart filter (Photoshop), which - // re-runs from the source instead of baking into a copy of the pixels. - if crate::adjust_cmds::adjust_as_smart_filter(s, &kind, &label, recorded.as_ref().unwrap_or(p))? { - return Ok(Value::Null); - } - destructive_adjust(s, &label, adj, p) - }, - journal: true, - }); - } - v.extend(crate::layer_style::specs()); - v.extend(crate::contour_lib_cmds::specs()); - v.extend(crate::layer_list_cmds::specs()); - v.extend(crate::filters::specs()); - v.extend(crate::filters_ext::specs()); - v.extend(crate::color_to_alpha_cmds::specs()); - v.extend(crate::gallery_cmds::specs()); - v.extend(crate::gradient_fill_cmds::specs()); - v.extend(crate::solid_fill_cmds::specs()); - v.extend(crate::pattern_fill_cmds::specs()); - v.extend(crate::type_cmds::specs()); - v.extend(crate::type_mask_cmds::specs()); - v.extend(crate::transform_cmds::specs()); - v.extend(crate::float_cmds::specs()); - v.extend(crate::vector_cmds::specs()); - v.extend(crate::path_edit_cmds::specs()); - v.extend(crate::smartselect_cmds::specs()); - v.extend(crate::cutout_cmds::specs()); - v.extend(crate::symmetry_cmds::specs()); - v.extend(crate::edit_cmds::specs()); - v.extend(crate::smart_svg_cmds::specs()); - v.extend(crate::color_cmds::specs()); - v.extend(crate::brush_cmds::specs()); - v.extend(crate::brush_preset_cmds::specs()); - v.extend(crate::eraser_cmds::specs()); - v.extend(crate::preset_import_cmds::specs()); - v.extend(crate::style_asl_cmds::specs()); - v.extend(crate::atn_cmds::specs()); - v.extend(crate::actions_edit_cmds::specs()); - v.extend(crate::swatch_cmds::specs()); - v.extend(crate::retouch_cmds::specs()); - v.extend(crate::redeye_cmds::specs()); - v.extend(crate::image_cmds::specs()); - v.extend(crate::perspective_crop_cmds::specs()); - v.extend(crate::selection_cmds::specs()); - v.extend(crate::magnetic_cmds::specs()); - v.extend(crate::select_extra_cmds::specs()); - v.extend(crate::paint_cmds::specs()); - v.extend(crate::extra_cmds::specs()); - v.extend(crate::background_cmds::specs()); - v.extend(crate::file_cmds::specs()); - v.extend(crate::exr_cmds::specs()); - v.extend(crate::type_extra_cmds::specs()); - v.extend(crate::type_area_cmds::specs()); - v.extend(crate::type_styles_cmds::specs()); - v.extend(crate::type_spell_cmds::specs()); - v.extend(crate::type_caret_cmds::specs()); - v.extend(crate::smart_cmds::specs()); - v.extend(crate::layer_multi_cmds::specs()); - v.extend(crate::layer_copy_cmds::specs()); - v.extend(crate::prefs::specs()); - v.extend(crate::updates_cmds::specs()); - v.extend(crate::edit_menu_cmds::specs()); - v.extend(crate::fill_key_cmds::specs()); - v.extend(crate::sample_cmds::specs()); - v.extend(crate::face_cmds::specs()); - v.extend(crate::sampler_cmds::specs()); - v.extend(crate::brush_key_cmds::specs()); - v.extend(crate::stamp_cmds::specs()); - v.extend(crate::align_cmds::specs()); - v.extend(crate::photo_cmds::specs()); - v.extend(crate::lens_cmds::specs()); - v.extend(crate::vp_cmds::specs()); - v.extend(crate::channel_cmds::specs()); - v.extend(crate::adjust_cmds::specs()); - v.extend(crate::layer_menu_cmds::specs()); - v.extend(crate::layer_label_cmds::specs()); - v.extend(crate::layer_css_cmds::specs()); - v.extend(crate::layer_xmp_cmds::specs()); - v.extend(crate::mode_cmds::specs()); - v.extend(crate::multichannel_cmds::specs()); - v.extend(crate::pattern_cmds::specs()); - v.extend(crate::warp_cmds::specs()); - v.extend(crate::comps_cmds::specs()); - v.extend(crate::artboard_cmds::specs()); - v.extend(crate::distort_cmds::specs()); - v.extend(crate::analysis_cmds::specs()); - v.extend(crate::notes_cmds::specs()); - v.extend(crate::font_library_cmds::specs()); - v.extend(crate::history_cmds::specs()); - v.extend(crate::history_options_cmds::specs()); - v.extend(crate::history_menu_cmds::specs()); - v.extend(crate::history_source_cmds::specs()); - v.extend(crate::history_select_cmds::specs()); - v.extend(crate::proof_sim::specs()); - v.extend(crate::presets::specs()); - v.extend(crate::document_preset_cmds::specs()); - v.extend(crate::export_preset_cmds::specs()); - v.extend(crate::render_cmds::specs()); - v.extend(crate::slice_cmds::specs()); - v.extend(crate::web_cmds::specs()); - v.extend(crate::automate_cmds::specs()); - v.extend(crate::print_cmds::specs()); - v.extend(crate::installed_profiles::specs()); - v.extend(crate::pick_cmds::specs()); - v.extend(crate::layer_nav_cmds::specs()); - v.extend(crate::frame_cmds::specs()); - v.extend(crate::migrate_cmds::specs()); - v.extend(crate::trap_cmds::specs()); - v.extend(crate::timeline_cmds::specs()); - v.extend(crate::video_cmds::specs()); - v.extend(crate::jobs::specs()); - v.extend(crate::wia_cmds::specs()); - v.extend(crate::rasterize_style_cmds::specs()); - v.extend(crate::variables_cmds::specs()); - v.extend(crate::plugin_cmds::specs()); - v.extend(crate::group_view_cmds::specs()); - v.extend(crate::fx_view_cmds::specs()); - v.extend(crate::fx_visibility_cmds::specs()); - v.extend(crate::mask_view_cmds::specs()); - v.extend(crate::layer_mask_props_cmds::specs()); - v.extend(crate::actions_cmds::specs()); +/// Every registered command, in the order of SPECS. +fn build() -> Vec { + let specs = SPECS.iter().flat_map(|specs| specs()); // The dispatch guard's unit test needs a command that panics on purpose (REL-3). #[cfg(test)] - v.push(test_panic_command()); - v + let specs = specs.chain(std::iter::once(test_panic_command())); + specs.collect() } /// A command whose `run` panics on purpose, so the last-resort guard in `jobs::dispatch` diff --git a/crates/engine/src/cmd/adjustments.rs b/crates/engine/src/cmd/adjustments.rs new file mode 100644 index 0000000000..fa92e68d3a --- /dev/null +++ b/crates/engine/src/cmd/adjustments.rs @@ -0,0 +1,147 @@ +use super::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment}; + +/// The adjustment layers and the Image › Adjustments commands, generated from one table. +pub(super) fn specs() -> Vec { + let mut v = Vec::new(); + // Adjustment layers + destructive adjustments, generated from one list. + // Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale), + // cyan/magenta/yellow/black (CMYK), lightness/a/b (Lab); see `adjust_params`. + const ADJ: &[(&str, &str, &str)] = &[ + ("brightnessContrast", "Brightness/Contrast…", r##"{"brightness":-150..150=0,"contrast":-50..100=0,"legacy":bool=false}"##), + ( + "levels", + "Levels…", + r##"{"inBlack":0..253=0,"gamma":0.01..9.99=1,"inWhite":2..255=255,"outBlack":0..255=0,"outWhite":0..255=255,"red":json,"green":json,"blue":json,"eyedropper":json} (top level = composite; per channel {"inBlack","gamma","inWhite","outBlack","outWhite"} under red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}: black/white set each channel's input black/white to the sample, gray each channel's gamma so the sample turns neutral at its luma; colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given levels)"##, + ), + ( + "curves", + "Curves…", + r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}, colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given curves)"##, + ), + ("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##), + ("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##), + ( + "hueSaturation", + "Hue/Saturation…", + r##"{"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"colorize":bool=false,"reds":json,"yellows":json,"greens":json,"cyans":json,"blues":json,"magentas":json} (per range {"hue","saturation","lightness","range":[4 hue degrees]}; colorize: hue 0..360, saturation 0..100)"##, + ), + ( + "colorBalance", + "Color Balance…", + r##"{"shadows":json,"midtones":json,"highlights":json,"preserveLuminosity":bool=true} (each tone [cyan-red, magenta-green, yellow-blue] in -100..100)"##, + ), + ( + "blackWhite", + "Black & White…", + r##"{"reds":-200..300=40,"yellows":-200..300=60,"greens":-200..300=40,"cyans":-200..300=60,"blues":-200..300=20,"magentas":-200..300=80,"tint":bool=false,"tintColor":"#rrggbb"}"##, + ), + ( + "photoFilter", + "Photo Filter…", + r##"{"filter":"warming85|warmingLBA|warming81|cooling80|coolingLBB|cooling82|red|orange|yellow|green|cyan|blue|violet|magenta|sepia|deepRed|deepBlue|deepEmerald|deepYellow|underwater","color":"#rrggbb","density":0..100=25,"preserveLuminosity":bool=true}"##, + ), + ( + "channelMixer", + "Channel Mixer…", + r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##, + ), + ("invert", "Invert", "{}"), + ("posterize", "Posterize…", r##"{"levels":2..255=4}"##), + ("threshold", "Threshold…", r##"{"level":1..255=128}"##), + ("gradientMap", "Gradient Map…", r##"{"stops":json,"reverse":bool=false,"dither":bool=false} (stops [[location 0..1, "#rrggbb"], …], 2..64)"##), + ( + "selectiveColor", + "Selective Color…", + r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##, + ), + ( + "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)"##, + ), + ]; + for &(kind, label, params) in ADJ { + let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str()); + let image_id: &'static str = Box::leak(format!("image.adjustments.{kind}").into_boxed_str()); + v.push(CommandSpec { + id: layer_id, + label, + menu: &["Layer", "New Adjustment Layer"], + shortcut: None, + params: Box::leak(format!(r#"{params} + {{{NEW_LAYER_PATH},"opacity":0..1=1,"name":str?=the adjustment's name + number,"mode":blend mode name="normal" (not Pass Through),"clipToPrevious":bool=false}}"#).into_boxed_str()), + enabled: has_doc, + run: |s, p| { + let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); + let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::eyedropper_from_params(s, &kind, p)? } else { None }; + let adj = match eyedropped { + Some(adj) => adj, + None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?, + }; + new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}")) + }, + journal: true, + }); + v.push(CommandSpec { + id: image_id, + label, + menu: &["Image", "Adjustments"], + shortcut: match kind { + "levels" => Some("Cmd+L"), + "curves" => Some("Cmd+M"), + "hueSaturation" => Some("Cmd+U"), + "colorBalance" => Some("Cmd+B"), + "invert" => Some("Cmd+I"), + "blackWhite" => Some("Cmd+Alt+Shift+B"), + _ => None, + }, + params, + enabled: crate::adjust_cmds::has_adjustable, + run: |s, p| { + let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string(); + if matches!(kind.as_str(), "levels" | "curves") { + crate::channel_cmds::resolve_tone_target(s, false, p)?; + } + let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::destructive_eyedropper(s, &kind, p)? } else { None }; + // A smart filter re-runs its params, so it records what an eyedropper resolved + // to, not the sample (#3127). + let recorded = eyedropped.as_ref().map(|adj| { + let mut q = p.clone(); + if let (Value::Object(q), Value::Object(resolved)) = (&mut q, crate::adjust_params::to_params(adj)) { + q.remove("eyedropper"); + q.extend(resolved); + } + q + }); + let adj = match eyedropped { + Some(adj) => adj, + None => { + // A gray plane target keeps the neutral tone space even over params + // carrying RGB, Lab or CMYK records (#5335). + let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { + if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() } + } else { + p.clone() + }; + crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))? + } + }; + let adj = if matches!(kind.as_str(), "levels" | "curves") + && let Some(colors) = crate::color_channels::target(s, p)? + { + crate::color_channels::tone_adjustment(&kind, p, adj, doc_mode(s), colors)? + } else { + adj + }; + let label = adj.label().to_string(); + // A smart object records the adjustment as a smart filter (Photoshop), which + // re-runs from the source instead of baking into a copy of the pixels. + if crate::adjust_cmds::adjust_as_smart_filter(s, &kind, &label, recorded.as_ref().unwrap_or(p))? { + return Ok(Value::Null); + } + destructive_adjust(s, &label, adj, p) + }, + journal: true, + }); + } + v +} diff --git a/crates/engine/src/cmd/edit_menu.rs b/crates/engine/src/cmd/edit_menu.rs new file mode 100644 index 0000000000..06a2136837 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu.rs @@ -0,0 +1,62 @@ +use super::{CommandSpec, Value, can_redo, can_undo, has_pixel_or_channel, is_mask_target, json, layer_param}; + +/// Edit menu commands: Undo, Redo, Fill and Clear. +pub(super) fn specs() -> Vec { + vec![ + cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), + cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), + cmd!( + "edit.fill", + "Fill…", + ["Edit"], + Some("Shift+F5"), + r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, + has_pixel_or_channel, + crate::fill_cmds::fill + ), + cmd!( + "edit.clear", + "Clear", + ["Edit"], + Some("Delete"), + r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, + has_pixel_or_channel, + |s, p| { + let bg = s.tools.background; + // A targeted alpha channel or Quick Mask is filled instead (#2734). + let channel = if crate::channel_cmds::is_channel_target(p) { + Some(p.clone()) + } else if p.get("target").is_none() { + crate::channel_cmds::targeted_channel(s) + } else { + None + }; + if let Some(t) = channel { + s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; + return Ok(Value::Null); + } + let id = layer_param(s, p)?; + if is_mask_target(p) { + s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; + return Ok(Value::Null); + } + // A targeted colour channel clears that channel only (#2720). + if let Some(colors) = crate::color_channels::target(s, p)? { + s.edit("Clear", |doc, _| { + for k in colors.indices() { + crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; + } + Ok(()) + })?; + return Ok(Value::Null); + } + s.edit("Clear", |doc, _| { + let sel = doc.selection.clone(); + let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); + crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) + })?; + Ok(Value::Null) + } + ), + ] +} diff --git a/crates/engine/src/cmd/file_menu.rs b/crates/engine/src/cmd/file_menu.rs new file mode 100644 index 0000000000..73f25859b5 --- /dev/null +++ b/crates/engine/src/cmd/file_menu.rs @@ -0,0 +1,94 @@ +use super::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, bad, has_doc, json, parse_hex}; + +/// File menu commands: New and Close. +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "file.new", + "New…", + ["File"], + Some("Cmd+N"), + r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|backgroundColor|transparent|#rrggbb"="white","backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str,"artboard":bool=false (one artboard over the canvas, its background the chosen one, holding an empty Layer 1; no Background layer),"profile":"working"|built-in id|path to an .icc file="working" (the colour profile it is tagged with; it must suit the mode)}"##, + always, + |s, p| { + use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type}; + crate::document_preset_cmds::validate_new_params(s, p)?; + // A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254). + let px = |k: &str, d: u32| match p.get(k) { + Some(v) => v + .as_u64() + .map(|n| n.clamp(1, MAX_DIMENSION as u64) as u32) + .or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round().clamp(1.0, MAX_DIMENSION as f64) as u32)) + .unwrap_or(d), + None => d, + }; + let (w, h) = (px("width", 1920), px("height", 1080)); + let mode = color_mode(p.get("mode").and_then(Value::as_str).unwrap_or("rgb")).unwrap_or(ColorMode::Rgb); + let depth = sample_type(p.get("depth").and_then(Value::as_u64).unwrap_or(8)).unwrap_or(SampleType::U8); + let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string(); + let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, MAX_RESOLUTION) as f32; + // The background colour; `None` for Transparent. + let background = match p.get("background").and_then(Value::as_str).unwrap_or("white") { + "backgroundColor" => { + let bgc = background_color(p, s.tools.background, "file.new")?; + Some(Color::rgba(bgc[0], bgc[1], bgc[2], 1.0)) + } + "transparent" => None, + "black" => Some(Color::BLACK), + other => { + let c = parse_hex(other).unwrap_or([1.0; 4]); + Some(Color::rgba(c[0], c[1], c[2], c[3])) + } + }; + let mut doc = if p.get("artboard").and_then(Value::as_bool).unwrap_or(false) { + crate::artboard_cmds::new_artboard_document(name, Size::new(w, h), mode, depth, background) + } else if let Some(c) = background { + Document::with_background(name, Size::new(w, h), mode, depth, c) + } else { + let mut d = Document::new(name, Size::new(w, h), mode, depth); + d.layers.push(Layer::raster("Layer 1", d.pixel_format())); + d + }; + doc.resolution_dpi = res; + // Photoshop's New Document › Color Profile: tag the document with another profile + // than the working space (#321). Checked before the document opens. + if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) { + let prof = s.color.resolve(spec, Some(&doc), None)?; + if prof.color_space != crate::color_cmds::mode_space(doc.mode) { + return Err(EngineError::BadParams { + cmd: "file.new".into(), + msg: format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode), + }); + } + doc.icc_profile = Some(prof.to_bytes()); + } + let i = s.add_document(doc, None); + Ok(json!({ "document": i })) + } + ), + cmd!( + "file.close", + "Close", + ["File"], + Some("Cmd+W"), + r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, + has_doc, + |s, p| { + let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; + match p.get("save").filter(|v| !v.is_null()) { + Some(v) if v == "ask" => { + if s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() { + return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); + } + } + // `false` (don't save) is the older spelling of discard. + Some(Value::Bool(false)) => {} + Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), + _ => {} + } + s.close(i).ok_or(EngineError::NoDocument)?; + Ok(Value::Null) + } + ), + ] +} diff --git a/crates/engine/src/cmd/image_menu.rs b/crates/engine/src/cmd/image_menu.rs new file mode 100644 index 0000000000..5c1f65424b --- /dev/null +++ b/crates/engine/src/cmd/image_menu.rs @@ -0,0 +1,44 @@ +use super::{Adjustment, CommandSpec, destructive_adjust, has_doc, has_pixel_layer, turn}; + +/// Image menu commands: canvas rotations and flips, and Desaturate. +pub(super) fn specs() -> Vec { + vec![ + cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal) + }), + cmd!("image.imageRotation.flipCanvasVertical", "Flip Canvas Vertical", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Flip Canvas Vertical", crate::canvas_geom::Turn::FlipVertical) + }), + cmd!("image.imageRotation.180", "180°", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Rotate180) + }), + cmd!("image.imageRotation.90cw", "90° Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Cw90) + }), + cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { + turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) + }), + cmd!( + "image.adjustments.desaturate", + "Desaturate", + ["Image", "Adjustments"], + Some("Cmd+Shift+U"), + r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, + has_pixel_layer, + |s, p| { + destructive_adjust( + s, + "Desaturate", + Adjustment::HueSaturation { + hue: 0.0, + saturation: -100.0, + lightness: 0.0, + colorize: false, + ranges: photocraft_doc::adjust::HueRange::defaults(), + }, + p, + ) + } + ), + ] +} diff --git a/crates/engine/src/cmd/layer_menu.rs b/crates/engine/src/cmd/layer_menu.rs new file mode 100644 index 0000000000..2e7cfe2cc7 --- /dev/null +++ b/crates/engine/src/cmd/layer_menu.rs @@ -0,0 +1,578 @@ +use super::{ + Adjustment, BlendMode, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, + arrange, bad, blend_from_str, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, + mask_new_layer, merge_group, move_mask, pixels, set_clipped, set_mask, set_mask_and_deselect, +}; + +/// Layer menu commands, in registry order. +pub(super) fn specs() -> Vec { + [creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), fill_layers(), adjustments(), placement()] + .into_iter() + .flatten() + .collect() +} + +/// New layers and groups, and grouping the selected layers. +fn creation() -> Vec { + vec![ + cmd!( + "layer.new.layer", + "Layer…", + ["Layer", "New"], + Some("Cmd+Shift+N"), + r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##, + has_doc, + crate::new_layer::run + ), + cmd!( + "layer.new.group", + "Group…", + ["Layer", "New"], + None, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, + has_doc, + |s, p| { + let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; + let below = crate::group_options::below("layer.new.group", p)?; + let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; + let id = s.edit("New Group", |doc, active| { + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); + let mut group = Layer::group(name, vec![]); + opts.apply(&mut group); + let bg = crate::background_cmds::background_id(doc); + let id = crate::layer_place::insert_new(doc, *active, group, place); + crate::background_cmds::keep_background_at_bottom(bg, doc)?; + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + ), + cmd!( + "layer.groupLayers", + "Group Layers", + ["Layer"], + Some("Cmd+G"), + r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, + has_layer, + crate::layer_multi_cmds::group_layers + ), + ] +} + +/// Duplicate Layer, into the same document or a new one. +fn duplication() -> Vec { + vec![cmd!( + "layer.duplicate", + "Duplicate Layer…", + ["Layer"], + None, + r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##, + has_layer, + |s, p| { + if let Some(d) = p.get("document") { + if d.as_str() == Some("new") { + return crate::layer_copy_cmds::duplicate_to_new_document(s, p); + } + let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64)); + if !same { + return Err(EngineError::BadParams { + cmd: "layer.duplicate".into(), + msg: if d.as_u64().is_some() { + "the destination is another open document (use layer.copyToDocument)".into() + } else { + "`document` must be a document index or \"new\"".into() + }, + }); + } + } + let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false); + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); + if crate::layer_multi_cmds::multi(s, p) { + return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); + } + let id = layer_param(s, p)?; + let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); + // The dialog offers Duplicate Layer's own name: only a different one was typed (#9023). + let mut typed = None; + let mut shift = (0, 0); + let nid = s.edit("Duplicate Layer", |doc, active| { + let mut dup = layer_copy(doc, id, add_copy)?; + if let Some(name) = name.as_ref().filter(|n| **n != dup.name) { + dup.name.clone_from(name); + typed = Some(name.clone()); + } + let nid = doc.insert_above(Some(id), dup); + // A lone copy joins its original's link group, as in the reference application (#11217). + crate::layer_multi_cmds::relink_copies(doc, &[nid])?; + if !in_place { + shift = crate::artboard_cmds::place_copy(doc, nid)?; + } + *active = Some(nid); + Ok(nid) + })?; + crate::artboard_cmds::follow_shift(s, shift); + if let Some(name) = typed { + crate::type_cmds::note_typed_name(s, nid, &name); + } + Ok(json!({ "layer": nid.0 })) + } + )] +} + +/// Deleting and selecting layers, and setting their properties. +fn deletion_and_selection() -> Vec { + vec![ + cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| { + if crate::layer_multi_cmds::multi(s, p) { + return crate::layer_multi_cmds::delete_selected(s); + } + let id = layer_param(s, p)?; + s.edit("Delete Layer", |doc, active| { + let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id); + let before = crate::clip_group::Before::read(doc, &[id]); + doc.remove(id).ok_or(EngineError::NoLayer(id))?; + crate::clip_group::settle(doc, &[], &before, false); + if doc.layers.is_empty() { + return Err(EngineError::Other("a document must keep at least one layer".into())); + } + if active.is_some_and(|current| doc.layer(current).is_none()) { + *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); + } + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!( + "layer.select", + "Select Layer", + [], + None, + r##"{"layer":id|str|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"} | "name":str,"occurrence":index?,"mode":"replace|toggle|range|add|remove"="replace"} (typed references use the recorded full layer stack; name occurrence: zero-based document walk order; required for duplicate names; toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##, + has_doc, + crate::layer_multi_cmds::select + ), + cmd!( + "layer.setProps", + "Layer Properties", + [], + None, + r##"{"layer":id?,"layers":[id,…]? (the same change to each, one step: the Layers panel's controls with several layers selected),"name":str? (one layer only),"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?,"channels":[bool,…]? (Advanced Blending: which colour channels blend, R G B / C M Y K / L a b)}"##, + has_layer, + set_props + ), + ] +} + +/// Arranging layers and clipping masks. +fn order_and_clipping() -> Vec { + vec![ + cmd!("layer.arrange.bringForward", "Bring Forward", ["Layer", "Arrange"], Some("Cmd+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, 1)), + cmd!("layer.arrange.sendBackward", "Send Backward", ["Layer", "Arrange"], Some("Cmd+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, -1)), + cmd!("layer.arrange.bringToFront", "Bring to Front", ["Layer", "Arrange"], Some("Cmd+Shift+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange( + s, + p, + i32::MAX + )), + cmd!("layer.arrange.sendToBack", "Send to Back", ["Layer", "Arrange"], Some("Cmd+Shift+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange( + s, + p, + i32::MIN + )), + cmd!( + "layer.createClippingMask", + "Create Clipping Mask", + ["Layer"], + Some("Cmd+Alt+G"), + r##"{"layer":id?} (no layer: every selected layer but the lowest clips to the layer below it)"##, + has_layer, + |s, p| set_clipped(s, p, true) + ), + cmd!( + "layer.releaseClippingMask", + "Release Clipping Mask", + ["Layer"], + None, + r##"{"layer":id?} (no layer: every selected layer)"##, + has_layer, + |s, p| set_clipped(s, p, false) + ), + ] +} + +/// Layer mask commands. +fn masks() -> Vec { + vec![ + cmd!( + "layer.layerMask.revealAll", + "Reveal All", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_layer, + |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::reveal_all())) + ), + cmd!( + "layer.layerMask.hideAll", + "Hide All", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_layer, + |s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::hide_all())) + ), + cmd!( + "layer.layerMask.revealSelection", + "Reveal Selection", + ["Layer", "Layer Mask"], + None, + r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##, + has_selection, + |s, p| { + let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?; + let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() }; + // The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a + // following Invert (⌘I) on the targeted mask then inverts all of it, not just the + // part inside the old selection. Same undo step as the mask. + set_mask_and_deselect(s, p, "Add Layer Mask", mask) + } + ), + cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask( + s, + p, + "Delete Layer Mask", + None + )), + cmd!( + "layer.layerMask.moveTo", + "Move Layer Mask", + [], + None, + r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, + has_layer, + move_mask + ), + ] +} + +/// Merge Down, Merge Group and Flatten Image. +fn merging() -> Vec { + vec![ + cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { + let id = layer_param(s, p)?; + s.edit("Merge Down", |doc, active| { + let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?; + let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) }; + if idx == 0 { + return Err(EngineError::Other("no layer below to merge into".into())); + } + let mut below = parent.to_vec(); + below.push(idx - 1); + let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone(); + let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); + let merged = pixels::merge_down(doc, &lower, &upper); + doc.remove(id); + *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged; + *active = Some(lower.id); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("layer.mergeGroup", "Merge Group", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { + let id = layer_param(s, p)?; + if !s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { + return Err(EngineError::Other("Merge Group needs a group".into())); + } + merge_group(s, id) + }), + cmd!("layer.flattenImage", "Flatten Image", ["Layer"], None, "{}", has_doc, |s, _| { + s.edit("Flatten Image", |doc, active| { + let fmt = doc.pixel_format(); + let mut bg = Layer::raster("Background", fmt); + bg.locks.transparency = true; + bg.locks.position = true; + *crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0])); + *active = Some(bg.id); + doc.layers = vec![bg]; + Ok(()) + })?; + Ok(Value::Null) + }), + ] +} + +/// Solid color and gradient fill layers. +fn fill_layers() -> Vec { + vec![ + cmd!( + "layer.newFillLayer.solidColor", + "Solid Color…", + ["Layer", "New Fill Layer"], + None, + r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, + has_doc, + |s, p| { + let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; + // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead + // of what its sRGB stand-in converts back to through the document profile (#8568). + let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { + Some(k) => Some(k), + None => s.tools.picked_cmyk([c[0], c[1], c[2]]), + }; + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + let id = s.edit("New Color Fill Layer", |doc, active| { + let fill = match inks { + Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), + _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), + }; + let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + ), + cmd!( + "layer.newFillLayer.gradient", + "Gradient…", + ["Layer", "New Fill Layer"], + None, + r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, + has_doc, + |s, p| { + let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; + let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; + let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; + let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); + let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + // The rest of a recorded Gradient Fill (a loaded action's Make): applied as + // `gradient.fill.set` would, in the same step. + let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] + .iter() + .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) + .collect(); + let (fg, bg) = (s.tools.foreground, s.tools.background); + let id = s.edit("New Gradient Fill Layer", |doc, active| { + let mut fill = Fill::gradient( + vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], + angle, + 1.0, + style, + reverse, + ); + if !rest.is_empty() { + let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); + fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; + } + let fill = fill.in_mode(doc.mode); + let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + ), + ] +} + +/// Editing an adjustment layer's properties. +fn adjustments() -> Vec { + vec![cmd!( + "layer.setAdjustment", + "Adjustment Properties", + [], + None, + r##"{"layer":id?, …params of that adjustment kind} (Levels, Curves: "eyedropper":{"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1} = the Properties panel's Set Black/Neutral Gray/White Point, sampling the image below the layer, RGB and Grayscale (no gray) only)"##, + has_layer, + |s, p| { + let id = layer_param(s, p)?; + let eyedropped = crate::adjust_params::layer_eyedropper(s, id, p)?; + s.edit("Modify Adjustment", |doc, _| { + let mode = doc.mode; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) }; + if matches!(adj, Adjustment::Unsupported { .. }) { + return Err(EngineError::Other("this adjustment can't be edited (kept as imported)".into())); + } + let kind = adjustment_kind(adj); + // No params resets to the defaults; otherwise params merge over the current values. + *adj = if let Some(eyedropped) = eyedropped { + eyedropped + } else if crate::adjust_params::user_keys(p).is_empty() { + crate::adjust_params::default_for(kind, mode)? + } else { + crate::adjust_params::from_params(kind, p, Some(adj), mode)? + }; + Ok(()) + })?; + Ok(Value::Null) + } + )] +} + +/// Moving layers in the stack and on the canvas. +fn placement() -> Vec { + vec![ + cmd!( + "layer.moveTo", + "Reorder Layer", + [], + None, + r##"{"layer":id|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"}?| "layers":[id,…]?, "target":id|name|{"index":uint},"targetOccurrence":n? (which of several layers named `target`, in document order),"position":"above|below|into"="above","copy":bool=false} (typed target: pre-move recorded stack boundary, omit position; layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row; recorded typed references retain their form)"##, + has_layer, + crate::layer_multi_cmds::move_to + ), + cmd!( + "layer.translate", + "Move Layer", + [], + None, + r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false,"wrap":bool=false,"nest":bool=false} → null | {nested:[id]} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step; wrap: View › Pattern Preview, pixels that leave the canvas come back on the opposite edge so the tile stays seamless; nest: auto-nesting as the Move tool does it, a layer whose bounds centre lands on another artboard joins it and one whose centre is off every artboard leaves for the top level; a clipping base takes the layers clipped to it along and a clipped layer goes only where its base goes; artboards, the Background, empty layers, layers whose board doesn't change, groups that would nest too deep and layers locked with Prevent Auto-Nesting (on the layer, a group around it or the destination board) stay put, with their whole clipping group; nested lists the layers that changed board)"##, + has_layer, + crate::layer_multi_cmds::translate + ), + ] +} + +/// Applies layer.setProps to its target layers as one history step. +fn set_props(s: &mut Session, p: &Value) -> Result { + let ids = prop_targets(s, p)?; + if ids.len() > 1 && p.get("name").is_some() { + return Err(bad("layer.setProps", "`name` renames one layer, not several")); + } + let (opacity, fill) = (unit_prop(p, "opacity")?, unit_prop(p, "fill")?); + let label = props_label(p); + // The eye: a history state only with History Options › Make Layer Visibility + // Changes Undoable. + let record = label != "Layer Visibility" || s.visibility_undoable(); + s.edit_with(label, record, |doc, _| { + // The Background has no opacity, fill or blend mode: like Photoshop, setting + // one that changes its look turns it into a normal layer ("Layer 0") first. + let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); + let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal); + for &id in &ids { + if num("opacity") || num("fill") || blends { + crate::extra_cmds::background_to_layer(doc, id); + } + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + apply_props(l, p, opacity, fill)?; + } + Ok(()) + })?; + // The Layers panel's in-place rename: a name the user typed (#9023). + if let (Some(name), [id]) = (p.get("name").and_then(Value::as_str), ids.as_slice()) { + crate::type_cmds::note_typed_name(s, *id, name); + } + Ok(Value::Null) +} + +/// Several layers at once (the Layers panel with several selected, as in Photoshop), +/// else the given or active one. +fn prop_targets(s: &Session, p: &Value) -> Result> { + match p.get("layers") { + None | Some(Value::Null) => Ok(vec![layer_param(s, p)?]), + Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut ids = Vec::with_capacity(a.len()); + for v in a { + let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; + if doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + if !ids.contains(&id) { + ids.push(id); + } + } + Ok(ids) + } + Some(v) => Err(bad("layer.setProps", format!("`layers` is a non-empty list of layer ids, got {v}"))), + } +} + +/// Opacity and Fill are fractions here, while the Layer Style commands take +/// percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242). +fn unit_prop(p: &Value, key: &str) -> Result> { + let Some(v) = p.get(key) else { return Ok(None) }; + match v.as_f64() { + Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)), + _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))), + } +} + +/// Photoshop's History names for a single kind of change; a mix is "Layer Properties". +fn props_label(p: &Value) -> &'static str { + let changed: Vec<&str> = + p.as_object().map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "layers" | "coalesce")).collect()).unwrap_or_default(); + match changed.as_slice() { + ["visible"] => "Layer Visibility", + ["opacity"] => "Opacity Change", + ["fill"] => "Fill Opacity Change", + ["blend"] => "Blending Change", + ["name"] => "Rename Layer", + _ => "Layer Properties", + } +} + +/// Sets the requested name, visibility, opacity, fill and blend mode on one layer. +fn apply_props(l: &mut Layer, p: &Value, opacity: Option, fill: Option) -> Result<()> { + if let Some(v) = p.get("name").and_then(Value::as_str) { + l.name = v.to_string(); + } + if let Some(v) = p.get("visible").and_then(Value::as_bool) { + l.visible = v; + } + if let Some(v) = opacity { + l.opacity = v; + } + if let Some(v) = fill { + l.fill_opacity = v; + } + if let Some(v) = p.get("blend").and_then(Value::as_str) { + l.blend = blend_prop(l, v)?; + } + apply_clip_and_locks(l, p) +} + +/// Sets the requested clipping, channel and lock flags on one layer. +fn apply_clip_and_locks(l: &mut Layer, p: &Value) -> Result<()> { + if let Some(v) = p.get("clipped").and_then(Value::as_bool) { + l.clipped = v; + } + if let Some(v) = p.get("locked").and_then(Value::as_bool) { + l.locks.all = v; + } + if let Some(Value::Array(ch)) = p.get("channels") { + // Blending Options › Advanced Blending › Channels: unchecked = left out. + l.excluded_channels = ch.iter().take(32).enumerate().filter(|(_, v)| v.as_bool() == Some(false)).fold(0, |m, (i, _)| m | 1 << i); + } + if let Some(Value::Object(m)) = p.get("locks") { + set_locks(l, m)?; + } + Ok(()) +} + +/// Parses a blend mode for the layer, refusing Pass Through on anything but a group. +fn blend_prop(l: &Layer, v: &str) -> Result { + let b = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; + // Pass Through is a group's mode only, as in Photoshop. + if b == BlendMode::PassThrough && !l.is_group() { + return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0))); + } + Ok(b) +} + +/// Sets each named lock, refusing an unknown name. +fn set_locks(l: &mut Layer, m: &serde_json::Map) -> Result<()> { + for (k, v) in m { + let v = v.as_bool().unwrap_or(false); + if !l.locks.set(k, v) { + return Err(bad("layer.setProps", format!("unknown lock `{k}`"))); + } + } + Ok(()) +} diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs new file mode 100644 index 0000000000..6a20325452 --- /dev/null +++ b/crates/engine/src/cmd/paint.rs @@ -0,0 +1,55 @@ +use super::{CommandSpec, Value, always, cmyk_param, color_param, has_paintable}; + +/// Painting commands: strokes and the foreground and background colors. +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "paint.stroke", + "Brush Stroke", + [], + None, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + has_paintable, + crate::brush_cmds::paint_stroke + ), + cmd!( + "tools.setColors", + "Set Colors", + [], + None, + r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##, + always, + |s, p| { + let cmyk = |key: &str| cmyk_param("tools.setColors", p, key); + let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?); + let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?; + let background = color_param("tools.setColors", p, "background", s.tools.background)?; + s.tools.foreground = foreground; + s.tools.background = background; + if let Some(k) = fg_cmyk { + let [r, g, b, _] = s.tools.foreground; + s.tools.remember_cmyk([r, g, b], k); + } + if let Some(k) = bg_cmyk { + let [r, g, b, _] = s.tools.background; + s.tools.remember_cmyk([r, g, b], k); + } + Ok(Value::Null) + } + ), + cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| { + std::mem::swap(&mut s.tools.foreground, &mut s.tools.background); + Ok(Value::Null) + }), + cmd!("tools.defaultColors", "Default Foreground and Background Colors", [], Some("D"), "{}", always, |s, _| { + if s.tools.mask_targeted { + s.tools.foreground = crate::ToolState::MASK_COLORS[0]; + s.tools.background = crate::ToolState::MASK_COLORS[1]; + } else { + s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + s.tools.background = [1.0, 1.0, 1.0, 1.0]; + } + Ok(Value::Null) + }), + ] +} diff --git a/crates/engine/src/cmd/queries.rs b/crates/engine/src/cmd/queries.rs new file mode 100644 index 0000000000..13e7603743 --- /dev/null +++ b/crates/engine/src/cmd/queries.rs @@ -0,0 +1,122 @@ +use super::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry}; + +/// Commands that report session and document state or switch documents. +pub(super) fn specs() -> Vec { + vec![ + CommandSpec { + id: "session.inspect", + label: "Inspect Session", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: |s, _| Ok(inspect::session(s)), + journal: false, + }, + CommandSpec { + id: "document.inspect", + label: "Inspect Document", + menu: &[], + shortcut: None, + params: r##"{"document":index?}"##, + enabled: has_doc, + run: |s, p| { + let d = match p.get("document") { + Some(v) => { + let i = v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.inspect", "`document` must be an index"))?; + s.documents().get(i).ok_or_else(|| EngineError::Other(format!("no document at index {i}")))? + } + None => s.active().ok_or(EngineError::NoDocument)?, + }; + Ok(inspect::document(d)) + }, + journal: false, + }, + CommandSpec { + id: "document.activate", + label: "Activate Document", + menu: &[], + shortcut: None, + params: r##"{"document":index|{"index":uint}} or {"offset":int} (numeric document: zero-based tab index; typed index: one-based opening order; offset: places after the active document in opening order, before it when negative) → {document}"##, + enabled: has_doc, + run: |s, p| { + // A null key counts as omitted. + let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + let idx = match (given("document"), given("offset")) { + (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")), + (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")), + // Recorded offsets wrap in opening order, independently of dragged tabs. + (None, Some(o)) => { + let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?; + s.document_at_offset(o)? + } + (Some(d), None) => { + if let Some(selector) = d.as_object() { + let index = selector + .get("index") + .filter(|_| selector.len() == 1) + .and_then(Value::as_u64) + .ok_or_else(|| bad("document.activate", "document reference needs one non-negative index"))?; + return s + .document_at_index(index) + .and_then(|idx| if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::NoDocument) }); + } + let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?; + usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))? + } + }; + if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) } + }, + journal: true, + }, + CommandSpec { + id: "document.move", + label: "Move Document", + menu: &[], + shortcut: None, + params: r##"{"document":index?,"to":index}"##, + enabled: has_doc, + run: |s, p| { + let index = |key: &str| { + p.get(key) + .map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index")))) + }; + let from = match index("document") { + Some(i) => i?, + None => s.active_index().ok_or(EngineError::NoDocument)?, + }; + let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??; + let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?; + Ok(json!({"document": to})) + }, + journal: false, + }, + CommandSpec { + id: "command.list", + label: "List Commands", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())), + journal: false, + }, + CommandSpec { + id: "document.pixel", + label: "Read Composite Pixel", + menu: &[], + shortcut: None, + params: r##"{"x":i32,"y":i32}"##, + enabled: has_doc, + run: |s, p| { + let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits"))); + let (x, y) = (coord("x")?, coord("y")?); + let d = s.active().ok_or(EngineError::NoDocument)?; + // At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent. + let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default(); + Ok(json!(px)) + }, + journal: false, + }, + ] +} diff --git a/crates/engine/src/cmd/select_menu.rs b/crates/engine/src/cmd/select_menu.rs new file mode 100644 index 0000000000..9e3d9e1dc5 --- /dev/null +++ b/crates/engine/src/cmd/select_menu.rs @@ -0,0 +1,112 @@ +use super::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds}; + +/// Select menu commands: All, Deselect, Inverse and rectangular selections. +pub(super) fn specs() -> Vec { + vec![ + cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| { + s.edit("Select All", |doc, _| { + let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); + m.fill_rect(doc.bounds(), &[1.0]); + doc.selection = Some(m); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("select.deselect", "Deselect", ["Select"], Some("Cmd+D"), "{}", has_selection, |s, _| { + // Nothing selected: nothing to do and no history step, as in Photoshop (#6744). + if s.active().is_none_or(|d| d.doc.selection.is_none()) { + return Ok(Value::Null); + } + s.edit("Deselect", |doc, _| { + doc.selection = None; + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!("select.inverse", "Inverse", ["Select"], Some("Cmd+Shift+I"), "{}", has_selection, |s, _| { + s.edit("Inverse", |doc, _| { + let old = doc.selection.take().unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8)); + doc.selection = Some(photocraft_algo::selection::inverse_surface(&old, doc.bounds())); + Ok(()) + })?; + Ok(Value::Null) + }), + cmd!( + "select.rect", + "Rectangular Selection", + [], + None, + r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"line":"row|column"?,"antiAlias":bool=true,"feather":px=0}"##, + has_doc, + |s, p| { + let get = |k: &str| int_i32("select.rect", p, k).and_then(|v| v.ok_or_else(|| bad("select.rect", format!("missing `{k}`")))); + let r = Rect::from_xywh(get("x")?, get("y")?, get("width")?.max(0) as u32, get("height")?.max(0) as u32); + let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string(); + let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false); + // The History step is named after the tool: the Single Row / Single Column + // Marquee send `line` (Photoshop). + let step = match p.get("line").and_then(Value::as_str) { + Some("row") => "Single Row Marquee", + Some("column") => "Single Column Marquee", + Some(other) => return Err(bad("select.rect", format!("unknown `line` {other:?} (row|column)"))), + None if ellipse => "Elliptical Marquee", + None => "Rectangular Marquee", + }; + // Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only). + let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); + let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32; + s.edit(step, |doc, _| { + let area = doc.bounds(); + // A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse + // keeps the dragged shape and is only cut there. + use photocraft_algo::selection as sel; + let shape = if ellipse { + sel::ellipse_surface(r, area, aa) + } else { + let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8); + s.fill_rect(r.intersect(&area), &[1.0]); + s + }; + if feather > 0.0 { + let window = selection_cmds::feather_window(r, area, feather); + let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); + doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); + return Ok(()); + } + let old = doc.selection.take(); + let combined = match (mode.as_str(), old) { + ("add", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a.max(b)), + ("subtract", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a * (1.0 - b)), + ("intersect", Some(o)) => sel::combine_surfaces(&o, &shape, area, |a, b| a.min(b)), + // With no existing selection, neither operation can select new pixels. + ("subtract" | "intersect", None) => Surface::new(photocraft_color::PixelFormat::GRAY8), + _ => shape, + }; + // Sparse Add/Subtract keeps untouched pixels outside the canvas. Only pixels + // inside the document count when deciding whether a selection remains. + let has_on_canvas_pixels = (combined.default_bytes().first().copied().unwrap_or(0) != 0 && { + let canvas_tiles = u64::from(area.width().div_ceil(TILE_SIZE as u32)) * u64::from(area.height().div_ceil(TILE_SIZE as u32)); + let stored = combined.tiles().filter(|(coord, _)| !coord.rect().intersect(&area).is_empty()).count() as u64; + stored < canvas_tiles + }) || combined.tiles().any(|(coord, tile)| { + let tile_rect = coord.rect(); + let overlap = tile_rect.intersect(&area); + if overlap.is_empty() { + return false; + } + let x0 = (overlap.x0 - tile_rect.x0) as usize; + let x1 = (overlap.x1 - tile_rect.x0) as usize; + (overlap.y0 - tile_rect.y0..overlap.y1 - tile_rect.y0).any(|y| { + let row_start = y as usize * TILE_SIZE as usize; + let start = row_start + x0; + tile.bytes().get(start..row_start + x1).is_some_and(|row| row.iter().any(|&v| v != 0)) + }) + }); + doc.selection = has_on_canvas_pixels.then_some(combined); + Ok(()) + })?; + Ok(Value::Null) + } + ), + ] +} From a5402d9962a3e500bea7d39c52c1fd3df9a892d1 Mon Sep 17 00:00:00 2001 From: Omar Saidahmed Date: Wed, 11 Nov 2026 19:46:19 -0500 Subject: [PATCH 03/38] pin the registered command ids in order --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/command_ids.txt | 1010 ++++++++++++++++++ crates/engine/src/cmd/command_order_tests.rs | 11 + 3 files changed, 1023 insertions(+) create mode 100644 crates/engine/src/cmd/command_ids.txt create mode 100644 crates/engine/src/cmd/command_order_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 76b34e70f3..5bfcd6608e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -66,6 +66,8 @@ pub mod brush_preset_cmds; pub mod channel_cmds; pub mod color_cmds; pub mod color_to_alpha_cmds; +#[cfg(test)] +mod command_order_tests; pub mod comps_cmds; pub mod contour_lib_cmds; #[cfg(test)] diff --git a/crates/engine/src/cmd/command_ids.txt b/crates/engine/src/cmd/command_ids.txt new file mode 100644 index 0000000000..0bfe60ad8f --- /dev/null +++ b/crates/engine/src/cmd/command_ids.txt @@ -0,0 +1,1010 @@ +file.new +file.close +edit.undo +edit.redo +edit.fill +edit.clear +select.all +select.deselect +select.inverse +select.rect +layer.new.layer +layer.new.group +layer.groupLayers +layer.duplicate +layer.delete +layer.select +layer.setProps +layer.arrange.bringForward +layer.arrange.sendBackward +layer.arrange.bringToFront +layer.arrange.sendToBack +layer.createClippingMask +layer.releaseClippingMask +layer.layerMask.revealAll +layer.layerMask.hideAll +layer.layerMask.revealSelection +layer.layerMask.delete +layer.layerMask.moveTo +layer.mergeDown +layer.mergeGroup +layer.flattenImage +layer.newFillLayer.solidColor +layer.newFillLayer.gradient +layer.setAdjustment +layer.moveTo +layer.translate +image.imageRotation.flipCanvasHorizontal +image.imageRotation.flipCanvasVertical +image.imageRotation.180 +image.imageRotation.90cw +image.imageRotation.90ccw +image.adjustments.desaturate +paint.stroke +tools.setColors +tools.swapColors +tools.defaultColors +session.inspect +document.inspect +document.activate +document.move +command.list +document.pixel +layer.newAdjustmentLayer.brightnessContrast +image.adjustments.brightnessContrast +layer.newAdjustmentLayer.levels +image.adjustments.levels +layer.newAdjustmentLayer.curves +image.adjustments.curves +layer.newAdjustmentLayer.exposure +image.adjustments.exposure +layer.newAdjustmentLayer.vibrance +image.adjustments.vibrance +layer.newAdjustmentLayer.hueSaturation +image.adjustments.hueSaturation +layer.newAdjustmentLayer.colorBalance +image.adjustments.colorBalance +layer.newAdjustmentLayer.blackWhite +image.adjustments.blackWhite +layer.newAdjustmentLayer.photoFilter +image.adjustments.photoFilter +layer.newAdjustmentLayer.channelMixer +image.adjustments.channelMixer +layer.newAdjustmentLayer.invert +image.adjustments.invert +layer.newAdjustmentLayer.posterize +image.adjustments.posterize +layer.newAdjustmentLayer.threshold +image.adjustments.threshold +layer.newAdjustmentLayer.gradientMap +image.adjustments.gradientMap +layer.newAdjustmentLayer.selectiveColor +image.adjustments.selectiveColor +layer.newAdjustmentLayer.colorLookup +image.adjustments.colorLookup +layer.layerStyle.dropShadow +layer.layerStyle.innerShadow +layer.layerStyle.outerGlow +layer.layerStyle.innerGlow +layer.layerStyle.stroke +layer.layerStyle.colorOverlay +layer.layerStyle.gradientOverlay +layer.layerStyle.patternOverlay +layer.layerStyle.bevelEmboss +layer.layerStyle.satin +layer.layerStyle.replace +layer.layerStyle.makeDefault +layer.layerStyle.defaultFor +layer.layerStyle.clear +layer.layerStyle.contours.list +layer.layerStyle.contours.new +layer.layerStyle.contours.delete +layer.layerStyle.contours.load +layer.layerStyle.contours.save +layer.list +filter.blur.gaussianBlur +filter.blur.average +filter.blur.blur +filter.blur.blurMore +filter.sharpen.sharpen +filter.sharpen.sharpenMore +filter.sharpen.sharpenEdges +filter.noise.despeckle +filter.blur.boxBlur +filter.blur.motionBlur +filter.blur.radialBlur +filter.blur.surfaceBlur +filter.sharpen.unsharpMask +filter.sharpen.smartSharpen +filter.noise.addNoise +filter.noise.median +filter.noise.dustAndScratches +filter.pixelate.mosaic +filter.stylize.emboss +filter.stylize.findEdges +filter.stylize.solarize +filter.distort.twirl +filter.distort.pinch +filter.distort.spherize +filter.distort.wave +filter.distort.ripple +filter.distort.polarCoordinates +filter.other.highPass +filter.other.minimum +filter.other.maximum +filter.other.offset +filter.lastFilter +filter.pixelate.colorHalftone +filter.pixelate.crystallize +filter.pixelate.facet +filter.pixelate.fragment +filter.pixelate.mezzotint +filter.pixelate.pointillize +filter.stylize.diffuse +filter.stylize.extrude +filter.stylize.oilPaint +filter.stylize.tiles +filter.stylize.traceContour +filter.stylize.wind +filter.distort.displace +filter.distort.shear +filter.distort.zigZag +filter.render.clouds +filter.render.differenceClouds +filter.render.fibers +filter.render.lensFlare +filter.render.lightingEffects +filter.render.relight +filter.noise.reduceNoise +filter.blur.smartBlur +filter.blur.lensBlur +filter.blur.shapeBlur +filter.blurGallery.tiltShift +filter.blurGallery.irisBlur +filter.blurGallery.fieldBlur +filter.blurGallery.spinBlur +filter.blurGallery.pathBlur +filter.other.custom +filter.other.hsbHsl +filter.video.deInterlace +filter.video.ntscColors +filter.other.colorToAlpha +filter.filterGallery +filter.gallery.coloredPencil +filter.gallery.cutout +filter.gallery.dryBrush +filter.gallery.filmGrain +filter.gallery.fresco +filter.gallery.neonGlow +filter.gallery.paintDaubs +filter.gallery.paletteKnife +filter.gallery.plasticWrap +filter.gallery.posterEdges +filter.gallery.roughPastels +filter.gallery.smudgeStick +filter.gallery.sponge +filter.gallery.underpainting +filter.gallery.watercolor +filter.gallery.accentedEdges +filter.gallery.angledStrokes +filter.gallery.crosshatch +filter.gallery.darkStrokes +filter.gallery.inkOutlines +filter.gallery.spatter +filter.gallery.sprayedStrokes +filter.gallery.sumiE +filter.gallery.diffuseGlow +filter.gallery.glass +filter.gallery.oceanRipple +filter.gallery.basRelief +filter.gallery.chalkCharcoal +filter.gallery.charcoal +filter.gallery.chrome +filter.gallery.conteCrayon +filter.gallery.graphicPen +filter.gallery.halftonePattern +filter.gallery.notePaper +filter.gallery.photocopy +filter.gallery.plaster +filter.gallery.reticulation +filter.gallery.stamp +filter.gallery.tornEdges +filter.gallery.waterPaper +filter.gallery.glowingEdges +filter.gallery.craquelure +filter.gallery.grain +filter.gallery.mosaicTiles +filter.gallery.patchwork +filter.gallery.stainedGlass +filter.gallery.texturizer +gradient.fill.create +gradient.fill.set +gradient.fill.stop +gradient.fill.get +layer.fill.solidColor.set +layer.fill.pattern.set +type.create +type.edit +type.setStyle +type.rasterize +type.info +type.fonts +type.increaseSize +type.decreaseSize +type.increaseSizeMore +type.decreaseSizeMore +type.createSelection +edit.transform +select.float +select.drop +shape.create +shape.edit +shape.info +shape.rasterize +path.list +path.info +path.set +path.delete +path.transform +path.clippingPath.set +path.clippingPath.clear +path.style.copyFill +path.style.copyStroke +path.style.pasteFill +path.style.pasteStroke +path.rename +path.toSelection +path.addToSelection +path.subtractFromSelection +path.intersectWithSelection +path.toShape +select.toWorkPath +path.fill +path.stroke +layer.vectorMask.add +layer.vectorMask.fromPath +layer.vectorMask.edit +layer.vectorMask.delete +layer.rasterize.vectorMask +layer.vectorMask.revealAll +layer.vectorMask.hideAll +layer.vectorMask.currentPath +layer.vectorMask.enabled +layer.vectorMask.linked +layer.rasterize.shape +layer.combineShapes.unite +layer.combineShapes.subtractFrontShape +layer.combineShapes.intersectShapeAreas +layer.combineShapes.excludeOverlappingShapes +layer.combineShapes.mergeShapeComponents +select.convertToShape +layer.vectorMask.info +path.moveAnchors +path.moveHandle +path.bendSegment +path.convertPoint +path.addAnchor +path.deleteAnchor +path.mergeShapeComponents +path.setOperation +select.quick +select.object +select.subject +select.refineEdge +select.focusArea +layer.removeBackground +paint.setSymmetry +paint.symmetryFromPath +paint.symmetryDisable +edit.cut +edit.copy +edit.copyMerged +edit.paste +file.newFromClipboard +edit.pasteSpecial.pasteInPlace +layer.new.layerViaCopy +layer.new.layerViaCut +layer.mergeVisible +image.autoTone +image.autoContrast +image.autoColor +edit.toggleLastState +edit.transform.again +edit.transform.againCopy +view.newGuide +view.moveGuide +view.editGuide +view.deleteGuide +view.clearGuides +view.setRulerOrigin +view.resetRulerOrigin +layer.smartObjects.exportSvg +layer.smartObjects.updateVectorSource +layer.smartObjects.updateSvg +edit.assignProfile +edit.convertToProfile +edit.colorSettings +color.profileMismatch +edit.profileInfo +view.proofSetup +view.proofColors +view.gamutWarning +brush.mixer.sample +paint.pencil +paint.mixerBrush +brush.mixer.load +brush.mixer.clean +brush.mixer.autoLoad +brush.mixer.autoClean +brush.mixer.sampleAllLayers +paint.mixerLoad +paint.colorReplacement +brush.presets.list +brush.presets.save +brush.presets.update +brush.presets.delete +brush.presets.setCurrent +brush.defineFromSelection +brush.get +tools.setBrush +brush.presets.rename +brush.presets.move +brush.presets.moveGroup +brush.presets.renameGroup +brush.presets.deleteGroup +paint.magicEraser +paint.backgroundEraser +brush.presets.importAbr +brush.presets.importImage +gradient.presets.importGrd +style.presets.importAsl +style.presets.exportAsl +actions.load +actions.save +actions.stopMessage +actions.menuItem +actions.photoshopStep +actions.insertMenuItem +actions.insertPath +actions.allowToolRecording +actions.recordAgain +actions.duplicate +actions.insert +actions.dialog +actions.conditional +actions.assignSet +actions.newSet +swatches.list +swatches.add +swatches.delete +swatches.rename +swatches.move +swatches.newGroup +swatches.renameGroup +swatches.deleteGroup +swatches.use +swatches.reset +swatches.import +swatches.export +paint.cloneStamp +paint.patternStamp +paint.healingBrush +paint.spotHealing +paint.patch +paint.contentAwareMove +paint.remove +paint.dodge +paint.burn +paint.sponge +paint.blur +paint.sharpen +paint.smudge +paint.historyBrush +paint.artHistoryBrush +paint.redEye +image.imageSize +image.canvasSize +image.crop +image.trim +image.mode.rgb +image.mode.grayscale +image.mode.cmyk +image.mode.lab +image.mode.bits8 +image.mode.bits16 +image.mode.bits32 +image.duplicate +image.perspectiveCrop +select.magicWand +select.colorRange +select.modify.border +select.modify.smooth +select.modify.expand +select.modify.contract +select.modify.feather +select.grow +select.similar +select.lasso +select.magneticLasso +select.sky +select.isolateLayers +select.transformSelection +paint.bucket +paint.gradient +edit.stroke +edit.transform.rotate180 +edit.transform.rotate90Cw +edit.transform.rotate90Ccw +edit.transform.flipHorizontal +edit.transform.flipVertical +edit.pasteSpecial.pasteInto +edit.pasteSpecial.pasteOutside +select.reselect +image.adjustments.equalize +image.revealAll +layer.new.layerFromBackground +layer.layerStyle.copyLayerStyle +layer.layerStyle.pasteLayerStyle +layer.layerStyle.hideAllEffects +layer.layerStyle.showAllEffects +layer.layerMask.enabled +layer.layerMask.linked +layer.rasterize.layer +layer.rasterize.allLayers +layer.rasterize.type +layer.rasterize.fillContent +layer.rasterize.smartObject +layer.delete.hiddenLayers +file.scripts.deleteAllEmptyLayers +layer.ungroupLayers +layer.hideLayers +layer.showLayers +layer.toggleLockTransparency +layer.showOnly +layer.new.backgroundFromLayer +file.closeAll +file.closeOthers +file.revealInFinder +file.revert +file.saveACopy +file.openAs +file.openAsSmartObject +file.approveMemory +file.placeEmbedded +file.placeLinked +file.fileInfo +file.automate.fitImage +file.automate.conditionalModeChange +file.automate.batch +file.scripts.imageProcessor +file.scripts.loadFilesIntoStack +file.scripts.flattenAllLayerEffects +file.scripts.flattenAllMasks +file.export.layersToFiles +file.export.colorLookupTables +view.newGuideLayout +view.newGuidesFromShape +view.clearCanvasGuides +file.exrParts +file.openExrParts +type.antiAlias.none +type.antiAlias.sharp +type.antiAlias.crisp +type.antiAlias.strong +type.antiAlias.smooth +type.antiAlias.windowsLcd +type.antiAlias.windows +type.orientation.horizontal +type.orientation.vertical +type.openType.standardLigatures +type.openType.contextualAlternates +type.openType.discretionaryLigatures +type.openType.swash +type.openType.oldstyle +type.openType.stylisticAlternates +type.openType.titlingAlternates +type.openType.ornaments +type.openType.ordinals +type.openType.fractions +type.openType.numerals.default +type.openType.numerals.lining +type.openType.numerals.oldstyle +type.openType.numerals.proportional +type.openType.numerals.tabular +type.openType.numerals.proportionalLining +type.openType.numerals.tabularLining +type.openType.numerals.proportionalOldstyle +type.openType.numerals.tabularOldstyle +type.createWorkPath +type.convertToShape +type.rasterizeTypeLayer +type.convertToParagraphText +type.convertToPointText +type.warpText +type.attachToPath +type.setPathPlacement +type.detachFromPath +type.updateAllTextLayers +type.replaceAllMissingFonts +type.resolveMissingFonts +type.pasteLoremIpsum +type.saveDefaultTypeStyles +type.loadDefaultTypeStyles +type.openType.stylisticSets.set1 +type.openType.stylisticSets.set2 +type.openType.stylisticSets.set3 +type.openType.stylisticSets.set4 +type.openType.stylisticSets.set5 +type.openType.stylisticSets.set6 +type.openType.stylisticSets.set7 +type.openType.stylisticSets.set8 +type.openType.stylisticSets.set9 +type.openType.stylisticSets.set10 +type.openType.stylisticSets.set11 +type.openType.stylisticSets.set12 +type.openType.stylisticSets.set13 +type.openType.stylisticSets.set14 +type.openType.stylisticSets.set15 +type.openType.stylisticSets.set16 +type.openType.stylisticSets.set17 +type.openType.stylisticSets.set18 +type.openType.stylisticSets.set19 +type.openType.stylisticSets.set20 +type.fillPath +type.characterStyle.new +type.characterStyle.duplicate +type.characterStyle.delete +type.characterStyle.rename +type.characterStyle.set +type.characterStyle.apply +type.characterStyle.redefine +type.characterStyle.clearOverride +type.characterStyle.list +type.paragraphStyle.new +type.paragraphStyle.duplicate +type.paragraphStyle.delete +type.paragraphStyle.rename +type.paragraphStyle.set +type.paragraphStyle.apply +type.paragraphStyle.redefine +type.paragraphStyle.clearOverride +type.paragraphStyle.list +edit.checkSpelling +type.insertText +type.hitTest +type.caret +type.navigate +layer.smartObjects.convertToSmartObject +filter.convertForSmartFilters +layer.smartObjects.newSmartObjectViaCopy +layer.smartObjects.rasterize +layer.smartObjects.editContents +layer.smartObjects.resetTransform +layer.smartObjects.saveContents +layer.smartObjects.replaceContents +layer.smartObjects.exportContents +layer.smartObjects.relinkToFile +layer.smartObjects.updateModifiedContent +layer.smartObjects.updateChanged +layer.smartObjects.updateAllModifiedContent +layer.smartObjects.convertToLayers +layer.smartObjects.convertToEmbedded +layer.smartObjects.embedAllLinked +layer.smartObjects.convertToLinked +layer.smartFilter.disableSmartFilters +layer.smartFilter.deleteFilterMask +layer.smartFilter.disableFilterMask +layer.smartFilter.blendingOptions +layer.smartFilter.clearSmartFilters +layer.smartFilter.setVisible +layer.smartFilter.setParams +layer.smartFilter.delete +layer.smartFilter.move +layer.smartFilter.transfer +select.allLayers +select.deselectLayers +select.findLayers +layer.selectLinkedLayers +layer.align.topEdges +layer.align.verticalCenters +layer.align.bottomEdges +layer.align.leftEdges +layer.align.horizontalCenters +layer.align.rightEdges +layer.distribute.topEdges +layer.distribute.verticalCenters +layer.distribute.bottomEdges +layer.distribute.leftEdges +layer.distribute.horizontalCenters +layer.distribute.rightEdges +layer.distribute.horizontally +layer.distribute.vertically +layer.linkLayers +layer.mergeLayers +layer.new.groupFromLayers +layer.arrange.reverse +layer.lockLayers +layer.renameLayer +layer.copyToDocument +prefs.get +prefs.set +prefs.reset +edit.preferences.general +edit.preferences.interface +edit.preferences.workspace +edit.preferences.tools +edit.preferences.historyLog +edit.preferences.fileHandling +edit.preferences.export +edit.preferences.performance +edit.preferences.scratchDisks +edit.preferences.cursors +edit.preferences.transparencyAndGamut +edit.preferences.unitsAndRulers +edit.preferences.guidesGridAndSlices +edit.preferences.plugIns +edit.preferences.type +edit.preferences.enhancedControls +edit.preferences.rawDefaults +edit.preferences.integrations +edit.keyboardShortcuts +edit.menus +edit.toolbar +help.checkForUpdates +updates.status +edit.fade +edit.purge.undo +edit.purge.clipboard +edit.purge.histories +edit.purge.videoCache +edit.purge.all +edit.contentAwareFill +edit.deleteAndFillSelection +edit.contentAwareScale +edit.defineBrushPreset +edit.defineCustomShape +edit.findAndReplaceText +edit.presets.presetManager +edit.presets.exportImportPresets +edit.fillForeground +edit.fillBackground +edit.fillForegroundPreserve +edit.fillBackgroundPreserve +edit.fillHistory +document.sampleColor +image.detectFaces +view.colorSamplers.add +view.colorSamplers.move +view.colorSamplers.delete +view.colorSamplers.clear +view.colorSamplers.list +tools.decreaseBrushSize +tools.increaseBrushSize +tools.decreaseBrushHardness +tools.increaseBrushHardness +tools.previousBrush +tools.nextBrush +tools.firstBrush +tools.lastBrush +tools.rotateBrush +layer.stampVisible +layer.stampDown +edit.autoAlignLayers +edit.autoBlendLayers +file.automate.photomerge +file.automate.mergeToHdrPro +file.automate.cropAndStraightenPhotos +filter.lensCorrection +filter.adaptiveWideAngle +filter.cameraRaw +file.automate.lensCorrection +filter.vanishingPoint +select.saveSelection +select.loadSelection +select.editInQuickMaskMode +image.applyImage +image.calculations +channel.new +channel.newSpot +channel.duplicate +channel.delete +channel.rename +channel.move +channel.target +channel.setVisible +channel.options +channel.mergeSpot +channel.split +channel.merge +channel.list +channel.target.composite +channel.target.layerMask +select.loadLuminosity +channel.target.slot3 +channel.target.slot4 +channel.target.slot5 +channel.target.slot6 +channel.target.slot7 +channel.target.slot8 +channel.target.slot9 +image.adjustments.shadowsHighlights +image.adjustments.replaceColor +image.adjustments.matchColor +image.adjustments.hdrToning +image.adjustments.colorLookup.list +layer.layerMask.apply +layer.layerMask.fromTransparency +layer.layerMask.hideSelection +layer.maskAllObjects +layer.matting.defringe +layer.matting.removeBlackMatte +layer.matting.removeWhiteMatte +layer.matting.colorDecontaminate +layer.smartObjects.stackMode.entropy +layer.smartObjects.stackMode.kurtosis +layer.smartObjects.stackMode.maximum +layer.smartObjects.stackMode.mean +layer.smartObjects.stackMode.median +layer.smartObjects.stackMode.minimum +layer.smartObjects.stackMode.range +layer.smartObjects.stackMode.skewness +layer.smartObjects.stackMode.standardDeviation +layer.smartObjects.stackMode.summation +layer.smartObjects.stackMode.variance +layer.smartObjects.stackMode.none +layer.smartObjects.revealInFinder +layer.layerStyle.blendingOptions +layer.layerStyle.globalLight +layer.layerStyle.createLayer +layer.layerStyle.scaleEffects +layer.layerStyle.transferEffects +layer.layerContentOptions +layer.quickExportAsPng +layer.exportAs +layer.setLabelColor +layer.copyCSS +layer.xmpMetadata +image.rotation.arbitrary +image.mode.indexedColor +image.mode.colorTable +image.mode.bitmap +image.mode.duotone +image.mode.multichannel +edit.definePattern +pattern.list +pattern.rename +pattern.delete +pattern.import +pattern.export +layer.newFillLayer.pattern +brush.texturePattern +edit.transform.warp +layer.smartObjects.warp +edit.transform.splitWarpCrosswise +edit.transform.splitWarpHorizontally +edit.transform.splitWarpVertically +edit.transform.removeWarpSplit +edit.transform.warpGrid +layerComp.new +layerComp.update +layerComp.apply +layerComp.previous +layerComp.next +layerComp.delete +layerComp.reorder +layerComp.duplicate +layerComp.rename +layerComp.setComment +layerComp.setOptions +layerComp.restoreLastDocumentState +layerComp.updateWarnings +layerComp.list +file.export.layerCompsToFiles +layer.new.artboard +layer.new.artboardFromGroup +layer.new.artboardFromLayers +layer.artboard.set +view.clearSelectedArtboardGuides +layer.artboard.addBeside +file.export.artboardsToFiles +file.export.artboardsToPdf +filter.liquify +edit.puppetWarp +layer.smartObjects.puppetWarp +edit.perspectiveWarp +layer.smartObjects.perspectiveWarp +image.analysis.setMeasurementScale +image.analysis.selectDataPoints +image.analysis.recordMeasurements +image.analysis.rulerTool +image.analysis.countTool +image.analysis.placeScaleMarker +image.analysis.straightenLayer +image.analysis.info +count.add +count.remove +count.move +count.clear +count.newGroup +count.deleteGroup +count.setGroup +measurementLog.list +measurementLog.delete +measurementLog.export +notes.add +notes.set +notes.delete +notes.list +file.import.notes +type.font.favorite +type.font.library +history.undo +history.redo +history.deleteState +history.newDocument +history.newSnapshot +history.selectSnapshot +history.renameSnapshot +history.deleteSnapshot +history.options +history.stepForward +history.stepBackward +history.clear +history.setSource +history.selectState +view.proofSetup.workingCyanPlate +view.proofSetup.workingMagentaPlate +view.proofSetup.workingYellowPlate +view.proofSetup.workingBlackPlate +view.proofSetup.workingCmyPlate +view.proofSetup.legacyMacintoshRgb +view.proofSetup.colorBlindnessProtanopia +view.proofSetup.colorBlindnessDeuteranopia +view.thirtyTwoBitPreviewOptions +gradient.presets.list +gradient.presets.select +gradient.presets.stop +gradient.presets.apply +gradient.presets.new +gradient.presets.edit +gradient.presets.reset +pattern.presets.list +pattern.presets.select +pattern.presets.apply +pattern.presets.new +pattern.presets.edit +style.presets.list +style.presets.apply +style.presets.new +style.presets.edit +style.presets.reset +shape.presets.importCsh +shape.presets.list +shape.presets.place +shape.presets.new +shape.presets.edit +shape.presets.reset +tool.presets.list +tool.presets.new +tool.presets.select +tool.presets.edit +tool.presets.reset +cloneSource.list +cloneSource.select +cloneSource.set +cloneSource.resetTransform +cloneSource.overlay +document.presets.list +document.presets.get +document.presets.save +document.presets.delete +document.recent.list +document.recent.add +file.export.presets.list +file.export.presets.get +file.export.presets.save +file.export.presets.delete +filter.render.flame +filter.render.pictureFrame +filter.render.tree +slice.new +slice.fromGuides +slice.set +slice.promote +slice.delete +slice.divide +slice.list +layer.newLayerBasedSlice +view.lockSlices +view.clearSlices +file.export.saveForWebLegacy +file.export.exportPreferences +file.export.quickExport +file.generate.imageAssets +file.automate.contactSheetII +file.automate.createDroplet +file.automate.runDroplet +file.scripts.statistics +file.scripts.browse +file.scripts.scriptEventsManager +file.print +file.print.printers +file.print.page +file.printers +file.printOneCopy +file.package +file.export.pathsToIllustrator +edit.installedProfiles +layer.selectInRect +layer.pickAt +layer.selectAbove +layer.selectBelow +layer.selectTop +layer.selectBottom +layer.addAboveToSelection +layer.addBelowToSelection +layer.new.frame +layer.new.frameFromLayers +layer.frame.set +layer.frame.info +layer.frame.convert +layer.frame.setContent +layer.frame.fit +edit.presets.migratePresets +image.trap +timeline.create +timeline.delete +timeline.setFrame +timeline.nextFrame +timeline.previousFrame +timeline.setProps +timeline.info +layer.videoLayers.newBlankVideoLayer +layer.videoLayers.insertBlankFrame +layer.videoLayers.duplicateFrame +layer.videoLayers.deleteFrame +layer.videoLayers.restoreFrame +layer.videoLayers.restoreAllFrames +layer.videoLayers.showAlteredVideo +layer.videoLayers.rasterize +layer.rasterize.video +layer.videoLayers.newVideoLayerFromFile +layer.videoLayers.replaceFootage +layer.videoLayers.interpretFootage +layer.videoLayers.reloadFrame +file.import.videoFramesToLayers +file.export.renderVideo +jobs.list +jobs.cancel +file.import.wiaSupport +layer.rasterize.layerStyle +image.variables.define +image.variables.dataSets +image.applyDataSet +file.import.variableDataSets +file.export.dataSetsAsFiles +variables.list +plugin.list +plugin.install +plugin.remove +plugin.reload +plugin.run +layer.setExpanded +layer.setEffectsExpanded +layer.setEffectsVisible +view.layerMask +layer.toggleMaskOverlay +layer.layerMask.edit +actions.setHistory +actions.setPlayback +actions.move +actions.list +actions.get +actions.record +actions.stop +actions.play +actions.delete +actions.toggle +actions.rename +actions.setColor +test.panic diff --git a/crates/engine/src/cmd/command_order_tests.rs b/crates/engine/src/cmd/command_order_tests.rs new file mode 100644 index 0000000000..840f66a72e --- /dev/null +++ b/crates/engine/src/cmd/command_order_tests.rs @@ -0,0 +1,11 @@ +use super::command_specs; + +#[test] +fn registered_command_ids_keep_their_order() { + let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); + let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); + if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { + panic!("command {i} is {} where {} was registered", ids[i], expected[i]); + } + assert_eq!(ids.len(), expected.len(), "the number of registered commands changed"); +} From aedac66d9514b38681cfa71b676d0d830b20866e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:35:26 +0100 Subject: [PATCH 04/38] WIP: Art History Brush: Area 0-500 px, field alerts and tooltips (#12630) From 4eb0b6ea23f4ae8934f3632691e466a15f0028a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:59:26 +0100 Subject: [PATCH 05/38] Art History Brush: Area 0-500 px, field alerts and tooltips (#12630) Area takes whole pixels 0-500 in the options bar and in paint.artHistoryBrush; Area and Tolerance alert on a typed value past their range; Tolerance gets a slider arrow; Opacity, Area and Tolerance get the reference tooltips; the hint text is gone. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/retouch_cmds.rs | 2 +- .../src/cmd/retouch_cmds/art_history.rs | 3 +- crates/ui-egui/src/panels/options_bar.rs | 2 +- crates/ui-egui/src/tools.rs | 3 + .../src/tools/art_history_fields_tests.rs | 122 ++++++++++++++++++ crates/ui-egui/src/tools/retouch_ui.rs | 21 ++- 6 files changed, 146 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tools/art_history_fields_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 6c891b8449..278e1cac02 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -411,7 +411,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightMedium","area":0..100=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"# + r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightMedium","area":0..500=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"# ), enabled: has_pixel_layer, run: art_history::run, diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index cca503f536..2f3c14493b 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -204,7 +204,8 @@ pub fn run(s: &mut Session, p: &Value) -> Result { let hardness = ranged(p, "hardness", s.tools.brush.hardness * 100.0, 0.0, 100.0)? / 100.0; let opacity = ranged(p, "opacity", 100.0, 0.0, 100.0)? / 100.0; let flow = ranged(p, "flow", 100.0, 0.0, 100.0)? / 100.0; - let area = ranged(p, "area", 50.0, 0.0, 100.0)?; + // Area takes 0..500 px, as the reference's field does (#12630). + let area = ranged(p, "area", 50.0, 0.0, 500.0)?; // Percent of the channel range; 0 (paint everywhere) is the default, as in Photoshop. let tolerance = ranged(p, "tolerance", 0.0, 0.0, 100.0)? / 100.0; let style = style_of(p)?; diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 005bf4793e..3ddf000387 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -176,7 +176,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Art History has no Mode (the engine paints Normal) and no Flow. if tool == Tool::ArtHistoryBrush { let width = if t.pro { 62.0 } else { 66.0 }; - percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); + percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width).on_hover_text(tl!("Set opacity for stroke")); } crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); widgets::vline(ui, 22.0); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 503bbe0a7d..8c83cab741 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -60,6 +60,9 @@ pub mod vector_ui; pub mod warp_preview; pub mod zoom_tool; +#[cfg(test)] +mod art_history_fields_tests; + #[cfg(test)] mod gradient_mode_greyed_tests; diff --git a/crates/ui-egui/src/tools/art_history_fields_tests.rs b/crates/ui-egui/src/tools/art_history_fields_tests.rs new file mode 100644 index 0000000000..1764e53bb0 --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_fields_tests.rs @@ -0,0 +1,122 @@ +//! #12630: the Art History Brush's Area takes whole pixels 0..500 and Tolerance whole percents +//! 0..100; a value typed past either range becomes the closest one with the reference's "Closest +//! value inserted" alert. Opacity, Area and Tolerance carry the reference's tooltips, and the bar +//! has no hint text. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::retouch_ui::ART_HISTORY_AREA_ALERT; +use crate::PhotocraftApp; +use crate::panels::options_bar::ZERO_TO_100; +use crate::state::{DialogKind, Tool}; + +/// The options bar with the Art History Brush active. +fn bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state( + |ui, app| { + crate::field_wheel::begin_frame(ui.ctx()); + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +/// Types `text` into the field labelled `label`, then Tabs out of it. +fn type_into(h: &mut Harness<'static, PhotocraftApp>, label: &str, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// The descriptions (tooltips) of the controls with `role` labelled `label`. +fn tips(h: &Harness<'static, PhotocraftApp>, role: Role, label: &str) -> Vec { + h.query_all_by_role(role) + .filter(|n| n.accesskit_node().label().as_deref() == Some(label)) + .filter_map(|n| n.accesskit_node().description().map(|d| d.to_string())) + .collect() +} + +#[test] +fn area_past_0_500_takes_the_closest_value_and_alerts() { + for (typed, want) in [("600", 500.0), ("-5", 0.0)] { + let mut h = bar(); + type_into(&mut h, "Area", typed); + assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}"); + assert_eq!(alerts(&h), vec![ART_HISTORY_AREA_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn area_in_range_is_a_whole_number_without_an_alert() { + for (typed, want) in [("500", 500.0), ("250", 250.0), ("0", 0.0), ("37.6", 38.0)] { + let mut h = bar(); + type_into(&mut h, "Area", typed); + assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range: {:?}", alerts(&h)); + } +} + +#[test] +fn tolerance_past_0_100_takes_the_closest_value_and_alerts() { + for (typed, want) in [("150", 100.0), ("-3", 0.0)] { + let mut h = bar(); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}"); + assert_eq!(alerts(&h), vec![ZERO_TO_100.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn tolerance_in_range_is_a_whole_number_without_an_alert() { + for (typed, want) in [("100", 100.0), ("12.4", 12.0)] { + let mut h = bar(); + type_into(&mut h, "Tolerance", typed); + assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn opacity_area_and_tolerance_have_the_reference_tooltips() { + let h = bar(); + assert!(tips(&h, Role::SpinButton, "Opacity:").contains(&"Set opacity for stroke".to_string())); + assert!(tips(&h, Role::SpinButton, "Area").contains(&"Painting area diameter".to_string())); + assert!(tips(&h, Role::SpinButton, "Tolerance").contains(&"Painting tolerance".to_string())); + assert!(tips(&h, Role::Button, "Tolerance slider").contains(&"Painting tolerance".to_string()), "the slider arrow"); + assert!(tips(&h, Role::Button, "Area").is_empty(), "Area has no slider"); +} + +#[test] +fn the_bar_has_no_hint_text() { + let h = bar(); + assert!(h.query_by_label("Stylized dabs from a history state").is_none()); +} + +#[test] +fn the_command_takes_an_area_up_to_500() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + let stroke = |area: f64| json!({"points": [[10, 40], [70, 40]], "size": 8, "area": area}); + assert!(app.run("paint.artHistoryBrush", stroke(500.0)).is_ok()); + assert!(app.run("paint.artHistoryBrush", stroke(250.0)).is_ok()); + assert!(app.run("paint.artHistoryBrush", stroke(500.5)).is_err()); + assert!(app.run("paint.artHistoryBrush", stroke(-1.0)).is_err()); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 944c9a28b9..53ad702e91 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -795,6 +795,9 @@ fn cam_amount_slider(ui: &mut egui::Ui, name: &str, value: &mut f32, lo: f32, hi }); } +/// The reference's alert for an Art History Brush Area typed past 0..500 px (#12630). +pub(crate) const ART_HISTORY_AREA_ALERT: &str = "An integer between 0 pixel and 500 Pixels is required. Closest value inserted."; + /// Opens the alert with `message` (English, translated here) unless it is already up. fn open_alert_once(app: &mut PhotocraftApp, message: &str) { let message = tl!(message).to_owned(); @@ -1140,12 +1143,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo ("looseCurl".to_string(), tl!("Loose Curl")), ]; crate::widgets::dropdown(ui, "art-history-style", tl!("Style"), &mut o.art_history_style, &styles, 130.0); + // Area: whole pixels 0..500, no slider; Tolerance: whole percents 0..100 with a slider + // arrow. Both alert on a typed value past their range, as the reference does (#12630). opt(ui, tl!("Area")); - crate::widgets::value_field(ui, &mut o.art_history_area, 0.0..=100.0, "", 50.0); + let (area, area_out) = crate::widgets::value_field_whole_alerting(ui, tl!("Area"), &mut o.art_history_area, 0.0..=500.0, "px", 66.0); + area.on_hover_text(tl!("Painting area diameter")); opt(ui, tl!("Tolerance")); - crate::widgets::value_field(ui, &mut o.art_history_tolerance, 0.0..=100.0, "", 50.0); - crate::widgets::vline(ui, 22.0); - opt(ui, tl!("Stylized dabs from a history state")); + let (tolerance, tolerance_out) = + crate::widgets::value_field_whole_alerting(ui, tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0, "%", 58.0); + tolerance.on_hover_text(tl!("Painting tolerance")); + cam_amount_slider(ui, tl!("Tolerance slider"), &mut o.art_history_tolerance, 0.0, 100.0, "Painting tolerance"); + if area_out { + open_alert_once(app, ART_HISTORY_AREA_ALERT); + } + if tolerance_out { + open_alert_once(app, crate::panels::options_bar::ZERO_TO_100); + } } Tool::QuickSelection => { crate::widgets::checkbox(ui, &mut o.sample_all.quick_selection, tl!("Sample All Layers")); From a55396638cf9169c3b68e2151f0c1a1050753045 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 02:23:18 +0100 Subject: [PATCH 06/38] Art History Brush: move its options into their own function Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/retouch_ui.rs | 63 ++++++++++++++------------ 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 53ad702e91..aa698f1535 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -795,6 +795,38 @@ fn cam_amount_slider(ui: &mut egui::Ui, name: &str, value: &mut f32, lo: f32, hi }); } +/// The Art History Brush's Style, Area and Tolerance. +fn art_history_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let o = &mut app.ui.tool_options; + opt(ui, tl!("Style")); + let styles = [ + ("tightShort".to_string(), tl!("Tight Short")), + ("tightMedium".to_string(), tl!("Tight Medium")), + ("tightLong".to_string(), tl!("Tight Long")), + ("looseMedium".to_string(), tl!("Loose Medium")), + ("looseLong".to_string(), tl!("Loose Long")), + ("dab".to_string(), tl!("Dab")), + ("tightCurl".to_string(), tl!("Tight Curl")), + ("looseCurl".to_string(), tl!("Loose Curl")), + ]; + crate::widgets::dropdown(ui, "art-history-style", tl!("Style"), &mut o.art_history_style, &styles, 130.0); + // Area: whole pixels 0..500, no slider; Tolerance: whole percents 0..100 with a slider + // arrow. Both alert on a typed value past their range, as the reference does (#12630). + opt(ui, tl!("Area")); + let (area, area_out) = crate::widgets::value_field_whole_alerting(ui, tl!("Area"), &mut o.art_history_area, 0.0..=500.0, "px", 66.0); + area.on_hover_text(tl!("Painting area diameter")); + opt(ui, tl!("Tolerance")); + let (tolerance, tolerance_out) = crate::widgets::value_field_whole_alerting(ui, tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0, "%", 58.0); + tolerance.on_hover_text(tl!("Painting tolerance")); + cam_amount_slider(ui, tl!("Tolerance slider"), &mut o.art_history_tolerance, 0.0, 100.0, "Painting tolerance"); + if area_out { + open_alert_once(app, ART_HISTORY_AREA_ALERT); + } + if tolerance_out { + open_alert_once(app, crate::panels::options_bar::ZERO_TO_100); + } +} + /// The reference's alert for an Art History Brush Area typed past 0..500 px (#12630). pub(crate) const ART_HISTORY_AREA_ALERT: &str = "An integer between 0 pixel and 500 Pixels is required. Closest value inserted."; @@ -1130,36 +1162,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo None => opt(ui, tl!("The History Brush source was deleted: set a new source in the History panel")), } } - Tool::ArtHistoryBrush => { - opt(ui, tl!("Style")); - let styles = [ - ("tightShort".to_string(), tl!("Tight Short")), - ("tightMedium".to_string(), tl!("Tight Medium")), - ("tightLong".to_string(), tl!("Tight Long")), - ("looseMedium".to_string(), tl!("Loose Medium")), - ("looseLong".to_string(), tl!("Loose Long")), - ("dab".to_string(), tl!("Dab")), - ("tightCurl".to_string(), tl!("Tight Curl")), - ("looseCurl".to_string(), tl!("Loose Curl")), - ]; - crate::widgets::dropdown(ui, "art-history-style", tl!("Style"), &mut o.art_history_style, &styles, 130.0); - // Area: whole pixels 0..500, no slider; Tolerance: whole percents 0..100 with a slider - // arrow. Both alert on a typed value past their range, as the reference does (#12630). - opt(ui, tl!("Area")); - let (area, area_out) = crate::widgets::value_field_whole_alerting(ui, tl!("Area"), &mut o.art_history_area, 0.0..=500.0, "px", 66.0); - area.on_hover_text(tl!("Painting area diameter")); - opt(ui, tl!("Tolerance")); - let (tolerance, tolerance_out) = - crate::widgets::value_field_whole_alerting(ui, tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0, "%", 58.0); - tolerance.on_hover_text(tl!("Painting tolerance")); - cam_amount_slider(ui, tl!("Tolerance slider"), &mut o.art_history_tolerance, 0.0, 100.0, "Painting tolerance"); - if area_out { - open_alert_once(app, ART_HISTORY_AREA_ALERT); - } - if tolerance_out { - open_alert_once(app, crate::panels::options_bar::ZERO_TO_100); - } - } + Tool::ArtHistoryBrush => art_history_options(app, ui), Tool::QuickSelection => { crate::widgets::checkbox(ui, &mut o.sample_all.quick_selection, tl!("Sample All Layers")); crate::widgets::checkbox(ui, &mut o.enhance_edge, tl!("Enhance Edge")); From f65e543eb44692f59ae6a3a93439764f519a9649 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 02:54:07 +0100 Subject: [PATCH 07/38] Art History Brush: Reset Tool gives a 21 px soft tip (#12631) The Art History Brush now starts, and comes back after Reset Tool and Reset All Tools, with a 21 px soft round (hardness 0, angle 0, roundness 100 %) at 25 % spacing, full opacity and no smoothing, as the reference application does. Before, it kept the default 20 px hard tip at 10 % spacing, and its first use took the previous tool's tip. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/paint_mouse.rs | 24 +++-- .../ui-egui/src/canvas/paint_mouse/tests.rs | 6 +- crates/ui-egui/src/tools.rs | 3 + .../src/tools/art_history_reset_tip_tests.rs | 94 +++++++++++++++++++ 4 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/tools/art_history_reset_tip_tests.rs diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index be57e18fb7..d6175b68bf 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -40,12 +40,16 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). - // The Art History Brush also starts at full opacity (#10263), and the Pattern Stamp at full - // opacity and flow (#12616): those fields are their own. + // The Pattern Stamp also starts at full opacity and flow (#12616): those fields are its own. // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone - // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush - // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { + // Stamp, the Smudge tool and the Art History Brush start with their own measured tips + // instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684, + // #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263). + None if matches!( + tool, + Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::ArtHistoryBrush + ) => + { fresh_brush(tool, ¤t) } // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping @@ -54,7 +58,6 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { None => { let fresh = BrushSettings::default(); let (opacity, flow) = match tool { - Tool::ArtHistoryBrush => (fresh.opacity, current.flow), Tool::PatternStamp => (fresh.opacity, fresh.flow), _ => (current.opacity, current.flow), }; @@ -99,6 +102,8 @@ const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25); const TONING_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25); /// The Clone Stamp's tip after Reset Tool (#12601): a 21 px soft round at 25 % spacing. const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); +/// The Art History Brush's tip after Reset Tool (#12631): a 21 px soft round at 25 % spacing. +const ART_HISTORY_BRUSH_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); /// The Remove tool's size after Reset Tool (#12548): 19 px. Its hardness and spacing are not /// measured, so they stay the default brush's. const REMOVE_TOOL_SIZE: f32 = 19.0; @@ -109,7 +114,8 @@ const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's /// [`HEALING_BRUSH_TIP`], the Burn, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge +/// [`CLONE_STAMP_TIP`] and the Art History Brush's [`ART_HISTORY_BRUSH_TIP`], both with no +/// smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge /// tool's [`SMUDGE_TOOL_TIP`] and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the /// default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { @@ -125,6 +131,10 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings (brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP; brush.smoothing.amount = 0.0; } + Tool::ArtHistoryBrush => { + (brush.size, brush.hardness, brush.spacing) = ART_HISTORY_BRUSH_TIP; + brush.smoothing.amount = 0.0; + } Tool::Remove => brush.size = REMOVE_TOOL_SIZE, _ => {} } diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index b20920dae9..452fff8e68 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -569,8 +569,8 @@ fn the_brush_is_a_per_tool_option_that_presets_keep() { tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE); } -/// #10263: the Art History Brush starts at full opacity the first time it is picked, though it -/// keeps the rest of the brush the old tool left (other tools still take its opacity). +/// #10263: the Art History Brush starts at full opacity the first time it is picked, with its own +/// tip rather than the old tool's (#12631; other tools still take its opacity). #[test] fn art_history_brush_starts_at_full_opacity() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -581,7 +581,7 @@ fn art_history_brush_starts_at_full_opacity() { app.ui.tool = Tool::ArtHistoryBrush; sync_tool_brush(&mut app); assert_eq!(app.session.tools.brush.opacity, 1.0, "Art History starts at 100%"); - assert_eq!(app.session.tools.brush.size, 40.0, "and inherits the size"); + assert_eq!(app.session.tools.brush.size, 21.0, "with its own 21 px tip"); app.ui.tool = Tool::HistoryBrush; sync_tool_brush(&mut app); assert_eq!(app.session.tools.brush.opacity, 1.0, "the History Brush takes the Art History brush's opacity"); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 503bbe0a7d..dc06fb7122 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -87,5 +87,8 @@ mod path_selection_shape_over_saved_path_tests; #[cfg(test)] mod remove_default_size_tests; +#[cfg(test)] +mod art_history_reset_tip_tests; + #[cfg(test)] mod ellipse_center_mark_tests; diff --git a/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs new file mode 100644 index 0000000000..9ad99ec401 --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs @@ -0,0 +1,94 @@ +//! #12631: the Art History Brush starts, and comes back after Reset Tool, with the reference +//! application's tip: a 21 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing and full opacity, with no smoothing. Other tools' starting tips are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness, spacing, angle, roundness, opacity and smoothing of the live brush, as +/// `brush.get` reports the tip. +fn tip(app: &mut PhotocraftApp) -> [f64; 7] { + let b = app.run("brush.get", json!({})).unwrap(); + let [size, hardness, spacing, angle, roundness] = ["size", "hardness", "spacing", "angle", "roundness"].map(|k| b[k].as_f64().unwrap()); + let brush = &app.session.tools.brush; + let (opacity, smoothing) = (f64::from(brush.opacity), f64::from(brush.smoothing.amount)); + [size, hardness, spacing, angle, roundness, opacity, smoothing].map(|v| (v * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness, b.opacity, b.smoothing.amount) = (57.0, 0.4, 0.6, 30.0, 0.5, 0.3, 0.3); +} + +const ART_HISTORY_TIP: [f64; 7] = [21.0, 0.0, 0.25, 0.0, 1.0, 1.0, 0.0]; + +#[test] +fn reset_tool_gives_the_art_history_brush_a_21_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 21.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Art History Brush's first pick, after + // another tool's tip. + let mut app = app(); + pick(&mut app, Tool::Brush); + scramble(&mut app); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Brush); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), ART_HISTORY_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::ArtHistoryBrush); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::ArtHistoryBrush); + assert_eq!(tip(&mut app), ART_HISTORY_TIP, "picked after the reset"); +} + +#[test] +fn other_tools_keep_their_reset_tips() { + for (tool, want) in [ + (Tool::Brush, [13.0, 0.0, 0.25, 0.0, 1.0, 1.0, 0.1]), + (Tool::BackgroundEraser, [13.0, 1.0, 0.25, 0.0, 1.0, 1.0, 0.1]), + (Tool::Healing, [19.0, 1.0, 0.25, 0.0, 1.0, 1.0, 0.1]), + (Tool::CloneStamp, [21.0, 0.0, 0.25, 0.0, 1.0, 1.0, 0.0]), + (Tool::HistoryBrush, [20.0, 1.0, 0.1, 0.0, 1.0, 1.0, 0.1]), + (Tool::PatternStamp, [20.0, 1.0, 0.1, 0.0, 1.0, 1.0, 0.1]), + ] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a), want, "{tool:?}"); + } + // The History Brush's first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::HistoryBrush); + assert_eq!(tip(&mut a)[0], 57.0, "History Brush, first use"); +} From d4f05619037e71746889307ddc4d3063f7158d35 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 03:46:14 +0100 Subject: [PATCH 08/38] Art History Brush: first use keeps the outgoing pressure toggles (#12631) The tip's pressure settings were not measured, so the first pick keeps them from the outgoing brush as before; only the measured tip, spacing and opacity come from the tool's starting brush. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/paint_mouse.rs | 10 +++++----- .../src/tools/art_history_reset_tip_tests.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index d6175b68bf..090d2dd800 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -45,13 +45,13 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // Stamp, the Smudge tool and the Art History Brush start with their own measured tips // instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684, // #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263). - None if matches!( - tool, - Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::ArtHistoryBrush - ) => - { + None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { fresh_brush(tool, ¤t) } + // Its pressure toggles are not measured, so its first use keeps the outgoing ones (#12631). + None if tool == Tool::ArtHistoryBrush => { + BrushSettings { pressure_size: current.pressure_size, pressure_opacity: current.pressure_opacity, ..fresh_brush(tool, ¤t) } + } // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping // the outgoing opacity. None if tool == Tool::Pencil => BrushSettings { opacity: current.opacity, ..fresh_brush(tool, ¤t) }, diff --git a/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs index 9ad99ec401..7256f89d61 100644 --- a/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs +++ b/crates/ui-egui/src/tools/art_history_reset_tip_tests.rs @@ -53,6 +53,19 @@ fn a_first_use_starts_with_the_tip() { assert_eq!(tip(&mut app)[0], 42.0); } +#[test] +fn a_first_use_keeps_the_outgoing_pressure_toggles() { + // The pressure settings of the tip are not measured, so they stay what the first pick gave + // before: the outgoing brush's. + let mut app = app(); + pick(&mut app, Tool::Brush); + (app.session.tools.brush.pressure_size, app.session.tools.brush.pressure_opacity) = (true, true); + pick(&mut app, Tool::ArtHistoryBrush); + let b = &app.session.tools.brush; + assert_eq!((b.pressure_size, b.pressure_opacity), (true, true)); + assert_eq!(tip(&mut app), ART_HISTORY_TIP); +} + #[test] fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { let mut app = app(); From 883ce7f4da149e456587b3091f7d8c95677f7aad Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 04:08:08 +0100 Subject: [PATCH 09/38] Art History Brush: Tolerance threshold per stroke start (#12633) Tolerance is now measured in a small neighbourhood around where a dab starts instead of the mean under the whole dab, and compared with 0.6 x Tolerance: a 20-level change paints at 10 but not at 20, red over grey paints up to 80 and nothing paints from 90, as measured in the reference application. A dab that starts on a changed area paints its whole footprint. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/art_history.rs | 47 ++++-- crates/algo/src/art_history/tests.rs | 10 +- .../algo/src/art_history/tolerance_tests.rs | 159 ++++++++++++++++++ 3 files changed, 199 insertions(+), 17 deletions(-) create mode 100644 crates/algo/src/art_history/tolerance_tests.rs diff --git a/crates/algo/src/art_history.rs b/crates/algo/src/art_history.rs index 76a3402e7f..01dcbd306d 100644 --- a/crates/algo/src/art_history.rs +++ b/crates/algo/src/art_history.rs @@ -442,6 +442,7 @@ pub struct StampParams<'a> { pub hardness: f32, pub opacity: f32, pub flow: f32, + /// Tolerance as a fraction (Tolerance 50 % is `0.5`). pub tolerance: f32, /// Destination tile edge; `0` processes the whole buffer as one tile. pub tile: i32, @@ -581,26 +582,41 @@ fn dab_intersects(dab: &Dab, tile: (i32, i32, i32, i32)) -> bool { x0 < tile.2 && x1 > tile.0 && y0 < tile.3 && y1 > tile.1 } -/// Mean difference between `src` and `dest` over the dab's covered pixels (working-space peak is -/// 1, so a tolerance of 50% is `0.5`). Per pixel it is the larger of the mean colour change and the -/// alpha change: an opaque pixel's unchanged alpha must not water a colour change down, and the -/// Eraser keeps the colour and lowers only the alpha. Fully transparent source samples are left -/// out; a dab whose samples are all transparent has a mean of `0.0`. `None` if nothing is covered. -fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option { - let (x0, y0, x1, y1) = dab_bounds(dab)?; +/// Radius, in pixels, of the neighbourhood around a stroke's start that Tolerance measures. +const START_RADIUS: f32 = 2.5; + +/// Difference, in working-space units, that 100 % Tolerance asks for. The reference application +/// starts strokes on a 20-level change (about 8 %) at Tolerance 10 but not 20, and on red over grey +/// (about 50 %) at 80 but not 90, which a linear threshold of `0.6 × Tolerance` reproduces. +const TOLERANCE_SCALE: f32 = 0.6; + +/// Mean difference between `src` and `dest` around the dab's centre, where its stroke starts +/// (working-space peak is 1). Per pixel it is the larger of the mean colour change and the alpha +/// change: an opaque pixel's unchanged alpha must not water a colour change down, and the Eraser +/// keeps the colour and lowers only the alpha. Fully transparent source samples are left out; a +/// start whose samples are all transparent has a mean of `0.0`. `None` if nothing is there. +fn start_diff(p: &StampParams<'_>, dab: &Dab) -> Option { + if !(dab.x.is_finite() && dab.y.is_finite()) { + return None; + } + let x0 = floor_i32(dab.x - START_RADIUS); + let y0 = floor_i32(dab.y - START_RADIUS); + let x1 = floor_i32(dab.x + START_RADIUS).saturating_add(1); + let y1 = floor_i32(dab.y + START_RADIUS).saturating_add(1); let mut sampled = vec![0.0f32; p.ch]; let mut sum = 0.0f32; let mut count = 0u32; let mut transparent = 0u32; for y in y0..y1 { for x in x0..x1 { - if coverage_at(dab, x, y, p.hardness) <= 0.0 { + // The history state at the same position, not the dab's rotated read. + let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5); + if (cx - dab.x).hypot(cy - dab.y) > START_RADIUS { continue; } let Some(di) = origin_index(p.dest_origin, x, y, p.dest_w, p.dest_h, p.ch) else { continue }; let Some(dst) = p.dest.get(di..di.saturating_add(p.ch)) else { continue }; - let (sx, sy) = rotated_source(dab, x, y); - if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, sx, sy, &mut sampled) { + if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, cx, cy, &mut sampled) { continue; } let nch = p.ch.min(dst.len()).min(sampled.len()); @@ -636,8 +652,10 @@ fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option { /// Stamp posed dabs into `dest`, tile by tile, reading `src` at each dab's rotated positions. /// -/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Returns how many destination pixels were -/// written (tolerance-skipped dabs count as zero). +/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Tolerance is decided where a dab starts +/// (around its centre), so a dab that starts on a changed area also paints the unchanged pixels +/// it reaches. Returns how many destination pixels were written (tolerance-skipped dabs count as +/// zero). pub fn stamp(p: &mut StampParams<'_>) -> Result { dest_pixels(p)?; if p.src_w == 0 || p.src_h == 0 { @@ -653,9 +671,10 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { let tiles = tile_grid(p.dest_w, p.dest_h, p.dest_origin, p.tile); let mut written = 0u32; let dabs: Vec = p.dabs.to_vec(); + let threshold = p.tolerance * TOLERANCE_SCALE; for dab in &dabs { let Some(bounds) = dab_bounds(dab) else { continue }; - if p.tolerance > 0.0 && dab_mean_diff(p, dab).is_some_and(|m| m < p.tolerance) { + if p.tolerance > 0.0 && start_diff(p, dab).is_some_and(|m| m < threshold) { continue; } let overlapping: Vec<(i32, i32, i32, i32)> = tiles.iter().copied().filter(|t| dab_intersects(dab, *t)).collect(); @@ -676,3 +695,5 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { #[cfg(test)] mod tests; +#[cfg(test)] +mod tolerance_tests; diff --git a/crates/algo/src/art_history/tests.rs b/crates/algo/src/art_history/tests.rs index 61692cda74..a3567f98e9 100644 --- a/crates/algo/src/art_history/tests.rs +++ b/crates/algo/src/art_history/tests.rs @@ -23,7 +23,8 @@ fn tolerance_ignores_fully_transparent_samples() { } }); let dab = Dab { x: 1.0, y: 0.5, theta: 0.0, radius: 2.0, pressure: 1.0 }; - for tolerance in [0.6, 0.3] { + // Mean difference 0.4: under the 0.6 x Tolerance threshold at 1.0, over it at 0.3. + for tolerance in [1.0, 0.3] { let mut dest = before.clone(); let written = stamp(&mut StampParams { dest: &mut dest, @@ -46,7 +47,7 @@ fn tolerance_ignores_fully_transparent_samples() { alpha: Some(ch - 1), }) .unwrap(); - if tolerance == 0.6 { + if tolerance == 1.0 { assert_eq!(written, 0, "channels={ch}, hidden={hidden}"); assert_eq!(dest, before); } else { @@ -377,12 +378,13 @@ fn tolerance_zero_writes_where_history_differs() { #[test] fn tolerance_ignores_unchanged_alpha() { - // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. + // Colour moved by 0.3 and alpha did not: the 0.27 threshold (Tolerance 45 %) must not see a + // 0.225 average. let (w, h, ch) = (48usize, 48usize, 4); let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - for (tolerance, paints) in [(0.25, true), (0.35, false)] { + for (tolerance, paints) in [(0.45, true), (0.55, false)] { let mut dest = dest0.clone(); let mut p = StampParams { dest: &mut dest, diff --git a/crates/algo/src/art_history/tolerance_tests.rs b/crates/algo/src/art_history/tolerance_tests.rs new file mode 100644 index 0000000000..f68740c783 --- /dev/null +++ b/crates/algo/src/art_history/tolerance_tests.rs @@ -0,0 +1,159 @@ +//! Tolerance decides where a stroke may start, with the reference application's threshold (#12633). + +use super::*; + +const W: usize = 80; +const H: usize = 40; +const CH: usize = 4; + +fn level(v: u8) -> f32 { + f32::from(v) / 255.0 +} + +/// Source: grey on the left half, green on the right half (the measured Setup state). +fn setup_source() -> Vec { + image(|x| if x < W / 2 { [128, 128, 128] } else { [40, 160, 60] }) +} + +/// Current layer: red on the left half (far from grey), 20 levels off the green on the right. +fn current_layer() -> Vec { + image(|x| if x < W / 2 { [255, 0, 0] } else { [60, 180, 80] }) +} + +fn image(rgb: impl Fn(usize) -> [u8; 3]) -> Vec { + let mut v = Vec::with_capacity(W * H * CH); + for _ in 0..H { + for x in 0..W { + let [r, g, b] = rgb(x); + v.extend_from_slice(&[level(r), level(g), level(b), 1.0]); + } + } + v +} + +fn dab(x: f32, radius: f32) -> Dab { + Dab { x, y: H as f32 / 2.0, theta: 0.0, radius, pressure: 1.0 } +} + +/// Stamps `dabs` at `tolerance` (a fraction, Tolerance 50 % = 0.5) and returns the new layer. +fn paint(dest: &[f32], dabs: &[Dab], tolerance: f32) -> Vec { + let src = setup_source(); + let mut out = dest.to_vec(); + let mut p = StampParams { + dest: &mut out, + dest_w: W, + dest_h: H, + dest_origin: (0, 0), + src: &src, + src_w: W, + src_h: H, + src_origin: (0, 0), + ch: CH, + dabs, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + stamp(&mut p).unwrap(); + out +} + +/// Pixels changed in columns `x0..x1`. +fn changed(before: &[f32], after: &[f32], x0: usize, x1: usize) -> usize { + let mut n = 0; + for y in 0..H { + for x in x0..x1 { + let i = (y * W + x) * CH; + if (0..CH).any(|c| (before[i + c] - after[i + c]).abs() > 1.0e-4) { + n += 1; + } + } + } + n +} + +const LEFT: f32 = 12.0; +const RIGHT: f32 = 68.0; + +#[test] +fn a_small_difference_starts_strokes_at_10_but_not_at_20() { + let before = current_layer(); + let dabs = [dab(RIGHT, 6.0)]; + assert!(changed(&before, &paint(&before, &dabs, 0.10), 40, 80) > 0, "20 levels off paints at Tolerance 10"); + assert_eq!(changed(&before, &paint(&before, &dabs, 0.20), 0, 80), 0, "20 levels off paints nothing at Tolerance 20"); +} + +#[test] +fn red_over_grey_starts_strokes_up_to_80_and_nothing_from_90() { + let before = current_layer(); + let dabs = [dab(LEFT, 6.0)]; + for tolerance in [0.60, 0.80] { + assert!(changed(&before, &paint(&before, &dabs, tolerance), 0, 40) > 0, "red over grey paints at {tolerance}"); + } + let both = [dab(LEFT, 6.0), dab(RIGHT, 6.0)]; + for tolerance in [0.90, 0.95, 0.99, 1.0] { + assert_eq!(changed(&before, &paint(&before, &both, tolerance), 0, 80), 0, "nothing paints at {tolerance}"); + } +} + +#[test] +fn tolerance_zero_paints_everywhere() { + let before = current_layer(); + let after = paint(&before, &[dab(LEFT, 6.0), dab(RIGHT, 6.0)], 0.0); + assert!(changed(&before, &after, 0, 40) > 0); + assert!(changed(&before, &after, 40, 80) > 0); + // Even where the layer equals the source, the dab is stamped (nothing visible changes). + let src = setup_source(); + let mut out = src.clone(); + let d = [dab(LEFT, 6.0)]; + let mut p = StampParams { + dest: &mut out, + dest_w: W, + dest_h: H, + dest_origin: (0, 0), + src: &src, + src_w: W, + src_h: H, + src_origin: (0, 0), + ch: CH, + dabs: &d, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + assert!(stamp(&mut p).unwrap() > 0); +} + +/// Several dabs across both halves at Tolerance 20: only those starting on the red half paint, and +/// the right half changes only where a red-half dab reaches into it. +#[test] +fn at_20_strokes_start_only_on_the_large_difference() { + let before = current_layer(); + let dabs: Vec = [8.0, 20.0, 36.0, 52.0, 64.0, 76.0].iter().map(|&x| dab(x, 6.0)).collect(); + let after = paint(&before, &dabs, 0.20); + assert!(changed(&before, &after, 0, 40) > 0); + assert_eq!(changed(&before, &after, 44, 80), 0, "no dab starts on the 20-level half"); + assert!(changed(&before, &after, 40, 44) > 0, "the dab at x 36 runs into the right half"); +} + +/// The rule is where a stroke starts, not the mean under the whole dab: a big dab that starts just +/// inside the red half paints over the right half too, and one that starts just inside the right +/// half paints nothing although a large part of it covers red. +#[test] +fn the_start_decides_not_the_whole_dab() { + let before = current_layer(); + let started_on_red = paint(&before, &[dab(37.0, 14.0)], 0.80); + assert!(changed(&before, &started_on_red, 40, 80) > 0, "a stroke started on red runs into the green half"); + let started_on_green = paint(&before, &[dab(43.0, 14.0)], 0.20); + assert_eq!(changed(&before, &started_on_green, 0, 80), 0, "a stroke started on the 20-level half stays unpainted"); +} From 0057b25216067b12b4abd48c3bff6e400d72844b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 04:43:49 +0100 Subject: [PATCH 10/38] WIP: Artboards to Files: Include Overlapping Areas option (#13629) From ea501cce730a450302f0a145e235d7036d7e021b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 04:44:26 +0100 Subject: [PATCH 11/38] Art History Brush: refusals use the reference application's alert texts (#12638) A hidden target layer, Lock All or Lock Image Pixels, a group, no source, another canvas size and a target layer the source state lacks are refused with the reference application's "Could not use the art history brush because ..." texts, shown as an alert with OK. The History Brush keeps its own texts: history_source_cmds::checked_source leaves the wording of the source refusals to the caller. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/history_source_cmds.rs | 37 ++++- crates/engine/src/cmd/retouch_cmds.rs | 2 +- .../src/cmd/retouch_cmds/art_history.rs | 63 +++++++- .../retouch_cmds/art_history_refusal_tests.rs | 143 ++++++++++++++++++ crates/engine/src/hidden_target.rs | 6 +- .../tools/art_history_refusal_alert_tests.rs | 87 +++++++++++ crates/ui-egui/src/tools/brush_refusal.rs | 16 +- crates/ui-egui/src/tools/retouch_ui.rs | 7 + 8 files changed, 339 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs create mode 100644 crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs diff --git a/crates/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index 4c85903740..bc2b44229b 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -86,19 +86,40 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { /// Photoshop refuses too, "the current canvas size does not match that of the history state" /// (its message as users report it; Adobe's help doesn't document the case). pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result> { + checked_source(st, p, cmd)?.map_err(|why| { + EngineError::Other(match why { + SourceRefusal::NoSource => "the History Brush source was deleted: set a new source in the History panel".into(), + SourceRefusal::CanvasSize { source } => format!( + "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", + st.doc.size.width, st.doc.size.height, source.width, source.height + ), + }) + }) +} + +/// Why [`checked_source`] found no source to paint from, so each tool can word it (#12638). +#[derive(Debug)] +pub(crate) enum SourceRefusal { + /// No `state` or `snapshot` passed, and the History panel's source was deleted. + NoSource, + /// The source has another canvas size than the document. + CanvasSize { source: photocraft_geom::Size }, +} + +/// [`paint_source`] with the refusal left to the caller: bad params and a `state` or `snapshot` +/// that is gone are errors, the two refusals the tools word themselves are the inner `Err`. +pub(crate) fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result, SourceRefusal>> { let doc = match parse(st, p, cmd)? { Some(src) => source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?, - None => source(st) - .and_then(|src| source_of(st, src)) - .ok_or_else(|| EngineError::Other("the History Brush source was deleted: set a new source in the History panel".into()))?, + None => match source(st).and_then(|src| source_of(st, src)) { + Some(doc) => doc, + None => return Ok(Err(SourceRefusal::NoSource)), + }, }; if doc.size != st.doc.size { - return Err(EngineError::Other(format!( - "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel", - st.doc.size.width, st.doc.size.height, doc.size.width, doc.size.height - ))); + return Ok(Err(SourceRefusal::CanvasSize { source: doc.size })); } - Ok(doc) + Ok(Ok(doc)) } /// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 6c891b8449..a53e60bcb8 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -413,7 +413,7 @@ pub fn specs() -> Vec { params: brush_params!( r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightMedium","area":0..100=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"# ), - enabled: has_pixel_layer, + enabled: art_history::enabled, run: art_history::run, journal: true, }, diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index cca503f536..455d1707c2 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -163,6 +163,55 @@ fn stamp_region( } } +/// The reference application's alerts for the refusals below (#12638); a hidden target is +/// [`crate::hidden_target::ART_HISTORY_HIDDEN`]. +pub const LOCKED: &str = "Could not use the art history brush because the layer is locked."; +pub const GROUP: &str = "Could not use the art history brush because the pixels in a group cannot be edited without merging the group."; +pub const LACKS_LAYER: &str = "Could not use the art history brush because the history state lacks a corresponding layer."; +pub const CANVAS_SIZE: &str = "Could not use the art history brush because the current canvas size does not match that of the history state."; +pub const NO_SOURCE: &str = "Could not use the art history brush because no history state has been designated as the source for painting."; + +/// The command's precondition: a pixel layer, as the other retouching tools, with the alert text +/// when a group is active. +pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { + super::has_pixel_layer(s).map_err(|why| if crate::active_layer_of(s).is_ok_and(|l| l.is_group()) { GROUP.into() } else { why }) +} + +/// Lock All or Lock Image Pixels on the targeted layer's pixels, refused with the alert text. +/// A mask or channel target keeps the shared check (not measured). +fn refuse_locked(s: &Session, id: Option, p: &Value) -> Result<()> { + let (Some(id), Some(st)) = (id, s.active()) else { return Ok(()) }; + if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels || st.doc.layer(id).is_none() { + return Ok(()); + } + let locks = st.doc.effective_locks(id); + if locks.all || locks.pixels { Err(EngineError::Other(LOCKED.into())) } else { Ok(()) } +} + +/// The source the stroke paints from, the History Brush's (the `state` or `snapshot` passed, else +/// the History panel's source, through the shared [`super::history_source`]), refused with the +/// alert texts: no source, then another canvas size, then another colour mode or a depth but 8 +/// bits ([`refuse_format`]), then a target layer the source state lacks. A missing mask or channel +/// keeps today's text (not measured). +fn source_surface(s: &Session, id: Option, p: &Value) -> Result { + use crate::history_source_cmds::{SourceRefusal, checked_source}; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = checked_source(st, p, CMD)?.map_err(|why| { + EngineError::Other( + match why { + SourceRefusal::NoSource => NO_SOURCE, + SourceRefusal::CanvasSize { .. } => CANVAS_SIZE, + } + .into(), + ) + })?; + refuse_format(&st.doc, &doc)?; + super::history_source(s, id, p, CMD).map_err(|e| { + let pixels = crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; + if pixels && crate::channel_cmds::read_target_surface(&doc, id, p).is_err() { EngineError::Other(LACKS_LAYER.into()) } else { e } + }) +} + /// A source of another colour mode, then any document but an 8-bit one, refused with the reference /// application's alert texts (#12637). The 16-bit text was seen with one layer only; two layers, /// or a depth change after the source, showed "not directly editable", so that text covers every @@ -215,13 +264,9 @@ pub fn run(s: &mut Session, p: &Value) -> Result { } let (stroke, id) = parse_brush(s, p, CMD)?; let _ = stroke; - // The same source as the History Brush: the `state` or `snapshot` passed, else the History - // panel's source, refused after a canvas size change, then after a colour mode change (#12826) - // or at a depth other than 8 bits, as Photoshop does, before a layer missing from it. Compare - // document modes: the pixel format reads Indexed and Multichannel as RGB. - let st = s.active().ok_or(EngineError::NoDocument)?; - refuse_format(&st.doc, &*crate::history_source_cmds::paint_source(st, p, CMD)?)?; - let src_surface = super::history_source(s, id, p, CMD)?; + refuse_locked(s, id, p)?; + // Compare document modes: the pixel format reads Indexed and Multichannel as RGB (#12826). + let src_surface = source_surface(s, id, p)?; // Truncating a huge row index only changes the seed. let seed = RNG_SEED ^ p.get("state").and_then(Value::as_u64).map_or(0, |i| i as u32); let dabs = art_history::place_dabs(&pts, size, area, style, seed).map_err(|e| match e { @@ -567,3 +612,7 @@ mod art_history_mode_mismatch_tests; #[cfg(test)] #[path = "art_history_depth_tests.rs"] mod art_history_depth_tests; + +#[cfg(test)] +#[path = "art_history_refusal_tests.rs"] +mod refusal_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs new file mode 100644 index 0000000000..0f757d9765 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs @@ -0,0 +1,143 @@ +//! The Art History Brush's refusals use the reference application's alert texts (#12638): a +//! hidden target, Lock All or Lock Image Pixels, a group, a target layer the source state lacks, +//! another canvas size and no source. Each adds no history state and changes no pixel, and the +//! History Brush keeps its own texts. + +use serde_json::{Value, json}; + +use super::{CANVAS_SIZE, GROUP, LACKS_LAYER, LOCKED, NO_SOURCE}; +use crate::Session; +use crate::hidden_target::{ART_HISTORY_HIDDEN, HIDDEN}; + +/// An RGB document with a red "Layer 1" above the white Background, the layer active. History +/// rows: 0 Open, 1 New Layer, 2 Fill. +fn session() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "white"})).unwrap(); + let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + (s, id) +} + +fn stroke(cmd: &str) -> Value { + let mut p = json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100}); + if cmd == "paint.artHistoryBrush" { + p["style"] = json!("tightMedium"); + } + p +} + +/// Runs `cmd` with `extra` params, expects a refusal and returns its text, checking that the +/// document and its history are unchanged. +fn refused(s: &mut Session, cmd: &str, extra: Value) -> String { + let mut p = stroke(cmd); + if let Some(map) = extra.as_object() { + for (k, v) in map { + p[k] = v.clone(); + } + } + let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.entries().len()); + let e = s.execute(cmd, p).unwrap_err().to_string(); + let st = s.active().unwrap(); + assert_eq!(st.history.entries().len(), steps, "{cmd}: no history state for {e}"); + for l in &doc.layers { + assert_eq!(st.doc.layer(l.id).and_then(|n| n.surface()), l.surface(), "{cmd}: no pixel changes for {e}"); + } + e +} + +#[test] +fn a_hidden_target_layer() { + let (mut s, id) = session(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), ART_HISTORY_HIDDEN); + assert_eq!(refused(&mut s, "paint.historyBrush", json!({})), HIDDEN); +} + +#[test] +fn lock_all_or_lock_image_pixels() { + for key in ["all", "pixels"] { + let (mut s, id) = session(); + s.execute("layer.setProps", json!({"layer": id, "locks": {key: true}})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LOCKED, "{key}"); + // Row 1 holds Layer 1, so the History Brush gets as far as the lock. + let e = refused(&mut s, "paint.historyBrush", json!({"state": 1})); + assert!(e.contains("Could not complete your request because the layer \"Layer 1\" is locked"), "{key}: {e}"); + } +} + +/// Lock Transparent Pixels was not measured: it still paints, as before. +#[test] +fn lock_transparent_pixels_still_paints() { + let (mut s, id) = session(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locks": {"transparency": true}})).unwrap(); + s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap(); +} + +#[test] +fn a_group_is_active() { + let (mut s, _) = session(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", json!({})); + assert!(e.contains(GROUP), "{e}"); + assert!(!s.is_enabled("paint.artHistoryBrush")); + assert_eq!(s.disabled_reason("paint.artHistoryBrush").as_deref(), Some(GROUP)); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("not a pixel layer") && !e.contains("art history"), "{e}"); +} + +/// Row 1 (New Layer) holds the Background and Layer 1; a second layer added after it is missing. +#[test] +fn the_source_state_lacks_the_target_layer() { + let (mut s, _) = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), LACKS_LAYER); + // The History panel's source too. + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LACKS_LAYER); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("the target did not exist"), "{e}"); +} + +#[test] +fn the_canvas_size_changed() { + let (mut s, _) = session(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), CANVAS_SIZE); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), CANVAS_SIZE); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("does not match that of the History Brush source (48×32)"), "{e}"); +} + +#[test] +fn no_source_is_set() { + let (mut s, _) = session(); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE); + let e = refused(&mut s, "paint.historyBrush", json!({})); + assert!(e.contains("the History Brush source was deleted"), "{e}"); +} + +/// No source and another canvas size: the missing source is reported, as before. +#[test] +fn no_source_comes_before_the_canvas_size() { + let (mut s, _) = session(); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE); +} + +/// The checks don't stop a stroke that may paint: row 2 is the red layer, now blue. +#[test] +fn a_valid_stroke_still_paints() { + let (mut s, _) = session(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); +} diff --git a/crates/engine/src/hidden_target.rs b/crates/engine/src/hidden_target.rs index c8bcbf54db..d7e75a18fc 100644 --- a/crates/engine/src/hidden_target.rs +++ b/crates/engine/src/hidden_target.rs @@ -11,6 +11,9 @@ use crate::Session; /// Photoshop's alert text. pub const HIDDEN: &str = "Could not complete your request because the target layer is hidden."; +/// The Art History Brush's own alert text (#12638). +pub const ART_HISTORY_HIDDEN: &str = "Could not use the art history brush because the target layer is hidden."; + /// Commands that paint on, or move, the target layer. const GATED: &[&str] = &[ "paint.stroke", @@ -53,7 +56,8 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { } let st = s.active()?; let layer = crate::commands::layer_param(s, ¶ms).ok()?; - (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(HIDDEN) + let why = if id == "paint.artHistoryBrush" { ART_HISTORY_HIDDEN } else { HIDDEN }; + (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why) } #[cfg(test)] diff --git a/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs new file mode 100644 index 0000000000..5501f12aad --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs @@ -0,0 +1,87 @@ +//! #12638: when the Art History Brush can't paint, a stroke opens the reference application's +//! alert with OK and paints nothing: at the press for a hidden target layer, Lock All, Lock Image +//! Pixels or a group's pixels; at the release for the source refusals (another canvas size, no +//! source, a target layer the source state lacks). The History Brush keeps today's status bar. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; + +/// The fixture's history: 0 Open, 1 New Layer, 2 Fill; the source is the Open state, which holds +/// only the Background, so a stroke paints from row 1, which holds the active layer. +fn art_history() -> PhotocraftApp { + let mut app = app(Tool::ArtHistoryBrush); + app.run("history.setSource", json!({"state": 1})).unwrap(); + app +} + +#[test] +fn a_hidden_target_layer() { + let mut app = art_history(); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the art history brush because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + for lock in ["all", "pixels"] { + let mut app = art_history(); + app.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut app, "Could not use the art history brush because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + let mut app = art_history(); + app.run("layer.new.group", json!({})).unwrap(); + refused(&mut app, "Could not use the art history brush because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn the_canvas_size_changed() { + let mut app = art_history(); + app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap(); + refused(&mut app, "Could not use the art history brush because the current canvas size does not match that of the history state."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn no_source_is_set() { + let mut app = app(Tool::ArtHistoryBrush); + let snap = app.run("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + app.run("history.setSource", json!({"snapshot": snap})).unwrap(); + app.run("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + refused(&mut app, "Could not use the art history brush because no history state has been designated as the source for painting."); +} + +#[test] +fn the_source_state_lacks_the_target_layer() { + let mut app = art_history(); + app.run("layer.new.layer", json!({})).unwrap(); + refused(&mut app, "Could not use the art history brush because the history state lacks a corresponding layer."); +} + +#[test] +fn a_stroke_from_a_valid_source_paints() { + let mut app = art_history(); + app.run("history.setSource", json!({"state": 2})).unwrap(); + app.run("edit.fill", json!({"color": "#1e1edc"})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1); +} + +/// The History Brush keeps its status-bar texts. +#[test] +fn the_history_brush_keeps_the_status_bar() { + let mut app = app(Tool::HistoryBrush); + app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert!(!app.ui.status.contains("art history"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index 18f48b01e0..0332921ddc 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -38,14 +38,15 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> { } /// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the -/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965) and the Classic gradient -/// (the live Gradient makes a fill layer and isn't measured, #12017). +/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Art History Brush +/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017). pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), Tool::Sharpen => Some(tl!("sharpen tool")), Tool::Sponge => Some(tl!("sponge tool")), Tool::Smudge => Some(tl!("smudge tool")), + Tool::ArtHistoryBrush => Some(tl!("art history brush")), Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")), _ => None, } @@ -99,10 +100,11 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { } } -/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools Lock Image -/// Pixels as well (measured for them; the Brush keeps today's behaviour there). +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools and the +/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's +/// behaviour there). fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { - locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge) && locks.pixels) + locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::ArtHistoryBrush) && locks.pixels) } /// Opens the alert: ordinary dialog state, listed by `ui.inspect` and closed by `ui.dialog.confirm`. @@ -141,3 +143,7 @@ mod remove_locked_alert_tests; #[cfg(test)] #[path = "remove_hidden_layer_tests.rs"] mod remove_hidden_layer_tests; + +#[cfg(test)] +#[path = "art_history_refusal_alert_tests.rs"] +mod art_history_refusal_alert_tests; diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 7d5811f28d..65fec08b59 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -299,6 +299,13 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ app.ui.pattern_stamp_phase = r.get("phase").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.pattern_stamp_aligned); } Ok(_) => {} + // The Art History Brush's source refusals are alerts with OK, as the press-time ones, and + // not in the status bar as well (#12638). + Err(e) if tool == Tool::ArtHistoryBrush && e.starts_with("Could not use the art history brush because") => { + app.ui.status.clear(); + app.ui.status_error = false; + crate::brush_refusal::prompt(app, tl!(&e)); + } Err(e) => { app.ui.status = e; app.ui.status_error = true; From 926738b5eb4af9f0a0681a966a93a880fb502f46 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 05:08:37 +0100 Subject: [PATCH 12/38] Artboards to Files: Include Overlapping Areas / Artboard Content Only (#13629) The dialog gets the radio pair below the prefix, Include Overlapping Areas selected by default, and file.export.artboardsToFiles a matching "content" param. With overlapping, a board's file also shows the visible boards stacked above it where they overlap it: each as a plain group cut to the file, with a "Background for " pixel layer, as the reference application writes it. Boards below never show. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 100 ++++++- .../artboard_cmds/overlapping_areas_tests.rs | 245 ++++++++++++++++++ .../src/artboards_overlap_dialog_tests.rs | 73 ++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds/dialogs.rs | 22 +- 5 files changed, 434 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs create mode 100644 crates/ui-egui/src/artboards_overlap_dialog_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..8c4f330533 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -657,10 +657,87 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result Ok(Some(one)) } +/// Include Overlapping Areas: each visible artboard stacked above board `id` that overlaps it, as +/// the reference application writes it into the board's file: a plain group (no longer an +/// artboard) holding its layers over a new pixel layer "Background for " filled with the +/// board's background where the two boards overlap, in source coordinates and bottom to top. A +/// group whose layers reach past its own board (effects, pixels outside the board, adjustments) +/// gets a mask to its board, which the artboard clipped them to. +fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { + let above = doc.layers.iter().skip_while(|l| l.id != id).skip(1); + let mut out = Vec::new(); + for l in above.filter(|l| l.visible) { + let Some(ab) = l.artboard().cloned() else { continue }; + let overlap = ab.rect.intersect(&rect); + if overlap.is_empty() { + continue; + } + let mut group = l.clone(); + if let LayerContent::Group(g) = &mut group.content { + g.artboard = None; + cut_pixels(&mut g.children, overlap, 0); + } + let reach = photocraft_compose::change_bounds(&group, doc.bounds()); + if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) { + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0]); + mask.surface.fill_rect(ab.rect, &[1.0]); + group.mask = Some(mask); + } + if let (Some(bg), Some(children)) = (ab.background.rgba(), group.children_mut()) { + let fmt = doc.pixel_format(); + let mut surf = Surface::new(fmt); + surf.fill_rect(overlap, &photocraft_raster::from_rgba(&fmt, bg)); + children.insert(0, Layer::new(format!("Background for {}", l.name), LayerContent::Raster(surf))); + } + out.push(group); + } + out +} + +/// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to +/// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers +/// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board. +fn cut_pixels(layers: &mut [Layer], keep: Rect, depth: usize) { + const MAX_DEPTH: usize = 64; + for l in layers { + match &mut l.content { + LayerContent::Group(g) if depth < MAX_DEPTH => cut_pixels(&mut g.children, keep, depth + 1), + LayerContent::Raster(surf) => { + let r = surf.content_bounds().intersect(&keep); + let mut cut = Surface::with_default(surf.format(), &surf.default_pixel()); + if !r.is_empty() { + let Ok(px) = surf.try_read_region(r) else { continue }; + if cut.try_write_region(r, &px).is_err() { + continue; + } + } + *surf = cut; + } + _ => {} + } + } +} + /// [`artboard_document`] for each chosen board, all built before any file is written so a -/// board that can't be exported fails the export without leaving a partial set behind. -fn chosen_documents(doc: &Document, p: &Value) -> Result> { - chosen_artboards(doc, p).into_iter().filter_map(|id| artboard_document(doc, id).transpose()).collect() +/// board that can't be exported fails the export without leaving a partial set behind. With +/// `overlapping`, each file also holds the boards above that overlap it ([`overlapping_boards`]). +fn chosen_documents(doc: &Document, p: &Value, overlapping: bool) -> Result> { + let mut out = Vec::new(); + for id in chosen_artboards(doc, p) { + let Some(mut one) = artboard_document(doc, id)? else { continue }; + if overlapping && let Some(r) = doc.layer(id).and_then(|l| l.artboard()).map(|a| a.rect) { + // `artboard_document` has checked that the board's origin negates. + let (dx, dy) = (r.x0.saturating_neg(), r.y0.saturating_neg()); + for mut group in overlapping_boards(doc, id, r) { + crate::commands::translate_layer(doc, &mut group, dx, dy); + crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(dx), f64::from(dy)); + one.layers.push(group); + } + } + out.push(one); + } + Ok(out) } /// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first. @@ -683,9 +760,17 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let save = SaveOpts::from_params(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); + let overlapping = match p.get("content") { + None | Some(Value::Null) => true, + Some(v) => match v.as_str() { + Some("overlapping") => true, + Some("artboard") => false, + _ => return Err(bad(cmd, format!("`content` must be \"overlapping\" or \"artboard\", not {v}"))), + }, + }; let doc = d.doc.clone(); let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + for (i, one) in chosen_documents(&doc, p, overlapping)?.into_iter().enumerate() { // Names may be identical, or collide after sanitizing or filesystem case folding. let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{format}")); @@ -752,7 +837,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); let mut pages = Vec::new(); - for one in chosen_documents(&doc, p)? { + for one in chosen_documents(&doc, p, false)? { let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); @@ -829,7 +914,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, export_artboards, artboards_to_files ), @@ -848,5 +933,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/overlapping_areas_tests.rs"] +mod overlapping_areas_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs new file mode 100644 index 0000000000..d88f58559d --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -0,0 +1,245 @@ +//! Artboards to Files › Include Overlapping Areas / Artboard Content Only (#13629): the boards +//! stacked above an exported board that overlap it show in its file (PNG pixels, PSD structure), +//! boards below never do, and the source document is left alone. + +use super::*; +use photocraft_geom::Rect; + +const RED: [u8; 3] = [220, 30, 30]; +const BLUE: [u8; 3] = [30, 30, 220]; +const WHITE: [u8; 3] = [255, 255, 255]; + +/// The measured test document: 800 x 400, transparent, bottom to top `Red Board` 0,0-200,150 +/// (pixel layer `Red` at 20,20-120,100), `Blue Board` 120,30-320,230 (pixel layer `Blue` at +/// 130,40-230,140) and `Empty Board` 600,0-700,100, all with white backgrounds. +fn session(depth: u32) -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + let board = + |s: &mut Session, name: &str, rect: [i64; 4]| s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap()["layer"].as_u64().unwrap(); + let red = board(&mut s, "Red Board", [0, 0, 200, 150]); + let blue = board(&mut s, "Blue Board", [120, 30, 200, 200]); + let empty = board(&mut s, "Empty Board", [600, 0, 100, 100]); + paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), RED); + paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), BLUE); + (s, [red, blue, empty]) +} + +/// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers. +fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { + s.edit(name, |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + let [r, g, b] = color.map(|c| f32::from(c) / 255.0); + l.surface_mut().unwrap().fill_rect(rect, &photocraft_raster::from_rgba(&fmt, [r, g, b, 1.0])); + doc.layer_mut(LayerId(board)).unwrap().children_mut().unwrap().push(l); + Ok(()) + }) + .unwrap(); +} + +struct Out(std::path::PathBuf); + +impl Out { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("photocraft-overlap-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Out(dir) + } + fn dir(&self) -> String { + self.0.to_string_lossy().into_owned() + } +} + +impl Drop for Out { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Exports board `board` with `extra` params and reads the one file back. +fn export(s: &mut Session, out: &Out, board: u64, extra: Value) -> Document { + let mut p = json!({"dir": out.dir(), "prefix": "", "artboards": [board]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let format = p.get("format").and_then(Value::as_str).unwrap_or("png").to_string(); + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{r}"); + let path = files[0].as_str().unwrap(); + photocraft_io::import(&format!("x.{format}"), &std::fs::read(path).unwrap()).unwrap().document +} + +/// The file's composite pixel at (x, y) as 8-bit RGBA. +fn px(d: &Document, x: i32, y: i32) -> [u8; 4] { + let flat = photocraft_compose::flatten(d); + let w = d.size.width as usize; + flat.px[y as usize * w + x as usize].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn rgb(p: [u8; 4]) -> [u8; 3] { + [p[0], p[1], p[2]] +} + +fn names(layers: &[Layer]) -> Vec<&str> { + layers.iter().map(|l| l.name.as_str()).collect() +} + +#[test] +fn include_overlapping_areas_is_the_default_and_shows_the_board_above() { + for depth in [8, 16] { + let (mut s, [red, _, _]) = session(depth); + let out = Out::new(&format!("default-{depth}")); + for extra in [json!({}), json!({"content": "overlapping"})] { + let f = export(&mut s, &out, red, extra.clone()); + assert_eq!((f.size.width, f.size.height), (200, 150), "{depth} bit {extra}"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{depth} bit {extra}: Blue's pixels"); + assert_eq!(rgb(px(&f, 125, 35)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 125, 50)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{depth} bit {extra}: Red stays red"); + } + } +} + +#[test] +fn artboard_content_only_keeps_the_board_on_its_own() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("content-only"); + let f = export(&mut s, &out, red, json!({"content": "artboard"})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE, "nothing of Blue Board"); + assert_eq!(rgb(px(&f, 110, 50)), RED); + let psd = export(&mut s, &out, red, json!({"content": "artboard", "format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn an_overlapping_psd_holds_the_board_above_as_a_plain_group_with_its_background() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("psd"); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!((psd.size.width, psd.size.height), (200, 150)); + // Bottom to top: the exported artboard, then the overlapping board as a plain group. + assert_eq!(names(&psd.layers), ["Red Board", "Blue Board"]); + let [board, group] = [&psd.layers[0], &psd.layers[1]]; + assert_eq!(board.artboard().map(|a| a.rect), Some(Rect::new(0, 0, 200, 150))); + assert_eq!(names(board.children().unwrap()), ["Red"]); + assert!(matches!(&group.content, LayerContent::Group(g) if g.artboard.is_none()), "no longer an artboard"); + let kids = group.children().unwrap(); + assert_eq!(names(kids), ["Background for Blue Board", "Blue"]); + // Blue (130,40-230,140 in the source) is cut to the file: 130,40-200,140. + let blue = photocraft_compose::bounds::content_bounds(kids[1].surface().unwrap()); + assert_eq!(blue, Rect::new(130, 40, 200, 140)); + // The background covers where the boards overlap: 120..200 x 30..150. + let bg = photocraft_compose::bounds::content_bounds(kids[0].surface().unwrap()); + assert_eq!(bg, Rect::new(120, 30, 200, 150)); + assert_eq!(rgb(px(&psd, 150, 60)), BLUE); + assert_eq!(rgb(px(&psd, 125, 35)), WHITE); + assert_eq!(rgb(px(&psd, 110, 50)), RED); +} + +#[test] +fn boards_below_do_not_show_in_either_mode() { + let (mut s, [_, blue, _]) = session(8); + // A transparent Blue Board shows whatever leaks in from Red Board's white background below. + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + let out = Out::new("below"); + for content in ["overlapping", "artboard"] { + let f = export(&mut s, &out, blue, json!({"content": content})); + assert_eq!((f.size.width, f.size.height), (200, 200), "{content}"); + // Source (125,35): Red Board's background, outside Blue's pixels. + assert_eq!(px(&f, 5, 5)[3], 0, "{content}: nothing of Red Board"); + assert_eq!(rgb(px(&f, 30, 30)), BLUE, "{content}"); + let psd = export(&mut s, &out, blue, json!({"content": content, "format": "psd"})); + assert_eq!(names(&psd.layers), ["Blue Board"], "{content}"); + } +} + +#[test] +fn the_source_document_is_unchanged_and_gets_no_history_entry() { + let (mut s, [red, blue, _]) = session(8); + let out = Out::new("source"); + for content in ["overlapping", "artboard"] { + for board in [red, blue] { + let d = s.active().unwrap(); + let (before, rev, past) = (d.doc.clone(), d.revision, d.history.past_len()); + export(&mut s, &out, board, json!({"content": content, "format": "psd"})); + let d = s.active().unwrap(); + assert!(d.doc == before, "{content} changed the document"); + assert_eq!((d.revision, d.history.past_len()), (rev, past), "{content}"); + } + } +} + +/// The artboard clipped its layers to the board; as a plain group in the file they still stop +/// at the board's edge, so Blue pixels outside Blue Board never cover Red Board. +#[test] +fn the_layers_of_the_board_above_stay_inside_their_board() { + let (mut s, [red, blue, _]) = session(8); + paint(&mut s, blue, "Spill", Rect::new(100, 45, 125, 55), BLUE); + let out = Out::new("spill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 122, 50)), BLUE, "{format}: inside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{format}"); + } +} + +/// A layer that covers the whole canvas (a solid colour fill) in the board above is clipped to +/// that board by a mask on the group, so it can't paint over the rest of the exported board. +#[test] +fn a_fill_layer_in_the_board_above_stays_inside_its_board() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Fill", |doc, _| { + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().push(fill); + Ok(()) + }) + .unwrap(); + let out = Out::new("fill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 10, 140)), WHITE, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), [0, 255, 0], "{format}: inside Blue Board"); + } +} + +/// Not measured (keeps today's behaviour): a hidden board above shows nothing. +#[test] +fn a_hidden_board_above_does_not_show() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Hide", |doc, _| { + doc.layer_mut(LayerId(blue)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let out = Out::new("hidden"); + let f = export(&mut s, &out, red, json!({})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn a_bad_content_value_is_rejected_without_writing_anything() { + let (mut s, _) = session(8); + let out = Out::new("bad"); + for bad in [json!("both"), json!(""), json!(1), json!(true), json!(["overlapping"])] { + let d = s.active().unwrap(); + let (before, past) = (d.doc.clone(), d.history.past_len()); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": out.dir(), "content": bad})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{bad}: {err}"); + let d = s.active().unwrap(); + assert!(d.doc == before && d.history.past_len() == past, "{bad}"); + assert_eq!(std::fs::read_dir(&out.0).unwrap().count(), 0, "{bad}: nothing written"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToFiles").unwrap(); + assert!(spec.params.contains(r#""content":"overlapping|artboard"="overlapping""#), "{}", spec.params); +} diff --git a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs new file mode 100644 index 0000000000..574e95a139 --- /dev/null +++ b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs @@ -0,0 +1,73 @@ +//! #13629: the Artboards to Files dialog has the radio pair Include Overlapping Areas (selected +//! by default) / Artboard Content Only right below the prefix, and OK passes the choice to +//! `file.export.artboardsToFiles` as `content`. Layer Comps to Files has no such choice. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const OVERLAPPING: &str = "Include Overlapping Areas"; +const CONTENT_ONLY: &str = "Artboard Content Only"; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).unwrap(); + app.run("layerComp.new", json!({"name": "Comp"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, id: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, id, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + dialog +} + +fn selected(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::RadioButton, label).accesskit_node().toggled() == Some(Toggled::True) +} + +#[test] +fn the_dialog_offers_the_two_radios_below_the_prefix_overlapping_first_and_selected() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let radios: Vec = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).collect(); + assert_eq!(radios, [OVERLAPPING, CONTENT_ONLY]); + assert!(selected(&h, OVERLAPPING) && !selected(&h, CONTENT_ONLY)); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + let keys = crate::view_cmds::form_keys(fields); + assert_eq!(keys.iter().position(|k| k == "content"), keys.iter().position(|k| k == "prefix").map(|i| i + 1), "{keys:?}"); + assert_eq!(crate::filter_dialog::params_of(fields)["content"], "overlapping"); +} + +#[test] +fn clicking_artboard_content_only_passes_it_to_the_command() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + h.get_by_role_and_label(Role::RadioButton, CONTENT_ONLY).click(); + h.run_steps(4); + assert!(selected(&h, CONTENT_ONLY) && !selected(&h, OVERLAPPING)); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + assert_eq!(crate::filter_dialog::params_of(fields)["content"], "artboard"); + h.get_by_role_and_label(Role::RadioButton, OVERLAPPING).click(); + h.run_steps(4); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + assert_eq!(crate::filter_dialog::params_of(fields)["content"], "overlapping"); +} + +#[test] +fn layer_comps_to_files_has_no_overlap_choice() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + assert_eq!(h.query_all_by_role(Role::RadioButton).count(), 0); + assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("content").is_none()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..bf0da497ff 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1056,6 +1056,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_overlap_dialog_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..f0fc43aba6 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -191,6 +191,20 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { ui.end_row(); continue; } + // A choice named in `__radios` is a column of radio buttons, one per option. + let radios = f.get("__radios").and_then(Value::as_array).is_some_and(|r| r.iter().any(|n| n.as_str() == Some(k.as_str()))); + if radios && let (Some(cur), Some(opts)) = (v.as_str(), choices.get(&k).and_then(Value::as_array)) { + let mut s = cur.to_owned(); + ui.label(""); + ui.vertical(|ui| { + for o in opts.iter().filter_map(Value::as_str) { + ui.radio_value(&mut s, o.to_owned(), label(o)); + } + }); + f.insert(k, json!(s)); + ui.end_row(); + continue; + } let new = match &v { Value::Array(_) | Value::Object(_) | Value::Null => continue, Value::Bool(b) => { @@ -507,9 +521,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}) } else { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "__order": ["dir", "prefix", "format", "quality"]}) + // Include Overlapping Areas / Artboard Content Only, right below the prefix. + json!({"dir": dir, "prefix": prefix, "content": "overlapping", "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, + "__radios": ["content"], "__labels": {"overlapping": tl!("Include Overlapping Areas"), "artboard": tl!("Artboard Content Only")}, + "__order": ["dir", "prefix", "content", "format", "quality"]}) }; - dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) + let content = if id == "file.export.artboardsToFiles" { json!(["overlapping", "artboard"]) } else { Value::Null }; + dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"], "content": content})) } "file.export.artboardsToPdf" => { let (_, _, name) = doc?; From 7fafc8962722b65b1115e3b096dc2477676a3db6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 05:27:40 +0100 Subject: [PATCH 13/38] Art History Brush: alert texts only for a layer's pixels; refuse a masked group's pixels A hidden layer's mask and a mask or channel target with no source or another canvas size keep the History Brush's texts (not measured). A group with a mask passes the precondition for its mask, but its pixels are refused with the group alert. Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/retouch_cmds/art_history.rs | 53 +++++++++++-------- .../retouch_cmds/art_history_refusal_tests.rs | 29 ++++++++++ crates/engine/src/hidden_target.rs | 4 +- 3 files changed, 63 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index 455d1707c2..4a843216d9 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -177,39 +177,48 @@ pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { super::has_pixel_layer(s).map_err(|why| if crate::active_layer_of(s).is_ok_and(|l| l.is_group()) { GROUP.into() } else { why }) } -/// Lock All or Lock Image Pixels on the targeted layer's pixels, refused with the alert text. -/// A mask or channel target keeps the shared check (not measured). -fn refuse_locked(s: &Session, id: Option, p: &Value) -> Result<()> { +/// The targeted layer's pixels can't be painted: a group's (also one with a mask, which the +/// precondition lets through for its mask), or Lock All or Lock Image Pixels, refused with the +/// alert texts. A mask or channel target keeps the shared checks (not measured). +fn refuse_layer(s: &Session, id: Option, p: &Value) -> Result<()> { let (Some(id), Some(st)) = (id, s.active()) else { return Ok(()) }; - if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels || st.doc.layer(id).is_none() { - return Ok(()); + let Some(layer) = st.doc.layer(id).filter(|_| pixel_target(p)) else { return Ok(()) }; + if layer.is_group() { + return Err(EngineError::Other(GROUP.into())); } let locks = st.doc.effective_locks(id); if locks.all || locks.pixels { Err(EngineError::Other(LOCKED.into())) } else { Ok(()) } } +fn pixel_target(p: &Value) -> bool { + crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels +} + /// The source the stroke paints from, the History Brush's (the `state` or `snapshot` passed, else /// the History panel's source, through the shared [`super::history_source`]), refused with the /// alert texts: no source, then another canvas size, then another colour mode or a depth but 8 -/// bits ([`refuse_format`]), then a target layer the source state lacks. A missing mask or channel -/// keeps today's text (not measured). +/// bits ([`refuse_format`]), then a target layer the source state lacks. A mask or channel target +/// keeps the History Brush's texts for the source refusals (not measured). fn source_surface(s: &Session, id: Option, p: &Value) -> Result { - use crate::history_source_cmds::{SourceRefusal, checked_source}; + use crate::history_source_cmds::{SourceRefusal, checked_source, paint_source}; let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = checked_source(st, p, CMD)?.map_err(|why| { - EngineError::Other( - match why { - SourceRefusal::NoSource => NO_SOURCE, - SourceRefusal::CanvasSize { .. } => CANVAS_SIZE, - } - .into(), - ) - })?; + let pixels = pixel_target(p); + let doc = if pixels { + checked_source(st, p, CMD)?.map_err(|why| { + EngineError::Other( + match why { + SourceRefusal::NoSource => NO_SOURCE, + SourceRefusal::CanvasSize { .. } => CANVAS_SIZE, + } + .into(), + ) + })? + } else { + paint_source(st, p, CMD)? + }; refuse_format(&st.doc, &doc)?; - super::history_source(s, id, p, CMD).map_err(|e| { - let pixels = crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; - if pixels && crate::channel_cmds::read_target_surface(&doc, id, p).is_err() { EngineError::Other(LACKS_LAYER.into()) } else { e } - }) + super::history_source(s, id, p, CMD) + .map_err(|e| if pixels && crate::channel_cmds::read_target_surface(&doc, id, p).is_err() { EngineError::Other(LACKS_LAYER.into()) } else { e }) } /// A source of another colour mode, then any document but an 8-bit one, refused with the reference @@ -264,7 +273,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result { } let (stroke, id) = parse_brush(s, p, CMD)?; let _ = stroke; - refuse_locked(s, id, p)?; + refuse_layer(s, id, p)?; // Compare document modes: the pixel format reads Indexed and Multichannel as RGB (#12826). let src_surface = source_surface(s, id, p)?; // Truncating a huge row index only changes the seed. diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs index 0f757d9765..6d18e01a89 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history_refusal_tests.rs @@ -141,3 +141,32 @@ fn a_valid_stroke_still_paints() { s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap(); assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); } + +/// A group with a mask passes the precondition (for its mask), but its pixels are still refused. +#[test] +fn a_group_with_a_mask_and_its_pixels_targeted() { + let (mut s, _) = session(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"target": "pixels"})), GROUP); +} + +/// A mask target was not measured: a hidden layer, no source and another canvas size keep the +/// History Brush's texts. +#[test] +fn a_mask_target_keeps_todays_texts() { + let (mut s, id) = session(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let mask = json!({"target": "mask"}); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(refused(&mut s, "paint.artHistoryBrush", mask.clone()), HIDDEN); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", mask.clone()); + assert!(e.contains("does not match that of the History Brush source"), "{e}"); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap(); + let e = refused(&mut s, "paint.artHistoryBrush", mask); + assert!(e.contains("the History Brush source was deleted"), "{e}"); +} diff --git a/crates/engine/src/hidden_target.rs b/crates/engine/src/hidden_target.rs index d7e75a18fc..01e9ec0959 100644 --- a/crates/engine/src/hidden_target.rs +++ b/crates/engine/src/hidden_target.rs @@ -56,7 +56,9 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { } let st = s.active()?; let layer = crate::commands::layer_param(s, ¶ms).ok()?; - let why = if id == "paint.artHistoryBrush" { ART_HISTORY_HIDDEN } else { HIDDEN }; + // The Art History Brush's text was measured on a layer's pixels only. + let pixels = crate::channel_cmds::target_of(¶ms) == crate::channel_cmds::Target::Pixels; + let why = if id == "paint.artHistoryBrush" && pixels { ART_HISTORY_HIDDEN } else { HIDDEN }; (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why) } From 21672d4a300715f9f17a1db43e7980de35d36c65 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 06:26:42 +0100 Subject: [PATCH 14/38] Artboards to Files: keep layers with effects whole when cutting an overlapping board A layer outside the exported board can cast a shadow or glow into it, so its pixels must stay for the effect; the board's mask still clips it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 5 +++ .../artboard_cmds/overlapping_areas_tests.rs | 37 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 8c4f330533..d29c389af0 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -698,9 +698,14 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { /// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to /// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers /// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board. +/// A layer with effects, or inside a group with effects, stays whole too: pixels outside `keep` +/// can cast a shadow or glow into it. fn cut_pixels(layers: &mut [Layer], keep: Rect, depth: usize) { const MAX_DEPTH: usize = 64; for l in layers { + if photocraft_compose::effects::has_effects(l) { + continue; + } match &mut l.content { LayerContent::Group(g) if depth < MAX_DEPTH => cut_pixels(&mut g.children, keep, depth + 1), LayerContent::Raster(surf) => { diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs index d88f58559d..b91fb70eed 100644 --- a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -207,6 +207,43 @@ fn a_fill_layer_in_the_board_above_stays_inside_its_board() { } } +/// A layer of the board above that lies outside the exported board still casts its drop shadow +/// into it, as it does in the document: its pixels are not cut away before the effect is built. +#[test] +fn a_shadow_cast_into_the_exported_board_from_outside_it_still_shows() { + use photocraft_doc::effects::{Contour, FxCommon, Shadow}; + let (mut s, [red, blue, _]) = session(8); + // Caster at 210..240 x 160..180 (in Blue Board, outside Red Board); its shadow, 40 px up and + // to the left, falls on 170..200 x 120..140, inside Red Board. + paint(&mut s, blue, "Caster", Rect::new(210, 160, 240, 180), [0, 160, 0]); + s.edit("Shadow", |doc, _| { + let caster = doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().last_mut().unwrap(); + caster.effects.items.push(photocraft_doc::Effect::DropShadow(Shadow { + common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + color: Color::rgb(0.0, 0.0, 0.0), + angle: -45.0, + use_global_light: false, + distance: 40.0_f32.hypot(40.0), + spread: 0.0, + size: 0.0, + contour: Contour::Linear, + anti_alias: false, + noise: 0.0, + knocks_out: true, + })); + Ok(()) + }) + .unwrap(); + let source = px(&s.active().unwrap().doc, 185, 130); + assert_eq!(rgb(source), [0, 0, 0], "the shadow lands there in the document"); + let out = Out::new("shadow"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(px(&f, 185, 130), source, "{format}"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}"); + } +} + /// Not measured (keeps today's behaviour): a hidden board above shows nothing. #[test] fn a_hidden_board_above_does_not_show() { From 321c308f90be1766f8500c151119ebdec1aaf548 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 14:47:26 +0100 Subject: [PATCH 15/38] Variables: Apply Data Set refuses a locked text layer (#14499) A data set with a Text value for a type layer under Lock All now applies nothing, still adds one history state that changes nothing, and fails with the reference application's message, which the app shows as an alert. Visibility and Pixel Replacement values keep applying to locked layers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/variables_cmds.rs | 28 ++- .../variables_cmds/locked_text_layer_tests.rs | 208 ++++++++++++++++++ crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/app.rs | 3 + .../src/app/apply_data_set_alert_tests.rs | 43 ++++ crates/ui-egui/src/app/commands.rs | 5 + 6 files changed, 287 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs create mode 100644 crates/ui-egui/src/app/apply_data_set_alert_tests.rs diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index d109959bdd..15c5f20c33 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -278,11 +278,34 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { let (set, idx) = resolve_set(s, p, "image.applyDataSet")?; let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone(); authorize_pixel_paths(s, &set)?; - s.edit(&format!("Apply Data Set \"{}\"", set.name), |doc, _| apply_to_doc(doc, &vars, &set))?; + let label = format!("Apply Data Set \"{}\"", set.name); + if replaces_locked_text(&s.active().ok_or(EngineError::NoDocument)?.doc, &vars, &set) { + // As in the reference application, nothing of the set is applied, but the attempt is + // still a history state (one that changes nothing), and the alert names no layer (#14499). + s.edit(&label, |_, _| Ok(()))?; + return Err(EngineError::Other(DATA_SET_LAYER_LOCKED.into())); + } + s.edit(&label, |doc, _| apply_to_doc(doc, &vars, &set))?; set_vars(s, |v| v.active = Some(idx))?; Ok(json!({"applied": set.name, "index": idx})) } +/// The reference application's alert when Apply Data Set would replace the text of a layer +/// under Lock All. +pub const DATA_SET_LAYER_LOCKED: &str = "Could not apply data set because the layer is locked."; + +/// Whether `set` has a Text value for a type layer with its own Lock All. Visibility and Pixel +/// Replacement values still apply to locked layers, as in the reference application; partial +/// locks and a locked group were not measured and keep applying (#14499). +fn replaces_locked_text(doc: &Document, vars: &Variables, set: &DataSet) -> bool { + set.values.iter().any(|dv| { + matches!(dv.value, VarValue::Text(_)) + && vars.def(&dv.variable).is_some_and(|def| { + matches!(def.kind, VarKind::TextReplacement) && doc.layer(def.layer).is_some_and(|l| l.locks.all && matches!(l.content, LayerContent::Text(_))) + }) + }) +} + /// Resolve a data set from `{name}` or `{index}`. fn resolve_set(s: &Session, p: &Value, cmd: &str) -> Result<(DataSet, usize)> { let vars = &s.active().ok_or(EngineError::NoDocument)?.doc.variables; @@ -569,3 +592,6 @@ mod tests; #[cfg(test)] mod import_enabled_tests; + +#[cfg(test)] +mod locked_text_layer_tests; diff --git a/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs b/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs new file mode 100644 index 0000000000..dbd0ca2995 --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/locked_text_layer_tests.rs @@ -0,0 +1,208 @@ +//! #14499: Apply Data Set refuses with the reference application's alert when a Text value would +//! replace the text of a type layer under Lock All. Nothing of the set is applied, but one history +//! state that changes nothing is still added. Visibility and Pixel Replacement values keep +//! applying to locked layers; partial locks and Data Sets as Files keep today's behaviour. + +use super::*; +use photocraft_doc::{Layer, Locks, TextLayer}; +use photocraft_geom::Rect; + +const APPLY: &str = "image.applyDataSet"; + +/// A document with a raster layer "photo", a red raster "badge" and a text layer "title", bound +/// to the variables `photo` (pixels), `showBadge`, `showTitle` (visibility) and `headline` (text). +fn session() -> (Session, LayerId, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let (photo, badge, title) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut photo = Layer::raster("photo", fmt); + photo.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0])); + let mut badge = Layer::raster("badge", fmt); + badge.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 10, 10), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() })); + let ids = (photo.id, badge.id, title.id); + doc.layers.extend([photo, badge, title]); + Ok(ids) + }) + .unwrap(); + s.execute( + "image.variables.define", + json!({"defs": [ + {"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"}, + {"name": "showBadge", "layer": badge.0, "type": "visibility"}, + {"name": "showTitle", "layer": title.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + ]}), + ) + .unwrap(); + (s, photo, badge, title) +} + +/// A blue 8x8 PNG for the `photo` variable. +fn blue_png(name: &str) -> (String, String) { + let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-{name}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let png = dir.join("blue.png"); + let mut src = Session::new(); + src.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap(); + let bytes = photocraft_io::export(&src.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; + std::fs::write(&png, bytes).unwrap(); + (dir.to_string_lossy().into_owned(), png.to_string_lossy().into_owned()) +} + +fn data_sets(s: &mut Session, sets: Value) { + s.execute("image.variables.dataSets", json!({ "dataSets": sets })).unwrap(); +} + +fn lock(s: &mut Session, id: LayerId, locks: Locks) { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks = locks; + Ok(()) + }) + .unwrap(); +} + +fn all() -> Locks { + Locks { all: true, ..Locks::default() } +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn text_of(s: &Session, id: LayerId) -> String { + match &doc(s).layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + _ => panic!("not a text layer"), + } +} + +fn visible(s: &Session, id: LayerId) -> bool { + doc(s).layer(id).unwrap().visible +} + +fn pixel(s: &Session, id: LayerId) -> Vec { + doc(s).layer(id).unwrap().surface().unwrap().pixel(32, 24) +} + +fn history(s: &Session) -> (usize, Option) { + let h = &s.active().unwrap().history; + (h.past_len(), h.entries().last().map(|e| e.to_string())) +} + +#[test] +fn a_text_value_for_a_locked_type_layer_applies_nothing_and_alerts() { + let (mut s, photo, badge, title) = session(); + let (dir, png) = blue_png("refuse"); + data_sets( + &mut s, + json!([{"name": "Zed", "values": [ + {"variable": "photo", "kind": "pixels", "value": png}, + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "showTitle", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Alpha\rLine2"}, + ]}]), + ); + lock(&mut s, title, all()); + let photo_before = pixel(&s, photo); + let (n, _) = history(&s); + + let r = s.execute(APPLY, json!({"name": "Zed"})); + assert!(matches!(&r, Err(EngineError::Other(m)) if m == DATA_SET_LAYER_LOCKED), "{r:?}"); + assert_eq!(DATA_SET_LAYER_LOCKED, "Could not apply data set because the layer is locked."); + + // Nothing of the set: the text, both visibilities and the photo's pixels stay. + assert_eq!(text_of(&s, title), "Old"); + assert!(visible(&s, title) && visible(&s, badge)); + assert_eq!(pixel(&s, photo), photo_before); + assert_eq!(doc(&s).variables.active, None, "the set did not become the applied one"); + + // One history state for the attempt, which changes nothing. + let (after, label) = history(&s); + assert_eq!(after, n + 1); + assert!(label.as_deref().is_some_and(|l| l.starts_with("Apply Data Set")), "{label:?}"); + let applied = doc(&s).clone(); + assert!(s.undo()); + assert_eq!(history(&s).0, n); + assert_eq!(text_of(&s, title), "Old"); + assert!(s.redo()); + assert_eq!(doc(&s).layers, applied.layers, "the state changes nothing"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_same_set_applies_once_the_layer_is_unlocked() { + let (mut s, _photo, badge, title) = session(); + data_sets( + &mut s, + json!([{"name": "Zed", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Alpha"}, + ]}]), + ); + lock(&mut s, title, all()); + assert!(s.execute(APPLY, json!({"name": "Zed"})).is_err()); + lock(&mut s, title, Locks::default()); + s.execute(APPLY, json!({"name": "Zed"})).unwrap(); + assert_eq!(text_of(&s, title), "Alpha"); + assert!(!visible(&s, badge)); + assert_eq!(doc(&s).variables.active, Some(0)); +} + +#[test] +fn visibility_values_still_apply_to_locked_layers() { + let (mut s, _photo, badge, title) = session(); + data_sets( + &mut s, + json!([{"name": "Hide", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "showTitle", "kind": "visibility", "value": false}, + ]}]), + ); + lock(&mut s, badge, all()); + lock(&mut s, title, all()); + s.execute(APPLY, json!({"name": "Hide"})).unwrap(); + assert!(!visible(&s, badge) && !visible(&s, title)); +} + +#[test] +fn pixel_replacement_still_applies_to_a_locked_pixel_layer() { + let (mut s, photo, _badge, _title) = session(); + let (dir, png) = blue_png("pixels"); + data_sets(&mut s, json!([{"name": "Blue", "values": [{"variable": "photo", "kind": "pixels", "value": png}]}])); + lock(&mut s, photo, all()); + s.execute(APPLY, json!({"name": "Blue"})).unwrap(); + assert_eq!(pixel(&s, photo), vec![0.0, 0.0, 1.0, 1.0]); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn partial_locks_keep_applying_text() { + let partial = [ + Locks { transparency: true, ..Locks::default() }, + Locks { pixels: true, ..Locks::default() }, + Locks { position: true, ..Locks::default() }, + Locks { transparency: true, pixels: true, position: true, artboard: true, all: false }, + ]; + for locks in partial { + let (mut s, _photo, _badge, title) = session(); + data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}])); + lock(&mut s, title, locks); + s.execute(APPLY, json!({"name": "T"})).unwrap_or_else(|e| panic!("{locks:?}: {e}")); + assert_eq!(text_of(&s, title), "New", "{locks:?}"); + } +} + +#[test] +fn data_sets_as_files_keeps_exporting_a_locked_type_layer() { + let (mut s, _photo, _badge, title) = session(); + data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}])); + lock(&mut s, title, all()); + let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-export", std::process::id())); + let out = s.execute("file.export.dataSetsAsFiles", json!({"dir": dir.to_string_lossy(), "format": "png"})).unwrap(); + assert_eq!(out["files"].as_array().map(Vec::len), Some(1), "{out}"); + assert_eq!(text_of(&s, title), "Old", "the export leaves the document alone"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef4eae9be2..8c770cd9b1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,7 +45,7 @@ pub mod select_mask_edits; pub mod shell_commands; pub mod shortcut_sets; pub mod snap; -pub use variables_cmds::{export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{DATA_SET_LAYER_LOCKED, export_data_sets_with, import_data_sets_text}; pub use video_cmds::render_video_with; use std::sync::Arc; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 428aa6a1dc..e35eda5b19 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -319,3 +319,6 @@ impl eframe::App for PhotocraftApp { #[cfg(test)] mod clipboard_tests; + +#[cfg(test)] +mod apply_data_set_alert_tests; diff --git a/crates/ui-egui/src/app/apply_data_set_alert_tests.rs b/crates/ui-egui/src/app/apply_data_set_alert_tests.rs new file mode 100644 index 0000000000..acf609fec1 --- /dev/null +++ b/crates/ui-egui/src/app/apply_data_set_alert_tests.rs @@ -0,0 +1,43 @@ +//! #14499: Apply Data Set on a type layer under Lock All shows the reference application's alert; +//! its other refusals stay status-bar messages. + +use super::*; +use serde_json::json; + +const LOCKED: &str = "Could not apply data set because the layer is locked."; + +/// An app with a type layer bound to a `headline` text variable and one data set `Zed` for it, +/// the layer under Lock All when `locked`. +fn app(locked: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let id = app.session.execute("type.create", json!({"x": 4, "y": 30, "text": "Old", "size": 12})).unwrap()["layer"].clone(); + app.session.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": id, "type": "textReplacement"}]})).unwrap(); + app.session + .execute("image.variables.dataSets", json!({"dataSets": [{"name": "Zed", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}]})) + .unwrap(); + if locked { + app.session.execute("layer.lockLayers", json!({"all": true})).unwrap(); + } + app.sync_views(); + app +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == state::DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(String::from)).collect() +} + +#[test] +fn a_locked_type_layer_refuses_with_an_alert() { + let mut app = app(true); + assert_eq!(app.run("image.applyDataSet", json!({"name": "Zed"})), Err(LOCKED.to_string())); + assert_eq!(alerts(&app), [LOCKED]); +} + +#[test] +fn other_refusals_and_an_unlocked_layer_show_no_alert() { + let mut app = app(false); + assert!(app.run("image.applyDataSet", json!({"name": "Missing"})).is_err()); + app.run("image.applyDataSet", json!({"name": "Zed"})).unwrap(); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1aa81115d4..fe7281c182 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -213,6 +213,11 @@ impl PhotocraftApp { Err(e) => { self.ui.status = e.clone(); self.ui.status_error = true; + if id == "image.applyDataSet" && e == photocraft_engine::DATA_SET_LAYER_LOCKED { + // The reference application refuses a locked type layer with an alert (#14499). + let message = json!({"message": tl!(photocraft_engine::DATA_SET_LAYER_LOCKED)}); + self.ui.open_dialog(state::DialogKind::Error, message.as_object().cloned().unwrap_or_default()); + } } } if suppress_events { From af15d2769973a1200f851df7405c323589f2ff31 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 16:14:38 +0100 Subject: [PATCH 16/38] Apply Image: Preserve Transparency blends fully and keeps the alpha (#14473) With Preserve Transparency on, a semi-transparent pixel took only part of the blend: the weight and the blend were both scaled by the layer's alpha. The colour now moves to the full blend result (scaled by opacity, mask and selection) and the alpha stays the layer's; transparent pixels stay as they are. Co-Authored-By: Claude Opus 5.5 --- .../apply_image_preserve_tests.rs | 104 ++++++++++++++++++ crates/engine/src/cmd/channel_cmds/calc.rs | 25 +++-- 2 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs new file mode 100644 index 0000000000..a7cf9a7f96 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_preserve_tests.rs @@ -0,0 +1,104 @@ +//! #14473: Apply Image with Preserve Transparency gives a semi-transparent pixel the full blend +//! result and keeps its alpha, as the reference application does. + +use crate::Session; +use serde_json::{Value, json}; + +/// Target "target" (document 0): white Background, layer "Top" transparent except a 0/255/0 +/// square at alpha 128 over (10,4)-(19,13). Source "source" (document 1): 128/128/128. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "target"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + s.set_active(0); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 4, "width": 10, "height": 10, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00", "opacity": 50})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) +} + +fn apply(s: &mut Session, extra: Value) { + let mut p = json!({"source": {"document": 1, "layer": "merged", "channel": "composite"}}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("image.applyImage", p).unwrap(); +} + +/// Checks RGBA in 0..=255 levels, one level of slack (the fill's 50% alpha is 127.5). +fn assert_rgba(got: &[f32], want: [f32; 4], what: &str) { + let got: Vec = got.iter().map(|v| v * 255.0).collect(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.01), "{what}: {got:?}, want {want:?}"); +} + +const GRAY: f32 = 128.0; +const HALF: f32 = 127.5; + +#[test] +fn normal_with_preserve_transparency_takes_the_source_and_keeps_alpha() { + for depth in [8, 16, 32] { + let mut s = session(depth); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, HALF], &format!("depth {depth}: green pixel")); + assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel")); + } +} + +#[test] +fn multiply_with_preserve_transparency_blends_fully_and_keeps_alpha() { + for depth in [8, 16, 32] { + let mut s = session(depth); + apply(&mut s, json!({"blending": "multiply", "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [0.0, GRAY, 0.0, HALF], &format!("depth {depth}: green pixel")); + assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel")); + } +} + +#[test] +fn opacity_and_selection_still_scale_the_preserved_blend() { + let mut s = session(8); + // 50% Normal: the colour moves half way to the source, the alpha stays. + apply(&mut s, json!({"blending": "normal", "opacity": 50, "preserveTransparency": true})); + assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "opacity 50"); + s.undo(); + // Outside the selection nothing changes. + s.execute("select.rect", json!({"x": 10, "y": 4, "width": 5, "height": 10, "mode": "replace"})).unwrap(); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true})); + assert_rgba(&px(&s, 12, 8), [GRAY, GRAY, GRAY, HALF], "inside the selection"); + assert_rgba(&px(&s, 17, 8), [0.0, 255.0, 0.0, HALF], "outside the selection"); +} + +#[test] +fn a_mask_still_scales_the_preserved_blend() { + let mut s = session(8); + // A 50% gray alpha channel as the mask halves the effect, like 50% opacity. + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + apply(&mut s, json!({"blending": "normal", "preserveTransparency": true, "mask": {"document": 0, "channel": 0}})); + assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "mask at 50%"); +} + +#[test] +fn without_preserve_transparency_the_results_stay() { + let mut s = session(8); + apply(&mut s, json!({"blending": "normal"})); + assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, 255.0], "normal, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "normal, transparent pixel"); + s.undo(); + apply(&mut s, json!({"blending": "multiply"})); + assert_rgba(&px(&s, 15, 8), [64.0, GRAY, 64.0, 255.0], "multiply, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "multiply, transparent pixel"); + s.undo(); + apply(&mut s, json!({"blending": "normal", "opacity": 50})); + assert_rgba(&px(&s, 15, 8), [85.0, 170.0, 85.0, 191.5], "normal 50%, green pixel"); + assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, HALF], "normal 50%, transparent pixel"); +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 9c1d0ea6b8..510c526237 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -4,6 +4,10 @@ use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec}; use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface}; use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel}; +#[cfg(test)] +#[path = "apply_image_preserve_tests.rs"] +mod apply_image_preserve_tests; + // --------------------------------------------------------------------------------------------- // Apply Image / Calculations @@ -66,11 +70,9 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { let mut v = surf.read_region(area); for (i, px) in v.chunks_exact_mut(n).enumerate() { let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 }; - let mut w = weight(i); - if preserve { - w *= base_a; - } - if w <= 0.0 { + let w = weight(i); + // Preserve Transparency leaves transparent pixels as they are. + if w <= 0.0 || (preserve && base_a <= 0.0) { continue; } // Painted over the layer like a brush: the blend only acts where the layer has @@ -85,8 +87,17 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { let k = if src_mode == ColorMode::Cmyk && sf.mode != ColorMode::Cmyk { src.get(3).map_or(1.0, |pl| tone(src_mode, pl[i])) } else { 1.0 }; let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] }; let base = tone(sf.mode, *b); - let blended = top + (blending.apply(base, top) - top) * base_a; - *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); + // With Preserve Transparency the colour takes the full blend and only the alpha + // stays the layer's (a pixel at 50% alpha turns fully to the source in Normal). + *b = tone( + sf.mode, + if preserve { + base + (blending.apply(base, top) - base) * w + } else { + let blended = top + (blending.apply(base, top) - top) * base_a; + (w * blended + base_a * (1.0 - w) * base) / out_a + }, + ); } if sf.alpha { px[colors] = out_a; From a4fd4343fe36b2aa478e146f67c9d4b6e572d207 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 16:35:00 +0100 Subject: [PATCH 17/38] Apply Image: a transparency-locked layer keeps its transparency (#14474) Lock Transparent Pixels now works as Preserve Transparency for a layer target, whether or not the checkbox is ticked, as in the reference application. The lock is read through the layer's effective locks, so a lock from a parent group counts too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/channel_cmds.rs | 2 + .../apply_image_lock_transparency_tests.rs | 103 ++++++++++++++++++ crates/engine/src/cmd/channel_cmds/calc.rs | 2 + 3 files changed, 107 insertions(+) create mode 100644 crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..52f0ba1f1a 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -23,6 +23,8 @@ use serde_json::{Value, json}; use crate::commands::CommandSpec; use crate::{DocState, EngineError, Result, Session}; +#[cfg(test)] +mod apply_image_lock_transparency_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs new file mode 100644 index 0000000000..a026a2a15a --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_lock_transparency_tests.rs @@ -0,0 +1,103 @@ +//! Apply Image on a layer with Lock Transparent Pixels: the lock acts as Preserve Transparency. + +use super::*; + +/// A 40 x 20 document whose layer "Top" is empty except a half-transparent green 10 x 10 square +/// at (10,5), and a second document "source" filled with 50% gray. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 5, "width": 10, "height": 10, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 50})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + s.set_active(0); + s +} + +fn layer(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + layer(s).surface().unwrap().read_region(d.doc.bounds()) +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + layer(s).surface().unwrap().pixel(x, y) +} + +fn close(a: &[f32], b: &[f32]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5) +} + +/// The layer's pixels after Apply Image with `extra` params, unlocked and with Preserve transparency. +fn preserved(depth: u32, extra: &Value) -> Vec { + let mut s = session(depth); + let mut p = json!({"source": {"document": 1}, "blending": "normal", "preserveTransparency": true}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("image.applyImage", p).unwrap(); + pixels(&s) +} + +#[test] +fn transparency_lock_acts_as_preserve_transparency() { + for depth in [8, 16, 32] { + for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] { + let want = preserved(depth, &extra); + let mut s = session(depth); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let mut p = json!({"source": {"document": 1}, "blending": "normal"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("image.applyImage", p).unwrap(); + assert!(close(&pixels(&s), &want), "{depth} bit {extra}: the lock must keep the layer's transparency"); + assert_eq!(px(&s, 30, 2), vec![0.0; 4], "{depth} bit {extra}: a transparent pixel stays transparent"); + assert!((px(&s, 15, 10)[3] - px(&session(depth), 15, 10)[3]).abs() < 1e-5, "{depth} bit {extra}: the square keeps its alpha"); + } + } +} + +#[test] +fn transparency_lock_inside_a_selection_acts_as_preserve_transparency() { + let sel = |s: &mut Session| s.execute("select.rect", json!({"x": 0, "y": 0, "width": 15, "height": 20, "mode": "replace"})).unwrap(); + let mut want = session(8); + sel(&mut want); + want.execute("image.applyImage", json!({"source": {"document": 1}, "preserveTransparency": true})).unwrap(); + let mut s = session(8); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + sel(&mut s); + s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap(); + assert!(close(&pixels(&s), &pixels(&want))); + assert_eq!(px(&s, 2, 2), vec![0.0; 4]); +} + +#[test] +fn lock_stays_on_and_one_history_step_is_added() { + let mut s = session(8); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap(); + assert!(layer(&s).locks.transparency, "the lock stays on"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one Apply Image step"); + s.undo(); + assert!(close(&pixels(&s), &pixels(&session(8))), "undo restores the layer"); +} + +#[test] +fn unlocked_layer_keeps_source_over() { + for depth in [8, 16, 32] { + let mut s = session(depth); + s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "normal"})).unwrap(); + let g = 128.0 / 255.0; + let p = px(&s, 30, 2); + assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{depth} bit: {p:?}"); + } +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 9c1d0ea6b8..2ad0a038b1 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -55,6 +55,8 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { return Ok(()); } let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + // Lock Transparent Pixels works as Preserve Transparency, ticked or not. + let preserve = preserve || doc.effective_locks(id).transparency; let fmt = doc.pixel_format(); let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; let sf = surf.format(); From e5ce74d868644dd175eb6934ff3c43b13f5554b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 17:42:42 +0100 Subject: [PATCH 18/38] Apply Image: a locked layer takes the image and keeps its transparency (#14476) A fully locked or pixel-locked layer no longer refuses Apply Image. As in the reference application, the image is applied in one Apply Image step and the layer keeps its transparency, as with Preserve transparency. A lock that comes from a group still refuses, and other commands keep refusing locked layers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/channel_cmds.rs | 3 + .../apply_image_locked_layer_tests.rs | 149 ++++++++++++++++++ crates/engine/src/cmd/channel_cmds/calc.rs | 13 +- 3 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..d2c098cd2e 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -119,6 +119,9 @@ mod targeting; mod tone_target; mod view; +#[cfg(test)] +mod apply_image_locked_layer_tests; + use calc::{apply_image, calculations}; use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; use planes::edit_mode; diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs new file mode 100644 index 0000000000..6888bb7a70 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_locked_layer_tests.rs @@ -0,0 +1,149 @@ +//! Apply Image on a fully locked or pixel-locked layer: it applies, and the layer keeps its +//! transparency as with Preserve transparency (#14476). + +use super::*; + +/// The spec's test document "target" (400 x 300): layer "Top" is empty except a 100 x 100 square +/// at (150,100) of 0/255/0 at alpha 128. Document "source" is 128/128/128 on the left half and +/// white on the right half. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "target"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.execute("select.rect", json!({"x": 150, "y": 100, "width": 100, "height": 100, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 128.0 / 255.0 * 100.0})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "source"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.set_active(0); + s +} + +fn apply() -> Value { + json!({"source": {"document": 1}, "blending": "normal", "opacity": 100}) +} + +fn layer(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + layer(s).surface().unwrap().read_region(d.doc.bounds()) +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + layer(s).surface().unwrap().pixel(x, y) +} + +fn close(a: &[f32], b: &[f32]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5) +} + +fn lock(s: &mut Session, locks: &Value) { + s.execute("layer.setProps", json!({"locks": locks})).unwrap(); +} + +const LOCKS: [&str; 2] = [r#"{"all": true}"#, r#"{"pixels": true}"#]; + +fn locks() -> impl Iterator { + LOCKS.iter().map(|l| serde_json::from_str(l).unwrap()) +} + +#[test] +fn a_locked_layer_takes_the_image_in_one_step_and_keeps_its_transparency() { + for depth in [8, 16, 32] { + for locks in locks() { + let mut s = session(depth); + lock(&mut s, &locks); + let before = px(&s, 175, 125); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.applyImage", apply()).unwrap(); + let d = s.active().unwrap(); + assert_eq!(d.history.past_len(), steps + 1, "{depth} bit {locks}: one history step"); + assert_eq!(d.history.undo_label(), Some("Apply Image"), "{depth} bit {locks}"); + assert!(!close(&px(&s, 175, 125), &before), "{depth} bit {locks}: (175,125) changes"); + assert_eq!(px(&s, 50, 50), vec![0.0; 4], "{depth} bit {locks}: (50,50) stays transparent"); + assert!((px(&s, 175, 125)[3] - before[3]).abs() < 1e-5, "{depth} bit {locks}: the square keeps its alpha"); + } + } +} + +#[test] +fn a_locked_layer_gets_the_preserve_transparency_result() { + for depth in [8, 16, 32] { + for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] { + let with = |p: Value| { + let mut p = p; + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let mut want = session(depth); + let mut p = with(apply()); + p["preserveTransparency"] = json!(true); + want.execute("image.applyImage", p).unwrap(); + for locks in locks() { + let mut s = session(depth); + lock(&mut s, &locks); + s.execute("image.applyImage", with(apply())).unwrap(); + assert!(close(&pixels(&s), &pixels(&want)), "{depth} bit {locks} {extra}"); + } + } + } +} + +#[test] +fn the_locks_stay_and_other_commands_keep_refusing() { + for locks in locks() { + let mut s = session(8); + lock(&mut s, &locks); + let set = layer(&s).locks; + s.execute("image.applyImage", apply()).unwrap(); + assert_eq!(layer(&s).locks, set, "{locks}: the lock flags are unchanged"); + let after = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + let fill = s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap_err().to_string(); + assert!(fill.contains("is locked"), "{locks}: Fill refuses: {fill}"); + let stroke = s.execute("paint.stroke", json!({"points": [[160, 110], [240, 190]], "size": 20})).unwrap_err().to_string(); + assert!(stroke.contains("is locked"), "{locks}: a brush stroke refuses: {stroke}"); + assert!(close(&pixels(&s), &after), "{locks}: nothing else painted"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{locks}: no more steps"); + s.undo(); + assert!(close(&pixels(&s), &pixels(&session(8))), "{locks}: undo restores the layer"); + } +} + +#[test] +fn a_lock_from_a_group_still_refuses() { + // Not measured in the reference application: keeps today's refusal, also when the layer is + // locked itself as well. + for own in [None, Some(json!({"pixels": true})), Some(json!({"all": true}))] { + let mut s = session(8); + let top = s.active().unwrap().active_layer.unwrap(); + if let Some(own) = &own { + lock(&mut s, own); + } + s.execute("layer.new.groupFromLayers", json!({})).unwrap(); + lock(&mut s, &json!({"all": true})); + s.set_active_layer(Some(top)); + let before = pixels(&s); + let err = s.execute("image.applyImage", apply()).unwrap_err().to_string(); + assert!(err.contains("is locked"), "{own:?}: {err}"); + assert!(close(&pixels(&s), &before), "{own:?}"); + } +} + +#[test] +fn an_unlocked_layer_keeps_source_over() { + let mut s = session(8); + s.execute("image.applyImage", apply()).unwrap(); + let p = px(&s, 50, 50); + let g = 128.0 / 255.0; + assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{p:?}"); +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 9c1d0ea6b8..23de66e2a9 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -56,7 +56,18 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { } let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; let fmt = doc.pixel_format(); - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + // A fully locked or pixel-locked layer still takes the image, as in the reference + // application, and keeps its transparency as with Preserve transparency. A lock that comes + // from a group around it still refuses, through `paint_surface`. + let own = doc.layer(id).map(|l| l.locks).unwrap_or_default(); + let groups = doc.path_of(id).map_or_else(Default::default, |p| doc.locks_at(p.get(..p.len().saturating_sub(1)).unwrap_or_default())); + let locked = (own.pixels || own.all) && !(groups.pixels || groups.all); + let preserve = preserve || locked; + let surf = if locked { + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))? + } else { + crate::commands::paint_surface(doc, id, &Value::Null)? + }; let sf = surf.format(); if sf != fmt { return Err(EngineError::Other("the target layer's format doesn't match the document".into())); From 7acd50ca9dabd88a39a0a3a305b90855c60bd0b5 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 19:04:21 +0100 Subject: [PATCH 19/38] fix(engine): Perspective Crop refuses type layers, smart objects and Bitmap images Perspective Crop rasterized type layers and smart objects and accepted Bitmap mode documents, where the reference stops with an alert and changes nothing. image.perspectiveCrop now refuses a document holding a type layer or smart object anywhere (hidden or inside a group) and a Bitmap mode document, before rasterizing or warping, so the document and its history stay untouched. The tool shows the same alert (message and OK) on the first press instead of starting a quad, and on Enter if the command refuses. Shape and fill layers are still rasterized. The alert texts have literal translation keys. --- crates/engine/src/cmd.rs | 2 + .../engine/src/cmd/perspective_crop_cmds.rs | 54 ++++- .../src/cmd/perspective_crop_refuse_tests.rs | 205 ++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 175 ++++++++++++++- 4 files changed, 422 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/cmd/perspective_crop_refuse_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 36a1081edd..30a87407d0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -139,6 +139,8 @@ pub(super) mod path_edit_cmds; pub mod pattern_cmds; pub mod pattern_fill_cmds; pub mod perspective_crop_cmds; +#[cfg(test)] +mod perspective_crop_refuse_tests; pub mod photo_cmds; pub mod pick_cmds; pub mod plugin_cmds; diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index 161fa35e70..bed7292739 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -8,12 +8,15 @@ //! Background over the background colour where the quad reaches past the image, and pixels outside //! the quad are deleted (Photoshop's Perspective Crop has no Delete Cropped Pixels option). //! -//! Type, shape, fill and smart object layers are rasterized first: a projective map has no -//! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine -//! map closest to the homography (exact when the quad is a parallelogram). +//! A document holding a type layer or a smart object anywhere, and a Bitmap mode document, are +//! refused with the tool's alerts ([`UNSUPPORTED_LAYERS_ERROR`] and [`BITMAP_MODE_ERROR`], #11799) +//! before anything is rasterized or warped, so the document stays exactly as it was. Shape and fill +//! layers are rasterized first: a projective map has no editable equivalent for them (keeping them +//! live is #11800). Vector masks, paths, notes, slices and guides follow the affine map closest to +//! the homography (exact when the quad is a parallelogram). use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; -use photocraft_color::PixelFormat; +use photocraft_color::{ColorMode, PixelFormat}; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; @@ -31,6 +34,34 @@ const MAX_COORD: f64 = 1e7; /// (#11977). const MAX_RESOLUTION: f64 = 29_999.999; +/// The reference's alert when the document holds a layer the tool can't map (#11799): an alert with +/// only an OK button on the tool's first press. The UI shows this text through `tl!` (English is +/// the catalog source); the command returns it as its error. +pub const UNSUPPORTED_LAYERS_ERROR: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; +/// The reference's alert for a Bitmap mode document (#11799), shown the same way. +pub const BITMAP_MODE_ERROR: &str = + "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// Does `doc` hold a layer the perspective crop can't map: a type layer or a smart object, anywhere +/// in it - visible or hidden, active or not, also inside a group (#11799)? The alert is about the +/// document, not the targeted layer. Shape, fill, adjustment, pixel and group layers do not refuse +/// it (measured); keeping shape and fill layers live is #11800. +pub fn has_unsupported_layers(doc: &Document) -> bool { + doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Smart(_))) +} + +/// The alert `doc` gets instead of a perspective crop, or `None` when the crop can go through +/// (#11799). The text is exactly what `image.perspectiveCrop` answers with, so the tool can refuse +/// the press with what the command would later refuse. Bitmap is checked first: converting to +/// Bitmap flattens the document (`mode_cmds`), so a Bitmap document never holds a type layer or a +/// smart object and the order is not observable. +pub fn refusal(doc: &Document) -> Option<&'static str> { + if doc.mode == ColorMode::Bitmap { + return Some(BITMAP_MODE_ERROR); + } + has_unsupported_layers(doc).then_some(UNSUPPORTED_LAYERS_ERROR) +} + fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } @@ -224,12 +255,15 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result { let res = resolution(p)?; let interp = interpolation(p)?; let d = s.active().ok_or(EngineError::NoDocument)?; + // #11799: what the reference answers with an alert, it answers before it touches anything: no + // rasterization, no warp, no history step. The tool shows the same text on the press. + if let Some(msg) = refusal(&d.doc) { + return Err(EngineError::Other(msg.into())); + } crate::image_cmds::check_resample_budget(CMD, &d.doc, w, h, "")?; - let rasterize = d - .doc - .walk() - .iter() - .any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Fill(_) | LayerContent::Smart(_))); + // A type layer or a smart object can't get here (they are refused above), so only shape and + // fill layers are ever rasterized (#11800 is about keeping those live). + let rasterize = d.doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Shape(_) | LayerContent::Fill(_))); let map = quad_to_rect(&q, f64::from(w), f64::from(h)).ok_or_else(|| bad("the corners don't define a perspective"))?; let bg = s.tools.background; // The Color Sampler points follow their pixels through the homography, which the edit's @@ -263,7 +297,7 @@ pub fn specs() -> Vec { label: "Perspective Crop", menu: &[], shortcut: None, - params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; type, shape, fill and smart object layers are rasterized)"##, + params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; shape and fill layers are rasterized; refused with the tool's alert, and nothing changes: a document holding a type layer or a smart object anywhere, hidden or inside a group included, answers "Could not use the perspective crop tool because the image contains unsupported layers types.", a Bitmap mode document "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")"##, enabled: has_doc, run: perspective_crop, journal: true, diff --git a/crates/engine/src/cmd/perspective_crop_refuse_tests.rs b/crates/engine/src/cmd/perspective_crop_refuse_tests.rs new file mode 100644 index 0000000000..03d556b7e5 --- /dev/null +++ b/crates/engine/src/cmd/perspective_crop_refuse_tests.rs @@ -0,0 +1,205 @@ +//! #11799: the Perspective Crop refuses a document that holds a type layer or a smart object, and +//! a Bitmap mode document, with the reference application's alerts, before anything is rasterized +//! or warped. Nothing about the document changes on a refusal: no history step, no warped pixels, +//! and the other layers keep their kind. +//! +//! Measured (issue #11799): the alert fires for the *document*, not the active layer, so a type +//! layer or a smart object counts wherever it sits - visible or hidden, active or not, also inside +//! a group. A Levels adjustment layer, a Color Fill layer, a rectangle shape layer, a group, a +//! mask, a style, a locked and a hidden layer do not trigger it: those documents still crop. +//! Keeping shape and fill layers live instead of rasterizing them is #11800, so this file pins +//! only that they still crop. + +use photocraft_doc::{Color, ColorMode, Document, Fill, Group, Layer, LayerContent, SampleType, ShapeLayer, Size, SmartObject, SmartSource, TextLayer}; +use photocraft_geom::{Affine, Rect}; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::Session; + +/// What the reference shows (an alert with one OK button) for a type layer or a smart object. +const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; +/// What it shows for a Bitmap mode document. +const NOT_BITMAP: &str = "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +const CMD: &str = "image.perspectiveCrop"; +/// A skewed quad on the 160 x 120 fixture, and the upright output it is mapped onto. +const QUAD: [[f64; 2]; 4] = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; + +fn crop_params() -> Value { + json!({"corners": QUAD, "width": 100, "height": 80}) +} + +fn rgb_format() -> photocraft_color::PixelFormat { + Document::with_background("f", Size::new(2, 2), ColorMode::Rgb, SampleType::U8, Color::WHITE).pixel_format() +} + +/// 160 x 120 RGB/8 with a white Background and `extra` on top, in a fresh session: nothing has +/// been edited yet, so any history step the crop records shows up as `past_len() > 0`. +fn session(extra: Vec) -> Session { + let mut doc = Document::with_background("refuse", Size::new(160, 120), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for l in extra { + doc.insert_above(None, l); + } + let mut s = Session::new(); + s.add_document(doc, None); + s +} + +/// A type layer reading "Hello", visible or hidden. +fn type_layer(visible: bool) -> Layer { + let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() })); + l.visible = visible; + l +} + +/// A smart object with a red cache and a linked source, visible or hidden. +fn smart_layer(visible: bool) -> Layer { + let mut cache = Surface::new(rgb_format()); + cache.fill_rect(Rect::from_xywh(20, 20, 60, 40), &[1.0, 0.0, 0.0, 1.0]); + let mut l = Layer::new("Photo", LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, Affine::IDENTITY, Some(cache)))); + l.visible = visible; + l +} + +/// A red rectangle shape layer: what the crop rasterizes today alongside a type layer, so a +/// refusal that comes before the rasterize leaves it a shape. +fn shape_layer() -> Layer { + let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0); + Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.8, 0.2, 0.1))), ..Default::default() })) +} + +/// A group holding `children`, visible or hidden. +fn group_of(children: Vec, visible: bool) -> Layer { + let mut l = Layer::new("Group 1", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); + l.visible = visible; + l +} + +/// Every layer as a refusal must leave it: name, kind, visibility and, for a type layer, its text. +type LayerRecord = (String, &'static str, bool, String); + +/// What a refusal must leave alone: the layers, the canvas size, the document revision, the steps. +type Snapshot = (Vec, Size, u64, usize); + +/// Every layer in `doc`, bottom to top. A refusal leaves this list exactly as it was, so it is both +/// the layer-kind and the text check. +fn fingerprint(doc: &Document) -> Vec { + doc.walk() + .iter() + .map(|(_, _, l)| { + let text = match &l.content { + LayerContent::Text(t) => t.text.clone(), + _ => String::new(), + }; + (l.name.clone(), l.content.kind_name(), l.visible, text) + }) + .collect() +} + +/// What a refusal must leave alone. +fn snapshot(s: &Session) -> Snapshot { + let d = s.active().unwrap(); + (fingerprint(&d.doc), d.doc.size, d.revision, d.history.past_len()) +} + +/// The document holds a type layer or a smart object, wherever it sits; every other layer keeps +/// its kind, because the refusal comes before `rasterize_all`. +fn assert_refused(s: &mut Session, want: &str, case: &str) { + let before = snapshot(s); + let err = s.execute(CMD, crop_params()).unwrap_err().to_string(); + assert_eq!(err, want, "{case}"); + let d = s.active().unwrap(); + assert_eq!(fingerprint(&d.doc), before.0, "{case}: layers unchanged"); + assert_eq!(d.doc.size, before.1, "{case}: canvas unchanged"); + assert_eq!(d.revision, before.2, "{case}: document unchanged"); + assert_eq!(d.history.past_len(), 0, "{case}: no history step"); +} + +/// A type layer anywhere in the document - visible, hidden, or inside a group - is the reference's +/// unsupported-layers alert, not a rasterization (#11799). +#[test] +fn a_type_layer_anywhere_refuses_the_perspective_crop() { + for (case, extra) in [ + ("visible", vec![type_layer(true), shape_layer()]), + ("hidden", vec![type_layer(false), shape_layer()]), + ("in a group", vec![group_of(vec![type_layer(true), shape_layer()], true), shape_layer()]), + ("in a hidden group", vec![group_of(vec![type_layer(true)], false), shape_layer()]), + ] { + let mut s = session(extra); + assert_refused(&mut s, UNSUPPORTED, &format!("{case} type layer")); + let d = s.active().unwrap(); + let text: Vec<&str> = d + .doc + .walk() + .iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(t) => Some(t.text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(text, ["Hello"], "{case}: the type layer is still a type layer with its text"); + assert!(d.doc.walk().iter().any(|(_, _, l)| l.content.kind_name() == "Shape"), "{case}: nothing was rasterized"); + } +} + +/// The same for a smart object: visible, hidden, or inside a group. +#[test] +fn a_smart_object_anywhere_refuses_the_perspective_crop() { + for (case, extra) in [ + ("visible", vec![smart_layer(true), shape_layer()]), + ("hidden", vec![smart_layer(false), shape_layer()]), + ("in a group", vec![group_of(vec![smart_layer(false)], true), shape_layer()]), + ] { + let mut s = session(extra); + assert_refused(&mut s, UNSUPPORTED, &format!("{case} smart object")); + } +} + +/// Both at once is still one refusal with the same message, and still changes nothing. +#[test] +fn a_type_layer_and_a_smart_object_refuse_once() { + let mut s = session(vec![type_layer(false), smart_layer(true), shape_layer()]); + assert_refused(&mut s, UNSUPPORTED, "type layer and smart object"); +} + +/// A Bitmap mode document is the reference's Bitmap alert (#11799). +#[test] +fn a_bitmap_document_refuses_the_perspective_crop() { + let doc = Document::with_background("bitmap", Size::new(160, 120), ColorMode::Bitmap, SampleType::U8, Color::WHITE); + let mut s = Session::new(); + s.add_document(doc, None); + assert_refused(&mut s, NOT_BITMAP, "Bitmap document"); +} + +/// The measured rows that keep working: a document of only pixel, adjustment, Color Fill, shape +/// and group layers still crops, in one undo step (#11799). Whether the shape and the fill stay +/// live is #11800, so this pins the crop, not their kind. +#[test] +fn pixel_adjustment_fill_shape_and_group_layers_still_crop() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 500})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#3366cc"})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [200, 300, 150, 100], "fill": "#cc3333"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "G"})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let r = s.execute(CMD, json!({"corners": [[100.0, 50.0], [700.0, 60.0], [690.0, 450.0], [110.0, 440.0]], "width": 600, "height": 400})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(600), Some(400))); + assert_eq!(s.active().unwrap().doc.size, Size::new(600, 400), "the crop went through"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one undo step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.size, Size::new(800, 500), "one undo restores it"); +} + +/// Only Bitmap refuses on the mode: RGB, Grayscale and CMYK documents are unaffected (#11799). +#[test] +fn rgb_grayscale_and_cmyk_documents_are_not_refused() { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] { + let doc = Document::with_background("m", Size::new(160, 120), mode, SampleType::U8, Color::WHITE); + let mut s = Session::new(); + s.add_document(doc, None); + s.execute(CMD, crop_params()).unwrap(); + assert_eq!(s.active().unwrap().doc.size, Size::new(100, 80), "{mode:?} cropped"); + } +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index aad099ee2c..4c30f7defc 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -10,17 +10,21 @@ //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the //! quad shows in perspective. Esc (or ⊘) cancels. +//! - a document holding a type layer or a smart object, and a Bitmap document, refuse the press +//! with the reference's alert (message + OK) and start nothing: no box, no corner, no session +//! (#11799). `image.perspectiveCrop` answers with the same text, so ↵ is refused the same way. //! //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; +use photocraft_engine::perspective_crop_cmds::{BITMAP_MODE_ERROR, UNSUPPORTED_LAYERS_ERROR}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; use crate::PhotocraftApp; use crate::canvas::{ToolEvent, ViewXform}; -use crate::state::Tool; +use crate::state::{DialogKind, Tool}; /// A drag shorter than this (screen px) is a click: it places a corner. const CLICK_PX: f64 = 3.0; @@ -91,6 +95,36 @@ pub(crate) fn cancel_stale(app: &mut PhotocraftApp) { app.pcrop.doc = doc; } +/// The alert this document gets instead of a perspective crop (#11799): `Some(text)` means the tool +/// refuses the press. The check is the engine's, so the press and `image.perspectiveCrop` can never +/// disagree about what is cropped. +fn document_alert(app: &PhotocraftApp) -> Option<&'static str> { + app.session.active().and_then(|st| photocraft_engine::perspective_crop_cmds::refusal(&st.doc)) +} + +/// The alert as `image.perspectiveCrop`'s error text (#11799), so ↵ shows what the press shows +/// rather than only the status bar. +fn error_alert(error: &str) -> Option<&'static str> { + [UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR].into_iter().find(|text| *text == error) +} + +/// Opens the alert: the message and an OK button, as a refused Move does (`move_lock::prompt`). +fn refuse(app: &mut PhotocraftApp, message: &str) { + app.ui.open_dialog(DialogKind::Error, json!({"message": alert_text(message)}).as_object().cloned().unwrap_or_default()); +} + +/// The alert in the UI language. Literal keys, so `cargo xtask i18n-coverage` lists both alerts for +/// the translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts. +fn alert_text(message: &str) -> &str { + match message { + UNSUPPORTED_LAYERS_ERROR => tl!("Could not use the perspective crop tool because the image contains unsupported layers types."), + BITMAP_MODE_ERROR => { + tl!("Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).") + } + other => tl!(other), + } +} + /// Four points in quad order: clockwise on screen around their centre, starting top-left. pub fn ordered(points: [[f64; 2]; 4]) -> [[f64; 2]; 4] { let c = [points.iter().map(|p| p[0]).sum::() / 4.0, points.iter().map(|p| p[1]).sum::() / 4.0]; @@ -188,6 +222,15 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.pcrop.hover = None; return true; } + // A document the tool can't crop (#11799): the press shows the reference's alert and starts + // nothing - no box, no clicked corner, no drag - and the document is left as it is. Only the + // press answers: the drag that follows it has nothing to move. + if matches!(ev, ToolEvent::Down { .. }) + && let Some(message) = document_alert(app) + { + refuse(app, message); + return true; + } cancel_stale(app); match ev { ToolEvent::Down { .. } => { @@ -308,8 +351,15 @@ pub fn commit(app: &mut PhotocraftApp) { let Some(q) = app.ui.perspective_crop else { return }; let mut p = json!({"corners": q}); size_params(app, &mut p); - if app.run("image.perspectiveCrop", p).is_ok() { - cancel(app); + match app.run("image.perspectiveCrop", p) { + Ok(_) => cancel(app), + // A document the crop refuses (#11799) gets the alert the press gets, not just the status + // bar; the quad stays for fixing or cancelling after the document can be cropped. + Err(e) => { + if let Some(message) = error_alert(&e) { + refuse(app, message); + } + } } } @@ -562,7 +612,124 @@ mod perspective_crop_mirrored_tests; #[cfg(test)] mod tests { use super::*; - use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + use photocraft_doc::{Color, ColorMode, Document, Layer, LayerContent, SampleType, ShapeLayer, Size, SmartObject, SmartSource, TextLayer}; + + /// #11799: a document holding a type layer or a smart object (hidden or not), and a Bitmap + /// document, refuse the press with the reference's alert - the message and an OK button - and + /// start nothing: no quad, no clicked corner, no drag, and the document is untouched. + #[test] + fn a_press_on_a_refused_document_shows_the_alert_and_starts_nothing() { + /// The reference's two alerts, as measured. + const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types."; + const NOT_BITMAP: &str = + "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + + /// A 200 x 150 RGB document with `extra` on the Background. + fn doc(mode: ColorMode, extra: Option) -> Document { + let mut d = Document::with_background("p", Size::new(200, 150), mode, SampleType::U8, Color::WHITE); + if let Some(l) = extra { + d.insert_above(None, l); + } + d + } + + fn text(visible: bool) -> Layer { + let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() })); + l.visible = visible; + l + } + + fn smart(visible: bool) -> Layer { + let mut l = Layer::new( + "Photo", + LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, photocraft_geom::Affine::IDENTITY, None)), + ); + l.visible = visible; + l + } + + let cases = [ + ("visible type layer", doc(ColorMode::Rgb, Some(text(true))), UNSUPPORTED), + ("hidden type layer", doc(ColorMode::Rgb, Some(text(false))), UNSUPPORTED), + ("visible smart object", doc(ColorMode::Rgb, Some(smart(true))), UNSUPPORTED), + ("hidden smart object", doc(ColorMode::Rgb, Some(smart(false))), UNSUPPORTED), + ("Bitmap", doc(ColorMode::Bitmap, None), NOT_BITMAP), + ]; + for (case, document, want) in cases { + let mut s = photocraft_engine::Session::new(); + s.add_document(document, None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::PerspectiveCrop; + let st = app.session.active().unwrap(); + let (size, layer_kinds, steps) = (st.doc.size, kinds(&st.doc), st.history.past_len()); + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE), "{case}"); + // The first press-and-drag: one alert with the reference's text (`DialogKind::Error` + // shows the message and an OK button), and no box. + ev(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 120.0, y: 90.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 120.0, y: 90.0 }); + assert_eq!(alerts(&app), [want], "{case}: the alert, with its text"); + assert!(app.ui.perspective_crop.is_none(), "{case}: no quad"); + assert!(app.pcrop.drag.is_none(), "{case}: no drag"); + // OK closes the alert: `DialogKind::Error` answers with nothing but closing. + let open: Vec = app.ui.dialogs.iter().map(|d| d.id).collect(); + for id in open { + app.ui.close_dialog(id); + } + // A press after that is refused the same way: it places no corner. + ev(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }); + assert_eq!(alerts(&app), [want], "{case}: the click is refused too"); + assert!(app.pcrop.clicks.is_empty(), "{case}: no clicked corner"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.size, size, "{case}: canvas untouched"); + assert_eq!(kinds(&st.doc), layer_kinds, "{case}: layers untouched"); + assert_eq!(st.history.past_len(), steps, "{case}: no history step"); + } + } + + /// Every layer's kind, bottom to top. + fn kinds(doc: &Document) -> Vec<&'static str> { + doc.walk().iter().map(|(_, _, l)| l.content.kind_name()).collect() + } + + /// #11874: the literal translation keys are the engine's alert texts, so an English UI shows + /// exactly what `image.perspectiveCrop` answers and the catalogs translate the right string. + #[test] + fn alert_keys_match_the_engine_texts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for text in [UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR] { + assert_eq!(alert_text(text), text); + } + }); + } + + /// The message of every open error dialog, in the order they were opened. + fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() + } + + /// #11799: a document of only pixel, shape and fill layers takes the press as before, and a + /// commit on such a document keeps working (the refusal is about type and smart object layers + /// and the Bitmap mode alone). + #[test] + fn a_press_on_a_cropable_document_still_draws_the_quad() { + let mut d = Document::with_background("p", Size::new(200, 150), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0); + d.insert_above(None, Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, ..Default::default() }))); + let mut s = photocraft_engine::Session::new(); + s.add_document(d, None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::PerspectiveCrop; + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE)); + ev(&mut app, ToolEvent::Down { x: 20.0, y: 10.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 120.0, y: 90.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 120.0, y: 90.0 }); + assert_eq!(app.ui.perspective_crop, Some([[20.0, 10.0], [120.0, 10.0], [120.0, 90.0], [20.0, 90.0]])); + assert!(app.ui.dialogs.iter().all(|d| d.kind != DialogKind::Error), "no alert"); + commit(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 80), "the quad's mean side lengths"); + } /// A straight drag (no width or no height) leaves no zero-area box that only Esc could clear, /// and a plain click still counts as a corner click. From bdd484a35a818dc508626ad1a6c5e82b5c8fe59b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 19:09:11 -0600 Subject: [PATCH 20/38] Brush smoothing: lag and pulled string as measured in the reference (#11888) Exponential smoothing's pull per 16 ms step comes from a time constant fitted to the reference's lag (tau = 314 ms x amount^0.864: a 200 px drag in 40 moves 10 ms apart ends about 19 px short at 10 % and 76 px at 50 %). The pulled string is 300 px at 100 % (150 px at 50 %), and in Pulled String Mode Catch-up on Stroke End no longer jumps the brush to the release point. Existing tests that pinned the old lag and string length are updated. --- crates/engine/src/cmd/retouch_cmds/tests.rs | 5 ++ crates/paint/src/brush_tests.rs | 37 ++++++------ crates/paint/src/dynamics.rs | 29 ++++++++-- crates/paint/src/smoothing_lag_tests.rs | 63 +++++++++++++++++++++ 4 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 crates/paint/src/smoothing_lag_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index c6918ef1db..0c3bb526ba 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2179,6 +2179,11 @@ live_coordinate_regression!( fn live_dodge_matches_the_commit_across_cells() { let mut s = session(200, 90, 32, "rgb"); paint_layer(&mut s, texture); + // About the cells' summation order, not smoothing: the live stroke is compared before its + // release, and with the brush's default smoothing lag (#11888) the commit's end catch-up runs + // from the trailing brush along most of the last segment. Live against commit with smoothing + // is the hand-off tests' "smoothing" case. + s.tools.brush.smoothing.enabled = false; let all = [[10.0, 40.0], [100.0, 60.0], [180.0, 40.0], [60.0, 30.0], [150.0, 70.0]]; let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::>(); let opts = |p: &[[f64; 2]]| json!({"points": p, "size": 40, "hardness": 30, "exposure": 60, "range": "midtones"}); diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index da5f546b0f..5cd38adf09 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -882,26 +882,27 @@ fn smoothing_modes() { // Pulled string: jitter smaller than the string moves nothing; the brush trails by the string. let ps = Smoothing { amount: 0.2, pulled_string: true, catch_up_on_end: false, ..Default::default() }; let jitter: Vec = (0..20).map(|i| StrokePoint::new(if i % 2 == 0 { 0.0 } else { 5.0 }, 0.0, 1.0)).collect(); - assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 20 px string: no motion"); + assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 60 px string: no motion"); let far = smooth_points(&ps, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); - assert!((far.last().unwrap().x - 80.0).abs() < 1e-4); + assert!((far.last().unwrap().x - 40.0).abs() < 1e-4); // Adjust for zoom: at 200 % zoom the string is half as long in image pixels. let far = smooth_points(&ps, 2.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); - assert!((far.last().unwrap().x - 90.0).abs() < 1e-4); + assert!((far.last().unwrap().x - 70.0).abs() < 1e-4); // Stroke catch-up: a pause (timestamps) lets the brush converge on the pointer. let mut a = StrokePoint::new(0.0, 0.0, 1.0); a.time = 0.0; let b = StrokePoint { x: 100.0, time: 16.0, ..a }; - let c = StrokePoint { time: 500.0, ..b }; + let c = StrokePoint { time: 1000.0, ..b }; + let d = StrokePoint { time: 2000.0, ..b }; let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: true, catch_up_on_end: false, ..Default::default() }, 1.0); let mut out = Vec::new(); - for p in [a, b, c] { + for p in [a, b, c, d] { s.push(p, &mut out); } assert!(out.last().unwrap().x > 99.0, "{}", out.last().unwrap().x); let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: false, catch_up_on_end: false, ..Default::default() }, 1.0); let mut out = Vec::new(); - for p in [a, b, c] { + for p in [a, b, c, d] { s.push(p, &mut out); } assert!(out.last().unwrap().x < 70.0, "{}", out.last().unwrap().x); @@ -933,7 +934,10 @@ fn disabled_smoothing_keeps_its_settings_and_paints_unsmoothed_at_every_depth() let mut back: Smoothing = serde_json::from_value(serde_json::to_value(&smoothing).unwrap()).unwrap(); assert_eq!(back, smoothing); back.enabled = true; - assert!(smooth_points(&back, 1.0, &pts).iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y)); + // Re-enabled, it smooths again: different points, or fewer (a pulled string that hasn't + // been pulled taut leaves the brush where it started, #11888). + let again = smooth_points(&back, 1.0, &pts); + assert!(again.len() != pts.len() || again.iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y)); } // Existing brush JSON has no switch and must retain its old smoothing behavior. let legacy: Smoothing = serde_json::from_str(r#"{"amount":0.8,"pulledString":true}"#).unwrap(); @@ -975,8 +979,9 @@ fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() { out.last().map_or(0.0, |p| p.x) }; let (fast, slow) = (run(1.0), run(16.0)); - // Two 16 ms steps of a 0.2 pull: 1 - 0.8² = 36 % of the way. - assert!((slow - 36.0).abs() < 1e-4, "{slow}"); + // Two 16 ms steps of one step's pull `a`: 1 - (1 - a)² of the way. + let a = crate::dynamics::smoothing_pull(0.8); + assert!((slow - 100.0 * (1.0 - (1.0 - a).powi(2))).abs() < 1e-4, "{slow}"); assert!((fast - slow).abs() < 1e-4, "1000 Hz {fast} vs 60 Hz {slow}"); // Without timestamps each point is one step, as before. let mut s = Smoother::new(&cfg, 1.0); @@ -984,7 +989,7 @@ fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() { for x in [0.0, 100.0] { s.push(StrokePoint::new(x, 0.0, 1.0), &mut out); } - assert!((out.last().map_or(0.0, |p| p.x) - 20.0).abs() < 1e-4); + assert!((out.last().map_or(0.0, |p| p.x) - 100.0 * a).abs() < 1e-4); } #[test] @@ -1024,13 +1029,13 @@ fn a_pulled_string_brush_takes_the_pose_along_the_string() { let a = StrokePoint { rotation: 350.0, ..StrokePoint::new(0.0, 0.0, 1.0) }; let b = StrokePoint { rotation: 10.0, tilt_x: 40.0, ..StrokePoint::new(100.0, 0.0, 0.0) }; let out = smooth_points(&ps, 1.0, &[a, b]); - // The 20 px string leaves the brush 80 % of the way to the pointer. + // The 60 px string leaves the brush 40 % of the way to the pointer. let p = out.last().unwrap(); - assert!((p.x - 80.0).abs() < 1e-4, "{}", p.x); - assert!((p.pressure - 0.2).abs() < 1e-4, "{}", p.pressure); - assert!((p.tilt_x - 32.0).abs() < 1e-3, "{}", p.tilt_x); - // Rotation the short way round: 350° + 80 % of 20°. - assert!((p.rotation - 6.0).abs() < 1e-3, "{}", p.rotation); + assert!((p.x - 40.0).abs() < 1e-4, "{}", p.x); + assert!((p.pressure - 0.6).abs() < 1e-4, "{}", p.pressure); + assert!((p.tilt_x - 16.0).abs() < 1e-3, "{}", p.tilt_x); + // Rotation the short way round: 350° + 40 % of 20°. + assert!((p.rotation - 358.0).abs() < 1e-3, "{}", p.rotation); } #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index e9987cc899..f8281dab0d 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -10,10 +10,24 @@ use crate::brush::{BrushSettings, Control, Dynamic, Smoothing}; use crate::rng::{rand_signed, rand01, stream}; use crate::{Dab, StrokePoint}; -/// Maximum pulled-string length at 100 % smoothing, in screen pixels. -pub const MAX_STRING_PX: f64 = 100.0; +/// Maximum pulled-string length at 100 % smoothing, in screen pixels: 150 px at 50 %, as measured +/// in the reference application (#11888). +pub const MAX_STRING_PX: f64 = 300.0; /// Stroke time over which exponential smoothing moves its fraction of the way to the pointer. pub const SMOOTHING_STEP_MS: f64 = 16.0; +/// Exponential smoothing's time constant at 100 % smoothing, in ms, and the power of the amount +/// it scales by: `tau = SMOOTHING_TAU_MS · amount^SMOOTHING_TAU_EXP`. Fitted to the reference +/// application's lag (#11888): a 200 px drag in 40 moves 10 ms apart ends 19 px short at 10 % +/// (tau 43 ms) and 78 px short at 50 % (tau 173 ms). +pub const SMOOTHING_TAU_MS: f64 = 314.0; +pub const SMOOTHING_TAU_EXP: f64 = 0.864; + +/// The fraction of the way to the pointer exponential smoothing moves in one +/// [`SMOOTHING_STEP_MS`] at `amount` (0..1, above 0). +pub fn smoothing_pull(amount: f64) -> f64 { + let tau = SMOOTHING_TAU_MS * amount.clamp(0.0, 1.0).powf(SMOOTHING_TAU_EXP); + if tau > 0.0 { 1.0 - (-SMOOTHING_STEP_MS / tau).exp() } else { 1.0 } +} /// With Spacing unchecked, one dab per this many milliseconds of stroke time, so faster strokes /// space their dabs further apart (Photoshop: "the speed of the cursor determines the spacing"). @@ -150,7 +164,7 @@ impl Smoother { // Exponential: every SMOOTHING_STEP_MS of stroke time moves `a` of the way towards the // pointer, so the feel doesn't depend on how often the device reports. Input without // timestamps takes one step per point. - let a = 1.0 - amount.min(0.95); + let a = smoothing_pull(amount); let dt = prev_input.map_or(0.0, |q| p.time - q.time); let still = prev_input.is_some_and(|q| q.x == p.x && q.y == p.y); if still && !self.cfg.catch_up { @@ -191,9 +205,10 @@ impl Smoother { } /// End of stroke: with Catch-Up On Stroke End the brush finishes at the last pointer position - /// and pose. + /// and pose. Not in Pulled String Mode: the brush stays the string's length behind the pointer + /// (measured, #11888). pub fn finish(&mut self, out: &mut Vec) { - if !self.active() || !self.cfg.catch_up_on_end { + if !self.active() || !self.cfg.catch_up_on_end || self.cfg.pulled_string { return; } if let (Some(pos), Some(last)) = (self.pos, self.last_input) @@ -1082,3 +1097,7 @@ mod streaming_tests { assert_eq!(dabs.len(), 2_000_001); } } + +#[cfg(test)] +#[path = "smoothing_lag_tests.rs"] +mod smoothing_lag_tests; diff --git a/crates/paint/src/smoothing_lag_tests.rs b/crates/paint/src/smoothing_lag_tests.rs new file mode 100644 index 0000000000..27ae2574be --- /dev/null +++ b/crates/paint/src/smoothing_lag_tests.rs @@ -0,0 +1,63 @@ +//! #11888: Smoothing trails the pointer as far as in the reference application, and Pulled String +//! Mode stops the string's length short of the release point, with or without Catch-up on Stroke +//! End. The drag is the issue's: (100, 199) to (300, 199) in 40 moves 10 ms apart, then released. + +use super::*; +use crate::brush::Smoothing; + +fn drag() -> Vec { + (0..=40).map(|i| StrokePoint { time: f64::from(i) * 10.0, ..StrokePoint::new(100.0 + f64::from(i) * 5.0, 199.0, 1.0) }).collect() +} + +/// How far short of the release point (300) the smoothed stroke ends. +fn short(cfg: &Smoothing) -> f64 { + let out = smooth_points(cfg, 1.0, &drag()); + 300.0 - out.last().map_or(f64::NAN, |p| p.x) +} + +fn within(got: f64, want: f64, tolerance: f64) -> bool { + (got - want).abs() <= want * tolerance +} + +#[test] +fn ten_and_fifty_percent_lag_as_measured() { + let off_end = Smoothing { catch_up_on_end: false, ..Default::default() }; + let ten = short(&Smoothing { amount: 0.1, ..off_end.clone() }); + let fifty = short(&Smoothing { amount: 0.5, ..off_end }); + assert!(within(ten, 19.0, 0.25), "10 %: {ten} px short (reference 19)"); + assert!(within(fifty, 78.0, 0.25), "50 %: {fifty} px short (reference 78)"); +} + +#[test] +fn catch_up_on_stroke_end_still_reaches_the_release_point() { + let cfg = Smoothing { amount: 0.5, catch_up_on_end: true, ..Default::default() }; + assert_eq!(short(&cfg), 0.0); +} + +#[test] +fn the_pulled_string_stops_its_length_short_either_way() { + for catch_up_on_end in [false, true] { + let cfg = Smoothing { amount: 0.5, pulled_string: true, catch_up_on_end, ..Default::default() }; + let s = short(&cfg); + assert!((s - 150.0).abs() < 1e-9, "catch-up on end {catch_up_on_end}: {s} px short (reference about 150)"); + } +} + +#[test] +fn zero_and_disabled_smoothing_paint_through_every_point() { + let pts = drag(); + for cfg in [Smoothing { amount: 0.0, ..Default::default() }, Smoothing { enabled: false, amount: 0.5, ..Default::default() }] { + let out = smooth_points(&cfg, 1.0, &pts); + assert_eq!(out.len(), pts.len(), "{cfg:?}"); + assert!(out.iter().zip(&pts).all(|(a, b)| (a.x, a.y, a.pressure) == (b.x, b.y, b.pressure)), "{cfg:?}"); + } +} + +#[test] +fn the_pull_grows_with_less_smoothing_and_stays_a_fraction() { + let pulls: Vec = [0.01, 0.1, 0.25, 0.5, 0.75, 1.0].iter().map(|a| smoothing_pull(*a)).collect(); + assert!(pulls.windows(2).all(|w| w[0] > w[1]), "{pulls:?}"); + assert!(pulls.iter().all(|p| *p > 0.0 && *p < 1.0), "{pulls:?}"); + assert_eq!(smoothing_pull(0.0), 1.0, "no time constant: straight to the pointer"); + assert_eq!(smoothing_pull(f64::NAN), 1.0, "a bad amount never makes a NaN position"); +} From 853b82d0604590c84f85b45db029ddc5331222a6 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 8 Nov 2026 13:50:54 -0600 Subject: [PATCH 21/38] smoothing_pull's doc says it clamps the amount and gives 1.0 at 0 or NaN (eliets2 review on crates/paint/src/dynamics.rs:26) --- crates/paint/src/dynamics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index f8281dab0d..96d9c8413a 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -23,7 +23,7 @@ pub const SMOOTHING_TAU_MS: f64 = 314.0; pub const SMOOTHING_TAU_EXP: f64 = 0.864; /// The fraction of the way to the pointer exponential smoothing moves in one -/// [`SMOOTHING_STEP_MS`] at `amount` (0..1, above 0). +/// [`SMOOTHING_STEP_MS`] at `amount`, clamped to 0..1. At 0 (or NaN) it is 1.0: no smoothing. pub fn smoothing_pull(amount: f64) -> f64 { let tau = SMOOTHING_TAU_MS * amount.clamp(0.0, 1.0).powf(SMOOTHING_TAU_EXP); if tau > 0.0 { 1.0 - (-SMOOTHING_STEP_MS / tau).exp() } else { 1.0 } From a3a595737d0603324b03644afeb8e4f2c0dd7ff3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:40:26 +0100 Subject: [PATCH 22/38] PR #12246: Smoothing docs name the 300 px string and the Pulled String exception Co-Authored-By: Hector Villarreal Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/brush.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index be23a0429a..7d8c842182 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -526,11 +526,13 @@ pub struct Smoothing { pub enabled: bool, /// 0..1. pub amount: f32, - /// Lazy-mouse: paint only when the pointer pulls a string of `amount × 100 px` taut. + /// Lazy-mouse: paint only when the pointer pulls a string of `amount × 300 px` taut + /// ([`crate::dynamics::MAX_STRING_PX`], screen pixels before Adjust for Zoom). pub pulled_string: bool, /// Keep catching up with the pointer while it pauses (uses point timestamps). pub catch_up: bool, - /// Finish the stroke at the last pointer position. + /// Finish the stroke at the last pointer position. No effect in Pulled String Mode, where the + /// stroke ends the string's length behind the pointer (measured, #11888). pub catch_up_on_end: bool, /// Divide the string length by the view zoom (the command's `zoom` param). pub adjust_for_zoom: bool, From 4476684ca3cc1d6c55b3bf2b3b6349d357fee9f5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 14:04:15 +0100 Subject: [PATCH 23/38] PR #12246: Hard Round taper test paints through to the end with the measured lag main's #8842 test smooths a 700 px stroke at 49 %; with the measured lag the brush ends about 150 px short, so its end cap fell inside the checked span and read as an opacity jump. The test now uses catch-up on stroke end. Co-Authored-By: Hector Villarreal Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/brush_tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 5cd38adf09..53b5803c93 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -359,6 +359,10 @@ fn hard_round_presets_have_continuous_pressure_opacity_tapers() { b.size = 150.0; b.pressure_opacity = true; b.smoothing.amount = smoothing; + // The measured lag (#11888) leaves a 49 % stroke ~150 px short of the pointer, so + // its end cap would fall inside the span checked below; catch-up on end paints it + // through to the last point. + b.smoothing.catch_up_on_end = true; let mut s = Surface::new(fmt); render_stroke(&mut s, &b, &points, None, false, 1.0); assert!(s.rgba(200, 120)[3] > 0.7 && s.rgba(699, 120)[3] < 0.3, "{}: the stroke must still taper", preset.name); From e9a204f9653e402889806b13cba9466d444f4e01 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Wed, 11 Nov 2026 07:46:09 -0600 Subject: [PATCH 24/38] Smoothing: strokes without timestamps keep their per-point pull (CI corpus tests), live handoff catch-up case (CodeRabbit nitpick) The measured lag (#11888) is by stroke time, so it needs timestamps. A stroke without them (a control-client or script paint.stroke, an old file) was never measured and took one step per point with the pull 1 - amount; the new curve made that 31 % at the default 10 %, so a two-point stroke stopped a third of the way and 58 engine tests (brush_clear_background_tests, mixer_live_tests, brush_cmds tests ...) failed in the corpus job. Untimed points keep 1 - amount again; timed ones use the measured curve. Test: strokes_without_timestamps_keep_their_per_point_pull. CodeRabbit's nitpick on retouch_cmds/tests.rs: the live hand-off test also runs a smoothing case with Catch-up on Stroke End. --- crates/engine/src/cmd/retouch_cmds/tests.rs | 6 +++++- crates/paint/src/brush_tests.rs | 2 +- crates/paint/src/dynamics.rs | 4 ++-- crates/paint/src/smoothing_lag_tests.rs | 11 +++++++++++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 0c3bb526ba..0e770c9fb6 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2313,7 +2313,7 @@ fn live_dab_batches_match_the_accumulating_renderer() { }); let id = s.active().unwrap().active_layer.unwrap(); let pre = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); - for case in ["soft", "hard", "sampled", "dynamics", "smoothing"] { + for case in ["soft", "hard", "sampled", "dynamics", "smoothing", "smoothing_catch_up"] { s.tools.brush = BrushSettings::default(); match case { "sampled" => s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(9, 7, |x, y| ((x * 3 + y) % 11) as f32 / 10.0)), @@ -2334,6 +2334,10 @@ fn live_dab_batches_match_the_accumulating_renderer() { b.texture.pattern = photocraft_paint::Pattern::Tile(GrayTile::from_fn(3, 3, |x, y| (x + y) as f32 / 4.0)); } "smoothing" => s.tools.brush.smoothing.amount = 0.65, + "smoothing_catch_up" => { + s.tools.brush.smoothing.amount = 0.65; + s.tools.brush.smoothing.catch_up_on_end = true; + } _ => {} } let points = [ diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 53b5803c93..4880f0a5ab 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -993,7 +993,7 @@ fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() { for x in [0.0, 100.0] { s.push(StrokePoint::new(x, 0.0, 1.0), &mut out); } - assert!((out.last().map_or(0.0, |p| p.x) - 100.0 * a).abs() < 1e-4); + assert!((out.last().map_or(0.0, |p| p.x) - 20.0).abs() < 1e-4); } #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 96d9c8413a..9e45ca175d 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -163,7 +163,7 @@ impl Smoother { } // Exponential: every SMOOTHING_STEP_MS of stroke time moves `a` of the way towards the // pointer, so the feel doesn't depend on how often the device reports. Input without - // timestamps takes one step per point. + // timestamps was never measured: it takes one step per point with the pull it always had. let a = smoothing_pull(amount); let dt = prev_input.map_or(0.0, |q| p.time - q.time); let still = prev_input.is_some_and(|q| q.x == p.x && q.y == p.y); @@ -177,7 +177,7 @@ impl Smoother { // Each of `iters` moves covers `steps / iters` steps' worth of pull. (iters as usize, 1.0 - (1.0 - a).powf(steps.min(64.0) / iters)) } else { - (1, a) + (1, 1.0 - amount.min(0.95)) }; let mut cur = pos; for _ in 0..iters { diff --git a/crates/paint/src/smoothing_lag_tests.rs b/crates/paint/src/smoothing_lag_tests.rs index 27ae2574be..f6b8435be5 100644 --- a/crates/paint/src/smoothing_lag_tests.rs +++ b/crates/paint/src/smoothing_lag_tests.rs @@ -61,3 +61,14 @@ fn the_pull_grows_with_less_smoothing_and_stays_a_fraction() { assert_eq!(smoothing_pull(0.0), 1.0, "no time constant: straight to the pointer"); assert_eq!(smoothing_pull(f64::NAN), 1.0, "a bad amount never makes a NaN position"); } + +/// Input without timestamps (a control-client stroke, a script, an old file) was never measured, +/// so each point keeps the pull it always had: `1 - amount` of the way to the pointer. At the +/// default 10 % a two-point stroke still ends 90 % of the way, not a third of it. +#[test] +fn strokes_without_timestamps_keep_their_per_point_pull() { + let cfg = Smoothing { amount: 0.1, catch_up_on_end: false, ..Default::default() }; + let out = smooth_points(&cfg, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]); + let x = out.last().map_or(f64::NAN, |p| p.x); + assert!((x - 90.0).abs() < 1e-4, "a 10 % untimed step reached {x}, want 90"); +} From 90816ab768a94bb973c16c4e1095859d1e81d4eb Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 15:43:58 +0100 Subject: [PATCH 25/38] Brush smoothing: a timed stroke stays timed on a zero-time report (#12246) Once time had passed between two input points, a later report with the same timestamp still took the untimed per-point pull (90 % of the way at 10 % smoothing), so the brush jumped. A timed stroke now remembers it is timed, and a report with no time since the last one leaves the brush where it is. Untimed input keeps its per-point pull. CodeRabbit finding on #12246. Co-Authored-By: Hector Villarreal Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/dynamics.rs | 13 +++++++++++-- crates/paint/src/smoothing_lag_tests.rs | 13 +++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 9e45ca175d..343e2cbda1 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -117,12 +117,15 @@ pub struct Smoother { zoom: f64, pos: Option, last_input: Option, + /// Has time passed between two input points? Then the stroke is timed, and a later point + /// with no time since the last one moves the brush no further (not by the untimed pull). + timed: bool, } impl Smoother { /// `zoom` is the view zoom (only used with `adjust_for_zoom`). pub fn new(cfg: &Smoothing, zoom: f32) -> Self { - Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None } + Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None, timed: false } } fn active(&self) -> bool { @@ -171,7 +174,13 @@ impl Smoother { // Without Stroke Catch-Up the brush stops while the pointer pauses (Photoshop). return; } - let (iters, step) = if dt > 0.0 && dt.is_finite() { + let has_time = dt > 0.0 && dt.is_finite(); + self.timed |= has_time; + if self.timed && !has_time { + // No time passed (two reports in one millisecond): the brush stays where it is. + return; + } + let (iters, step) = if has_time { let steps = dt / SMOOTHING_STEP_MS; let iters = steps.ceil().clamp(1.0, 64.0); // Each of `iters` moves covers `steps / iters` steps' worth of pull. diff --git a/crates/paint/src/smoothing_lag_tests.rs b/crates/paint/src/smoothing_lag_tests.rs index f6b8435be5..30d278e80e 100644 --- a/crates/paint/src/smoothing_lag_tests.rs +++ b/crates/paint/src/smoothing_lag_tests.rs @@ -72,3 +72,16 @@ fn strokes_without_timestamps_keep_their_per_point_pull() { let x = out.last().map_or(f64::NAN, |p| p.x); assert!((x - 90.0).abs() < 1e-4, "a 10 % untimed step reached {x}, want 90"); } + +/// A timed stroke stays timed: a report with no time since the last one (two events in one +/// millisecond) leaves the brush where it is, instead of jumping it by the untimed per-point pull. +#[test] +fn a_report_with_no_time_passed_does_not_move_a_timed_brush() { + let cfg = Smoothing { amount: 0.1, catch_up: true, catch_up_on_end: false, ..Default::default() }; + let at = |x: f64, time: f64| StrokePoint { time, ..StrokePoint::new(x, 0.0, 1.0) }; + let timed = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0)]); + let twice = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0), at(100.0, 10.0)]); + let (before, after) = (timed.last().map_or(f64::NAN, |p| p.x), twice.last().map_or(f64::NAN, |p| p.x)); + assert!(before > 0.0 && before < 90.0, "the timed move lags: {before}"); + assert_eq!(after, before, "no time passed, so the brush stays"); +} From 682ff6bf15d0cde043c4da9a112bbe59ff105dba Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:13:36 +0100 Subject: [PATCH 26/38] Address CodeRabbit review: keep an overlapping board's own mask in its file A board above whose layers reached past it had its mask replaced by the board clip, so what the mask hid inside the board showed in the exported file. Such a board, and any board with its own blend mode, opacity, effects or masks, now goes into the file as its own group inside the plain group, above the "Background for" layer, and only the plain group carries the hard board clip. The artboard painted its background beneath the board and composited the board over it; this keeps that order. A plain board keeps the reference application's layout (its layers directly over the background). The clip is decided after the background is in place. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 61 +++++++++++++++---- .../artboard_cmds/overlapping_areas_tests.rs | 32 ++++++++++ 2 files changed, 82 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 7569b1e5aa..a99c2b7cb2 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -664,7 +664,13 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result /// artboard) holding its layers over a new pixel layer "Background for " filled with the /// board's background where the two boards overlap, in source coordinates and bottom to top. A /// group whose layers reach past its own board (effects, pixels outside the board, adjustments) -/// gets a mask to its board, which the artboard clipped them to. +/// gets a hard mask to its board, which the artboard clipped them to. +/// +/// The artboard painted its background beneath the group and then composited the group (its +/// blend mode, opacity, effects and masks) over it. A board with any of those keeps them on a +/// group of its own inside the plain group, above the background, so they still apply to its +/// layers only and its own mask keeps its feather and Layer Mask Hides Effects setting; the plain +/// group then carries nothing but the board clip. fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { let above = doc.layers.iter().skip_while(|l| l.id != id).skip(1); let mut out = Vec::new(); @@ -674,29 +680,62 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { if overlap.is_empty() { continue; } - let mut group = l.clone(); - if let LayerContent::Group(g) = &mut group.content { + let mut board = l.clone(); + if let LayerContent::Group(g) = &mut board.content { g.artboard = None; cut_pixels(&mut g.children, overlap, 0); } - let reach = photocraft_compose::change_bounds(&group, doc.bounds()); - if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) { - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0]); - mask.surface.fill_rect(ab.rect, &[1.0]); - group.mask = Some(mask); - } - if let (Some(bg), Some(children)) = (ab.background.rgba(), group.children_mut()) { + let bg = ab.background.rgba(); + let mut group = if stacks_like_its_layers(&board, bg) { + board + } else { + board.clipped = false; + let mut plain = Layer::group(l.name.clone(), vec![board]); + plain.label = l.label; + plain + }; + if let (Some(bg), Some(children)) = (bg, group.children_mut()) { let fmt = doc.pixel_format(); let mut surf = Surface::new(fmt); surf.fill_rect(overlap, &photocraft_raster::from_rgba(&fmt, bg)); children.insert(0, Layer::new(format!("Background for {}", l.name), LayerContent::Raster(surf))); } + // With the background in place: its pixels widen what the group's layers can reach. + let reach = photocraft_compose::change_bounds(&group, doc.bounds()); + if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) { + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface = Surface::with_default(PixelFormat::GRAY8, &[0.0]); + mask.surface.fill_rect(ab.rect, &[1.0]); + group.mask = Some(mask); + } out.push(group); } out } +/// Whether artboard `board` (already a plain group) composites over its background `bg` exactly +/// as its layers stacked over that background in one pass-through group do: no effects, masks, +/// opacity, Blend If or other blending options of its own (Normal only over an opaque +/// background, which hides whatever an isolated group would leave out), and no mask the board +/// clip would replace. +fn stacks_like_its_layers(board: &Layer, bg: Option<[f32; 4]>) -> bool { + let blend = match board.blend { + photocraft_color::BlendMode::PassThrough => true, + photocraft_color::BlendMode::Normal => bg.is_some_and(|c| c[3] >= 1.0), + _ => false, + }; + blend + && board.opacity >= 1.0 + && board.fill_opacity >= 1.0 + && board.mask.is_none() + && board.vector_mask.is_none() + && board.frame.is_none() + && board.excluded_channels == 0 + && board.blend_if == photocraft_doc::BlendIf::default() + && board.advanced == photocraft_doc::AdvancedBlending::default() + && !photocraft_compose::effects::has_effects(board) +} + /// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to /// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers /// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board. diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs index b91fb70eed..616f0c2fbb 100644 --- a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -280,3 +280,35 @@ fn the_params_doc_names_the_option() { let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToFiles").unwrap(); assert!(spec.params.contains(r#""content":"overlapping|artboard"="overlapping""#), "{}", spec.params); } + +/// The source document's composite pixel at (x, y); Red Board sits at the canvas origin, so its +/// file pixels line up with these. +fn source_px(s: &Session, x: i32, y: i32) -> [u8; 4] { + px(&s.active().unwrap().doc, x, y) +} + +/// A mask on the board above keeps hiding what it hid when the export clips that board to its +/// rect: the board clip is added beside it instead of replacing it. +#[test] +fn a_mask_on_the_board_above_still_hides_its_part() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Mask", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + // A canvas-wide fill reaches past the board, so the export clips the board to its rect. + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + board.children_mut().unwrap().insert(0, fill); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(140, 50, 160, 70), &[0.0]); + board.mask = Some(mask); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 150, 60)), WHITE, "the mask shows Blue Board's background there"); + let out = Out::new("board-mask"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (145, 55), (170, 60), (125, 140), (110, 50), (10, 140)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} From 9bd2d6efd3998a8651a15f59f55b9b8d519b2675 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:33:10 +0100 Subject: [PATCH 27/38] Address CodeRabbit review: only a pass-through board stacks on its background A Normal board renders its layers on their own before they go over its background, so a Multiply or Screen layer in it must not blend with the background in the export. Only a pass-through board now stacks its layers directly on the background layer; a Normal one keeps its own group above it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 21 ++++++--------- .../artboard_cmds/overlapping_areas_tests.rs | 26 +++++++++++++++++++ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index a99c2b7cb2..3023f96680 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -686,7 +686,7 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { cut_pixels(&mut g.children, overlap, 0); } let bg = ab.background.rgba(); - let mut group = if stacks_like_its_layers(&board, bg) { + let mut group = if stacks_like_its_layers(&board) { board } else { board.clipped = false; @@ -713,18 +713,13 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { out } -/// Whether artboard `board` (already a plain group) composites over its background `bg` exactly -/// as its layers stacked over that background in one pass-through group do: no effects, masks, -/// opacity, Blend If or other blending options of its own (Normal only over an opaque -/// background, which hides whatever an isolated group would leave out), and no mask the board -/// clip would replace. -fn stacks_like_its_layers(board: &Layer, bg: Option<[f32; 4]>) -> bool { - let blend = match board.blend { - photocraft_color::BlendMode::PassThrough => true, - photocraft_color::BlendMode::Normal => bg.is_some_and(|c| c[3] >= 1.0), - _ => false, - }; - blend +/// Whether artboard `board` (already a plain group) composites over its background exactly as +/// its layers stacked over that background in one pass-through group do: pass-through (a Normal +/// group renders its layers on their own first, so a Multiply or Screen layer in it never blends +/// with the background), and no effects, masks, opacity, Blend If or other blending options of +/// its own, nor a mask the board clip would replace. +fn stacks_like_its_layers(board: &Layer) -> bool { + board.blend == photocraft_color::BlendMode::PassThrough && board.opacity >= 1.0 && board.fill_opacity >= 1.0 && board.mask.is_none() diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs index 616f0c2fbb..86df170247 100644 --- a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -312,3 +312,29 @@ fn a_mask_on_the_board_above_still_hides_its_part() { } } } + +/// A Normal board renders its layers on their own before they go over its background, so a +/// Multiply layer in it does not blend with that background; the export keeps the board as a +/// group of its own above the background layer instead of stacking its layers on it. +#[test] +fn a_multiply_layer_in_a_normal_board_above_does_not_blend_with_its_background() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Normal", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + board.blend = photocraft_color::BlendMode::Normal; + if let LayerContent::Group(g) = &mut board.content { + g.artboard.as_mut().unwrap().background = photocraft_doc::ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)); + } + board.children_mut().unwrap().last_mut().unwrap().blend = photocraft_color::BlendMode::Multiply; + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 150, 60)), BLUE, "Blue, rendered on its own, covers the green background"); + let out = Out::new("normal-multiply"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (125, 35), (110, 50)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} From 4aeb7e7c8da3141c67a8f13a40f7a4aaeeb033ad Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:14:05 +0100 Subject: [PATCH 28/38] WIP: shortcut test checks the table and presses one key per kind (#15678) Co-Authored-By: Claude Opus 5.5 From 7b2c58fc5ec67dbc1f6d463c03410183a5332157 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:44:21 +0100 Subject: [PATCH 29/38] Shortcut test: check every shortcut through the dispatcher, press one key per kind (#15678) The exhaustive test pressed every displayed shortcut and tool letter through the whole app from four focus places, about 555 presses with frames each (461 s on Windows CI in run 44349486353, 54 s locally). Split it in two: - every_displayed_shortcut_runs_its_menu_item fires the keymap's command for each of the 120 displayed shortcuts and every tool letter straight into run_fired (dry run), with no key events and no frames, and checks the same outcomes: ran and the menu item is enabled, or disabled with a reason. - every_kind_of_shortcut_dispatches_from_where_focus_usually_is presses one shortcut per (route, kind of key, modifiers) from the four focus places with the old assertions: 34 groups, plus one single-tool and one shared tool letter. Both run in about 10 s locally. Co-Authored-By: Claude Opus 5.5 --- .../src/input/shortcut_dispatch/tests.rs | 162 ++++++++++++++++-- 1 file changed, 150 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 472b385157..0128245ffd 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -1,6 +1,9 @@ //! #127: every shortcut the UI displays (menu items, shell commands, tool tooltips) dispatches its -//! command, or the item is visibly disabled with a reason — through the whole app, with a -//! realistic layered document, from the places focus usually is. +//! command, or the item is visibly disabled with a reason, in the whole app with a realistic layered +//! document. Every shortcut's command is fired into the dispatcher directly; one shortcut of each kind +//! of key and route is pressed from the places focus usually is (#15678). + +use std::collections::HashSet; use craft::keymap::Chord; use craft::ui::runtime::focus; @@ -204,11 +207,146 @@ fn displayed(app: &PhotocraftApp) -> Vec<(String, String, bool)> { v } -/// Press every displayed shortcut from each place focus usually is: each dispatches its command, -/// or the menu shows it disabled and the press reports why. (Dry run: File › Exit, Open, Help +/// The way [`super::run_fired`] takes a fired command `id`: a row of [`super::RUNTIME_COMMANDS`] by its kind, a tool +/// letter, a Shift+letter group step, a recorded action, else an app command through [`super::dispatch_as`]. +fn route(id: &str) -> String { + if let Some((_, bridged)) = super::RUNTIME_COMMANDS.iter().find(|(row, _)| *row == id) { + let kind = format!("{bridged:?}"); + return kind.split('(').next().unwrap_or(&kind).to_string(); + } + if crate::tool_shortcuts::tool(id).is_some() { + "tool".into() + } else if super::next_in_group_letter(id).is_some() { + "group".into() + } else if id.starts_with(crate::actions::SHORTCUT_PREFIX) { + "action".into() + } else { + "app".into() + } +} + +/// What a press of `chord` shares with every other chord of its group: the keyboard path (the runtime's key stage, +/// a focused field's typing rule, a focused component's held keys) depends on the kind of key and the modifiers, +/// not on the command. Letters, digits and function keys are one kind each; every other key is its own kind. +fn key_kind(chord: &Chord) -> String { + let key = chord.key; + let kind = if key.is_letter() { + "letter".to_string() + } else if key.is_digit() { + "digit".to_string() + } else if key.is_function_key() { + "function".to_string() + } else { + format!("{key:?}") + }; + let m = chord.mods; + format!("{kind} cmd={} ctrl={} alt={} shift={}", m.cmd, m.ctrl, m.alt, m.shift) +} + +/// Every live displayed shortcut (id, text) and its chord. +fn live_chords(app: &PhotocraftApp) -> Vec<(String, String, Chord)> { + displayed(app) + .into_iter() + .filter(|(_, _, live)| *live) + .map(|(id, sc, _)| { + let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}")); + (id, sc, chord) + }) + .collect() +} + +/// One displayed shortcut per (route, kind of key, modifiers): the shortcuts whose press goes the same way. +fn representatives(app: &PhotocraftApp) -> Vec<(String, String, Chord)> { + let mut seen = HashSet::new(); + live_chords(app).into_iter().filter(|(id, _, chord)| seen.insert((route(id), key_kind(chord)))).collect() +} + +/// The command the runtime fires for `chord`, shown for menu row `id`: the row's own command when the keymap shows +/// the chord for it (no other command wins it where the binding applies), else the key's holder. +fn fired_by(ctx: &egui::Context, id: &str, chord: &Chord) -> Option { + let own = super::keymap_command(id); + if craft::ui::runtime::commands::chord(ctx, &own) == Some(*chord) { + return Some(own); + } + // `holder` answers with no panel active; it falls back to a panel's binding when no unscoped command holds the key. + craft::ui::runtime::commands::holder(ctx, chord) +} + +/// Every displayed shortcut runs its menu item's command, or the menu shows the item disabled and the shortcut +/// says why: the keymap's command for each chord is fired into [`super::run_fired`] as a key press, with no key +/// events and no frames between them. The keyboard's way to the keymap is the same for every chord of a kind, and +/// [`every_kind_of_shortcut_dispatches_from_where_focus_usually_is`] presses one of each. The view, screen-mode, +/// momentary, Swatches and Workspace rows run in the runtime, the canvas or the shell instead of `run_fired`; that +/// test presses one of each kind of key for them. Every tool letter picks a tool of that letter. +#[test] +fn every_displayed_shortcut_runs_its_menu_item() { + use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; + let mut h = harness(); + set_dry_run(&h.ctx, true); + put_focus(&mut h, Place::Canvas); + let ctx = h.ctx.clone(); + let items = crate::menus::menu_rows(h.state()); + let chords = live_chords(h.state()); + assert!(chords.len() > 100, "the menus show their shortcuts: {}", chords.len()); + let fire = |h: &mut Harness<'_, Box>, command| { + super::run_fired(h.state_mut(), &ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]); + take_log(&ctx) + }; + let mut failures = Vec::new(); + let mut fired = 0; + for (id, sc, chord) in &chords { + let Some(command) = fired_by(&ctx, id, chord) else { + failures.push(format!("{sc} ({id}) runs nothing")); + continue; + }; + match route(id).as_str() { + "View" | "Momentary" | "ScreenMode" | "Swatches" | "Workspace" => { + if command != super::keymap_command(id) { + failures.push(format!("{sc} ({id}) fires {command:?}")); + } + continue; + } + "tool" | "group" => { + let want = crate::tool_shortcuts::tool(id).map(Tool::key).or_else(|| super::next_in_group_letter(id)); + fire(&mut h, command); + if Some(h.state().ui.tool.key()) != want { + failures.push(format!("{sc} ({id}) left {:?}", h.state().ui.tool)); + } + continue; + } + _ => {} + } + let enabled = items.iter().find(|i| i.command.id == *id).map_or_else(|| crate::menus::is_enabled(h.state(), id), |i| i.enabled); + fired += 1; + match fire(&mut h, command).as_slice() { + [(bound, Outcome::Ran)] if same(id, bound) && enabled => {} + [(bound, Outcome::Disabled(why))] if same(id, bound) && !enabled && !why.is_empty() => {} + other => failures.push(format!("{sc} ({id}, menu enabled: {enabled}) -> {other:?}")), + } + } + assert!(fired > 80, "most displayed shortcuts go through run_fired: {fired}"); + for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { + let chord = Chord::parse(&t.key().to_string()).unwrap_or_else(|_| panic!("tool key {}", t.key())); + let Some(command) = craft::ui::runtime::commands::holder(&ctx, &chord) else { + failures.push(format!("tool key {} runs nothing", t.key())); + continue; + }; + h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; + fire(&mut h, command); + if h.state().ui.tool.key() != t.key() { + failures.push(format!("tool key {} left {:?}", t.key(), h.state().ui.tool)); + } + } + assert!(failures.is_empty(), "{} shortcut failures:\n{}", failures.len(), failures.join("\n")); +} + +/// Press one displayed shortcut of each (route, kind of key, modifiers) from each place focus usually is: each +/// dispatches its command, or the menu shows it disabled and the press reports why; a focused field keeps its typing +/// keys and a focused component the keys it holds. The other shortcuts of a group take the same path to a different +/// row of the table [`every_displayed_shortcut_runs_its_menu_item`] checks. (Dry run: File › Exit, Open, Help /// links… resolve and check enablement without running.) #[test] -fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { +fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { let mut failures = Vec::new(); for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] { let mut h = harness(); @@ -216,11 +354,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { put_focus(&mut h, place); let typing = WindowHost::of(&h.ctx).typing(); let items = crate::menus::menu_rows(h.state()); - for (id, sc, live) in displayed(h.state()) { - if !live { - continue; - } - let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}")); + for (id, sc, chord) in representatives(h.state()) { // A press the focused component holds (the Layers rows' stacking and visibility keys) // is the component's and reaches no app command. let held = focus_holds(&h.ctx, chord); @@ -241,9 +375,13 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")), } } - // Tool letters from the tools panel tooltips ("Brush Tool (B)"). + // Tool letters from the tools panel tooltips ("Brush Tool (B)"): a letter of one tool and a letter its group + // shares take different picks (`pick_tool`); the table checks every letter's tool. if !typing { - for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { + let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1; + let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t)); + let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t)); + for t in one.into_iter().chain(many) { h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; press_in_one_frame(&mut h, &t.key().to_string()); if h.state().ui.tool.key() != t.key() { From a0882ab6c902785fdb0661f5344ea1ac8d228670 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:11:32 +0100 Subject: [PATCH 30/38] Shortcut test: tool letters typed into a focused field keep the tool (#15678) Co-Authored-By: Claude Opus 5.5 --- .../src/input/shortcut_dispatch/tests.rs | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 0128245ffd..77163189e0 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -376,17 +376,18 @@ fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { } } // Tool letters from the tools panel tooltips ("Brush Tool (B)"): a letter of one tool and a letter its group - // shares take different picks (`pick_tool`); the table checks every letter's tool. - if !typing { - let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1; - let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t)); - let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t)); - for t in one.into_iter().chain(many) { - h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; - press_in_one_frame(&mut h, &t.key().to_string()); - if h.state().ui.tool.key() != t.key() { - failures.push(format!("{place:?}: tool key {} left {:?}", t.key(), h.state().ui.tool)); - } + // shares take different picks (`pick_tool`); the table checks every letter's tool. In a focused text field the + // letter is typed and the tool stays. + let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1; + let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t)); + let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t)); + for t in one.into_iter().chain(many) { + let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; + h.state_mut().ui.tool = start; + press_in_one_frame(&mut h, &t.key().to_string()); + let want = if typing { start } else { t }; + if h.state().ui.tool.key() != want.key() { + failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key())); } } } From 40bd3e7e73beb34e796b3ad870d55b5faa3325d2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:05:43 +0000 Subject: [PATCH 31/38] Command catalog and keyed command states rebuilt only on change (#15709) The catalog's rows are rebuilt when the actions list's revision moves, and the keymap overrides when the preferences' catalog revision or the actions list moves, instead of on every preferences revision. The JSON row compare goes, and the catalog's id searches use an index. Command sources whose inputs have exact revisions (tools, slices, artboard) keep their states until their key changes. The rail's slots key on the catalog revision. --- crates/ui-egui/src/app/framework.rs | 168 ++++++++++++++---- .../src/app/framework/catalog_tests.rs | 84 +++++++++ crates/ui-egui/src/input/shortcut_dispatch.rs | 88 ++++----- crates/ui-egui/src/panels/tool_commands.rs | 12 +- .../ui-egui/src/prefs/prefs_ui/shortcuts.rs | 9 +- crates/ui-egui/src/tools/artboard_tool.rs | 5 + crates/ui-egui/src/tools/slice_ui.rs | 8 + 7 files changed, 287 insertions(+), 87 deletions(-) create mode 100644 crates/ui-egui/src/app/framework/catalog_tests.rs diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 4adf2e7624..2c6e535e69 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -89,14 +89,25 @@ pub struct Framework { /// The runtime's keymap overrides. The runtime rebuilds its keymap when the `Arc` changes, so /// it is replaced only when the bindings it carries change. overrides: Arc, - /// The preferences revision `overrides` and `catalog` were last built at. - overrides_rev: Option, - /// The app's command catalog as of `overrides_rev`. + /// What `overrides` was built from: the preferences' catalog revision and the actions list's revision. + overrides_key: Option<(u64, u64)>, + /// Advances each time `overrides` is replaced. + overrides_generation: u64, + /// The app's command catalog, built from `catalog_rows`. catalog: Option, - /// The rows `catalog` was built from, and its generation: the runtime rebuilds its keymap when the generation - /// changes, so it advances only when the rows differ. + /// The rows `catalog` was built from ([`command_rows`](crate::shortcut_dispatch::command_rows)), the actions + /// list's revision they were built at (their one input that changes at run time), and the catalog's generation: + /// the runtime rebuilds its keymap when the generation changes, so it advances only when the rows are rebuilt. catalog_rows: Vec, + catalog_rows_rev: Option, catalog_generation: u64, + /// How many times the rows and the overrides were built, for the count trials. + #[cfg(test)] + pub(crate) catalog_builds: usize, + #[cfg(test)] + pub(crate) overrides_builds: usize, + /// The states the keyed command sources last computed ([`command_states`]). + pub(crate) held_states: HeldStates, /// The file services the host gives components (pickers, reads and writes); `None` keeps the /// host's own default. files: Option>, @@ -271,10 +282,17 @@ impl Framework { dialogs: DialogHost::new(), captured: Default::default(), overrides: Arc::new(Overrides::new()), - overrides_rev: None, + overrides_key: None, + overrides_generation: 0, catalog: None, catalog_rows: Vec::new(), + catalog_rows_rev: None, catalog_generation: 0, + #[cfg(test)] + catalog_builds: 0, + #[cfg(test)] + overrides_builds: 0, + held_states: HeldStates::default(), files, fired: Vec::new(), refused: false, @@ -476,26 +494,47 @@ impl Framework { .unwrap_or_else(|| id.as_str().to_owned()) } - /// What the runtime's keymap was last built from: the preferences revision of the overrides and the catalog's - /// generation. They change at the start of the frame whose keymap follows them, so a surface that shows the - /// keymap's chords (the menu model) hashes them to rebuild in that frame. - pub(crate) fn keymap_inputs(&self) -> (Option, u64) { - (self.overrides_rev, self.catalog_generation) + /// What the runtime's keymap was last built from: the generations of the overrides and of the catalog. They + /// change at the start of the frame whose keymap follows them, so a surface that shows the keymap's chords (the + /// menu model) hashes them to rebuild in that frame. + pub(crate) fn keymap_inputs(&self) -> (u64, u64) { + (self.overrides_generation, self.catalog_generation) } - /// Rebuilds the catalog and the runtime's keymap overrides at preferences revision `rev`. The - /// pane moves are unbound in the overrides, because PhotoCraft's own table binds F6 and - /// Shift+F6 (Window › Color, Select › Modify › Feather) until those are a framework - /// `CommandSet`. The held `Arc` is replaced only when the bindings differ, so the runtime - /// rebuilds its keymap only on a change. - fn set_overrides(&mut self, rev: u64, catalog: Option, mut overrides: Overrides) { - self.overrides_rev = Some(rev); - self.catalog = catalog; + /// The catalog's rows when they were built at actions list revision `actions_rev`, else `None`. + pub(crate) fn catalog_rows_at(&self, actions_rev: u64) -> Option<&[craft::keymap::CommandDef]> { + (self.catalog_rows_rev == Some(actions_rev)).then_some(self.catalog_rows.as_slice()) + } + + /// Takes `rows`, built at actions list revision `actions_rev`, as the catalog's rows: a new catalog generation. + fn set_catalog(&mut self, actions_rev: u64, rows: Vec) { + self.catalog_generation += 1; + self.catalog = crate::shortcut_dispatch::catalog(rows.clone(), self.catalog_generation); + self.catalog_rows = rows; + self.catalog_rows_rev = Some(actions_rev); + #[cfg(test)] + { + self.catalog_builds += 1; + } + } + + /// Takes the runtime's keymap overrides built from `key` ([`Self::overrides_key`]). The pane + /// moves are unbound in the overrides, because PhotoCraft's own table binds F6 and Shift+F6 + /// (Window › Color, Select › Modify › Feather) until those are a framework `CommandSet`. The + /// held `Arc` is replaced only when the bindings differ, so the runtime rebuilds its keymap + /// only on a change. + fn set_overrides(&mut self, key: (u64, u64), mut overrides: Overrides) { + self.overrides_key = Some(key); for command in [NavCommand::NextPane, NavCommand::PreviousPane] { overrides.insert(CommandRef::from(command).key(), Vec::new()); } if *self.overrides != overrides { self.overrides = Arc::new(overrides); + self.overrides_generation += 1; + } + #[cfg(test)] + { + self.overrides_builds += 1; } } } @@ -505,6 +544,10 @@ impl Framework { pub(crate) struct CommandSource { /// The states of the source's commands for the coming frame. states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, + /// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when + /// the data changes: the states are computed again only when the key changes. `None`: computed every frame, + /// because what the source reads has no such revision yet. + key: Option StatesKey>, /// Runs `command` when it is this source's; whether it was. run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } @@ -512,23 +555,69 @@ pub(crate) struct CommandSource { /// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has /// no command state, and its picks run through `menus::invoke`. pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ - CommandSource { states: crate::panels::registry::states, run: crate::panels::registry::run_fired }, - CommandSource { states: tool_states, run: run_tool }, - CommandSource { states: crate::workspace_ui::states, run: crate::workspace_ui::run_fired }, - CommandSource { states: crate::slice_ui::command_states, run: crate::slice_ui::run_fired }, - CommandSource { states: crate::align_bar::command_states, run: crate::align_bar::run_fired }, - CommandSource { states: crate::artboard_tool::command_states, run: crate::artboard_tool::run_fired }, + CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired }, + CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool }, + CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired }, + CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired }, + CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired }, + CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. - CommandSource { states: |_| Vec::new(), run: crate::canvas_tool_menu::run_canvas_color }, + CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. - CommandSource { states: crate::panels::options_bar::selection::command_states, run: |_, _, _| false }, + CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false }, ]; +/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal +/// keys mean equal states. +pub(crate) type StatesKey = [u64; 4]; + +/// The states each keyed [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key. +#[derive(Default)] +pub(crate) struct HeldStates { + kept: Vec)>>, + /// How many times each source computed its states, for the count trials. + #[cfg(test)] + pub(crate) runs: Vec, +} + /// The tool commands: the current tool's row is checked. fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect() } +/// What [`tool_states`] reads: the tool. +fn tool_states_key(app: &PhotocraftApp) -> StatesKey { + [app.ui.tool as u64, 0, 0, 0] +} + +/// The states of every command source for the coming frame. A keyed source runs only when its key changed since it +/// last ran. +fn command_states(app: &PhotocraftApp, held: &mut HeldStates) -> Vec<(CommandRef, CommandState)> { + held.kept.resize(COMMAND_SOURCES.len(), None); + #[cfg(test)] + held.runs.resize(COMMAND_SOURCES.len(), 0); + let mut states = Vec::new(); + for (at, source) in COMMAND_SOURCES.iter().enumerate() { + let key = source.key.map(|key| key(app)); + match (&held.kept[at], key) { + (Some((was, kept)), Some(key)) if *was == key => states.extend_from_slice(kept), + _ => { + #[cfg(test)] + { + held.runs[at] += 1; + } + let computed = (source.states)(app); + states.extend_from_slice(&computed); + held.kept[at] = key.map(|key| (key, computed)); + } + } + } + states +} + +#[cfg(test)] +mod catalog_tests; + /// Selects the tool a tool command names. fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = crate::panels::tool_commands::ToolCommand::from_ref(command) else { @@ -549,23 +638,24 @@ impl PhotocraftApp { /// runs them), the commands the canvas ran (`record_view_commands`, in `logic`) and whether a /// component refused its input. pub(crate) fn framework_before_input(&mut self, ctx: &egui::Context) { - // The catalog and the bindings come from walking the whole command table: only after a - // preferences change. - let rev = self.session.prefs.rev(); - if self.framework.overrides_rev != Some(rev) { + // The catalog's rows change only with the actions list; the bindings also with the shortcut + // preferences. + let actions_rev = self.session.actions.list.revision(); + if self.framework.catalog_rows_rev != Some(actions_rev) { let rows = crate::shortcut_dispatch::command_rows(self); - if !crate::shortcut_dispatch::same_rows(&self.framework.catalog_rows, &rows) { - self.framework.catalog_generation += 1; - self.framework.catalog_rows = rows.clone(); - } - let catalog = crate::shortcut_dispatch::catalog(rows, self.framework.catalog_generation); - let overrides = crate::shortcut_dispatch::overrides(self); - self.framework.set_overrides(rev, catalog, overrides); + self.framework.set_catalog(actions_rev, rows); + } + let overrides_key = (self.session.prefs.catalog_rev(), actions_rev); + if self.framework.overrides_key != Some(overrides_key) { + let overrides = crate::shortcut_dispatch::overrides(self, &self.framework.catalog_rows); + self.framework.set_overrides(overrides_key, overrides); } if self.framework.sync_theme(&mut self.session) { crate::prefs_ui::show_selected_theme(self, ctx); } - let states: Vec<(CommandRef, CommandState)> = COMMAND_SOURCES.iter().flat_map(|source| (source.states)(self)).collect(); + let mut held = std::mem::take(&mut self.framework.held_states); + let states = command_states(self, &mut held); + self.framework.held_states = held; let gate = crate::menus::command_gate(self); let latched = self.ui.shell.latched; embed::before_input(ctx, |output: FrameOutput| { diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs new file mode 100644 index 0000000000..dd2e5a8d9a --- /dev/null +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -0,0 +1,84 @@ +//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what +//! they read changes. + +use serde_json::json; + +use super::{COMMAND_SOURCES, PhotocraftApp}; +use crate::canvas::testing; +use crate::state::Tool; + +/// The place of the tool commands' source in [`COMMAND_SOURCES`]. +const TOOL_SOURCE: usize = 1; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + testing::frame(&mut app); + app +} + +/// How many times the rows and the overrides were built. +fn builds(app: &PhotocraftApp) -> (usize, usize) { + (app.framework.catalog_builds, app.framework.overrides_builds) +} + +/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a +/// source that computes them every frame. +fn keyed_runs(app: &PhotocraftApp) -> Vec> { + COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect() +} + +fn frames(app: &mut PhotocraftApp, n: usize) { + for _ in 0..n { + testing::frame(app); + } +} + +#[test] +fn the_catalog_is_built_only_when_its_inputs_change() { + let mut app = app(); + assert_eq!(builds(&app), (1, 1), "the first frame builds the catalog and the overrides"); + + frames(&mut app, 100); + assert_eq!(builds(&app), (1, 1), "idle frames build nothing"); + + let prefs = app.session.prefs.rev(); + crate::tool_memory::select(&mut app, Tool::Brush); + app.run("tools.swapColors", json!({})).unwrap(); + frames(&mut app, 2); + assert_ne!(app.session.prefs.rev(), prefs, "the tool and the colours are preferences"); + assert_eq!(builds(&app), (1, 1), "a tool or colour change builds nothing"); + + let generation = app.framework.keymap_inputs().1; + app.session.edit_prefs(|p| { + p.shortcuts.insert("edit.copy".into(), "Ctrl+Shift+K".into()); + }); + frames(&mut app, 2); + assert_eq!(builds(&app), (1, 2), "a shortcut edit builds the overrides once and leaves the rows"); + assert_eq!(app.framework.keymap_inputs().1, generation, "the catalog keeps its generation"); + + app.session.actions.list.new_action("Trial", None).unwrap(); + frames(&mut app, 2); + assert_eq!(builds(&app), (2, 3), "a new action builds the rows and the overrides once"); + assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog takes a new generation"); + assert!(app.framework.catalog_rows.iter().any(|row| row.label == "Trial"), "the action has its row"); +} + +#[test] +fn keyed_command_states_run_only_when_their_key_changes() { + let mut app = app(); + assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands"); + let before = keyed_runs(&app); + assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once"); + + frames(&mut app, 100); + assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source"); + + let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; + crate::tool_memory::select(&mut app, other); + frames(&mut app, 2); + let after = keyed_runs(&app); + for (at, (was, now)) in before.iter().zip(&after).enumerate() { + let moved = usize::from(at == TOOL_SOURCE); + assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change"); + } +} diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 9bd05d2714..a629f0c7c1 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -10,7 +10,7 @@ //! shortcut whose command is disabled in the current state reports why on the status bar instead //! of doing nothing silently, as the greyed menu item shows. -use std::collections::HashSet; +use std::collections::HashMap; use craft::color_ui::ui::SwatchesCommand; use craft::keymap::{Binding, Chord, CommandDef, CommandKind, Overrides, Scope}; @@ -208,17 +208,31 @@ fn binding(text: &str) -> Option { /// The menu path of command `id`: its menu, then its label. fn menu_path(id: &str) -> Option> { - let (menu, label): (&[&str], &str) = crate::menu_catalog::CATALOG - .iter() - .find(|c| c.3 == id) - .map(|c| (c.0, c.1)) - .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id && !c.2.is_empty()).map(|c| (c.2, c.1)))?; - Some(menu.iter().chain([&label]).map(|part| (*part).to_string()).collect()) + let (menu, label) = menu_paths().get(id)?; + Some(menu.iter().chain([label]).map(|part| (*part).to_string()).collect()) } -/// Adds `def` unless an earlier source gave its id or the runtime defines it. -fn push_row(rows: &mut Vec, seen: &mut HashSet, def: CommandDef) { - if !is_bridged(&def.command.id) && seen.insert(def.command.id.clone()) { +/// Each command's menu and label: the catalogue's first row of the command, else the first shell command of that id +/// that has a menu. +fn menu_paths() -> &'static HashMap<&'static str, (&'static [&'static str], &'static str)> { + static PATHS: std::sync::OnceLock> = std::sync::OnceLock::new(); + PATHS.get_or_init(|| { + let mut paths = HashMap::new(); + for &(menu, label, _, id) in crate::menu_catalog::CATALOG { + paths.entry(id).or_insert((menu, label)); + } + for &(id, label, menu, _) in crate::menus::UI_COMMANDS.iter().filter(|c| !c.2.is_empty()) { + paths.entry(id).or_insert((menu, label)); + } + paths + }) +} + +/// Adds `def` unless an earlier source gave its id or the runtime defines it. `index` holds each row's place in +/// `rows` by its id. +fn push_row(rows: &mut Vec, index: &mut HashMap, def: CommandDef) { + if !is_bridged(&def.command.id) && !index.contains_key(&def.command.id) { + index.insert(def.command.id.clone(), rows.len()); rows.push(def); } } @@ -229,18 +243,18 @@ fn push_row(rows: &mut Vec, seen: &mut HashSet, def: Command /// ([`RUNTIME_COMMANDS`]) are not rows. The Keyboard Shortcuts dialog lists exactly these rows. pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { let mut rows: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); + let mut index: HashMap = HashMap::new(); let app_row = |id: &str, label: &str| CommandDef::new(CommandRef::new(id), label, Scope::app()); // The tool letters, and the Shift+letter step of each group. for def in crate::tool_shortcuts::defs(app) { - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } for (letter, first) in crate::tool_shortcuts::group_letters() { let label = format!("Next {}", first.label()); let mut def = app_row(&next_in_group_id(letter), &label).with_path(vec!["Tools".into(), label.clone()]); def.defaults.extend(binding(&format!("Shift+{}", letter.to_ascii_uppercase()))); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // The held erase key is momentary; the hand and zoom keys are the runtime's. for &(id, label, key) in photocraft_engine::prefs::TEMPORARY_TOOLS { @@ -249,7 +263,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { } let mut def = app_row(id, label).with_kind(CommandKind::Momentary).with_path(vec!["Tools".into(), "Temporary".into(), label.into()]); def.defaults.extend(binding(key)); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Alt+1 … Alt+0 set the brush smoothing (press only). The opacity and blend digits are command sets of the // framework (`OpacityDigit`, `BlendStep`, `BlendShortcut`), so they are no rows here. @@ -258,7 +272,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { let label = format!("Brush Smoothing {}%", digit * 10); let mut def = app_row(&format!("tools.smoothing.{key}"), &label).with_path(vec!["Tools".into(), "Smoothing".into(), label.clone()]); def.defaults.extend(binding(&format!("Alt+{key}"))); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // The engine's and the shell's commands, with the menu paths the shell knows. @@ -267,43 +281,43 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { if def.paths.is_empty() { def.paths.extend(menu_path(&def.command.id)); } - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Live menu items whose command has no row yet carry the catalogue's key. for &(_, label, shortcut, id) in crate::menu_catalog::CATALOG { // A Window panel item runs its shell command (`menus::panel_alias`), which has the row. - let owner = crate::menus::panel_alias(id).filter(|alias| seen.contains(*alias)).unwrap_or(id); + let owner = crate::menus::panel_alias(id).filter(|alias| index.contains_key(*alias)).unwrap_or(id); if label == "---" || !crate::menus::is_live(id) { continue; } - if seen.contains(owner) { + if let Some(&at) = index.get(owner) { // An engine row that names no key takes the catalogue's. if let Some(key) = shortcut.and_then(binding) - && let Some(row) = rows.iter_mut().find(|row| row.command.id == owner && row.defaults.is_empty()) + && rows[at].defaults.is_empty() { - row.defaults.push(key); + rows[at].defaults.push(key); } continue; } let mut def = app_row(id, label.trim_end_matches('…')); def.paths.extend(menu_path(id)); def.defaults.extend(shortcut.and_then(binding)); - push_row(&mut rows, &mut seen, def); + push_row(&mut rows, &mut index, def); } // Recorded actions run on their own key (the user's assignment is an override). for action in app.session.actions.list.actions() { let id = crate::actions::shortcut_id(&action.name); - push_row(&mut rows, &mut seen, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()])); + push_row(&mut rows, &mut index, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()])); } // A command's alternate keys (#3665: F3 is Copy as well as ⌘C), after every main key. for &(id, key) in photocraft_engine::prefs::ALTERNATE_SHORTCUTS { let Some(alternate) = binding(key) else { continue }; - if let Some(def) = rows.iter_mut().find(|d| d.command.id == id) - && !def.defaults.contains(&alternate) + if let Some(&at) = index.get(id) + && !rows[at].defaults.contains(&alternate) { - def.defaults.push(alternate); + rows[at].defaults.push(alternate); } } // Photoshop: ⌥ added to an adjustment's own key opens it at its last settings (⌥⌘L, ⌥⌘M, #8900); Layer › New › Layer's @@ -314,12 +328,12 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { } } // Edit in Quick Mask Mode is a button in the tool rail's footer, which shows its command's icon. - if let Some(def) = rows.iter_mut().find(|d| d.command.id == crate::panels::QUICK_MASK) { - def.icon = Some("square-dashed".into()); + if let Some(&at) = index.get(crate::panels::QUICK_MASK) { + rows[at].icon = Some("square-dashed".into()); } // Smart Objects › Reveal in Finder names this platform's file manager, in the list as in the menu. - if let Some(def) = rows.iter_mut().find(|d| d.command.id == "layer.smartObjects.revealInFinder") { - def.label = crate::menus::reveal_label().into(); + if let Some(&at) = index.get("layer.smartObjects.revealInFinder") { + rows[at].label = crate::menus::reveal_label().into(); } rows } @@ -350,25 +364,19 @@ pub(crate) fn bridged_rows() -> Vec { } /// The app's command catalog over `rows` ([`command_rows`]). The runtime rebuilds its keymap when `generation` -/// changes, so the holder takes a new one only when [`same_rows`] says the rows differ from the held ones. It -/// compares where the menu model rebuilds, which covers a new action and a tool list change. -// PLAN: hub-w1's `framework_before_input` holds the rows and the generation, and calls this in place of `catalog(app)`. +/// changes, so the holder (`framework_before_input`) takes a new one only when it rebuilds the rows: when the actions +/// list's revision moved. pub(crate) fn catalog(rows: Vec, generation: u64) -> Option { // `command_rows` gives each id once and every row the app scope, the two things `new` refuses; a refusal leaves the // runtime with no app catalog. AppCatalog::new(rows, generation).ok() } -/// Whether two row lists describe the same commands, labels, paths and keys. -pub(crate) fn same_rows(a: &[CommandDef], b: &[CommandDef]) -> bool { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| serde_json::to_value(x).ok() == serde_json::to_value(y).ok()) -} - /// The user's bindings for the runtime's keymap: Edit › Keyboard Shortcuts changes (`prefs.shortcuts`, /// `prefs.alternate_shortcuts`), the panel alias rule (#1272), and each row of [`RUNTIME_COMMANDS`] with its /// effective keys, so the framework command carries PhotoCraft's keys. The pane moves stay unbound -/// (`app::framework`: PhotoCraft binds F6 and Shift+F6). -pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides { +/// (`app::framework`: PhotoCraft binds F6 and Shift+F6). `rows` are the app's catalog rows ([`command_rows`]). +pub(crate) fn overrides(app: &PhotocraftApp, rows: &[CommandDef]) -> Overrides { let prefs = app.session.prefs(); // PLAN: `keymap_defs::prefs_overrides` is top-w20's tp.PT25 row, assumed as `prefs_overrides(&Preferences) -> Overrides`. let mut overrides = photocraft_engine::keymap_defs::prefs_overrides(prefs); @@ -409,7 +417,7 @@ pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides { // A key an action holds is the action's alone (it is checked before every command's key, as in Photoshop): the // command that has it by default keeps its other keys. if !taken.is_empty() { - for row in command_rows(app) { + for row in rows { let id = row.command.id.as_str(); if id.starts_with(crate::actions::SHORTCUT_PREFIX) || is_bridged(id) { continue; diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index a948757aae..2abdd835b2 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -338,14 +338,14 @@ pub(crate) fn slots(toolbar: &ToolbarCustomization) -> Vec> { slots } -/// The rail's [`slots`] for the stored layout, built once per preferences revision ([`PrefsStore::rev`]): the toolbar, its -/// measure and the dock's grid read them several times a frame, and the layout changes only with the preferences. +/// The rail's [`slots`] for the stored layout, built once per catalog revision ([`PrefsStore::catalog_rev`], which moves +/// with the toolbar layout): the toolbar, its measure and the dock's grid read them several times a frame. /// -/// [`PrefsStore::rev`]: photocraft_engine::prefs::PrefsStore::rev +/// [`PrefsStore::catalog_rev`]: photocraft_engine::prefs::PrefsStore::catalog_rev #[derive(Default)] pub(crate) struct ToolbarSlots(std::cell::RefCell>); -/// The rail's slots, shared by the readers of one preferences revision. +/// The rail's slots, shared by the readers of one catalog revision. type RailSlots = std::sync::Arc<[ToolSlot]>; impl ToolbarSlots { @@ -353,10 +353,10 @@ impl ToolbarSlots { pub(crate) fn get(&self, prefs: &photocraft_engine::prefs::PrefsStore) -> RailSlots { let mut held = self.0.borrow_mut(); match &*held { - Some((rev, slots)) if *rev == prefs.rev() => slots.clone(), + Some((rev, slots)) if *rev == prefs.catalog_rev() => slots.clone(), _ => { let built: RailSlots = slots(&prefs.get().toolbar).into(); - *held = Some((prefs.rev(), built.clone())); + *held = Some((prefs.catalog_rev(), built.clone())); built } } diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index 282c69dba3..7f035e8783 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -4,7 +4,7 @@ //! The session holds everything the dialog edits: the draft keymap, the shortcut sets, the Menus //! draft and the text of a set waiting to be reviewed. Cancel drops it and the runtime never saw //! a change; OK writes the preferences once ([`save_keys`], then the menus), and the runtime's -//! keymap follows the new preferences revision (`shortcut_dispatch::overrides`). +//! keymap follows the new shortcut preferences (`shortcut_dispatch::overrides`). //! //! The Toolbar tab is not here: Edit › Toolbar opens the toolbar drawer. @@ -79,7 +79,12 @@ pub(crate) fn profiles_of(prefs: &Preferences) -> Profiles { /// runtime's keymap is built for, and the preferences' bindings as overrides. pub(crate) fn draft_keymap(app: &PhotocraftApp) -> Keymap { let platform = windows::os_of(app.ctx()); - Keymap::new(crate::shortcut_dispatch::command_rows(app).into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform) + // The runtime catalog's held rows while they are current; built here before the first frame holds them. + let rows = match app.framework.catalog_rows_at(app.session.actions.list.revision()) { + Some(rows) => rows.to_vec(), + None => crate::shortcut_dispatch::command_rows(app), + }; + Keymap::new(rows.into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform) .with_reserved(reserved::system(platform)) .with_overrides(keymap_defs::prefs_overrides(app.session.prefs())) } diff --git a/crates/ui-egui/src/tools/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs index aa1604f9b2..982ed64deb 100644 --- a/crates/ui-egui/src/tools/artboard_tool.rs +++ b/crates/ui-egui/src/tools/artboard_tool.rs @@ -287,6 +287,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(ArtboardCommand::AddNew.into(), state)] } +/// What [`command_states`] reads: whether a document is open, and the placing mode. +pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { + [u64::from(app.session.active().is_some()), u64::from(app.ui.artboard_tool.adding), 0, 0] +} + /// Runs a fired Artboard command: Add New Artboard flips the placing mode and adds no board. `ctx` is the shape every /// command source takes. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index c09a67a0e3..dd2d513fcd 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -317,6 +317,14 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// What [`command_states`] reads: the active document and its revision (the selected slice resolves from its +/// slices), the selected slice's number and the lock. +pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { + let revision = app.session.active().map_or(u64::MAX, |st| st.revision); + let selected = app.ui.slices.selected.map_or(u64::MAX, |n| n as u64); + [app.session.active_generation(), revision, selected, u64::from(app.session.file_menu.slices_locked)] +} + /// Runs a fired slice command; whether it was one. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = SliceCommand::from_ref(command) else { return false }; From 8c4b530f3318eec3c14f9e32a33788e584e24934 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:14:37 +0000 Subject: [PATCH 32/38] Catalog trial edits the tool and colour preferences directly (#15709) --- crates/ui-egui/src/app/framework/catalog_tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs index dd2e5a8d9a..ba9971f262 100644 --- a/crates/ui-egui/src/app/framework/catalog_tests.rs +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -41,11 +41,16 @@ fn the_catalog_is_built_only_when_its_inputs_change() { frames(&mut app, 100); assert_eq!(builds(&app), (1, 1), "idle frames build nothing"); + // The tool and the colours as the app saves them: preference edits outside the catalog's inputs. let prefs = app.session.prefs.rev(); crate::tool_memory::select(&mut app, Tool::Brush); app.run("tools.swapColors", json!({})).unwrap(); + app.session.edit_prefs(|p| { + p.selected_tool = json!("Brush"); + p.tool_colors = Default::default(); + }); frames(&mut app, 2); - assert_ne!(app.session.prefs.rev(), prefs, "the tool and the colours are preferences"); + assert_ne!(app.session.prefs.rev(), prefs); assert_eq!(builds(&app), (1, 1), "a tool or colour change builds nothing"); let generation = app.framework.keymap_inputs().1; From 71a5a0bc4042525b65472c3e3b00bbed36805b62 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:27:32 +0000 Subject: [PATCH 33/38] Menus follow the preferences they show; catalog generation moves only with action names (#15709) The menu state hashes the preferences its rows read (Edit > Menus, the Quick Export format, the Font Preview Size) instead of relying on the keymap's inputs. The catalog keeps the action names it was built from: an action edit that keeps every name rebuilds neither the rows nor the overrides, which now key on the catalog's generation. Trials cover the slice and artboard keys and the step edit. --- crates/ui-egui/src/app/framework.rs | 38 +++++++++++----- .../src/app/framework/catalog_tests.rs | 45 ++++++++++++++++++- crates/ui-egui/src/menus/native_menu.rs | 9 +++- crates/ui-egui/src/menus/native_menu/tests.rs | 19 ++++++++ 4 files changed, 95 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 2c6e535e69..afa5267feb 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -89,16 +89,19 @@ pub struct Framework { /// The runtime's keymap overrides. The runtime rebuilds its keymap when the `Arc` changes, so /// it is replaced only when the bindings it carries change. overrides: Arc, - /// What `overrides` was built from: the preferences' catalog revision and the actions list's revision. + /// What `overrides` was built from: the preferences' catalog revision and the catalog's generation. overrides_key: Option<(u64, u64)>, /// Advances each time `overrides` is replaced. overrides_generation: u64, /// The app's command catalog, built from `catalog_rows`. catalog: Option, - /// The rows `catalog` was built from ([`command_rows`](crate::shortcut_dispatch::command_rows)), the actions - /// list's revision they were built at (their one input that changes at run time), and the catalog's generation: - /// the runtime rebuilds its keymap when the generation changes, so it advances only when the rows are rebuilt. + /// The rows `catalog` was built from ([`command_rows`](crate::shortcut_dispatch::command_rows)), the action + /// names they were built from (their one input that changes at run time), the actions list's revision those names + /// were last read at, and the catalog's generation: the runtime rebuilds its keymap when the generation changes, + /// so it advances only when the names change. The revision is the fast check; it assumes the list is edited in + /// place or through `ActionList::replace`, which keep it moving forward. catalog_rows: Vec, + catalog_actions: Vec, catalog_rows_rev: Option, catalog_generation: u64, /// How many times the rows and the overrides were built, for the count trials. @@ -286,6 +289,7 @@ impl Framework { overrides_generation: 0, catalog: None, catalog_rows: Vec::new(), + catalog_actions: Vec::new(), catalog_rows_rev: None, catalog_generation: 0, #[cfg(test)] @@ -506,11 +510,13 @@ impl Framework { (self.catalog_rows_rev == Some(actions_rev)).then_some(self.catalog_rows.as_slice()) } - /// Takes `rows`, built at actions list revision `actions_rev`, as the catalog's rows: a new catalog generation. - fn set_catalog(&mut self, actions_rev: u64, rows: Vec) { + /// Takes `rows`, built from the action names `actions` at actions list revision `actions_rev`, as the catalog's + /// rows: a new catalog generation. + fn set_catalog(&mut self, actions_rev: u64, actions: Vec, rows: Vec) { self.catalog_generation += 1; self.catalog = crate::shortcut_dispatch::catalog(rows.clone(), self.catalog_generation); self.catalog_rows = rows; + self.catalog_actions = actions; self.catalog_rows_rev = Some(actions_rev); #[cfg(test)] { @@ -638,14 +644,22 @@ impl PhotocraftApp { /// runs them), the commands the canvas ran (`record_view_commands`, in `logic`) and whether a /// component refused its input. pub(crate) fn framework_before_input(&mut self, ctx: &egui::Context) { - // The catalog's rows change only with the actions list; the bindings also with the shortcut - // preferences. - let actions_rev = self.session.actions.list.revision(); + // The catalog's rows change only with the action names; the bindings with the rows and the + // shortcut preferences. + let list = &self.session.actions.list; + let actions_rev = list.revision(); if self.framework.catalog_rows_rev != Some(actions_rev) { - let rows = crate::shortcut_dispatch::command_rows(self); - self.framework.set_catalog(actions_rev, rows); + let same = self.framework.catalog_rows_rev.is_some() + && self.framework.catalog_actions.iter().map(String::as_str).eq(list.actions().iter().map(|action| action.name.as_str())); + if same { + self.framework.catalog_rows_rev = Some(actions_rev); + } else { + let actions = list.actions().iter().map(|action| action.name.clone()).collect(); + let rows = crate::shortcut_dispatch::command_rows(self); + self.framework.set_catalog(actions_rev, actions, rows); + } } - let overrides_key = (self.session.prefs.catalog_rev(), actions_rev); + let overrides_key = (self.session.prefs.catalog_rev(), self.framework.catalog_generation); if self.framework.overrides_key != Some(overrides_key) { let overrides = crate::shortcut_dispatch::overrides(self, &self.framework.catalog_rows); self.framework.set_overrides(overrides_key, overrides); diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs index ba9971f262..24cf76cce6 100644 --- a/crates/ui-egui/src/app/framework/catalog_tests.rs +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -1,14 +1,17 @@ //! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what //! they read changes. +use craft::automation::actions::ActionStep; use serde_json::json; use super::{COMMAND_SOURCES, PhotocraftApp}; use crate::canvas::testing; use crate::state::Tool; -/// The place of the tool commands' source in [`COMMAND_SOURCES`]. +/// The places of the keyed sources in [`COMMAND_SOURCES`]. const TOOL_SOURCE: usize = 1; +const SLICE_SOURCE: usize = 3; +const ARTBOARD_SOURCE: usize = 5; fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -27,6 +30,11 @@ fn keyed_runs(app: &PhotocraftApp) -> Vec> { COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect() } +/// The keyed sources that computed their states between `before` and `after`. +fn ran(before: &[Option], after: &[Option]) -> Vec { + before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect() +} + fn frames(app: &mut PhotocraftApp, n: usize) { for _ in 0..n { testing::frame(app); @@ -54,11 +62,13 @@ fn the_catalog_is_built_only_when_its_inputs_change() { assert_eq!(builds(&app), (1, 1), "a tool or colour change builds nothing"); let generation = app.framework.keymap_inputs().1; + assert_eq!(app.framework.overrides.get("filter.blur.gaussian"), None); app.session.edit_prefs(|p| { - p.shortcuts.insert("edit.copy".into(), "Ctrl+Shift+K".into()); + p.shortcuts.insert("filter.blur.gaussian".into(), "Cmd+Alt+G".into()); }); frames(&mut app, 2); assert_eq!(builds(&app), (1, 2), "a shortcut edit builds the overrides once and leaves the rows"); + assert!(app.framework.overrides.get("filter.blur.gaussian").is_some_and(|keys| !keys.is_empty()), "the overrides carry the new key"); assert_eq!(app.framework.keymap_inputs().1, generation, "the catalog keeps its generation"); app.session.actions.list.new_action("Trial", None).unwrap(); @@ -66,6 +76,15 @@ fn the_catalog_is_built_only_when_its_inputs_change() { assert_eq!(builds(&app), (2, 3), "a new action builds the rows and the overrides once"); assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog takes a new generation"); assert!(app.framework.catalog_rows.iter().any(|row| row.label == "Trial"), "the action has its row"); + + // Edits that keep every action's name leave the rows. + let list = &mut app.session.actions.list; + let at = list.actions().iter().position(|action| action.name == "Trial").unwrap(); + list.insert_step(at, 0, ActionStep::new("layer.new", json!({}))).unwrap(); + list.toggle_step(at, 0).unwrap(); + frames(&mut app, 2); + assert_eq!(builds(&app), (2, 3), "a step edit builds nothing"); + assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation"); } #[test] @@ -86,4 +105,26 @@ fn keyed_command_states_run_only_when_their_key_changes() { let moved = usize::from(at == TOOL_SOURCE); assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change"); } + + let before = keyed_runs(&app); + app.ui.artboard_tool.adding = true; + frames(&mut app, 2); + assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode"); + + let before = keyed_runs(&app); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + frames(&mut app, 2); + let after = keyed_runs(&app); + assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens"); + let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled(); + assert!(has_doc(&app)); + + let before = keyed_runs(&app); + app.ui.slices.selected = Some(1); + frames(&mut app, 2); + let selected = keyed_runs(&app); + assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice"); + app.session.file_menu.slices_locked = true; + frames(&mut app, 2); + assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock"); } diff --git a/crates/ui-egui/src/menus/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs index 793776e391..42a60ed18d 100644 --- a/crates/ui-egui/src/menus/native_menu.rs +++ b/crates/ui-egui/src/menus/native_menu.rs @@ -76,7 +76,7 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) { /// What the menus' rows depend on, cheaply: commands run, the documents (their names, in tab /// order, for the Window menu) and the active one's revision, selection, recent files, panels and -/// view state, the language. `input` forces a change on frames with a click or key press, which +/// view state, the keymap, and the preferences the rows show. `input` forces a change on frames with a click or key press, which /// covers state the hash doesn't list. pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); @@ -119,7 +119,12 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { crate::panel_docking::is_checked(app, panel.id).hash(&mut h); } serde_json::to_string(&(&ui.extras, &ui.view, ui.theme.id().as_str(), ui.theme.is_dark(), ui.tool)).unwrap_or_default().hash(&mut h); - s.prefs().interface.language.hash(&mut h); + // The preferences the rows show: the language, Edit › Menus (hidden rows, colours), the Quick Export label and + // the Font Preview Size tick. + let prefs = s.prefs(); + prefs.interface.language.hash(&mut h); + (&prefs.menus.hidden, &prefs.menus.colors, prefs.interface.show_menu_colors).hash(&mut h); + (prefs.export.quick_export_format, prefs.type_.font_preview).hash(&mut h); h.finish() } diff --git a/crates/ui-egui/src/menus/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs index 24defb62cc..81083493c4 100644 --- a/crates/ui-egui/src/menus/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -237,3 +237,22 @@ fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() { h.run_steps(2); assert_eq!(ticked(&synced), Some(true), "ticked again once it shows"); } + +/// The menus follow the preferences they show, even when they change without input (settings merged from another +/// instance), and not the tool and colour preferences the app saves on every change. +#[test] +fn the_menu_state_follows_the_preferences_the_rows_show() { + let mut app = app(false); + let shown = state_hash(&app, None); + app.session.edit_prefs(|p| { + p.selected_tool = json!("Brush"); + p.tool_colors = Default::default(); + }); + assert_eq!(state_hash(&app, None), shown, "the saved tool and colours are not in the menus"); + + app.session.edit_prefs(|p| p.menus.hidden.push("filter.blur.gaussian".into())); + let hidden = state_hash(&app, None); + assert_ne!(hidden, shown, "Edit › Menus hides a row"); + app.session.edit_prefs(|p| p.export.quick_export_format = photocraft_engine::prefs::QuickExportFormat::Jpg); + assert_ne!(state_hash(&app, None), hidden, "the Quick Export label names the format"); +} From 1c97abb4751b1b17ed2bdad96834a2fc2eb67c4b Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:35:19 +0000 Subject: [PATCH 34/38] Split the command table into per-owner fragments Fragments live in cmd/table//.rs, one directory per future crate (core, model, store, paint, image). SPECS names each fragment so the order test can say which one a misplaced command comes from. scripts/engine_split/table_fragments.py moves a branch's edits of the old inline table into the fragments. --- crates/engine/src/cmd.rs | 284 ++++++++---------- crates/engine/src/cmd/adjust_cmds.rs | 2 +- crates/engine/src/cmd/command_order_tests.rs | 22 +- crates/engine/src/cmd/edit_menu.rs | 62 ---- crates/engine/src/cmd/table.rs | 8 + crates/engine/src/cmd/table/core.rs | 5 + crates/engine/src/cmd/table/core/edit_menu.rs | 9 + crates/engine/src/cmd/table/core/file_menu.rs | 28 ++ .../src/cmd/{ => table/core}/queries.rs | 4 +- .../src/cmd/{ => table/core}/select_menu.rs | 7 +- .../src/cmd/{paint.rs => table/core/tools.rs} | 15 +- crates/engine/src/cmd/table/image.rs | 2 + .../src/cmd/{ => table/image}/adjustments.rs | 4 +- .../engine/src/cmd/table/image/image_menu.rs | 24 ++ crates/engine/src/cmd/table/model.rs | 3 + .../engine/src/cmd/table/model/edit_menu.rs | 49 +++ .../src/cmd/{ => table/model}/image_menu.rs | 36 +-- .../src/cmd/{ => table/model}/layer_menu.rs | 130 +++----- crates/engine/src/cmd/table/paint.rs | 2 + .../engine/src/cmd/table/paint/edit_menu.rs | 14 + crates/engine/src/cmd/table/paint/stroke.rs | 14 + crates/engine/src/cmd/table/store.rs | 2 + .../src/cmd/{ => table/store}/file_menu.rs | 30 +- .../engine/src/cmd/table/store/layer_menu.rs | 43 +++ scripts/engine_split/table_fragments.py | 214 +++++++++++++ 25 files changed, 647 insertions(+), 366 deletions(-) delete mode 100644 crates/engine/src/cmd/edit_menu.rs create mode 100644 crates/engine/src/cmd/table.rs create mode 100644 crates/engine/src/cmd/table/core.rs create mode 100644 crates/engine/src/cmd/table/core/edit_menu.rs create mode 100644 crates/engine/src/cmd/table/core/file_menu.rs rename crates/engine/src/cmd/{ => table/core}/queries.rs (97%) rename crates/engine/src/cmd/{ => table/core}/select_menu.rs (96%) rename crates/engine/src/cmd/{paint.rs => table/core/tools.rs} (64%) create mode 100644 crates/engine/src/cmd/table/image.rs rename crates/engine/src/cmd/{ => table/image}/adjustments.rs (98%) create mode 100644 crates/engine/src/cmd/table/image/image_menu.rs create mode 100644 crates/engine/src/cmd/table/model.rs create mode 100644 crates/engine/src/cmd/table/model/edit_menu.rs rename crates/engine/src/cmd/{ => table/model}/image_menu.rs (52%) rename crates/engine/src/cmd/{ => table/model}/layer_menu.rs (81%) create mode 100644 crates/engine/src/cmd/table/paint.rs create mode 100644 crates/engine/src/cmd/table/paint/edit_menu.rs create mode 100644 crates/engine/src/cmd/table/paint/stroke.rs create mode 100644 crates/engine/src/cmd/table/store.rs rename crates/engine/src/cmd/{ => table/store}/file_menu.rs (76%) create mode 100644 crates/engine/src/cmd/table/store/layer_menu.rs create mode 100644 scripts/engine_split/table_fragments.py diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index accf8088c4..c5038b5600 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -27,27 +27,6 @@ pub struct CommandSpec { pub journal: bool, } -/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. -pub(crate) fn desaturate_adjustment() -> Adjustment { - Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } -} - -/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). -fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { - if let Some(d) = s.active() { - let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height)); - // Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point - // lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`). - let half = photocraft_geom::Affine::translate(0.5, 0.5); - s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5))); - } - s.edit(label, |doc, _| { - crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t)); - Ok(()) - })?; - Ok(Value::Null) -} - macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } @@ -58,7 +37,6 @@ pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; mod adjust_params; -mod adjustments; pub mod align_cmds; pub mod analysis_cmds; pub mod artboard_cmds; @@ -87,7 +65,6 @@ pub mod cutout_cmds; pub mod distort_cmds; pub mod document_preset_cmds; pub mod edit_cmds; -mod edit_menu; pub mod edit_menu_cmds; mod enabled; pub mod eraser_cmds; @@ -96,7 +73,6 @@ pub mod exr_cmds; pub mod extra_cmds; pub mod face_cmds; pub mod file_cmds; -mod file_menu; pub mod fill_cmds; pub mod fill_key_cmds; pub mod float_cmds; @@ -115,13 +91,11 @@ pub mod history_options_cmds; pub mod history_select_cmds; pub mod history_source_cmds; pub mod image_cmds; -mod image_menu; pub mod layer_copy_cmds; pub mod layer_css_cmds; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; -mod layer_menu; pub mod layer_menu_cmds; pub mod layer_multi_cmds; pub mod layer_nav_cmds; @@ -140,7 +114,6 @@ pub mod notes_cmds; #[cfg(test)] mod notes_stored_values_tests; mod ops; -mod paint; pub mod paint_cmds; mod params; pub(super) mod path_edit_cmds; @@ -152,7 +125,6 @@ pub mod pick_cmds; pub mod plugin_cmds; pub mod preset_import_cmds; pub mod print_cmds; -mod queries; pub mod rasterize_style_cmds; pub mod redeye_cmds; pub mod render_cmds; @@ -162,7 +134,6 @@ pub mod sample_cmds; mod sample_zoom_box_tests; pub mod sampler_cmds; pub mod select_extra_cmds; -mod select_menu; pub mod selection_cmds; pub mod slice_cmds; pub mod smart_cmds; @@ -173,6 +144,7 @@ pub mod stamp_cmds; pub mod style_asl_cmds; pub mod swatch_cmds; pub mod symmetry_cmds; +mod table; pub(super) mod timeline_cmds; pub mod transform_cmds; pub(super) mod trap_cmds; @@ -280,133 +252,141 @@ fn registry() -> &'static Registry { // ---------- the table ---------- -#[allow(clippy::too_many_lines)] -/// Register the core file, edit, layer and document commands. -const SPECS: &[fn() -> Vec] = &[ - file_menu::specs, - edit_menu::specs, - select_menu::specs, - layer_menu::specs, - image_menu::specs, - paint::specs, - queries::specs, - adjustments::specs, - crate::layer_style::specs, - crate::contour_lib_cmds::specs, - crate::layer_list_cmds::specs, - crate::filters::specs, - crate::filters_ext::specs, - crate::color_to_alpha_cmds::specs, - crate::gallery_cmds::specs, - crate::gradient_fill_cmds::specs, - crate::solid_fill_cmds::specs, - crate::pattern_fill_cmds::specs, - crate::type_cmds::specs, - crate::type_mask_cmds::specs, - crate::transform_cmds::specs, - crate::float_cmds::specs, - crate::vector_cmds::specs, - crate::path_edit_cmds::specs, - crate::smartselect_cmds::specs, - crate::cutout_cmds::specs, - crate::symmetry_cmds::specs, - crate::edit_cmds::specs, - crate::smart_svg_cmds::specs, - crate::color_cmds::specs, - crate::brush_cmds::specs, - crate::brush_preset_cmds::specs, - crate::eraser_cmds::specs, - crate::preset_import_cmds::specs, - crate::style_asl_cmds::specs, - crate::atn_cmds::specs, - crate::actions_edit_cmds::specs, - crate::swatch_cmds::specs, - crate::retouch_cmds::specs, - crate::redeye_cmds::specs, - crate::image_cmds::specs, - crate::perspective_crop_cmds::specs, - crate::selection_cmds::specs, - crate::magnetic_cmds::specs, - crate::select_extra_cmds::specs, - crate::paint_cmds::specs, - crate::extra_cmds::specs, - crate::background_cmds::specs, - crate::file_cmds::specs, - crate::exr_cmds::specs, - crate::type_extra_cmds::specs, - crate::type_area_cmds::specs, - crate::type_styles_cmds::specs, - crate::type_spell_cmds::specs, - crate::type_caret_cmds::specs, - crate::smart_cmds::specs, - crate::layer_multi_cmds::specs, - crate::layer_copy_cmds::specs, - crate::prefs::specs, - crate::edit_menu_cmds::specs, - crate::fill_key_cmds::specs, - crate::sample_cmds::specs, - crate::face_cmds::specs, - crate::sampler_cmds::specs, - crate::brush_key_cmds::specs, - crate::stamp_cmds::specs, - crate::align_cmds::specs, - crate::photo_cmds::specs, - crate::lens_cmds::specs, - crate::vp_cmds::specs, - crate::channel_cmds::specs, - crate::adjust_cmds::specs, - crate::layer_menu_cmds::specs, - crate::layer_label_cmds::specs, - crate::layer_css_cmds::specs, - crate::layer_xmp_cmds::specs, - crate::mode_cmds::specs, - crate::multichannel_cmds::specs, - crate::pattern_cmds::specs, - crate::warp_cmds::specs, - crate::comps_cmds::specs, - crate::artboard_cmds::specs, - crate::distort_cmds::specs, - crate::analysis_cmds::specs, - crate::notes_cmds::specs, - crate::font_library_cmds::specs, - crate::history_cmds::specs, - crate::history_options_cmds::specs, - crate::history_menu_cmds::specs, - crate::history_source_cmds::specs, - crate::history_select_cmds::specs, - crate::proof_sim::specs, - crate::presets::specs, - crate::document_preset_cmds::specs, - crate::export_preset_cmds::specs, - crate::render_cmds::specs, - crate::slice_cmds::specs, - crate::web_cmds::specs, - crate::automate_cmds::specs, - crate::print_cmds::specs, - crate::installed_profiles::specs, - crate::pick_cmds::specs, - crate::layer_nav_cmds::specs, - crate::frame_cmds::specs, - crate::migrate_cmds::specs, - crate::trap_cmds::specs, - crate::timeline_cmds::specs, - crate::video_cmds::specs, - crate::jobs::specs, - crate::wia_cmds::specs, - crate::rasterize_style_cmds::specs, - crate::variables_cmds::specs, - crate::plugin_cmds::specs, - crate::group_view_cmds::specs, - crate::fx_view_cmds::specs, - crate::fx_visibility_cmds::specs, - crate::mask_view_cmds::specs, - crate::layer_mask_props_cmds::specs, - crate::actions_cmds::specs, +/// Every table fragment with its name, in registry order. The order is part of the behaviour (menus +/// list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by the +/// crate that will own them; a menu split between owners has one fragment per contiguous run. +const SPECS: &[(&str, fn() -> Vec)] = &[ + ("store::file_menu", table::store::file_menu::specs), + ("core::file_menu", table::core::file_menu::specs), + ("core::edit_menu", table::core::edit_menu::specs), + ("paint::edit_menu", table::paint::edit_menu::specs), + ("model::edit_menu", table::model::edit_menu::specs), + ("core::select_menu", table::core::select_menu::specs), + ("model::layer_menu", table::model::layer_menu::specs_before_gradient), + ("store::layer_menu", table::store::layer_menu::specs), + ("model::layer_menu", table::model::layer_menu::specs_after_gradient), + ("model::image_menu", table::model::image_menu::specs), + ("image::image_menu", table::image::image_menu::specs), + ("paint::stroke", table::paint::stroke::specs), + ("core::tools", table::core::tools::specs), + ("core::queries", table::core::queries::specs), + ("image::adjustments", table::image::adjustments::specs), + ("layer_style", crate::layer_style::specs), + ("contour_lib_cmds", crate::contour_lib_cmds::specs), + ("layer_list_cmds", crate::layer_list_cmds::specs), + ("filters", crate::filters::specs), + ("filters_ext", crate::filters_ext::specs), + ("color_to_alpha_cmds", crate::color_to_alpha_cmds::specs), + ("gallery_cmds", crate::gallery_cmds::specs), + ("gradient_fill_cmds", crate::gradient_fill_cmds::specs), + ("solid_fill_cmds", crate::solid_fill_cmds::specs), + ("pattern_fill_cmds", crate::pattern_fill_cmds::specs), + ("type_cmds", crate::type_cmds::specs), + ("type_mask_cmds", crate::type_mask_cmds::specs), + ("transform_cmds", crate::transform_cmds::specs), + ("float_cmds", crate::float_cmds::specs), + ("vector_cmds", crate::vector_cmds::specs), + ("path_edit_cmds", crate::path_edit_cmds::specs), + ("smartselect_cmds", crate::smartselect_cmds::specs), + ("cutout_cmds", crate::cutout_cmds::specs), + ("symmetry_cmds", crate::symmetry_cmds::specs), + ("edit_cmds", crate::edit_cmds::specs), + ("smart_svg_cmds", crate::smart_svg_cmds::specs), + ("color_cmds", crate::color_cmds::specs), + ("brush_cmds", crate::brush_cmds::specs), + ("brush_preset_cmds", crate::brush_preset_cmds::specs), + ("eraser_cmds", crate::eraser_cmds::specs), + ("preset_import_cmds", crate::preset_import_cmds::specs), + ("style_asl_cmds", crate::style_asl_cmds::specs), + ("atn_cmds", crate::atn_cmds::specs), + ("actions_edit_cmds", crate::actions_edit_cmds::specs), + ("swatch_cmds", crate::swatch_cmds::specs), + ("retouch_cmds", crate::retouch_cmds::specs), + ("redeye_cmds", crate::redeye_cmds::specs), + ("image_cmds", crate::image_cmds::specs), + ("perspective_crop_cmds", crate::perspective_crop_cmds::specs), + ("selection_cmds", crate::selection_cmds::specs), + ("magnetic_cmds", crate::magnetic_cmds::specs), + ("select_extra_cmds", crate::select_extra_cmds::specs), + ("paint_cmds", crate::paint_cmds::specs), + ("extra_cmds", crate::extra_cmds::specs), + ("background_cmds", crate::background_cmds::specs), + ("file_cmds", crate::file_cmds::specs), + ("exr_cmds", crate::exr_cmds::specs), + ("type_extra_cmds", crate::type_extra_cmds::specs), + ("type_area_cmds", crate::type_area_cmds::specs), + ("type_styles_cmds", crate::type_styles_cmds::specs), + ("type_spell_cmds", crate::type_spell_cmds::specs), + ("type_caret_cmds", crate::type_caret_cmds::specs), + ("smart_cmds", crate::smart_cmds::specs), + ("layer_multi_cmds", crate::layer_multi_cmds::specs), + ("layer_copy_cmds", crate::layer_copy_cmds::specs), + ("prefs", crate::prefs::specs), + ("edit_menu_cmds", crate::edit_menu_cmds::specs), + ("fill_key_cmds", crate::fill_key_cmds::specs), + ("sample_cmds", crate::sample_cmds::specs), + ("face_cmds", crate::face_cmds::specs), + ("sampler_cmds", crate::sampler_cmds::specs), + ("brush_key_cmds", crate::brush_key_cmds::specs), + ("stamp_cmds", crate::stamp_cmds::specs), + ("align_cmds", crate::align_cmds::specs), + ("photo_cmds", crate::photo_cmds::specs), + ("lens_cmds", crate::lens_cmds::specs), + ("vp_cmds", crate::vp_cmds::specs), + ("channel_cmds", crate::channel_cmds::specs), + ("adjust_cmds", crate::adjust_cmds::specs), + ("layer_menu_cmds", crate::layer_menu_cmds::specs), + ("layer_label_cmds", crate::layer_label_cmds::specs), + ("layer_css_cmds", crate::layer_css_cmds::specs), + ("layer_xmp_cmds", crate::layer_xmp_cmds::specs), + ("mode_cmds", crate::mode_cmds::specs), + ("multichannel_cmds", crate::multichannel_cmds::specs), + ("pattern_cmds", crate::pattern_cmds::specs), + ("warp_cmds", crate::warp_cmds::specs), + ("comps_cmds", crate::comps_cmds::specs), + ("artboard_cmds", crate::artboard_cmds::specs), + ("distort_cmds", crate::distort_cmds::specs), + ("analysis_cmds", crate::analysis_cmds::specs), + ("notes_cmds", crate::notes_cmds::specs), + ("font_library_cmds", crate::font_library_cmds::specs), + ("history_cmds", crate::history_cmds::specs), + ("history_options_cmds", crate::history_options_cmds::specs), + ("history_menu_cmds", crate::history_menu_cmds::specs), + ("history_source_cmds", crate::history_source_cmds::specs), + ("history_select_cmds", crate::history_select_cmds::specs), + ("proof_sim", crate::proof_sim::specs), + ("presets", crate::presets::specs), + ("document_preset_cmds", crate::document_preset_cmds::specs), + ("export_preset_cmds", crate::export_preset_cmds::specs), + ("render_cmds", crate::render_cmds::specs), + ("slice_cmds", crate::slice_cmds::specs), + ("web_cmds", crate::web_cmds::specs), + ("automate_cmds", crate::automate_cmds::specs), + ("print_cmds", crate::print_cmds::specs), + ("installed_profiles", crate::installed_profiles::specs), + ("pick_cmds", crate::pick_cmds::specs), + ("layer_nav_cmds", crate::layer_nav_cmds::specs), + ("frame_cmds", crate::frame_cmds::specs), + ("migrate_cmds", crate::migrate_cmds::specs), + ("trap_cmds", crate::trap_cmds::specs), + ("timeline_cmds", crate::timeline_cmds::specs), + ("video_cmds", crate::video_cmds::specs), + ("jobs", crate::jobs::specs), + ("wia_cmds", crate::wia_cmds::specs), + ("rasterize_style_cmds", crate::rasterize_style_cmds::specs), + ("variables_cmds", crate::variables_cmds::specs), + ("plugin_cmds", crate::plugin_cmds::specs), + ("group_view_cmds", crate::group_view_cmds::specs), + ("fx_view_cmds", crate::fx_view_cmds::specs), + ("fx_visibility_cmds", crate::fx_visibility_cmds::specs), + ("mask_view_cmds", crate::mask_view_cmds::specs), + ("layer_mask_props_cmds", crate::layer_mask_props_cmds::specs), + ("actions_cmds", crate::actions_cmds::specs), ]; /// Every registered command, in the order of SPECS. fn build() -> Vec { - let specs = SPECS.iter().flat_map(|specs| specs()); + let specs = SPECS.iter().flat_map(|(_, specs)| specs()); // The dispatch guard's unit test needs a command that panics on purpose (REL-3). #[cfg(test)] let specs = specs.chain(std::iter::once(test_panic_command())); diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index f7dd8925bd..e0951ee2de 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -403,7 +403,7 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_ })?; } else if kind == "desaturate" { let mode = surf.format().mode; - if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() { + if crate::pixels::adjust_surface(&mut out, &super::table::image::image_menu::desaturate_adjustment(), None, mode).is_err() { return Ok(None); } } else if kind == "equalize" { diff --git a/crates/engine/src/cmd/command_order_tests.rs b/crates/engine/src/cmd/command_order_tests.rs index 840f66a72e..0dba5a1622 100644 --- a/crates/engine/src/cmd/command_order_tests.rs +++ b/crates/engine/src/cmd/command_order_tests.rs @@ -1,11 +1,27 @@ -use super::command_specs; +use super::{SPECS, command_specs}; +/// Menus, the Command Palette and the automation docs list commands in registry order, so the +/// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when +/// rebasing, adding each new command's id after its predecessor. #[test] fn registered_command_ids_keep_their_order() { let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { - panic!("command {i} is {} where {} was registered", ids[i], expected[i]); + panic!("command {i} is {} where {} was registered{}", ids[i], expected[i], fragment_of(i)); } - assert_eq!(ids.len(), expected.len(), "the number of registered commands changed"); + assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}", fragment_of(ids.len().min(expected.len()))); +} + +/// Names the fragment that registers command `index`, for the failure message. +fn fragment_of(index: usize) -> String { + let mut first = 0; + for (name, specs) in SPECS { + let len = specs().len(); + if index < first + len { + return format!(" (fragment `{name}`, commands {first}..{})", first + len); + } + first += len; + } + String::new() } diff --git a/crates/engine/src/cmd/edit_menu.rs b/crates/engine/src/cmd/edit_menu.rs deleted file mode 100644 index a21b3164b0..0000000000 --- a/crates/engine/src/cmd/edit_menu.rs +++ /dev/null @@ -1,62 +0,0 @@ -use super::{CommandSpec, Value, can_redo, can_undo, has_pixel_or_channel, is_mask_target, json, layer_param}; - -/// Edit menu commands: Undo, Redo, Fill and Clear. -pub(super) fn specs() -> Vec { - vec![ - cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), - cmd!( - "edit.fill", - "Fill…", - ["Edit"], - Some("Shift+F5"), - r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, - has_pixel_or_channel, - crate::fill_cmds::fill - ), - cmd!( - "edit.clear", - "Clear", - ["Edit"], - None, - r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, - has_pixel_or_channel, - |s, p| { - let bg = s.tools.background; - // A targeted alpha channel or Quick Mask is filled instead (#2734). - let channel = if crate::channel_cmds::is_channel_target(p) { - Some(p.clone()) - } else if p.get("target").is_none() { - crate::channel_cmds::targeted_channel(s) - } else { - None - }; - if let Some(t) = channel { - s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; - return Ok(Value::Null); - } - let id = layer_param(s, p)?; - if is_mask_target(p) { - s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; - return Ok(Value::Null); - } - // A targeted colour channel clears that channel only (#2720). - if let Some(colors) = crate::color_channels::target(s, p)? { - s.edit("Clear", |doc, _| { - for k in colors.indices() { - crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; - } - Ok(()) - })?; - return Ok(Value::Null); - } - s.edit("Clear", |doc, _| { - let sel = doc.selection.clone(); - let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); - crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) - })?; - Ok(Value::Null) - } - ), - ] -} diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs new file mode 100644 index 0000000000..c784954c76 --- /dev/null +++ b/crates/engine/src/cmd/table.rs @@ -0,0 +1,8 @@ +//! The command table's fragments, one directory per owner: the crate whose items the commands +//! call. Each directory moves whole into its crate; `SPECS` in `cmd.rs` fixes the order. + +pub(crate) mod core; +pub(crate) mod image; +pub(crate) mod model; +pub(crate) mod paint; +pub(crate) mod store; diff --git a/crates/engine/src/cmd/table/core.rs b/crates/engine/src/cmd/table/core.rs new file mode 100644 index 0000000000..d5311b7dcb --- /dev/null +++ b/crates/engine/src/cmd/table/core.rs @@ -0,0 +1,5 @@ +pub(crate) mod edit_menu; +pub(crate) mod file_menu; +pub(crate) mod queries; +pub(crate) mod select_menu; +pub(crate) mod tools; diff --git a/crates/engine/src/cmd/table/core/edit_menu.rs b/crates/engine/src/cmd/table/core/edit_menu.rs new file mode 100644 index 0000000000..a027818f5e --- /dev/null +++ b/crates/engine/src/cmd/table/core/edit_menu.rs @@ -0,0 +1,9 @@ +use crate::cmd::{CommandSpec, can_redo, can_undo, json}; + +/// Edit menu: Undo and Redo. +pub(crate) fn specs() -> Vec { + vec![ + cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))), + cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))), + ] +} diff --git a/crates/engine/src/cmd/table/core/file_menu.rs b/crates/engine/src/cmd/table/core/file_menu.rs new file mode 100644 index 0000000000..00126ebc8d --- /dev/null +++ b/crates/engine/src/cmd/table/core/file_menu.rs @@ -0,0 +1,28 @@ +use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc}; + +/// File menu: Close. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "file.close", + "Close", + ["File"], + Some("Cmd+W"), + r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, + has_doc, + |s, p| { + let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; + match p.get("save").filter(|v| !v.is_null()) { + Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => { + return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); + } + Some(v) if v == "ask" => {} + // `false` (don't save) is the older spelling of discard. + Some(Value::Bool(false)) => {} + Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), + _ => {} + } + s.close(i).ok_or(EngineError::NoDocument)?; + Ok(Value::Null) + } + )] +} diff --git a/crates/engine/src/cmd/queries.rs b/crates/engine/src/cmd/table/core/queries.rs similarity index 97% rename from crates/engine/src/cmd/queries.rs rename to crates/engine/src/cmd/table/core/queries.rs index 13e7603743..03fe314a3a 100644 --- a/crates/engine/src/cmd/queries.rs +++ b/crates/engine/src/cmd/table/core/queries.rs @@ -1,7 +1,7 @@ -use super::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry}; +use crate::cmd::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry}; /// Commands that report session and document state or switch documents. -pub(super) fn specs() -> Vec { +pub(crate) fn specs() -> Vec { vec![ CommandSpec { id: "session.inspect", diff --git a/crates/engine/src/cmd/select_menu.rs b/crates/engine/src/cmd/table/core/select_menu.rs similarity index 96% rename from crates/engine/src/cmd/select_menu.rs rename to crates/engine/src/cmd/table/core/select_menu.rs index 88db83f6a1..dee9830596 100644 --- a/crates/engine/src/cmd/select_menu.rs +++ b/crates/engine/src/cmd/table/core/select_menu.rs @@ -1,8 +1,9 @@ -use super::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds}; +use crate::cmd::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds}; -/// Select menu commands: All, Deselect, Inverse and rectangular selections. -pub(super) fn specs() -> Vec { +/// Select menu: All, Deselect, Inverse and rectangular selections. +pub(crate) fn specs() -> Vec { vec![ + // Select cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| { // With the active layer on an artboard (the board itself or a layer inside it), Select // All selects that board, as Photoshop does; otherwise the whole canvas (#10258). diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/table/core/tools.rs similarity index 64% rename from crates/engine/src/cmd/paint.rs rename to crates/engine/src/cmd/table/core/tools.rs index 6a20325452..3a2f9666c4 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/table/core/tools.rs @@ -1,17 +1,8 @@ -use super::{CommandSpec, Value, always, cmyk_param, color_param, has_paintable}; +use crate::cmd::{CommandSpec, Value, always, cmyk_param, color_param}; -/// Painting commands: strokes and the foreground and background colors. -pub(super) fn specs() -> Vec { +/// Tool state: foreground and background colors. +pub(crate) fn specs() -> Vec { vec![ - cmd!( - "paint.stroke", - "Brush Stroke", - [], - None, - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - has_paintable, - crate::brush_cmds::paint_stroke - ), cmd!( "tools.setColors", "Set Colors", diff --git a/crates/engine/src/cmd/table/image.rs b/crates/engine/src/cmd/table/image.rs new file mode 100644 index 0000000000..b6c29faec4 --- /dev/null +++ b/crates/engine/src/cmd/table/image.rs @@ -0,0 +1,2 @@ +pub(crate) mod adjustments; +pub(crate) mod image_menu; diff --git a/crates/engine/src/cmd/adjustments.rs b/crates/engine/src/cmd/table/image/adjustments.rs similarity index 98% rename from crates/engine/src/cmd/adjustments.rs rename to crates/engine/src/cmd/table/image/adjustments.rs index fa92e68d3a..80cc8b33cb 100644 --- a/crates/engine/src/cmd/adjustments.rs +++ b/crates/engine/src/cmd/table/image/adjustments.rs @@ -1,7 +1,7 @@ -use super::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment}; +use crate::cmd::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment}; /// The adjustment layers and the Image › Adjustments commands, generated from one table. -pub(super) fn specs() -> Vec { +pub(crate) fn specs() -> Vec { let mut v = Vec::new(); // Adjustment layers + destructive adjustments, generated from one list. // Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale), diff --git a/crates/engine/src/cmd/table/image/image_menu.rs b/crates/engine/src/cmd/table/image/image_menu.rs new file mode 100644 index 0000000000..8bcd87a0ef --- /dev/null +++ b/crates/engine/src/cmd/table/image/image_menu.rs @@ -0,0 +1,24 @@ +use crate::cmd::{Adjustment, CommandSpec, Value, destructive_adjust}; + +/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. +pub(crate) fn desaturate_adjustment() -> Adjustment { + Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } +} + +/// Image menu: Desaturate. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "image.adjustments.desaturate", + "Desaturate", + ["Image", "Adjustments"], + Some("Cmd+Shift+U"), + r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, + crate::adjust_cmds::has_adjustable, + |s, p| { + if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { + return Ok(Value::Null); + } + destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) + } + )] +} diff --git a/crates/engine/src/cmd/table/model.rs b/crates/engine/src/cmd/table/model.rs new file mode 100644 index 0000000000..a1154cd1a3 --- /dev/null +++ b/crates/engine/src/cmd/table/model.rs @@ -0,0 +1,3 @@ +pub(crate) mod edit_menu; +pub(crate) mod image_menu; +pub(crate) mod layer_menu; diff --git a/crates/engine/src/cmd/table/model/edit_menu.rs b/crates/engine/src/cmd/table/model/edit_menu.rs new file mode 100644 index 0000000000..46efa9ae85 --- /dev/null +++ b/crates/engine/src/cmd/table/model/edit_menu.rs @@ -0,0 +1,49 @@ +use crate::cmd::{CommandSpec, Value, has_pixel_or_channel, is_mask_target, layer_param}; + +/// Edit menu: Clear (channel and mask targets). +pub(crate) fn specs() -> Vec { + vec![cmd!( + "edit.clear", + "Clear", + ["Edit"], + None, + r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##, + has_pixel_or_channel, + |s, p| { + let bg = s.tools.background; + // A targeted alpha channel or Quick Mask is filled instead (#2734). + let channel = if crate::channel_cmds::is_channel_target(p) { + Some(p.clone()) + } else if p.get("target").is_none() { + crate::channel_cmds::targeted_channel(s) + } else { + None + }; + if let Some(t) = channel { + s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?; + return Ok(Value::Null); + } + let id = layer_param(s, p)?; + if is_mask_target(p) { + s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?; + return Ok(Value::Null); + } + // A targeted colour channel clears that channel only (#2720). + if let Some(colors) = crate::color_channels::target(s, p)? { + s.edit("Clear", |doc, _| { + for k in colors.indices() { + crate::channel_cmds::clear_color_channel(doc, id, k, bg)?; + } + Ok(()) + })?; + return Ok(Value::Null); + } + s.edit("Clear", |doc, _| { + let sel = doc.selection.clone(); + let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds()); + crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg) + })?; + Ok(Value::Null) + } + )] +} diff --git a/crates/engine/src/cmd/image_menu.rs b/crates/engine/src/cmd/table/model/image_menu.rs similarity index 52% rename from crates/engine/src/cmd/image_menu.rs rename to crates/engine/src/cmd/table/model/image_menu.rs index 569c8a839c..4beca02e10 100644 --- a/crates/engine/src/cmd/image_menu.rs +++ b/crates/engine/src/cmd/table/model/image_menu.rs @@ -1,7 +1,23 @@ -use super::{CommandSpec, Value, desaturate_adjustment, destructive_adjust, has_doc, turn}; +use crate::cmd::{CommandSpec, Result, Session, Value, has_doc}; -/// Image menu commands: canvas rotations and flips, and Desaturate. -pub(super) fn specs() -> Vec { +/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). +fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { + if let Some(d) = s.active() { + let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height)); + // Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point + // lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`). + let half = photocraft_geom::Affine::translate(0.5, 0.5); + s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5))); + } + s.edit(label, |doc, _| { + crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t)); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Image menu: canvas rotations and flips. +pub(crate) fn specs() -> Vec { vec![ cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal) @@ -18,19 +34,5 @@ pub(super) fn specs() -> Vec { cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) }), - cmd!( - "image.adjustments.desaturate", - "Desaturate", - ["Image", "Adjustments"], - Some("Cmd+Shift+U"), - r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, - crate::adjust_cmds::has_adjustable, - |s, p| { - if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { - return Ok(Value::Null); - } - destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) - } - ), ] } diff --git a/crates/engine/src/cmd/layer_menu.rs b/crates/engine/src/cmd/table/model/layer_menu.rs similarity index 81% rename from crates/engine/src/cmd/layer_menu.rs rename to crates/engine/src/cmd/table/model/layer_menu.rs index afae40bb43..42bc4961d5 100644 --- a/crates/engine/src/cmd/layer_menu.rs +++ b/crates/engine/src/cmd/table/model/layer_menu.rs @@ -1,15 +1,18 @@ -use super::{ - Adjustment, BlendMode, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, - arrange, bad, parse_blend, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, - mask_new_layer, merge_group, move_mask, pixels, set_clipped, set_mask, set_mask_and_deselect, +use crate::cmd::{ + Adjustment, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, arrange, + bad, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, mask_new_layer, merge_group, move_mask, + parse_blend, pixels, set_clipped, set_mask, set_mask_and_deselect, }; +use photocraft_color::BlendMode; -/// Layer menu commands, in registry order. -pub(super) fn specs() -> Vec { - [creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), fill_layers(), adjustments(), placement()] - .into_iter() - .flatten() - .collect() +/// Layer menu, first run: new layers and groups to the solid color fill layer. +pub(crate) fn specs_before_gradient() -> Vec { + [creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), solid_color_fill()].into_iter().flatten().collect() +} + +/// Layer menu, last run: adjustment layers, move and translate. +pub(crate) fn specs_after_gradient() -> Vec { + [adjustments(), placement()].into_iter().flatten().collect() } /// New layers and groups, and grouping the selected layers. @@ -301,83 +304,38 @@ fn merging() -> Vec { ] } -/// Solid color and gradient fill layers. -fn fill_layers() -> Vec { - vec![ - cmd!( - "layer.newFillLayer.solidColor", - "Solid Color…", - ["Layer", "New Fill Layer"], - None, - r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, - has_doc, - |s, p| { - let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; - // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead - // of what its sRGB stand-in converts back to through the document profile (#8568). - let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { - Some(k) => Some(k), - None => s.tools.picked_cmyk([c[0], c[1], c[2]]), +/// Solid color fill layer. +fn solid_color_fill() -> Vec { + vec![cmd!( + "layer.newFillLayer.solidColor", + "Solid Color…", + ["Layer", "New Fill Layer"], + None, + r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##, + has_doc, + |s, p| { + let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?; + // The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead + // of what its sRGB stand-in converts back to through the document profile (#8568). + let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? { + Some(k) => Some(k), + None => s.tools.picked_cmyk([c[0], c[1], c[2]]), + }; + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + let id = s.edit("New Color Fill Layer", |doc, active| { + let fill = match inks { + Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), + _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), }; - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - let id = s.edit("New Color Fill Layer", |doc, active| { - let fill = match inks { - Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }), - _ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode), - }; - let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - cmd!( - "layer.newFillLayer.gradient", - "Gradient…", - ["Layer", "New Fill Layer"], - None, - r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, - has_doc, - |s, p| { - let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; - let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; - let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; - let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); - let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); - let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); - // The rest of a recorded Gradient Fill (a loaded action's Make): applied as - // `gradient.fill.set` would, in the same step. - let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] - .iter() - .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) - .collect(); - let (fg, bg) = (s.tools.foreground, s.tools.background); - let id = s.edit("New Gradient Fill Layer", |doc, active| { - let mut fill = Fill::gradient( - vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], - angle, - 1.0, - style, - reverse, - ); - if !rest.is_empty() { - let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); - fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; - } - let fill = fill.in_mode(doc.mode); - let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); - mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) - } - ), - ] + let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + )] } /// Editing an adjustment layer's properties. diff --git a/crates/engine/src/cmd/table/paint.rs b/crates/engine/src/cmd/table/paint.rs new file mode 100644 index 0000000000..67945b6de2 --- /dev/null +++ b/crates/engine/src/cmd/table/paint.rs @@ -0,0 +1,2 @@ +pub(crate) mod edit_menu; +pub(crate) mod stroke; diff --git a/crates/engine/src/cmd/table/paint/edit_menu.rs b/crates/engine/src/cmd/table/paint/edit_menu.rs new file mode 100644 index 0000000000..b1ee43e47f --- /dev/null +++ b/crates/engine/src/cmd/table/paint/edit_menu.rs @@ -0,0 +1,14 @@ +use crate::cmd::{CommandSpec, has_pixel_or_channel}; + +/// Edit menu: Fill. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "edit.fill", + "Fill…", + ["Edit"], + Some("Shift+F5"), + r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, + has_pixel_or_channel, + crate::fill_cmds::fill + )] +} diff --git a/crates/engine/src/cmd/table/paint/stroke.rs b/crates/engine/src/cmd/table/paint/stroke.rs new file mode 100644 index 0000000000..8e456d5c48 --- /dev/null +++ b/crates/engine/src/cmd/table/paint/stroke.rs @@ -0,0 +1,14 @@ +use crate::cmd::{CommandSpec, has_paintable}; + +/// Painting: the stroke command. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "paint.stroke", + "Brush Stroke", + [], + None, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + has_paintable, + crate::brush_cmds::paint_stroke + )] +} diff --git a/crates/engine/src/cmd/table/store.rs b/crates/engine/src/cmd/table/store.rs new file mode 100644 index 0000000000..f176c41361 --- /dev/null +++ b/crates/engine/src/cmd/table/store.rs @@ -0,0 +1,2 @@ +pub(crate) mod file_menu; +pub(crate) mod layer_menu; diff --git a/crates/engine/src/cmd/file_menu.rs b/crates/engine/src/cmd/table/store/file_menu.rs similarity index 76% rename from crates/engine/src/cmd/file_menu.rs rename to crates/engine/src/cmd/table/store/file_menu.rs index 670a3f9075..97e62f9f5a 100644 --- a/crates/engine/src/cmd/file_menu.rs +++ b/crates/engine/src/cmd/table/store/file_menu.rs @@ -1,8 +1,9 @@ -use super::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, bad, has_doc, json, parse_hex}; +use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex}; -/// File menu commands: New and Close. -pub(super) fn specs() -> Vec { +/// File menu: New (new documents take their presets from the document preset store). +pub(crate) fn specs() -> Vec { vec![ + // File cmd!( "file.new", "New…", @@ -71,28 +72,5 @@ pub(super) fn specs() -> Vec { Ok(json!({ "document": i })) } ), - cmd!( - "file.close", - "Close", - ["File"], - Some("Cmd+W"), - r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##, - has_doc, - |s, p| { - let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; - match p.get("save").filter(|v| !v.is_null()) { - Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => { - return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them")); - } - Some(v) if v == "ask" => {} - // `false` (don't save) is the older spelling of discard. - Some(Value::Bool(false)) => {} - Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")), - _ => {} - } - s.close(i).ok_or(EngineError::NoDocument)?; - Ok(Value::Null) - } - ), ] } diff --git a/crates/engine/src/cmd/table/store/layer_menu.rs b/crates/engine/src/cmd/table/store/layer_menu.rs new file mode 100644 index 0000000000..817b346aa8 --- /dev/null +++ b/crates/engine/src/cmd/table/store/layer_menu.rs @@ -0,0 +1,43 @@ +use crate::cmd::{Color, CommandSpec, Fill, Layer, LayerContent, Value, color_param, has_doc, json, layer_panel_option, mask_new_layer}; + +/// Layer menu: the gradient fill layer. +pub(crate) fn specs() -> Vec { + vec![cmd!( + "layer.newFillLayer.gradient", + "Gradient…", + ["Layer", "New Fill Layer"], + None, + r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##, + has_doc, + |s, p| { + let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?; + let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?; + let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?; + let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); + let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); + let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true); + // The rest of a recorded Gradient Fill (a loaded action's Make): applied as + // `gradient.fill.set` would, in the same step. + let rest: serde_json::Map = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"] + .iter() + .filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))) + .collect(); + let (fg, bg) = (s.tools.foreground, s.tools.background); + let id = s.edit("New Gradient Fill Layer", |doc, active| { + let mut fill = + Fill::gradient(vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], angle, 1.0, style, reverse); + if !rest.is_empty() { + let l = Layer::new(String::new(), LayerContent::Fill(fill.clone())); + fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?; + } + let fill = fill.in_mode(doc.mode); + let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); + mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) + } + )] +} diff --git a/scripts/engine_split/table_fragments.py b/scripts/engine_split/table_fragments.py new file mode 100644 index 0000000000..528ac433be --- /dev/null +++ b/scripts/engine_split/table_fragments.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Move a branch's edits of the old inline command table into the table fragments. + +Before the table was split, `crates/engine/src/cmd.rs` held every core command in one `vec![...]` +inside `fn build()`. The entries now live in `crates/engine/src/cmd/table//.rs`, and +`cmd/command_ids.txt` pins the registry order. A branch that edited the old table carries its +edits in `cmd.rs`. This script applies them to the fragments: + + python3 scripts/engine_split/table_fragments.py --base --head + +Run it in a checkout of the new main (or of the branch rebased onto it, with its `cmd.rs` hunks +for the old table dropped). Per command id, compared between BASE and HEAD: + changed the entry in its fragment is replaced by HEAD's text (if the fragment still has + BASE's text; otherwise it is reported as a CONFLICT and left alone); + added the entry goes after its predecessor's entry, in the predecessor's fragment, and its id + goes after the predecessor's id in command_ids.txt; + removed the entry and its id are deleted. +Running it twice gives the same result. Anything it cannot place is listed at the end. +Edits outside the table (imports, helper fns, test modules) are not touched. +""" +import argparse, os, re, subprocess, sys + +CMD = "crates/engine/src/cmd.rs" +TABLE = "crates/engine/src/cmd/table" +IDS = "crates/engine/src/cmd/command_ids.txt" +ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"') + + +def skip(text, i): + """Index after the comment, string or char literal starting at i, or None.""" + if text.startswith("//", i): + j = text.find("\n", i) + return len(text) if j < 0 else j + m = re.match(r'r(#*)"', text[i:]) + if m and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")): + end = text.index('"' + m.group(1), i + len(m.group(0))) + return end + 1 + len(m.group(1)) + if text[i] == '"': + i += 1 + while text[i] != '"': + i += 2 if text[i] == "\\" else 1 + return i + 1 + if text[i] == "'": + m = re.match(r"'(\\.[^']*|[^\\'])'", text[i:]) + if m: + return i + len(m.group(0)) + return None + + +def split_entries(body): + """The top-level comma-separated entries of a `vec![...]` body.""" + entries, depth, start, i = [], 0, 0, 0 + while i < len(body): + j = skip(body, i) + if j is not None: + i = j + continue + c = body[i] + if c in "([{": + depth += 1 + elif c in ")]}": + depth -= 1 + elif c == "," and depth == 0: + entries.append(body[start : i + 1]) + start = i + 1 + i += 1 + if body[start:].strip(): + entries.append(body[start:]) + return entries + + +def entry_id(entry): + code = "\n".join(l for l in entry.splitlines() if not l.strip().startswith("//")) + m = ID_RE.search(code) + return m.group(1) if m else None + + +def build_entries(source): + """Entries of the `vec![` that starts `fn build()` in the old cmd.rs.""" + start = source.index("vec![", source.index("fn build()")) + len("vec![") + depth, i = 1, start + while depth: + j = skip(source, i) + if j is not None: + i = j + continue + depth += source[i] == "[" + depth -= source[i] == "]" + i += 1 + return split_entries(source[start : i - 1]) + + +def git_show(ref, path): + return subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True, check=True).stdout + + +class Fragments: + """Every `vec![...]` of the fragment files, with its entries.""" + + def __init__(self): + self.files = {} + for d, _, names in os.walk(TABLE): + for n in names: + if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != TABLE: + p = os.path.join(d, n) + if "vec![" in open(p).read(): + self.files[p] = open(p).read() + + def find(self, cid): + """(path, entry text) of the entry for a command id, or None.""" + for p, t in self.files.items(): + for e in self.entries(t): + if entry_id(e) == cid: + return p, e + return None + + @staticmethod + def spans(t): + """(start, end) of each vec! body in a fragment file.""" + out, pos = [], 0 + while True: + k = t.find("vec![", pos) + if k < 0: + return out + s, depth, i = k + 5, 1, k + 5 + while depth: + j = skip(t, i) + if j is not None: + i = j + continue + depth += t[i] == "[" + depth -= t[i] == "]" + i += 1 + out.append((s, i - 1)) + pos = i + + def entries(self, t): + return [e for s, f in self.spans(t) for e in split_entries(t[s:f])] + + def replace(self, path, old, new): + t = self.files[path] + assert t.count(old) == 1, (path, "entry not unique") + self.files[path] = t.replace(old, new) + + def insert_after(self, path, old, new): + self.replace(path, old, old + new) + + def delete(self, path, old): + self.replace(path, old, "") + + def save(self): + for p, t in self.files.items(): + open(p, "w").write(t) + + +def tidy(e): + """Entry text as a fragment stores it: starts at its own line, ends with a comma.""" + e = e.strip("\n") + return e if e.rstrip().endswith(",") else e.rstrip() + "," + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--base", required=True, help="the branch's merge-base with the old main") + ap.add_argument("--head", required=True, help="the branch") + a = ap.parse_args() + base = {entry_id(e): e for e in build_entries(git_show(a.base, CMD)) if entry_id(e)} + head_list = [e for e in build_entries(git_show(a.head, CMD)) if entry_id(e)] + head = {entry_id(e): e for e in head_list} + fr = Fragments() + ids = open(IDS).read().split("\n") + if ids and ids[-1] == "": + ids.pop() + report = [] + for pos, e in enumerate(head_list): + cid = entry_id(e) + text = tidy(e) + here = fr.find(cid) + if here: + path, cur = here + if cid in base and tidy(base[cid]) == text: + continue # the branch did not touch it + if tidy(cur) == text: + continue + if cid in base and tidy(cur) != tidy(base[cid]): + report.append(f"CONFLICT {cid} in {path}: the fragment differs from BASE too; merge by hand") + continue + fr.replace(path, cur, ("\n" if cur.startswith("\n") else "") + text) + report.append(f"changed {cid} in {path}") + continue + if cid in base: + report.append(f"MISSING {cid}: edited by the branch, but no fragment holds it") + continue + pred = next((entry_id(head_list[k]) for k in range(pos - 1, -1, -1) if fr.find(entry_id(head_list[k]))), None) + if pred is None: + report.append(f"UNPLACED {cid}: no predecessor in the fragments") + continue + path, pe = fr.find(pred) + fr.insert_after(path, pe, "\n" + text) + ids.insert(ids.index(pred) + 1, cid) if cid not in ids else None + report.append(f"added {cid} after {pred} in {path}") + for cid, e in base.items(): + if cid not in head and (here := fr.find(cid)): + fr.delete(*here) + ids = [i for i in ids if i != cid] + report.append(f"removed {cid} from {here[0]}") + fr.save() + open(IDS, "w").write("\n".join(ids) + "\n") + print("\n".join(report) or "nothing to do") + return 1 if any(r.startswith(("MISSING", "UNPLACED", "CONFLICT")) for r in report) else 0 + + +if __name__ == "__main__": + sys.exit(main()) From c4434c43afceb80c00ee874cfc4c07343ce14539 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:45:53 +0000 Subject: [PATCH 35/38] Name the kept command states (#15709) A struct in place of the nested tuple clippy's type_complexity refuses. --- crates/ui-egui/src/app/framework.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index afa5267feb..10a2fcdbe9 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -580,12 +580,19 @@ pub(crate) type StatesKey = [u64; 4]; /// The states each keyed [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key. #[derive(Default)] pub(crate) struct HeldStates { - kept: Vec)>>, + kept: Vec>, /// How many times each source computed its states, for the count trials. #[cfg(test)] pub(crate) runs: Vec, } +/// One keyed source's states and the key they were computed at. +#[derive(Clone)] +struct KeptStates { + key: StatesKey, + states: Vec<(CommandRef, CommandState)>, +} + /// The tool commands: the current tool's row is checked. fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect() @@ -606,7 +613,7 @@ fn command_states(app: &PhotocraftApp, held: &mut HeldStates) -> Vec<(CommandRef for (at, source) in COMMAND_SOURCES.iter().enumerate() { let key = source.key.map(|key| key(app)); match (&held.kept[at], key) { - (Some((was, kept)), Some(key)) if *was == key => states.extend_from_slice(kept), + (Some(kept), Some(key)) if kept.key == key => states.extend_from_slice(&kept.states), _ => { #[cfg(test)] { @@ -614,7 +621,7 @@ fn command_states(app: &PhotocraftApp, held: &mut HeldStates) -> Vec<(CommandRef } let computed = (source.states)(app); states.extend_from_slice(&computed); - held.kept[at] = key.map(|key| (key, computed)); + held.kept[at] = key.map(|key| KeptStates { key, states: computed }); } } } From 460958d80742f4b7303ec589140bc686ec51eaad Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:48:09 +0000 Subject: [PATCH 36/38] Bring command_ids.txt up to main's commands; add a way to regenerate it --- crates/engine/src/cmd/command_ids.txt | 9 +++++++++ crates/engine/src/cmd/command_order_tests.rs | 8 +++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/command_ids.txt b/crates/engine/src/cmd/command_ids.txt index 2c25899668..98f1ef8901 100644 --- a/crates/engine/src/cmd/command_ids.txt +++ b/crates/engine/src/cmd/command_ids.txt @@ -285,6 +285,7 @@ path.bendSegment path.convertPoint path.addAnchor path.deleteAnchor +path.deleteSegment path.mergeShapeComponents path.setOperation select.quick @@ -359,11 +360,15 @@ brush.presets.importImage gradient.presets.importGrd style.presets.importAsl style.presets.exportAsl +actions.replace actions.load actions.save actions.stopMessage actions.menuItem actions.photoshopStep +actions.clearAll +actions.reset +actions.undoLibrary actions.insertMenuItem actions.insertPath actions.allowToolRecording @@ -379,6 +384,7 @@ swatches.add swatches.delete swatches.rename swatches.move +swatches.moveGroup swatches.newGroup swatches.renameGroup swatches.deleteGroup @@ -729,6 +735,7 @@ image.adjustments.shadowsHighlights image.adjustments.replaceColor image.adjustments.matchColor image.adjustments.hdrToning +image.adjustments.blackWhite.auto image.adjustments.colorLookup.list layer.layerMask.apply layer.layerMask.fromTransparency @@ -896,12 +903,14 @@ document.presets.list document.presets.get document.presets.save document.presets.delete +document.presets.rename document.recent.list document.recent.add file.export.presets.list file.export.presets.get file.export.presets.save file.export.presets.delete +file.export.presets.rename filter.render.flame filter.render.pictureFrame filter.render.tree diff --git a/crates/engine/src/cmd/command_order_tests.rs b/crates/engine/src/cmd/command_order_tests.rs index 0dba5a1622..4c853a0c33 100644 --- a/crates/engine/src/cmd/command_order_tests.rs +++ b/crates/engine/src/cmd/command_order_tests.rs @@ -2,10 +2,16 @@ use super::{SPECS, command_specs}; /// Menus, the Command Palette and the automation docs list commands in registry order, so the /// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when -/// rebasing, adding each new command's id after its predecessor. +/// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS` +/// set, the test writes the file from the registry instead; review the diff before committing it. #[test] fn registered_command_ids_keep_their_order() { let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); + if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/cmd/command_ids.txt"); + std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::()).expect("write command_ids.txt"); + return; + } let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { panic!("command {i} is {} where {} was registered{}", ids[i], expected[i], fragment_of(i)); From 7bffc1d27149f4f2fea73e205a8643a0b3e4913a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 17:02:37 +0000 Subject: [PATCH 37/38] Name the fragment type; codemod handles the ADJ table, single-entry fragments and rustfmt The codemod three-way merges the adjustment table into table/image/adjustments.rs, reports other build() edits as unhandled, compares entries without comments and whitespace, adds the comma after a single-entry fragment, checks removals and duplicate ids, and adds the imports new entries need. The order test's failure message names the regeneration variable. --- crates/engine/src/cmd.rs | 5 +- crates/engine/src/cmd/command_order_tests.rs | 6 +- scripts/engine_split/table_fragments.py | 186 +++++++++++++++---- 3 files changed, 160 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c5038b5600..cc8ce14c02 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -252,10 +252,13 @@ fn registry() -> &'static Registry { // ---------- the table ---------- +/// A named group of commands: `SPECS` lists them in registry order. +type Fragment = (&'static str, fn() -> Vec); + /// Every table fragment with its name, in registry order. The order is part of the behaviour (menus /// list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by the /// crate that will own them; a menu split between owners has one fragment per contiguous run. -const SPECS: &[(&str, fn() -> Vec)] = &[ +const SPECS: &[Fragment] = &[ ("store::file_menu", table::store::file_menu::specs), ("core::file_menu", table::core::file_menu::specs), ("core::edit_menu", table::core::edit_menu::specs), diff --git a/crates/engine/src/cmd/command_order_tests.rs b/crates/engine/src/cmd/command_order_tests.rs index 4c853a0c33..74ef47ab97 100644 --- a/crates/engine/src/cmd/command_order_tests.rs +++ b/crates/engine/src/cmd/command_order_tests.rs @@ -4,6 +4,8 @@ use super::{SPECS, command_specs}; /// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when /// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS` /// set, the test writes the file from the registry instead; review the diff before committing it. +const HINT: &str = "\nadd the id to src/cmd/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff"; + #[test] fn registered_command_ids_keep_their_order() { let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); @@ -14,9 +16,9 @@ fn registered_command_ids_keep_their_order() { } let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect(); if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) { - panic!("command {i} is {} where {} was registered{}", ids[i], expected[i], fragment_of(i)); + panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], fragment_of(i)); } - assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}", fragment_of(ids.len().min(expected.len()))); + assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", fragment_of(ids.len().min(expected.len()))); } /// Names the fragment that registers command `index`, for the failure message. diff --git a/scripts/engine_split/table_fragments.py b/scripts/engine_split/table_fragments.py index 528ac433be..e711217873 100644 --- a/scripts/engine_split/table_fragments.py +++ b/scripts/engine_split/table_fragments.py @@ -14,11 +14,17 @@ for the old table dropped). Per command id, compared between BASE and HEAD: BASE's text; otherwise it is reported as a CONFLICT and left alone); added the entry goes after its predecessor's entry, in the predecessor's fragment, and its id goes after the predecessor's id in command_ids.txt; - removed the entry and its id are deleted. -Running it twice gives the same result. Anything it cannot place is listed at the end. -Edits outside the table (imports, helper fns, test modules) are not touched. + removed the entry and its id are deleted (if the fragment still has BASE's text). +The adjustment table and its loop (`ADJ`, between the `vec![...]` and the `v.extend(...)` list) are +three-way merged into table/image/adjustments.rs. Any other change inside `build()` (the module +table list, the test-only command) is reported as UNHANDLED: edit `SPECS` in cmd.rs by hand. +Entries are compared without comments and whitespace, so rustfmt does not matter. Names a new +entry uses from cmd.rs are added to its fragment's `use crate::cmd::{..}` list. Run +`cargo fmt --all` afterwards. Running the script twice gives the same result. CONFLICT, UNHANDLED, +UNPLACED, MISSING and DUPLICATE lines mean exit status 1; resolve those by hand. +Edits outside `build()` (imports in cmd.rs, helper fns, test modules) are not touched. """ -import argparse, os, re, subprocess, sys +import argparse, os, re, subprocess, sys, tempfile CMD = "crates/engine/src/cmd.rs" TABLE = "crates/engine/src/cmd/table" @@ -75,21 +81,6 @@ def entry_id(entry): return m.group(1) if m else None -def build_entries(source): - """Entries of the `vec![` that starts `fn build()` in the old cmd.rs.""" - start = source.index("vec![", source.index("fn build()")) + len("vec![") - depth, i = 1, start - while depth: - j = skip(source, i) - if j is not None: - i = j - continue - depth += source[i] == "[" - depth -= source[i] == "]" - i += 1 - return split_entries(source[start : i - 1]) - - def git_show(ref, path): return subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True, check=True).stdout @@ -159,14 +150,113 @@ def tidy(e): return e if e.rstrip().endswith(",") else e.rstrip() + "," +def norm(e): + """Entry text without comments and whitespace, and without trailing commas, for comparing.""" + out, i = [], 0 + while i < len(e): + j = skip(e, i) + if j is None: + out.append(e[i]) + i += 1 + elif e.startswith("//", i): + i = j + else: + out.append(e[i:j]) + i = j + s = re.sub(r"\s+", "", "".join(out)) + return re.sub(r",(?=[)\]}])", "", s).rstrip(",") + + +def words(e): + """Identifiers an entry uses as bare names (not paths, fields or inside literals).""" + out, i = [], 0 + while i < len(e): + j = skip(e, i) + if j is None: + out.append(e[i]) + i += 1 + else: + out.append(" ") + i = j + return set(re.findall(r"(? Date: Fri, 20 Nov 2026 01:06:03 +0800 Subject: [PATCH 38/38] Use shared PSD channel restriction helpers (#15779) --- crates/io/src/blocks.rs | 8 ++--- crates/io/src/psd_export.rs | 2 +- crates/io/src/psd_import.rs | 2 +- crates/io/tests/it/roundtrip.rs | 52 +++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 24cfba224a..5fa2056888 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -9,14 +9,10 @@ use photocraft_geom::Affine; /// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of /// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored). -pub fn parse_brst(data: &[u8]) -> u32 { - data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i) -} +pub use craft_psd::tagged::channel_restrictions as parse_brst; /// Inverse of [`parse_brst`]; `None` when every channel blends (no block). -pub fn brst_data(mask: u32) -> Option> { - (mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect()) -} +pub use craft_psd::tagged::channel_restrictions_data as brst_data; /// The Advanced Blending blocks, as (key, value for `a`, Photoshop's default value): `knko` /// (0 none, 1 shallow, 2 deep), `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`. Each is stored as one diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 6ab2dc4134..7b0fd16d0a 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -609,7 +609,7 @@ impl Ex<'_> { None => raw.retain(|(k, _)| k != b"fxrp"), } // Advanced Blending channel restrictions: written from the field (in place). - match crate::blocks::brst_data(l.excluded_channels) { + match craft_psd::tagged::channel_restrictions_data(l.excluded_channels) { Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") { Some(e) => e.1 = data, None => raw.push((*b"brst", data)), diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 706802ee26..e5c3e59330 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -479,7 +479,7 @@ impl Ctx<'_> { // Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out); // also kept in `psd_blocks`, where export rewrites it from the field. if let Some(b) = rec.block(b"brst") { - l.excluded_channels = crate::blocks::parse_brst(&b.data); + l.excluded_channels = craft_psd::tagged::channel_restrictions(&b.data); } // Advanced Blending (`knko`, `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`); the blocks stay in // `psd_blocks`, where export rewrites them from the field in place. diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index af72cd1e1c..076fbc7553 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -474,6 +474,58 @@ fn channel_restrictions_round_trip_as_brst() { assert!(f.layers().iter().find(|r| r.name() == "a").unwrap().block(b"brst").is_none()); } +fn channel_restrictions_psd(payload: Vec) -> Vec { + use craft_psd::{LayerSpec, PixelData, PsdBuilder, TaggedBlock}; + let mut layer = LayerSpec::new("restricted", 0, 0, 1, 1, PixelData::Rgba8(vec![80, 120, 160, 255])); + layer.extra_blocks = vec![TaggedBlock::new(*b"zBef", vec![1, 2, 3, 4]), TaggedBlock::new(*b"brst", payload), TaggedBlock::new(*b"zAft", vec![5, 6, 7, 8])]; + let mut builder = PsdBuilder::new(1, 1); + builder.push_layer(layer); + builder.composite(PixelData::Rgba8(vec![80, 120, 160, 255])); + builder.to_bytes().unwrap() +} + +#[test] +fn channel_restrictions_partial_records_preserve_valid_indices_and_neighboring_blocks() { + for trailing in [vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc]] { + // The complete indices are 31, 32, 0, 31: 32 is ignored and 31 is a duplicate. + let mut payload = vec![0, 0, 0, 31, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 31]; + payload.extend(trailing); + let bytes = channel_restrictions_psd(payload.clone()); + let document = import("restrictions.psd", &bytes).unwrap().document; + let layer = document.layers.iter().find(|layer| layer.name == "restricted").unwrap(); + assert_eq!(layer.excluded_channels, 0x8000_0001); + assert!(layer.psd_blocks.iter().any(|(key, data)| key == b"brst" && data.as_slice() == payload)); + + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + let preserved: Vec<_> = record.blocks.iter().filter(|block| [*b"zBef", *b"brst", *b"zAft"].contains(&block.key)).collect(); + assert_eq!(preserved.iter().map(|block| block.key).collect::>(), vec![*b"zBef", *b"brst", *b"zAft"]); + assert_eq!(preserved[0].data, vec![1, 2, 3, 4]); + assert_eq!(preserved[1].data, vec![0, 0, 0, 0, 0, 0, 0, 31]); + assert_eq!(preserved[2].data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0x8000_0001); + } +} + +#[test] +fn channel_restrictions_without_valid_records_are_omitted() { + for payload in [vec![], vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc], vec![0, 0, 0, 32, 255, 255, 255, 255]] { + let bytes = channel_restrictions_psd(payload); + let document = import("restrictions.psd", &bytes).unwrap().document; + assert_eq!(document.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + assert!(record.block(b"brst").is_none()); + assert_eq!(record.block(b"zBef").unwrap().data, vec![1, 2, 3, 4]); + assert_eq!(record.block(b"zAft").unwrap().data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + } +} + /// Advanced Blending maps to `knko` / `infx` / `clbl` / `tsly` / `lmgm` / `vmgm` (one byte + /// three of padding), at every depth: non-default values are written, default layers gain no /// blocks, and imported blocks are rewritten in place.