From e8c30125539f4f3fe75cc9335a21b729d2c85f48 Mon Sep 17 00:00:00 2001 From: admiralronton Date: Sat, 31 Oct 2026 10:46:53 -0700 Subject: [PATCH 01/85] 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 7c0c10da6600cf943c7caada4839012a220d73f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 17:39:08 +0100 Subject: [PATCH 02/85] fix(type-tool): record a history state for an unchanged text edit Ending an edit of an existing type layer now adds one `Edit Type` state even when the session changed nothing. Measured in the reference application (#12050): click into a text layer, change nothing, and end the edit with Escape (when it commits), Ctrl+Enter, the Commit button or a click on the canvas outside the text - one Edit Type Layer state is added and the layer is unchanged. Today the History list does not move. `commit_here` ran `type.edit` only for a layer the session had created, so an existing layer recorded nothing unless the text or a style changed during the session. It now also runs it for an existing layer, carrying the session's own coalesce key. That key is what keeps the run to a single state: `Session::edit_with` joins a step whose key matches the state it just recorded, so a session that did type or restyle its text folds into the state it already opened instead of adding an empty second one. The state carries the name the other edits of an existing type layer carry, so #12048 renames it along with them. The state is opened only while the edit is still the work in hand. The frame also commits a session when a tool switch, another layer or another document takes the work over (#6483), and #12050 leaves those not-measured cases as they are. The Cancel button ends through `cancel`, which never reaches `commit_here`, so it still adds no state, and undo of the new state leaves the document as it was. Tests go in the new `crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs`; `type_tool.rs` only gains the `mod` line it needs. --- crates/ui-egui/src/tools/type_tool.rs | 3 + crates/ui-egui/src/tools/type_tool/editing.rs | 25 +++ .../type_tool/unchanged_edit_history_tests.rs | 163 ++++++++++++++++++ 3 files changed, 191 insertions(+) create mode 100644 crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 42ad346f61..5c6b4436be 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -146,3 +146,6 @@ mod commit_tests; #[cfg(test)] mod ime_tests; + +#[cfg(test)] +mod unchanged_edit_history_tests; diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index f93826c1d1..35ee14d082 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -446,6 +446,10 @@ pub(super) fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { /// [`commit_with`] in the active document, which is the edit's own. fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { + // Read before the tool and the layer move on below: #12050 measures the commits the user + // makes, and an unchanged edit that ends because a tool switch or another layer took the + // work over (#6483) keeps today's behaviour of recording nothing. + let ends_an_edit = user_ends_the_edit(app); if app.ui.tool.is_type() { crate::type_transform::finish(app); } @@ -478,9 +482,30 @@ fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { } else if ed.created { let name = photocraft_engine::type_cmds::layer_name(&text); let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session})); + } else if ends_an_edit && worked_on_layer(app, &ed) { + // Ending an edit of an existing layer is a step of its own even when the session changed + // nothing (#12050), so the History list shows the edit the user just ended. It carries the + // session's own coalesce key, which keeps it to the one step: `type.edit` under the key of + // the state the session already opened joins that state instead of adding a second one. + // The Cancel button ends through `cancel`, which never runs this. + let _ = app.run("type.edit", json!({"layer": ed.layer, "coalesce": ed.session})); } } +/// Is a Type tool still the tool holding this session? The frame commits the edit when a tool +/// switch takes the work on (#6483), also between the Type tools and the Type Mask tools; that is +/// not an edit of the layer, so #12050's state is not opened for it. +fn user_ends_the_edit(app: &PhotocraftApp) -> bool { + app.ui.tool.is_type() && app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask == app.ui.tool.is_type_mask()) +} + +/// Is the session's layer still the one worked on? Selecting another layer or document commits the +/// session (#6483); #12050 does not measure that, so it records nothing. A background document's +/// edit is checked in its own document, where `commit_with` has just made it active. +fn worked_on_layer(app: &PhotocraftApp, ed: &TextEdit) -> bool { + app.session.active().is_some_and(|st| st.active_layer == Some(LayerId(ed.layer))) +} + /// Commit the edit once its layer is no longer the one worked on (#6483): another layer became /// active (a Layers panel menu, the canvas layer picker, automation) or another document did (a /// tab, File ▸ New/Open). Photoshop commits then; left open, the session took single-key diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs new file mode 100644 index 0000000000..2a14790df5 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -0,0 +1,163 @@ +//! BUG-TYPE-TOOL-UNCHANGED-EDIT-NO-HISTORY-STATE (#12050): ending a text edit that changed +//! nothing still adds one `Edit Type` history state. +//! +//! Measured in the reference application: click into an existing text layer, change nothing and +//! end the edit with Escape (when it commits), Ctrl+Enter, the Commit button or a click on the +//! canvas outside the text: one **Edit Type Layer** state is added and the layer is unchanged. +//! The Cancel button discards the session and adds no state. An edit that did change something +//! still gives one state, not two. + +use photocraft_doc::{LayerContent, LayerId}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A 400x200 document with one committed type layer: that layer active and the Type tool picked. +fn app() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + let id = LayerId(app.run("type.create", json!({"text": "Hello", "size": 24, "x": 40, "y": 100})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + app.ui.tool = Tool::Type; + (app, id) +} + +fn history(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn text_of(app: &PhotocraftApp, id: LayerId) -> String { + let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { + panic!("the layer is not a type layer"); + }; + t.text.clone() +} + +fn first_size(app: &PhotocraftApp, id: LayerId) -> f32 { + let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { return 0.0 }; + t.char_runs().first().map(|r| r.style.size_pt).unwrap_or_default() +} + +/// Click into the existing layer: an edit session with nothing changed yet. +fn click_into(app: &mut PhotocraftApp, id: LayerId) { + crate::type_tool::edit_active(app).unwrap(); + let ed = app.ui.text_edit.as_ref().expect("the edit session is open"); + assert_eq!(ed.layer, id.0, "the session edits the layer"); + assert!(!ed.created, "it is an existing layer"); +} + +/// What ending the session with `how` left behind: exactly one state, named like any other edit +/// of an existing type layer, on an unchanged layer. +fn ended(app: &PhotocraftApp, id: LayerId, before: &[String], how: &str) { + let after = history(app); + assert!(app.ui.text_edit.is_none(), "{how}: the session ended"); + assert_eq!(after.len(), before.len() + 1, "{how}: exactly one new history state, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type"), "{how}: the name other edits of an existing type layer carry"); + assert_eq!(text_of(app, id), "Hello", "{how}: the layer is unchanged"); +} + +/// Escape (with Preferences > Type > Use Escape to Commit on, the default), the Commit button and +/// Ctrl+Enter all end the session through `commit` / `commit_with`. +#[test] +fn an_unchanged_edit_records_one_edit_type_state_on_every_commit_path() { + // How each gesture ends the session: Escape runs the plain `commit`, the Commit button and + // Ctrl+Enter pass their held modifiers to `commit_with`. + for (how, mods) in [("Escape (Use Escape to Commit)", None), ("Commit button", Some(egui::Modifiers::NONE)), ("Ctrl+Enter", Some(egui::Modifiers::COMMAND))] + { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + match mods { + None => crate::type_tool::commit(&mut app), + Some(m) => crate::type_tool::commit_with(&mut app, m), + } + ended(&app, id, &before, how); + } +} + +/// A click on the canvas outside the text commits the session, and records it too. +#[test] +fn a_click_outside_the_text_records_one_edit_type_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + // Far from the glyphs and from the box: the Type tool's press commits the session. + assert!(crate::type_tool::pointer_down(&mut app, 380.0, 20.0, egui::Modifiers::NONE), "the Type tool took the click"); + ended(&app, id, &before, "click outside the text"); +} + +/// The Cancel button discards the session and adds no history state. +#[test] +fn cancel_still_adds_no_history_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::cancel(&mut app); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history(&app), before, "Cancel adds nothing"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// An edit that did change something gives one state, not two: the commit joins the state the +/// session already opened instead of adding an empty one of its own. +#[test] +fn a_changed_edit_still_gives_one_state_not_two() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + super::insert(&mut app, "x"); + assert_eq!(text_of(&app, id), "x", "the session changed the text"); + assert_eq!(history(&app).len(), before.len() + 1, "typing opened the session's state"); + crate::type_tool::commit(&mut app); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "ending it adds no second state, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type")); +} + +/// Undo of the state an unchanged edit left behind takes the document back to where it was. +#[test] +fn undoing_the_state_of_an_unchanged_edit_leaves_the_document_as_it_was() { + let (mut app, id) = app(); + let (text, size) = (text_of(&app, id), first_size(&app, id)); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app).len(), before.len() + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(text_of(&app, id), text, "the text is what it was"); + assert_eq!(first_size(&app, id), size, "the style is what it was"); +} + +/// Not measured in #12050, so it keeps today's behaviour: an unchanged session ended because +/// another layer took the focus records nothing. +#[test] +fn an_unchanged_edit_ended_by_another_layer_records_nothing() { + let (mut app, id) = app(); + // Made before the session opens, so its own history step is not counted. + let other = LayerId(app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + app.run("layer.select", json!({"layer": other.0})).unwrap(); + super::end_if_left(&mut app); + assert!(app.ui.text_edit.is_none(), "selecting another layer ends the session"); + assert_eq!(app.session.active().unwrap().active_layer, Some(other)); + assert_eq!(history(&app), before, "and adds no state to the edited layer's document"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// Also not measured, so unchanged: switching tools commits the session, and an unchanged one +/// still adds nothing. +#[test] +fn an_unchanged_edit_ended_by_another_tool_records_nothing() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + app.ui.tool = Tool::Move; + crate::type_tool::commit(&mut app); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history(&app), before, "the tool switch is not an edit of the layer"); + assert_eq!(text_of(&app, id), "Hello"); +} From 602d2b89b0e438e548280807c74bb994934bd717 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:46:16 +0100 Subject: [PATCH 03/85] #12132: no Edit Type state when a document switch or a Layers panel click on another layer ends an unchanged edit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commit_with made the edit's own document active again before the layer check, so a document switch passed it; the Layers panel commits before it selects, so a click on another layer's row passed it too. Both now commit as a switch (commit_before_selecting for the panel). Tests for both, and for a click on the edited layer's own row, which still records. Co-Authored-By: Hartmut Nörenberg Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/layers.rs | 2 +- crates/ui-egui/src/tools/type_tool.rs | 2 +- crates/ui-egui/src/tools/type_tool/editing.rs | 27 +++++++-- .../type_tool/unchanged_edit_history_tests.rs | 55 +++++++++++++++++++ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index cc71b6884b..2cd28f4c04 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -531,7 +531,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // A row click commits even when it selects the layer already being edited (#5584). // Finish before selection changes so the existing type session keeps its own target. if id == "layer.select" && app.ui.text_edit.is_some() { - crate::type_tool::commit(app); + crate::type_tool::commit_before_selecting(app, p.get("layer").and_then(serde_json::Value::as_u64)); } if id == "ui.maskTarget" { app.end_filter_mask_view(); diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 13a0acb7e9..33c6a6d970 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -41,7 +41,7 @@ use editing::selected_styles; #[cfg(test)] pub(crate) use editing::{CharToggle, step_char_metric, toggle_char_style, toggle_hyphenate}; pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; -pub(crate) use editing::{commit_shortcut, copy_selection, cut_selection, request_paste, select_all}; +pub(crate) use editing::{commit_before_selecting, commit_shortcut, copy_selection, cut_selection, request_paste, select_all}; #[cfg(test)] use editing::{insert, insert_typed, smart_quotes}; #[cfg(test)] diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index 2a523c2529..f13175f983 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -409,24 +409,41 @@ pub(crate) fn commit_shortcut(app: &mut PhotocraftApp, ctx: &egui::Context) -> b /// result, since a Type Mask always replaces the selection (#12073); the parameter stays so its /// callers don't change. pub fn commit_with(app: &mut PhotocraftApp, _mods: egui::Modifiers) { + commit_ending(app, true); +} + +/// The commit a Layers panel row click makes before it selects `layer` (#5584): a click on another +/// layer's row is a layer switch (#6483), so an unchanged session records nothing (#12050); a click +/// on the edited layer's own row ends the edit like any other commit. +pub(crate) fn commit_before_selecting(app: &mut PhotocraftApp, layer: Option) { + let switches = app.ui.text_edit.as_ref().is_some_and(|ed| layer.is_some_and(|l| l != ed.layer)); + commit_ending(app, !switches); +} + +/// [`commit_with`]'s body. `by_user`: the user ended the edit (a commit gesture), rather than a +/// switch to another layer or document taking the work over, which records nothing for an +/// unchanged session (#12050). +fn commit_ending(app: &mut PhotocraftApp, by_user: bool) { app.ui.type_insertion_style = None; // A box drag in progress keeps the box it reached, as when every move was applied. crate::type_box_preview::flush(app); crate::type_font_preview::clear(app); let current = app.session.active_index(); let Some(home) = app.ui.text_edit.as_ref().map(|ed| edit_home(app, ed)) else { - return commit_here(app); + return commit_here(app, by_user); }; match home { Some(home) if Some(home) != current => { // An edit left in a background document commits there, in its own history (#6483). + // Another document is active, so a document switch ended the edit: an unchanged + // session records nothing there, even though its own document is active now. app.session.set_active(home); - commit_here(app); + commit_here(app, false); if let Some(i) = current { app.session.set_active(i); } } - Some(_) => commit_here(app), + Some(_) => commit_here(app, by_user), // Its document closed: there is nothing to commit into, and the layer id may name a // layer of another document. None => { @@ -447,11 +464,11 @@ pub(super) fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { } /// [`commit_with`] in the active document, which is the edit's own. -fn commit_here(app: &mut PhotocraftApp) { +fn commit_here(app: &mut PhotocraftApp, by_user: bool) { // Read before the tool and the layer move on below: #12050 measures the commits the user // makes, and an unchanged edit that ends because a tool switch or another layer took the // work over (#6483) keeps today's behaviour of recording nothing. - let ends_an_edit = user_ends_the_edit(app); + let ends_an_edit = by_user && user_ends_the_edit(app); if app.ui.tool.is_type() { crate::type_transform::finish(app); } diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs index 2a14790df5..90a7d7dbe7 100644 --- a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -35,6 +35,14 @@ fn text_of(app: &PhotocraftApp, id: LayerId) -> String { t.text.clone() } +/// [`text_of`] in document `doc`, active or not. +fn text_of_in(app: &PhotocraftApp, doc: usize, id: LayerId) -> String { + let LayerContent::Text(t) = &app.session.documents()[doc].doc.layer(id).unwrap().content else { + panic!("the layer is not a type layer"); + }; + t.text.clone() +} + fn first_size(app: &PhotocraftApp, id: LayerId) -> f32 { let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { return 0.0 }; t.char_runs().first().map(|r| r.style.size_pt).unwrap_or_default() @@ -161,3 +169,50 @@ fn an_unchanged_edit_ended_by_another_tool_records_nothing() { assert_eq!(history(&app), before, "the tool switch is not an edit of the layer"); assert_eq!(text_of(&app, id), "Hello"); } + +/// A Layers panel click on another layer's row commits before it selects that layer (#5584), so +/// both of the tool's checks still see the edited layer: the panel says it is a layer switch, and +/// an unchanged session records nothing, as when the layer is selected first. +#[test] +fn an_unchanged_edit_ended_by_a_layers_panel_click_on_another_layer_records_nothing() { + let (mut app, id) = app(); + let other = LayerId(app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + // The panel's order: commit first, then select. + crate::type_tool::commit_before_selecting(&mut app, Some(other.0)); + app.run("layer.select", json!({"layer": other.0})).unwrap(); + assert!(app.ui.text_edit.is_none(), "the row click ends the session"); + assert_eq!(history(&app), before, "a layer switch adds no state"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// A Layers panel click on the edited layer's own row ends the edit like a commit (#5584), so it +/// records the state. +#[test] +fn a_layers_panel_click_on_the_edited_layers_row_records_one_state() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + crate::type_tool::commit_before_selecting(&mut app, Some(id.0)); + ended(&app, id, &before, "click on the edited layer's row"); +} + +/// Another document becoming active ends the edit in its own document (#6483), which is made +/// active again for the commit: that is a document switch, and an unchanged session records +/// nothing there. +#[test] +fn an_unchanged_edit_ended_by_another_document_records_nothing() { + let (mut app, id) = app(); + click_into(&mut app, id); + let home = app.session.active_index().unwrap(); + let before = history(&app); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert_ne!(app.session.active_index(), Some(home), "the new document is active"); + super::end_if_left(&mut app); + assert!(app.ui.text_edit.is_none(), "the document switch ends the session"); + assert_ne!(app.session.active_index(), Some(home), "the new document stays active"); + assert_eq!(app.session.documents()[home].history.entries(), before, "no state in the edited layer's document"); + assert_eq!(text_of_in(&app, home, id), "Hello"); +} From c6c562b3a11a6615c94b70d3a7d71b78cb1f918c Mon Sep 17 00:00:00 2001 From: Omar Saidahmed Date: Wed, 28 Oct 2026 18:57:08 -0400 Subject: [PATCH 04/85] 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 05/85] 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 d683d06d0b58fc1a7d3b6150c6f34f09ce60493b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sun, 8 Nov 2026 06:51:39 +0100 Subject: [PATCH 06/85] fix(type-tool): add no empty history state after the session's own step Review round on #12050 (c4502824768). A session that kerned a pair with Alt+left/right, or pressed one of the shift+ctrl style keys or option metric steps, ended with an empty "Edit Type" state behind its own step, so the History list grew a row that undid nothing. `dispatch` takes the coalesce key from the command's own `coalesce` param (engine/src/jobs.rs) and `edit_with` stores it on the document (engine/src/session/execute.rs), so those deliberately uncoalesced one-step-per-press commands left the key as None: the commit could not tell "the session has not stepped" from "the session stepped without a key", and the first round read it as the former and recorded. Those two commands now take a key of their own derived from the session, `-`: fresh per press, so a press still gets its own state and Cancel still does not undo one, but the state it leaves names the session that opened it. `commit_here` then adds a state of its own only when no state carries this session's key. Every other step a session can take - typing, the IME path, the paragraph-box drag, the temporary transform, the panels, the warp dialog - already carries `ed.session`, so the rule "the state a session leaves names that session" now holds throughout the tool. Tests: kerning and the style-key path each end with their own step and no empty one behind it; a later unchanged session still records after an earlier session stepped, which is why the marker has to be the session's key rather than the current state's label - the state before a new session can well be `Kerning`, and a label test would swallow the case the issue asks for. The seven tests from the first round, including the tool-switch and layer-switch holds, stay green. --- crates/ui-egui/src/tools/type_tool/editing.rs | 43 ++++++++++++--- .../type_tool/unchanged_edit_history_tests.rs | 55 +++++++++++++++++++ 2 files changed, 90 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index f13175f983..75e312a12a 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -214,7 +214,9 @@ fn opens_quote(prev: Option) -> bool { } /// Alt+←/→: kern the pair before the caret by `by` (1/1000 em). No pair (caret at a text or line -/// edge): nothing happens, like Photoshop. Not coalesced: one history step per press. +/// edge): nothing happens, like Photoshop. One history step per press: the press takes a fresh +/// key of its own ([`session_step_key`]) rather than no key, so it stays its own state and still +/// says which session opened it (#12050). pub(super) fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: f32) { let Some(text) = current_text(app, id) else { return }; let before = caret.checked_sub(1).and_then(|i| text.chars().nth(i)); @@ -223,7 +225,11 @@ pub(super) fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: return; } crate::type_transform::finish(app); - let _ = app.run("type.edit", json!({"layer": id.0, "kernPair": {"at": caret, "by": by}})); + let mut p = json!({"layer": id.0, "kernPair": {"at": caret, "by": by}}); + if let Some(session) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) { + p["coalesce"] = json!(session_step_key(app, &session)); + } + let _ = app.run("type.edit", p); } /// A character style the type editor's ⇧⌘ keys toggle (Photoshop: ⇧⌘K All Caps, ⇧⌘U @@ -296,6 +302,7 @@ fn set_style(app: &mut PhotocraftApp, ed: &TextEdit, range: (usize, usize), mut crate::type_transform::finish(app); p["layer"] = json!(ed.layer); p["range"] = json!([range.0, range.1]); + p["coalesce"] = json!(session_step_key(app, &ed.session)); if let Err(e) = app.run("type.setStyle", p) { app.ui.status = e; app.ui.status_error = true; @@ -529,16 +536,34 @@ fn commit_here(app: &mut PhotocraftApp, by_user: bool) { } else if ed.created { let name = photocraft_engine::type_cmds::layer_name(&text); let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session})); - } else if ends_an_edit && worked_on_layer(app, &ed) { + } else if ends_an_edit && worked_on_layer(app, &ed) && !session_recorded(app, &ed) { // Ending an edit of an existing layer is a step of its own even when the session changed - // nothing (#12050), so the History list shows the edit the user just ended. It carries the - // session's own coalesce key, which keeps it to the one step: `type.edit` under the key of - // the state the session already opened joins that state instead of adding a second one. - // The Cancel button ends through `cancel`, which never runs this. + // nothing (#12050), so the History list shows the edit the user just ended. The Cancel + // button ends through `cancel`, which never runs this. let _ = app.run("type.edit", json!({"layer": ed.layer, "coalesce": ed.session})); } } +/// A coalesce key for one deliberate step inside a typing session: the ⇧⌘ style keys, the ⌥ +/// metric steps and Alt+←/→ kerning are one history step per press, so each press takes a fresh +/// key and no two presses share a state. The key still names the session, which is how +/// [`session_recorded`] knows the session already opened a state and must not add an empty one +/// when the edit ends (#12050). +fn session_step_key(app: &mut PhotocraftApp, session: &str) -> String { + format!("{session}-{}", app.ui.alloc_id()) +} + +/// Has this session opened a history state of its own? Its typing carries the session's key, and +/// its one-step-per-press keys ([`session_step_key`]) carry that key with a press number, so the +/// state they leave names the session that made it. Ending such a session adds nothing: the undo +/// step the user just made is already there, and an empty state behind it would be a History row +/// that undoes nothing. A state left by an *earlier* session carries that session's key, so a +/// later unchanged edit of the same layer still records its own (#12050). +fn session_recorded(app: &PhotocraftApp, ed: &TextEdit) -> bool { + let pressed = format!("{}-", ed.session); + app.session.active().is_some_and(|st| st.coalesce.as_deref().is_some_and(|k| k == ed.session || k.starts_with(pressed.as_str()))) +} + /// Is a Type tool still the tool holding this session? The frame commits the edit when a tool /// switch takes the work on (#6483), also between the Type tools and the Type Mask tools; that is /// not an edit of the layer, so #12050's state is not opened for it. @@ -548,7 +573,9 @@ fn user_ends_the_edit(app: &PhotocraftApp) -> bool { /// Is the session's layer still the one worked on? Selecting another layer or document commits the /// session (#6483); #12050 does not measure that, so it records nothing. A background document's -/// edit is checked in its own document, where `commit_with` has just made it active. +/// edit is checked in its own document, where `commit_with` has just made it active - which is why +/// a document switch cannot be told from an in-place commit here, and still records (#12050 review +/// c4502824764). fn worked_on_layer(app: &PhotocraftApp, ed: &TextEdit) -> bool { app.session.active().is_some_and(|st| st.active_layer == Some(LayerId(ed.layer))) } diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs index 90a7d7dbe7..d52999a181 100644 --- a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -138,6 +138,61 @@ fn undoing_the_state_of_an_unchanged_edit_leaves_the_document_as_it_was() { assert_eq!(first_size(&app, id), size, "the style is what it was"); } +/// Alt+left/right makes Kerning its own step, deliberately not coalesced with the typing session. +/// Ending that session must leave the one `Kerning` state: an empty `Edit Type` state behind it +/// would be a History row that undoes nothing (#12050 review, c4502824768). +#[test] +fn a_kerned_session_ends_with_its_own_step_and_no_empty_one() { + let (mut app, id) = app(); + click_into(&mut app, id); + // A caret between two characters: what Alt+left/right needs. + if let Some(ed) = app.ui.text_edit.as_mut() { + (ed.caret, ed.anchor) = (2, 2); + } + let before = history(&app); + super::editing::kern_pair(&mut app, id, 2, 20.0); + let kerned = history(&app); + assert_eq!(kerned.len(), before.len() + 1, "the kerning is its own step, in {kerned:?}"); + assert_eq!(kerned.last().map(String::as_str), Some("Kerning")); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app), kerned, "ending the session adds no state of its own"); +} + +/// The ⇧⌘ style keys are one step per press for the same reason; the commit must not add an empty +/// state after them either. +#[test] +fn a_styled_session_ends_with_its_own_step_and_no_empty_one() { + let (mut app, id) = app(); + click_into(&mut app, id); + let before = history(&app); + super::toggle_char_style(&mut app, super::CharToggle::FauxBold); + let styled = history(&app); + assert_eq!(styled.len(), before.len() + 1, "the style key is its own step, in {styled:?}"); + crate::type_tool::commit(&mut app); + assert_eq!(history(&app), styled, "ending the session adds no state of its own"); +} + +/// The "this session already stepped" marker must belong to the session: a *later* unchanged edit +/// of the same layer still records its own state, even when the state before it came from an +/// earlier session's un-coalesced step. +#[test] +fn an_unchanged_edit_still_records_after_an_earlier_session_stepped() { + let (mut app, id) = app(); + click_into(&mut app, id); + if let Some(ed) = app.ui.text_edit.as_mut() { + (ed.caret, ed.anchor) = (2, 2); + } + super::editing::kern_pair(&mut app, id, 2, 20.0); + crate::type_tool::commit(&mut app); + let before = history(&app); + click_into(&mut app, id); + crate::type_tool::commit(&mut app); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "the second, unchanged session records, in {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Edit Type")); + assert_eq!(text_of(&app, id), "Hello"); +} + /// Not measured in #12050, so it keeps today's behaviour: an unchanged session ended because /// another layer took the focus records nothing. #[test] From aedac66d9514b38681cfa71b676d0d830b20866e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:35:26 +0100 Subject: [PATCH 07/85] 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 08/85] 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 09/85] 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 10/85] 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 11/85] 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 12/85] 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 13/85] 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 14/85] 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 15/85] 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 16/85] 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 17/85] 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 18/85] 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 19/85] 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 20/85] 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 21/85] 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 22/85] 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 23/85] 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 24/85] 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 25/85] 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 26/85] 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 27/85] 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 28/85] 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 29/85] 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 30/85] 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 487bd1bad7e7ab0bcfe95deb97dd3d01f5f06e11 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 22:41:47 -0800 Subject: [PATCH 31/85] test(ui): wait for stale thumbnail and Camera Raw workers --- crates/ui-egui/src/dialogs/camera_raw_ui.rs | 32 ++++++---- .../src/dialogs/camera_raw_ui/tests.rs | 20 ++++++- crates/ui-egui/src/home_recent_ui.rs | 58 +++++++++++++------ 3 files changed, 80 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index acfdd6327c..d20b98f241 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -50,6 +50,8 @@ pub use open::{ }; use open::{Target, non_defaults}; use proxy::{ProxyFrame, ProxyJob}; +#[cfg(not(target_arch = "wasm32"))] +type ProxyReceiver = std::sync::mpsc::Receiver>; pub use sidecar::sidecar_path; #[cfg(test)] use sidecar::{existing_sidecar_is_ours, read_bounded}; @@ -236,6 +238,22 @@ impl CameraRawDialog { self.preview_revision = self.preview_revision.saturating_add(1); } + /// Starts the same proxy worker used by the dialog, returning its completion handle. + #[cfg(not(target_arch = "wasm32"))] + fn spawn_proxy_worker(&self, ctx: &egui::Context) -> std::io::Result<(ProxyReceiver, std::thread::JoinHandle<()>)> { + let job = self.proxy_job(); + let (tx, rx) = std::sync::mpsc::channel::>(); + let repaint = ctx.clone(); + let worker = std::thread::Builder::new().name("camera-raw-proxy".into()).spawn(move || { + let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "RAW Develop preview failed".to_string()); + // The dialog may have closed or rendered on its own meanwhile; then nobody listens. + if tx.send(frame).is_ok() { + repaint.request_repaint(); + } + })?; + Ok((rx, worker)) + } + /// Starts developing the proxy with the current settings on a worker, unless one is already /// running: then [`Self::poll_render`] starts the next one with the settings of that moment. /// A slider drag never waits for the develop, which takes hundreds of milliseconds with @@ -246,18 +264,8 @@ impl CameraRawDialog { } #[cfg(not(target_arch = "wasm32"))] { - let job = self.proxy_job(); - let (tx, rx) = std::sync::mpsc::channel::>(); - let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("camera-raw-proxy".into()).spawn(move || { - let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "RAW Develop preview failed".to_string()); - // The dialog may have closed or rendered on its own meanwhile; then nobody listens. - if tx.send(frame).is_ok() { - repaint.request_repaint(); - } - }); - match spawned { - Ok(_) => { + match self.spawn_proxy_worker(ctx) { + Ok((rx, _worker)) => { self.pending = Some(rx); self.dirty = false; } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 93926c81c0..75c5975691 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -251,13 +251,31 @@ fn a_stale_worker_never_replaces_a_newer_synchronous_render() { let d = app.camera_raw.as_mut().unwrap(); d.params.highlights = -80.0; d.dirty = true; + #[cfg(not(target_arch = "wasm32"))] + let worker = { + let (rx, worker) = d.spawn_proxy_worker(&ctx).unwrap(); + d.pending = Some(rx); + d.dirty = false; + worker + }; + #[cfg(target_arch = "wasm32")] d.request_render(&ctx); assert!(d.render_pending()); let reply = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); assert_eq!(reply["previewPending"], false); let d = app.camera_raw.as_mut().unwrap(); let (revision, shown) = (d.preview_revision, d.processed.clone()); - std::thread::sleep(std::time::Duration::from_millis(200)); + #[cfg(not(target_arch = "wasm32"))] + { + // The synchronous render drops its receiver, not the detached worker. Wait + // for that worker itself before checking that its frame stayed discarded. + let start = std::time::Instant::now(); + while !worker.is_finished() && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(worker.is_finished(), "the stale RAW Develop preview worker never finished"); + worker.join().unwrap(); + } d.poll_render(&ctx).unwrap(); assert_eq!((d.preview_revision, &d.processed), (revision, &shown)); d.render(&ctx); diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index e8f25a1e72..c67a333209 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -340,6 +340,27 @@ fn drain_pending_thumbnails(app: &PhotocraftApp, ctx: &egui::Context, opts: Text } } +/// Starts the disk worker; callers may retain its handle to observe completion. +#[cfg(not(target_arch = "wasm32"))] +fn spawn_thumbnail_worker( + cache_arc: std::sync::Arc>, + ctx_clone: egui::Context, + path_str: String, + req_id: u64, + key_clone: CacheKey, + file_len: u64, +) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + let opt_img = load_thumbnail_catching_panic(|| load_thumbnail_image_bounded(&path_str, file_len)); + let mut cache = cache_arc.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Only enqueue if this request generation is still the active one + if cache.in_flight.get(&path_str).copied() == Some(req_id) { + cache.pending.push((path_str, req_id, key_clone, opt_img)); + ctx_clone.request_repaint(); + } + }) +} + /// Retrieve, lazily load, or regenerate the preview texture for `path`. /// /// If `path` is currently open in `app.session`, the thumbnail is rendered from @@ -476,15 +497,7 @@ pub(crate) fn get_or_load_thumbnail(app: &PhotocraftApp, ctx: &egui::Context, pa let path_str = path.to_string(); let key_clone = current_key; let file_len = meta.len(); - std::thread::spawn(move || { - let opt_img = load_thumbnail_catching_panic(|| load_thumbnail_image_bounded(&path_str, file_len)); - let mut cache = cache_arc.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - // Only enqueue if this request generation is still the active one - if cache.in_flight.get(&path_str).copied() == Some(req_id) { - cache.pending.push((path_str, req_id, key_clone, opt_img)); - ctx_clone.request_repaint(); - } - }); + let _ = spawn_thumbnail_worker(cache_arc, ctx_clone, path_str, req_id, key_clone, file_len); cached_entry.and_then(|e| e.texture) } else { let opt_img = load_thumbnail_image_bounded(path, meta.len()); @@ -1414,14 +1427,25 @@ mod tests { app.background_jobs = true; let ctx = egui::Context::default(); - let tex1 = get_or_load_thumbnail(&app, &ctx, &path_str); - assert!(tex1.is_none()); - - // Immediately invalidate while thread is in flight - app.thumbnail_cache.lock().unwrap().invalidate(&path_str); - - // Wait a short time for thread to complete - std::thread::sleep(std::time::Duration::from_millis(50)); + let meta = std::fs::metadata(&file_path).unwrap(); + let key = CacheKey::DiskFile { modified: meta.modified().ok(), len: meta.len() }; + let worker = { + // Hold the publication lock until invalidation, so even a fast decode must + // check its generation after this request has been removed. + let mut cache = app.thumbnail_cache.lock().unwrap(); + let req_id = cache.next_req_id; + cache.next_req_id = cache.next_req_id.wrapping_add(1); + cache.in_flight.insert(path_str.clone(), req_id); + let worker = spawn_thumbnail_worker(std::sync::Arc::clone(&app.thumbnail_cache), ctx.clone(), path_str.clone(), req_id, key, meta.len()); + cache.invalidate(&path_str); + worker + }; + let start = std::time::Instant::now(); + while !worker.is_finished() && start.elapsed() < std::time::Duration::from_secs(2) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(worker.is_finished(), "the invalidated thumbnail worker never finished"); + worker.join().unwrap(); // The background thread should have detected it was removed from in_flight and discarded its result let cache = app.thumbnail_cache.lock().unwrap(); From 2392112af8490755c081c96fda1edd79791a2eb1 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:34:52 +0100 Subject: [PATCH 32/85] Tests: font commit tests drop the mirrored patterns and the accept x commit grid (#15368) --- .../src/tools/type_tool/font_commit_tests.rs | 134 +++++++++--------- 1 file changed, 64 insertions(+), 70 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index bb80791b79..69ebd65944 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -167,25 +167,22 @@ fn commit(h: &mut Harness<'_, Probe>, method: &str) { } } +// A pattern picks the text's styles: 0 is all `FONTS[0]`, 2 is `FONTS[0]` with `FONTS[1]` on +// [2, 4]. Patterns 1 and 3 would be the same with the two fonts swapped, and every case already +// chooses each font as the target, so they would reach nothing new. #[test] fn selected_fonts_commit_pattern_0() { selected_fonts_commit_cases(0); } -#[test] -fn selected_fonts_commit_pattern_1() { - selected_fonts_commit_cases(1); -} - #[test] fn selected_fonts_commit_pattern_2() { selected_fonts_commit_cases(2); } -#[test] -fn selected_fonts_commit_pattern_3() { - selected_fonts_commit_cases(3); -} +/// Each way to accept a font, committed with the checkmark, and each way to commit after an +/// Enter: accepting and committing are separate steps, so their full grid repeats both. +const ACCEPT_THEN_COMMIT: [(&str, &str); 4] = [("enter", "checkmark"), ("click", "checkmark"), ("arrow-enter", "checkmark"), ("enter", "outside")]; fn selected_fonts_commit_cases(pattern: usize) { let mut cases = 0; @@ -193,79 +190,76 @@ fn selected_fonts_commit_cases(pattern: usize) { for character in [false, true] { for range in [[0, 2], [2, 4], [4, 6], [0, 6], [4, 2], [1, 5]] { for target in FONTS { - for accept in ["enter", "click", "arrow-enter"] { - for method in ["checkmark", "outside"] { - let label = (new, pattern, character, range, target, accept, method); - let (mut h, id) = fixture(new, pattern, character, "abcdef"); - select(&mut h, range); - h.run(); - let mut expected = families(&saved(&h, id)); - for font in &mut expected[range[0].min(range[1])..range[0].max(range[1])] { - *font = target.into(); - } - choose(&mut h, target, accept); - let applied = saved(&h, id); - assert_eq!(families(&applied), expected, "{label:?}"); - assert_eq!(fields(&h)[0].as_deref(), Some(target), "selected font caption: {label:?}"); - let pixels = layer(&h.state().app.session.active().unwrap().doc, id).cache.clone(); - commit(&mut h, method); - assert!(h.state().app.ui.text_edit.is_none(), "{label:?}"); - assert_eq!(saved(&h, id), applied, "{label:?}"); - assert_eq!(layer(&h.state().app.session.active().unwrap().doc, id).cache, pixels, "{label:?}"); - let uniform = expected.iter().all(|f| f == &expected[0]); - assert_eq!( - fields(&h)[0].clone().unwrap_or_default(), - if uniform { expected[0].clone() } else { String::new() }, - "mixed caption after commit: {label:?}" - ); - super::edit_active(&mut h.state_mut().app).unwrap(); - select(&mut h, range); - h.run(); - assert_eq!(fields(&h)[0].as_deref(), Some(target), "reselected caption: {label:?}"); - cases += 1; + for (accept, method) in ACCEPT_THEN_COMMIT { + let label = (new, pattern, character, range, target, accept, method); + let (mut h, id) = fixture(new, pattern, character, "abcdef"); + select(&mut h, range); + h.run(); + let mut expected = families(&saved(&h, id)); + for font in &mut expected[range[0].min(range[1])..range[0].max(range[1])] { + *font = target.into(); } + choose(&mut h, target, accept); + let applied = saved(&h, id); + assert_eq!(families(&applied), expected, "{label:?}"); + assert_eq!(fields(&h)[0].as_deref(), Some(target), "selected font caption: {label:?}"); + let pixels = layer(&h.state().app.session.active().unwrap().doc, id).cache.clone(); + commit(&mut h, method); + assert!(h.state().app.ui.text_edit.is_none(), "{label:?}"); + assert_eq!(saved(&h, id), applied, "{label:?}"); + assert_eq!(layer(&h.state().app.session.active().unwrap().doc, id).cache, pixels, "{label:?}"); + let uniform = expected.iter().all(|f| f == &expected[0]); + assert_eq!( + fields(&h)[0].clone().unwrap_or_default(), + if uniform { expected[0].clone() } else { String::new() }, + "mixed caption after commit: {label:?}" + ); + super::edit_active(&mut h.state_mut().app).unwrap(); + select(&mut h, range); + h.run(); + assert_eq!(fields(&h)[0].as_deref(), Some(target), "reselected caption: {label:?}"); + cases += 1; } } } } } - assert_eq!(cases, 288); + assert_eq!(cases, 192); } #[test] fn caret_font_choices_style_only_subsequent_typing_including_ime() { for new in [false, true] { for character in [false, true] { - for original in 0..2 { - for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - let n = text.chars().count(); - for caret in [0, n / 2, n] { - for accept in ["enter", "click", "arrow-enter"] { - let (mut h, id) = fixture(new, original, character, text); - select(&mut h, [caret, caret]); - h.run(); - let before = saved(&h, id); - let steps = h.state().app.session.active().unwrap().history.entries().len(); - let font = FONTS[1 - original]; - choose(&mut h, font, accept); - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters"); - assert_eq!(h.state().app.session.active().unwrap().history.entries().len(), steps); - assert_eq!(fields(&h)[0].as_deref(), Some(font)); - crate::type_font_preview::set(&mut h.state_mut().app, font.into()); - assert!(crate::type_font_preview::display_doc(&mut h.state_mut().app, 0).is_none()); - // Multiple preedit replacements and final commit keep the pending font. - super::ime_update(&mut h.state_mut().app, "é", false); - super::ime_update(&mut h.state_mut().app, "éX", true); - super::insert(&mut h.state_mut().app, "Z"); - let mut expected = families(&before); - expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected); - let typed = saved(&h, id); - commit(&mut h, "checkmark"); - assert_eq!(saved(&h, id), typed); - assert!(h.state().app.ui.type_insertion_style.is_none()); - } - } + // One original font and one acceptance: the original only decides which of the two + // fonts is chosen, and `selected_fonts_commit_cases` covers every acceptance. + let (original, accept) = (0, "enter"); + for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { + let n = text.chars().count(); + for caret in [0, n / 2, n] { + let (mut h, id) = fixture(new, original, character, text); + select(&mut h, [caret, caret]); + h.run(); + let before = saved(&h, id); + let steps = h.state().app.session.active().unwrap().history.entries().len(); + let font = FONTS[1 - original]; + choose(&mut h, font, accept); + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters"); + assert_eq!(h.state().app.session.active().unwrap().history.entries().len(), steps); + assert_eq!(fields(&h)[0].as_deref(), Some(font)); + crate::type_font_preview::set(&mut h.state_mut().app, font.into()); + assert!(crate::type_font_preview::display_doc(&mut h.state_mut().app, 0).is_none()); + // Multiple preedit replacements and final commit keep the pending font. + super::ime_update(&mut h.state_mut().app, "é", false); + super::ime_update(&mut h.state_mut().app, "éX", true); + super::insert(&mut h.state_mut().app, "Z"); + let mut expected = families(&before); + expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); + assert_eq!(families(&saved(&h, id)), expected); + let typed = saved(&h, id); + commit(&mut h, "checkmark"); + assert_eq!(saved(&h, id), typed); + assert!(h.state().app.ui.type_insertion_style.is_none()); } } } From e9796f05908c71542245f3ceaf1860bfeda64d92 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 17 Nov 2026 21:30:25 +0100 Subject: [PATCH 33/85] Toolbar: flyouts open to the right, flipped only at the window edge (#12517) The toolbar's tool flyouts, "..." flyout and Edit Toolbar drawer opened toward the canvas, so with the toolbar docked on the right between the dock's columns they opened to the left over the canvas. The reference application opens them to the right there too, over the panels, and flips them only where they would leave the window. They now always prefer the end side; the overlay placement already flips them when that side has no room. --- crates/ui-egui/src/panels/panel_docking.rs | 11 --- crates/ui-egui/src/panels/toolbar.rs | 15 +++- .../src/panels/toolbar_docking_tests.rs | 89 +++++++++++++++++++ 3 files changed, 101 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/panels/toolbar_docking_tests.rs diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 596f12af47..0911972911 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -6,7 +6,6 @@ //! The lock is `app.workspaces.set.locked`. use craft::behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target}; -use craft::behavior::overlay::Side; use craft::behavior::{DockSide, EditEvent, EditEvents, IconId}; use craft::ui::contract::{Bind, BodyCx, SizeLimits}; use craft::ui::docking::{ @@ -56,16 +55,6 @@ pub(crate) fn is_front(app: &PhotocraftApp, id: &str) -> bool { layout.panel_state(&panel) == PanelState::Front || (layout.opens_in_flyout(&panel) && app.ui.flyout.as_ref() == Some(&panel)) } -/// The side of the Toolbar its flyouts and drawer open on: the side of the canvas. A toolbar in the end dock opens -/// towards the start, any other toward the end. -pub(crate) fn toolbar_opens(app: &PhotocraftApp) -> Side { - let layout = &app.ui.docking.layout; - match layout.place(&TOOLBAR.to_owned()) { - Some(PanelPlace::Dock { path, .. }) if layout.dock_path(DockEdge::End).is_some_and(|end| end == path) => Side::Start, - _ => Side::End, - } -} - /// Shows or hides panel `id` (an id or a label). `Some(true)` opens a hidden panel at its place, and brings a shown /// one to the front, expanding its minimized group; `Some(false)` closes it; `None` shows a panel that is hidden, /// minimized or behind another tab and closes one that is in front. A panel in a column collapsed to icons opens and diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index acb14c1d00..36c511681a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -14,6 +14,9 @@ use photocraft_engine::prefs::ToolbarCustomization; use super::tool_commands; +#[cfg(test)] +#[path = "toolbar_docking_tests.rs"] +mod toolbar_docking_tests; #[cfg(test)] #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; @@ -154,7 +157,13 @@ fn quick_mask_button(app: &PhotocraftApp, ui: &mut egui::Ui) { let _ = FlyoutButton::new(&tools, &0).id_salt("quick-mask").selected(on).show(ui); } -/// The rail over `slots`, its flyouts and drawer opening on `opens`, the side of the canvas. +/// The side of the toolbar its tool flyouts, "…" flyout and Edit Toolbar drawer open on: the end (the right in a +/// left-to-right layout) wherever the toolbar is docked or floats, as in the reference application, which opens them +/// to the right even when the toolbar sits on the right between the dock's columns. The overlay flips them to the +/// other side only when they would leave the window. +const FLYOUTS_OPEN: Side = Side::End; + +/// The rail over `slots`, its flyouts and drawer opening on `opens`. fn rail<'a>(slots: &'a [ToolSlot], current: &'a Tool, remembered: &'a LastUsed, opens: Side, editing: bool) -> ToolRail<'a, Tool> { let rail = ToolRail::new(Label::Empty, slots, current, remembered).opens(opens).edit_toolbar(tl!("Edit Toolbar…").to_string()); // The drawer's open flag is the one source of "editing". @@ -184,7 +193,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 let slots = tool_commands::slots(&app.session.prefs().toolbar); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); rail(&slots, ¤t, &remembered, opens, editing).measure_rail(ui, width, |ui, at| footer(app, ui, at)).y } @@ -199,7 +208,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let slots = tool_commands::slots(&app.session.prefs().toolbar); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let out = rail(&slots, ¤t, &remembered, opens, editing).show_rail(ui, |ui, at| footer(app, ui, at)); if let Some(tool) = out.select { diff --git a/crates/ui-egui/src/panels/toolbar_docking_tests.rs b/crates/ui-egui/src/panels/toolbar_docking_tests.rs new file mode 100644 index 0000000000..156b370b4d --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_docking_tests.rs @@ -0,0 +1,89 @@ +//! The toolbar as a dock panel (#12517): its tool flyouts open to the right of the button wherever it is docked, and +//! flip to the left only where they would leave the window. + +use super::*; +use crate::panels::registry::TOOLBAR; +use craft::behavior::dock::{Action, DockPlacement, Target}; +use egui::{PointerButton, Pos2, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +const SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +/// The whole app in a 1200 x 800 window with a small document open. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(SIZE).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).expect("new document"); + app + }); + h.run_steps(4); + h +} + +/// Moves the toolbar's column beside the column holding `anchor`, after it in the dock's column order or before it. +fn dock_toolbar_beside(h: &mut Harness<'static, PhotocraftApp>, anchor: &str, after: bool) { + let action = Action::move_column(TOOLBAR.to_owned(), Target::at(anchor.to_owned(), DockPlacement::column(after))); + crate::panel_docking::apply(h.state_mut(), vec![action]).expect("the toolbar docks beside the column"); + h.run_steps(6); +} + +/// The rect of the innermost node named `label`. +fn rect_of(h: &Harness<'static, PhotocraftApp>, label: &str) -> Option { + h.query_all_by_label(label).last().map(|node| node.rect()) +} + +/// Right-clicks the middle of `rect`, which opens a tool slot's flyout. +fn right_click(h: &mut Harness<'static, PhotocraftApp>, rect: Rect) { + let at: Pos2 = rect.center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(4); +} + +/// The Lasso slot's flyout rows, opened from the toolbar: the slot's button and the Polygonal Lasso row. +fn lasso_flyout(h: &mut Harness<'static, PhotocraftApp>) -> (Rect, Rect) { + let button = rect_of(h, "Lasso Tool").expect("the Lasso slot is drawn"); + right_click(h, button); + let row = rect_of(h, "Polygonal Lasso Tool").expect("the Lasso flyout is open"); + (button, row) +} + +/// Docked on the right between the dock's icon column and its panel column, the toolbar still opens its flyouts to the +/// right of the button, over the panels, as the reference application does (they used to open toward the canvas). +#[test] +fn flyouts_open_to_the_right_between_the_end_docks_columns() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", true); + let toolbar = crate::panel_docking::probe::group_rect(&h, "toolbar"); + let panels = crate::panel_docking::probe::group_rect(&h, "color").expect("the Color group is drawn"); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() < panels.left(), "the toolbar sits left of the panel column: {button:?}, {panels:?}, {toolbar:?}"); + assert!(button.center().x > SIZE.x * 0.5, "the toolbar is on the right half of the window: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} + +/// At the right window edge there is no room to the right, so the flyout flips to the left of the button. +#[test] +fn flyouts_flip_left_at_the_right_window_edge() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", false); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() > SIZE.x - 80.0, "the toolbar is at the right window edge: {button:?}"); + assert!(row.right() <= button.left() + 0.5, "the flyout flips to the left of the button: row {row:?}, button {button:?}"); +} + +/// Docked at the left edge (the default), the flyout opens to the right. +#[test] +fn flyouts_open_to_the_right_at_the_left_edge() { + let mut h = harness(); + let (button, row) = lasso_flyout(&mut h); + assert!(button.left() < 80.0, "the toolbar is at the left window edge: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} From fbc9f98d1bca1fdaea30a593df4fd75d5c997458 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Wed, 18 Nov 2026 00:48:02 +0000 Subject: [PATCH 34/85] Dialogs: titles drop the menu item's ellipsis (#15541) Stroke, New Group, New Group from Layers and New Brush Preset showed the menu label with its trailing ellipsis as the window title. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- .../src/dialog_title_ellipsis_tests.rs | 49 +++++++++++++++++++ .../src/dialogs/brush_preset_dialog.rs | 2 +- crates/ui-egui/src/dialogs/new_group_ui.rs | 2 +- crates/ui-egui/src/dialogs/stroke_ui.rs | 2 +- crates/ui-egui/src/lib.rs | 2 + 5 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialog_title_ellipsis_tests.rs diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs new file mode 100644 index 0000000000..d958214bce --- /dev/null +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -0,0 +1,49 @@ +//! A dialog's title is its command's name without the menu item's ellipsis (#15541): Edit › Stroke… +//! opens "Stroke", as in Photoshop. Covers the dialogs that name themselves after their menu item. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; + +/// Opens one dialog. +type Open = fn(&mut PhotocraftApp); + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app + }); + h.run_steps(6); + h +} + +#[test] +fn dialog_titles_drop_the_menu_ellipsis() { + let cases: [(&str, Open); 4] = [ + ("Stroke", |app| { + crate::stroke_ui::open(app); + }), + ("New Group", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::NEW_GROUP); + }), + ("New Group from Layers", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::FROM_LAYERS); + }), + ("New Brush Preset", |app| { + crate::brush_preset_dialog::open(app, None); + }), + ]; + for (title, open) in cases { + let mut h = harness(); + open(h.state_mut()); + h.run_steps(4); + assert!(h.query_all_by_label(&format!("{title}…")).next().is_none(), "the {title} dialog's title has no ellipsis"); + assert!(h.query_all_by_label(title).next().is_some(), "the dialog is titled {title}"); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs index 30d680888d..fde37ee089 100644 --- a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs +++ b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs @@ -67,7 +67,7 @@ pub fn open(app: &mut PhotocraftApp, brush: Option<&BrushSettings>) -> DialogId // Include Color belongs to the tool settings: only with them, as in Photoshop. Param::new("color", tl!("Include Color"), ParamKind::bool(false)).enabled_when("toolSettings", true), ]; - let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset…"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); + let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); if let Some(why) = why { dialog = dialog.ok_reason(Label::from(why)); } diff --git a/crates/ui-egui/src/dialogs/new_group_ui.rs b/crates/ui-egui/src/dialogs/new_group_ui.rs index 2412592556..af393044ea 100644 --- a/crates/ui-egui/src/dialogs/new_group_ui.rs +++ b/crates/ui-egui/src/dialogs/new_group_ui.rs @@ -33,7 +33,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> DialogId { let command = if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP }; let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into()); // The window title, as in Photoshop. - let title = if command == FROM_LAYERS { tl!("New Group from Layers…") } else { tl!("New Group…") }; + let title = if command == FROM_LAYERS { tl!("New Group from Layers") } else { tl!("New Group") }; params::open_param(app, command, DialogFields::new(), Value::Null, move |fields: &mut DialogFields| { let rows = vec![ Param::new("name", tl!("Name:"), ParamKind::text(name.clone())), diff --git a/crates/ui-egui/src/dialogs/stroke_ui.rs b/crates/ui-egui/src/dialogs/stroke_ui.rs index e5a07a6707..2048251e57 100644 --- a/crates/ui-egui/src/dialogs/stroke_ui.rs +++ b/crates/ui-egui/src/dialogs/stroke_ui.rs @@ -43,7 +43,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { } let [r, g, b, _] = app.session.tools.foreground; let rows = rows([r, g, b]); - let title = Label::from(tl!("Stroke…")); + let title = Label::from(tl!("Stroke")); open_param(app, COMMAND, DialogFields::new(), held, move |fields| { ParamDialog::new(COMMAND, title.clone(), Cow::Owned(rows.clone())).values(Bind::bound(fields)).remember(SaveKey::named(REMEMBER)) }) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8b08795cd8..e6c73c7d3c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -799,6 +799,8 @@ mod navigator_gpu_tests; #[cfg(test)] mod color_swatch_tests; +#[cfg(test)] +mod dialog_title_ellipsis_tests; #[cfg(test)] mod profile_open_tests; From a7574415bb46f8f203eee0d1122dc2312fb6d106 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 19:10:26 -0800 Subject: [PATCH 35/85] Format the current-framework regression repair --- .../src/dialogs/camera_raw_ui/tests.rs | 22 ++++++++++++++----- crates/ui-egui/src/home_recent_ui.rs | 13 +++++------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 921f1e65a8..78dea66ce5 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -193,7 +193,6 @@ fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings ); } - /// An old job held after its real cancellation check. Drop always releases it and drains its queue, including on /// an assertion failure; all waits have bounds. This never substitutes for the production menu or develop job. #[cfg(not(target_arch = "wasm32"))] @@ -233,7 +232,8 @@ fn hold_old_preview(app: &PhotocraftApp) -> (HeldPreview, std::sync::mpsc::Recei let _ = arrived.send(order); let (released, wake) = &*release; let released = released.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let (released, _) = wake.wait_timeout_while(released, std::time::Duration::from_secs(30), |released| !*released).unwrap_or_else(std::sync::PoisonError::into_inner); + let (released, _) = + wake.wait_timeout_while(released, std::time::Duration::from_secs(30), |released| !*released).unwrap_or_else(std::sync::PoisonError::into_inner); if !*released { timed_out.store(true, std::sync::atomic::Ordering::Relaxed); } @@ -247,7 +247,11 @@ fn wait_for_newer_preview(app: &mut PhotocraftApp, order: u64) { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); loop { frame(app); - if session(app).source.developed().is_some_and(|result| result.revision > order && result.settings.exposure == -1.0 && result.settings.highlights == 0.0) { + if session(app) + .source + .developed() + .is_some_and(|result| result.revision > order && result.settings.exposure == -1.0 && result.settings.highlights == 0.0) + { return; } assert!(std::time::Instant::now() < deadline, "the real newer request must publish while the older job is held"); @@ -279,9 +283,17 @@ fn a_stale_worker_never_replaces_a_newer_synchronous_render() { frame(&mut app); let later = describe(&app); assert_eq!(later["previewPending"], false); - assert_eq!((&later["previewRevision"], &later["histogram"]), (&landed["previewRevision"], &landed["histogram"]), "the old result reached publication last and did not replace the newer frame"); + assert_eq!( + (&later["previewRevision"], &later["histogram"]), + (&landed["previewRevision"], &landed["histogram"]), + "the old result reached publication last and did not replace the newer frame" + ); assert_eq!(processed(&app), shown_pixels, "the old result did not replace the displayed proxy pixels"); - assert_eq!(session(&app).source.proxy_job(&shown(&app)).run().px, shown_pixels, "the pixels still match a synchronous develop of the control channel's settings"); + assert_eq!( + session(&app).source.proxy_job(&shown(&app)).run().px, + shown_pixels, + "the pixels still match a synchronous develop of the control channel's settings" + ); assert_eq!(landed["histogram"], single_develop_histogram(json!({"exposure": -1.0})), "the frame shown is the one for the latest settings"); } #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index d6d101a4c5..b2fd2fb533 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -486,13 +486,7 @@ mod tests { let ctx = app.ctx().clone(); let mut state = None; frames.frame(Vec::new(), |_| { - state = Some(thumbnails(&ctx).state( - &ctx, - &source(app, &ctx), - key, - &ThumbRequest::for_cell(64.0, 1.0), - craft::ui::primitives::Priority::VISIBLE, - )); + state = Some(thumbnails(&ctx).state(&ctx, &source(app, &ctx), key, &ThumbRequest::for_cell(64.0, 1.0), craft::ui::primitives::Priority::VISIBLE)); }); state.expect("the Home thumbnail caller ran") } @@ -564,7 +558,10 @@ mod tests { std::fs::write(&path_string, flat_png([20, 100, 60, 255])).unwrap(); // The former picture may be a stand-in, but it cannot satisfy the invalidated revision as Ready. - assert!(matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. }), "the completed old result is not current"); + assert!( + matches!(recent_thumbnail_pass(&app, &mut frames, &key), craft::ui::primitives::TextureState::Loading { .. }), + "the completed old result is not current" + ); assert_eq!(jobs.waiting(), 1, "the production source requests a replacement decoder"); assert!(jobs.run_next(), "the replacement decoder completes"); let state = recent_thumbnail_pass(&app, &mut frames, &key); From 02220e053db220d16e1fea0c8dd79afcf821fcc3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 16:08:41 +0000 Subject: [PATCH 36/85] Layer folder export tests: the planted-link test and its helpers build on Unix only (cherry picked from commit d8591f9d58507888fb7b3019e16a4b0d24c5aa33) --- .../layer_folder_export_tests.rs | 125 +++++++++--------- 1 file changed, 65 insertions(+), 60 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs index 3ed7cf24bd..62517df458 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs @@ -4,11 +4,7 @@ //! One file keeps the save dialog with the layer's name. use super::*; -use craft::host::{Picked, ScriptedFiles}; use photocraft_doc::{Color, Size}; -use std::{cell::RefCell, rc::Rc}; - -type Written = Rc>>; fn named(name: &str) -> Document { Document::with_background(name, Size::new(4, 4), ColorMode::Rgb, photocraft_doc::SampleType::U8, Color::WHITE) @@ -39,61 +35,70 @@ fn names_keep_spaces_replace_illegal_characters_and_number_duplicates_downwards( assert_eq!(layer_file_names(&docs, "jpg"), ["Dup-2.jpg", "Dup-1.jpg", "Dup.jpg"]); } -/// A document with filled layers `a/b:c*?`, `Dup` and `Dup` (bottom to top), plus an empty layer. Its file dialogs -/// stay open until the test answers them. -fn app() -> (PhotocraftApp, Vec, LayerId, Written, Arc) { - let written = Written::default(); - let capture = written.clone(); - let files = Arc::new(ScriptedFiles::held()); - let services = crate::Services { - files: Some(files.clone()), - export: Some(Box::new(|doc, path, settings| { - photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) - })), - write: Some(Box::new(move |path, _| { - capture.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); - app.run("layer.new.layer", json!({"name": "Blank"})).unwrap(); - let empty = app.session.active().unwrap().active_layer.unwrap(); - let mut ids = Vec::new(); - for (name, color) in [("a/b:c*?", "#ff0000"), ("Dup", "#00ff00"), ("Dup", "#0000ff")] { - app.run("layer.new.layer", json!({"name": name})).unwrap(); - app.run("paint.bucket", json!({"x": 0, "y": 0, "color": color})).unwrap(); - ids.push(app.session.active().unwrap().active_layer.unwrap()); - } - (app, ids, empty, written, files) -} - -/// Layer › Export As on `ids` as PNG: Export asks for a destination, which the user answers with `path`. Returns the -/// destination request. -fn export_layers_to(app: &mut PhotocraftApp, files: &ScriptedFiles, ids: &[LayerId], path: &std::path::Path) -> craft::host::PickRequest { - let ctx = app.ctx().clone(); - let id = open_layers(app, ids).unwrap(); - app.framework.dialogs.set_json_field(&ctx, id, "format", json!("png")).unwrap(); - crate::dialogs::confirm(app, &ctx, id).unwrap(); - let request = files.requests().last().cloned().expect("Export asks for a destination"); - files.answer(Picked::Paths(vec![path.to_path_buf()])).expect("the destination dialog is open"); - app.poll_file_dialog(); - // The dialog's next pass takes the answered path and exports. - crate::dialogs::confirm(app, &ctx, id).unwrap(); - request -} - +/// A planted link at the destination: the test needs Unix symlinks, and so do its helpers. #[cfg(unix)] -#[test] -fn a_planted_link_is_replaced_not_followed() { - let guard = tempfile::tempdir().unwrap(); - let dir = guard.path().to_path_buf(); - let link = dir.join("Dup.png"); - std::os::unix::fs::symlink(dir.join("victim"), &link).unwrap(); - let (mut app, ids, _, written, files) = app(); - export_layers_to(&mut app, &files, &ids, &dir); - assert!(link.symlink_metadata().is_err(), "the link is gone before the write"); - assert!(written.borrow().contains(&link.to_string_lossy().into_owned())); - assert!(!dir.join("victim").exists(), "nothing was written through the link"); +mod planted_link { + use super::*; + use craft::host::{Picked, ScriptedFiles}; + use std::{cell::RefCell, rc::Rc}; + + type Written = Rc>>; + + /// A document with filled layers `a/b:c*?`, `Dup` and `Dup` (bottom to top), plus an empty layer. Its file dialogs + /// stay open until the test answers them. + fn app() -> (PhotocraftApp, Vec, LayerId, Written, Arc) { + let written = Written::default(); + let capture = written.clone(); + let files = Arc::new(ScriptedFiles::held()); + let services = crate::Services { + files: Some(files.clone()), + export: Some(Box::new(|doc, path, settings| { + photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(move |path, _| { + capture.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("layer.new.layer", json!({"name": "Blank"})).unwrap(); + let empty = app.session.active().unwrap().active_layer.unwrap(); + let mut ids = Vec::new(); + for (name, color) in [("a/b:c*?", "#ff0000"), ("Dup", "#00ff00"), ("Dup", "#0000ff")] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + app.run("paint.bucket", json!({"x": 0, "y": 0, "color": color})).unwrap(); + ids.push(app.session.active().unwrap().active_layer.unwrap()); + } + (app, ids, empty, written, files) + } + + /// Layer › Export As on `ids` as PNG: Export asks for a destination, which the user answers with `path`. Returns the + /// destination request. + fn export_layers_to(app: &mut PhotocraftApp, files: &ScriptedFiles, ids: &[LayerId], path: &std::path::Path) -> craft::host::PickRequest { + let ctx = app.ctx().clone(); + let id = open_layers(app, ids).unwrap(); + app.framework.dialogs.set_json_field(&ctx, id, "format", json!("png")).unwrap(); + crate::dialogs::confirm(app, &ctx, id).unwrap(); + let request = files.requests().last().cloned().expect("Export asks for a destination"); + files.answer(Picked::Paths(vec![path.to_path_buf()])).expect("the destination dialog is open"); + app.poll_file_dialog(); + // The dialog's next pass takes the answered path and exports. + crate::dialogs::confirm(app, &ctx, id).unwrap(); + request + } + + #[test] + fn a_planted_link_is_replaced_not_followed() { + let guard = tempfile::tempdir().unwrap(); + let dir = guard.path().to_path_buf(); + let link = dir.join("Dup.png"); + std::os::unix::fs::symlink(dir.join("victim"), &link).unwrap(); + let (mut app, ids, _, written, files) = app(); + export_layers_to(&mut app, &files, &ids, &dir); + assert!(link.symlink_metadata().is_err(), "the link is gone before the write"); + assert!(written.borrow().contains(&link.to_string_lossy().into_owned())); + assert!(!dir.join("victim").exists(), "nothing was written through the link"); + } } From 4655db8f8c17b6d5b5b933820f2a171b7cab2191 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 21:08:05 -0800 Subject: [PATCH 37/85] Handle recorded thumbnail texture updates in headless tests Clear the owned texture deltas after checking every decoded pixel. The headless helper inspects these uploads without a renderer, so it must consume them before dropping the recorded frame. --- crates/ui-egui/src/home_recent_ui.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index b2fd2fb533..c159451de3 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -506,11 +506,13 @@ mod tests { fn assert_recent_picture(frames: &mut craft::ui::testing::Frames, state: craft::ui::primitives::TextureState, rgba: [u8; 4]) { let craft::ui::primitives::TextureState::Ready(texture) = state else { panic!("the completed decoder must supply a ready picture") }; assert_eq!((texture.size.width, texture.size.height), (4, 4)); - let paint = frames.take_paint().expect("texture uploads were recorded"); + let mut paint = frames.take_paint().expect("texture uploads were recorded"); let delta = paint.textures_delta.set.get(&texture.id).and_then(|changes| changes.last()).expect("the real decoder's texture was uploaded"); let egui::ImageData::Color(image) = &delta.image; assert_eq!(image.size, [4, 4]); assert!(image.pixels.iter().all(|pixel| pixel.to_array() == rgba), "the picture contains the decoded file's pixels"); + // The headless test inspected the uploads instead of rendering them. + paint.textures_delta.clear(); } #[cfg(not(target_arch = "wasm32"))] From 84ee720e61051509bc536e15baafbb79ff506487 Mon Sep 17 00:00:00 2001 From: DingusMcRinkyDinky <127614779+DingusMcRinkyDinky@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:25:34 +0100 Subject: [PATCH 38/85] Free Transform: the layer shows inside its box again While Free Transform is open, the canvas hides the layer being transformed from the document's picture and draws it as the transform preview. Both go into the canvas's picture slot in show order, and the canvas shows its controls (the preview among them) before it prepares the document's picture, so the document, without the layer, painted over the preview: only the layers below showed inside the box. The preview is now painted in place, taken out and handed to the canvas body, which adds it to the picture slot after the document and the channel overlay, as the Levels clipping display already joins it. The layers above the moving pixels go with them; the box, the warp grid and the guides still draw on top. Fixes #15546. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZbgszHyuEuWAzxaamteuU --- crates/ui-egui/src/canvas/document_display.rs | 5 + crates/ui-egui/src/canvas/tools/mod.rs | 4 +- .../ui-egui/src/tools/transform_tool/draw.rs | 30 ++-- .../tests/it/free_transform_preview_canvas.rs | 139 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 5 files changed, 168 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/tests/it/free_transform_preview_canvas.rs diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 768d2b4aec..6bc6a7fd79 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -335,6 +335,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, // What the controls report for the host's pass. let mut body_shown = tools::BodyShown::default(); let live = canvas_controls(app, ui, body.rect, host, &space, &mut turned, &mut body_shown); + // The Free Transform preview joins the picture slot after the document, which is prepared after the tools. + let transform_picture = std::mem::take(&mut body_shown.transform_picture); // The body can run more than once in a frame; a report from any of its runs counts. if let Some(context) = body_shown.crop.as_mut().and_then(craft::draw::ui::CropShown::take_context) { overlay_context = Some(context); @@ -414,6 +416,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, }; display.show_at(ui, body.rect); } + // The moving pixels over the document, which hides the layer they come from, and under the controls. + space.paint_picture(ctx, transform_picture); space.paint_picture(ctx, clipping); // The grid is drawn over the picture. if app.ui.view.shows(app.ui.view.show.pixel_grid) { @@ -528,6 +532,7 @@ fn canvas_controls( let session = if primary { crate::transform_tool::show_in_canvas(app, ui, rect, now) } else { crate::transform_tool::SessionShown::default() }; let session_box_shown = session.shown; reported.transform_snapped = session.snapped; + reported.transform_picture = session.picture; crate::cam_transform::show(app, ui, rect); super::transform_controls::show(app, ui, rect, session_box_shown); crate::move_box::show(app, ui, rect); diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 019e289041..8e39edf481 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -477,6 +477,8 @@ pub(crate) struct BodyShown { pub(crate) crop: Option, /// The snap lines of the open Free Transform's box, which its canvas tool hands to the host. pub(crate) transform_snapped: Vec, + /// The open Free Transform's preview, which the body adds to the canvas's picture slot after the document. + pub(crate) transform_picture: Vec, } /// Borrows a family tool as the host's `dyn`. @@ -513,7 +515,7 @@ fn with_rig( let transform_open = app.ui.transform.is_some(); let lends_transform = stand_ins && (!in_gesture || tools.gesture_pick == GesturePick::Transform); let free_transform = if lends_transform { app.ui.transform.take() } else { None }; - let BodyShown { crop: crop_shown, transform_snapped } = shown; + let BodyShown { crop: crop_shown, transform_snapped, .. } = shown; let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped)); // The symmetry session moves into the pass the same way. let symmetry_transform = if stand_ins && fam == Family::Paint { app.ui.symmetry_transform.take() } else { None }; diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 0eab00e4f0..a8723af30e 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -12,6 +12,7 @@ use craft::imaging::ui::transform_preview::{PreviewDisplay, PreviewMap, Transfor use craft::imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpGrid, WarpMesh}; use craft::ui::canvas::RasterDisplay; use craft::ui::contract::{Bind, Show as _}; +use craft::ui::primitives::PaintSlot; use photocraft_doc::DocId; use photocraft_geom::warp::WarpStyle; @@ -38,11 +39,16 @@ struct Shown { cylinder: Option>, /// A warp control has the pointer button down on it. busy: bool, + /// The preview's shapes, for the canvas's picture slot after the document ([`SessionShown::picture`]). + picture: Vec, } /// Shows the open Free Transform in the canvas body at `rect`, and applies what its controls /// report: the preview (moving pixels, covering layers, path outline), then the box or warp -/// controls. The canvas calls it after the document display and before the tool overlays. +/// controls. The canvas calls it with its controls, before it prepares the document's picture, so +/// the preview's moving pixels come back in [`SessionShown::picture`] for the canvas to add to its +/// picture slot after the document: added here, the document (which hides the moving layer) would +/// paint over them (#15546). /// /// Every control reads the frame's input once for its own pass, so a second pass of a frame /// reports no edit again and this applies only what the pass it ran in reported. @@ -55,7 +61,7 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return SessionShown::default() }; show_session(app, t, pv, ui, rect) }; - let Shown { edits, snapped, apply, discard, mesh, cylinder, busy } = shown; + let Shown { edits, snapped, apply, discard, mesh, cylinder, busy, picture } = shown; let mut need_warp = false; if let Some(t) = app.ui.transform.as_mut() { for edit in edits.iter().cloned() { @@ -85,13 +91,12 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re if let Some(t) = app.ui.transform.as_mut() { t.session.settle(now, busy); } - SessionShown { shown: true, snapped } + SessionShown { shown: true, snapped, picture } } /// The pass's shows, in paint order. fn show_session(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Shown { - show_preview(app, t, pv, ui, rect); - let mut out = Shown::default(); + let mut out = Shown { picture: show_preview(app, t, pv, ui, rect), ..Shown::default() }; if pv.committing.is_some() { // The moving pixels stay without the box until the commit job lands. return out; @@ -125,14 +130,19 @@ pub struct SessionShown { pub shown: bool, /// The snap lines of the box's drag. pub snapped: Vec, + /// The preview's shapes (the moving pixels, then the layers above them), which the canvas adds to its picture + /// slot after the document's picture. + pub picture: Vec, } /// The moving pixels as the session maps them (warped, skewed or styled), then the layers above /// them, both in the canvas's picture, under the grid, guides and controls. Nothing is shown for the Frame tool's transform. -fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) { +fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Vec { if crate::frame_tool::frame_transform(t) { - return; + return Vec::new(); } + // Painted in place after this mark, then taken out for the picture slot. + let mark = PaintSlot::reserve(ui.painter()); let display = preview_display(app, ui.ctx()); let boxed = t.session.phase() == TransformPhase::Box; // The layers that get the styled preview stay PhotoCraft's: a visible layer with a style. @@ -150,8 +160,7 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m .opacity(pv.opacity) .nearest(t.session.interpolation() == Interpolation::NearestNeighbor) .clip(canvas) - .dragging(t.session.dragging()) - .picture(); + .dragging(t.session.dragging()); if let Some(display) = display.as_ref() { preview = preview.display(display); } @@ -162,8 +171,9 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m if let Some(above) = &pv.above && let Some(frame) = above.frame() { - RasterDisplay::new("", above).mapped(frame, 1).picture().show_at(ui, rect); + RasterDisplay::new("", above).mapped(frame, 1).show_at(ui, rect); } + mark.take_after(ui.ctx()) } /// What the box draws for the styled layer at `zoom`, as the framework's styled preview builds it: the composite and its diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs new file mode 100644 index 0000000000..99681b74e6 --- /dev/null +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -0,0 +1,139 @@ +//! #15546: while Free Transform is open, the canvas shows the layer being transformed inside its box. +//! +//! The canvas hides that layer from the document's picture and draws it as the transform preview. The preview +//! joins the canvas's picture slot, and the document's picture is prepared after the canvas controls, so a preview +//! added with the controls lay under the document: only the layers below showed inside the box. These tests drive +//! the real app offscreen on wgpu, on the GPU canvas and on the CPU one, start Free Transform on a red layer over a +//! white background, and look at the rendered pixels inside the box, before and during a drag that moves it. +//! Skips when no GPU adapter exists (like `drag_preview_canvas.rs`). + +use craft::behavior::kurbo::Point; +use egui::{Modifiers, PointerButton, Pos2}; +use photocraft_geom::Rect; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The red square on the layer, in document pixels: x 100..200, y 100..200 of a 400 × 300 document. +fn square() -> Rect { + Rect::new(100, 100, 200, 200) +} + +fn harness(gpu_canvas: bool) -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + if gpu_canvas && let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +/// A white 400 × 300 document at 100 % with a layer holding the red square, active, and the Move tool. +fn setup(h: &mut Harness) { + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("new layer"); + app.session + .edit("paint", |doc, active| { + let id = active.expect("the new layer is active"); + let surface = doc.layer_mut(id).and_then(|l| l.surface_mut()).expect("a raster layer"); + surface.fill_rect(square(), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .expect("paint"); + app.sync_views(); + app.ui.extras.rulers = false; + } + control(h, "ui.set", json!({"tool": "move", "zoom": 1.0, "center": [200, 150]})); + h.run_steps(3); +} + +/// Screen point (egui points, one physical pixel each here) of document point `(x, y)`. +fn screen(h: &Harness, x: f64, y: f64) -> Pos2 { + photocraft_ui_egui::canvas::active_view(h.state()).expect("an active document view").to_screen(Point::new(x, y)) +} + +fn pointer_move(h: &mut Harness, at: Pos2) { + h.event(egui::Event::PointerMoved(at)); + h.step(); +} + +fn button(h: &mut Harness, at: Pos2, pressed: bool) { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// The rendered frame's RGB at document point `(x, y)`. +fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { + let p = screen(h, x, y); + let img = h.render().expect("render"); + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] +} + +fn is_red(c: [u8; 3]) -> bool { + c[0] > 200 && c[1] < 60 && c[2] < 60 +} + +fn is_white(c: [u8; 3]) -> bool { + c.iter().all(|&v| v > 230) +} + +fn shows_the_layer_inside_the_box(gpu_canvas: bool) { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(gpu_canvas) else { return }; + setup(&mut h); + assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(h.state().ui.transform.is_some(), "Free Transform is open"); + let inside = rgb_at(&mut h, 150.5, 150.5); + assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); + + // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the + // middle row, where the smart guide of the centred box is drawn. + let (from, to) = (screen(&h, 150.0, 150.0), screen(&h, 210.0, 150.0)); + pointer_move(&mut h, from); + button(&mut h, from, true); + for i in 1..=6 { + pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); + } + let moved = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); + let vacated = rgb_at(&mut h, 120.5, 130.5); + assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); + button(&mut h, to, false); + let released = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(released), "the moved square still shows after the release: {released:?}"); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_gpu_canvas() { + shows_the_layer_inside_the_box(true); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_cpu_canvas() { + shows_the_layer_inside_the_box(false); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f2143a01cf..1bb6bc452c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -19,6 +19,7 @@ mod crop_task_bar; mod display_shadows; mod drag_preview_canvas; mod eraser_reset_defaults; +mod free_transform_preview_canvas; mod full_res_preview; mod gpu_device_loss; mod healing_reset_tip; From 70e03a3b6113f692ab5643ac3265a9fc10a5af05 Mon Sep 17 00:00:00 2001 From: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:29:10 +0800 Subject: [PATCH 39/85] fix(xtask): classify craft as a UI dependency (#15467) --- xtask/src/layers.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 42e18e12a7..cc8e282730 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -98,7 +98,7 @@ fn standalone_exception(from: &str, to: &str) -> bool { /// External crates that constitute a UI toolkit / windowing dependency. /// Entries ending in `*` are prefixes. -pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy*"]; +pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy*"]; /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -340,7 +340,7 @@ mod tests { #[test] fn ui_crates_below_l6_flagged() { - for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy_ecs", "bevy"] { + for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy_ecs", "bevy"] { let v = check(&[c("photocraft-engine", &[(dep, Normal, false)])]); assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 5, .. }]), "{dep}"); } From ccc230d475cab68eee98e239202b1b41db68afb6 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:41:58 +0100 Subject: [PATCH 40/85] Tests: the caret font test covers every acceptance again --- .../src/tools/type_tool/font_commit_tests.rs | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index 3fd4054e27..876cff2020 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -88,7 +88,8 @@ fn fixture(pattern: usize, content: &str) -> (H, LayerId) { (h, id) } -/// Picks `font` in the first family field: open it, type the name, Enter, as `accept` says. +/// Picks `font` in the first family field: open it, type the name, then accept it as `accept` says +/// (Enter, ArrowDown then Enter, a click on its row, or a hover). fn choose(h: &mut H, font: &str, accept: &str) { h.query_all_by_label("Font family").next().unwrap().click(); h.run(); @@ -96,6 +97,11 @@ fn choose(h: &mut H, font: &str, accept: &str) { h.run(); match accept { "enter" => h.key_press(Key::Enter), + "arrow-enter" => { + h.key_press(Key::ArrowDown); + h.run(); + h.key_press(Key::Enter); + } "click" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).click(), "hover" => h.get_by_role_and_label(egui::accesskit::Role::TreeItem, font).hover(), _ => panic!("unknown acceptance"), @@ -111,19 +117,23 @@ fn checkmark(h: &mut H) { #[test] fn caret_font_choices_style_only_subsequent_typing_including_ime() { - for original in 0..2 { + // Every acceptance, as each reaches the caret's pending style by its own route through the + // family field. One original font, as it only decides which font is chosen, and the carets at + // both ends. + let original = 0; + for accept in ["enter", "click", "arrow-enter"] { for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - let n = text.chars().count(); - for caret in [0, n / 2, n] { + for caret in [0, text.chars().count()] { + let label = (accept, text, caret); let (mut h, id) = fixture(original, text); select(&mut h, [caret, caret]); h.run(); let before = saved(&h, id); let steps = h.state().session.active().unwrap().history.entries().len(); let font = FONTS[1 - original]; - choose(&mut h, font, "enter"); - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters"); - assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); + choose(&mut h, font, accept); + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); crate::type_font_preview::set(h.state_mut(), font.into()); assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); // Two preedit replacements and the final commit keep the pending font. @@ -138,11 +148,11 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { h.run(); let mut expected = families(&before); expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected); + assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); let typed = saved(&h, id); checkmark(&mut h); - assert_eq!(saved(&h, id), typed); - assert!(h.state().ui.type_insertion_style.is_none()); + assert_eq!(saved(&h, id), typed, "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "{label:?}"); } } } From 5dcb91a891ed51d0837e2dd4e984189c46195887 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:58:04 +0100 Subject: [PATCH 41/85] Control channel: list and cancel every dialog by the id it replies with (#15544) Since the move onto the craft UI framework, four dialogs could not be driven by the id the control channel gave for them: - Keyboard Shortcuts and Menus draws outside the framework's dialog host, so ui.inspect never listed it and ui.dialog.cancel {"dialog": "shortcuts"} failed, leaving every command refused behind its modal. It is now listed under "shortcuts" while open (first: it draws beneath the host's dialogs), and ui.dialog.cancel with that id closes it without saving, as its Cancel does. ui.dialog.set/confirm/apply refuse it with a pointer to edit.keyboardShortcuts params. - Preferences replied "preferences" but is listed under its host id. It now replies with that id, or with the reason it did not open. - Select > Color Range replied {"dialog": {"Ok": id}}: json! serialised the Result. It now replies through dialog_reply like every other dialog, and an open that fails is an error instead of ok with {"Err": ...} inside. - The unsaved-changes prompt was listed under a number with only `choice`. It is listed as "discard" again with the documented command, document, remaining, choices and default, and ui.dialog.confirm/cancel resolve "discard" to it (docs/control-protocol.md, #4920). Tests drive each through the control channel (handle with a ControlRequest). Two existing tests change with the documented ids: the Preferences apply test asserted the old "preferences" reply, and the save-authorization helper fed the listed prompt id to the host lookup. docs/control-protocol.md now says which dialogs have fixed ids and what menu items reply. --- crates/ui-egui/src/control/dialogs.rs | 23 +++- crates/ui-egui/src/control/inspect.rs | 5 + crates/ui-egui/src/control/tests.rs | 109 +++++++++++++++++- crates/ui-egui/src/dialogs/discard_ui.rs | 37 ++++++ crates/ui-egui/src/menus/invoke.rs | 4 +- crates/ui-egui/src/prefs/kys_import.rs | 4 +- crates/ui-egui/src/prefs/prefs_ui/dialogs.rs | 9 +- .../ui-egui/src/prefs/prefs_ui/shortcuts.rs | 23 +++- docs/control-protocol.md | 6 +- 9 files changed, 201 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/control/dialogs.rs b/crates/ui-egui/src/control/dialogs.rs index 3e40a1788a..08eb3f28a3 100644 --- a/crates/ui-egui/src/control/dialogs.rs +++ b/crates/ui-egui/src/control/dialogs.rs @@ -360,9 +360,26 @@ pub(crate) fn method(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Control if !matches!(req.method.as_str(), "ui.dialog.set" | "ui.dialog.confirm" | "ui.dialog.cancel" | "ui.dialog.apply") { return None; } - let id = match dialog_id(host(app), p) { - Ok(id) => id, - Err(e) => return Some(err(e)), + // Keyboard Shortcuts and Menus draws outside the host: Cancel closes it; its changes go through + // `edit.keyboardShortcuts` params (#15544). + if p.get("dialog").and_then(Value::as_str) == Some(crate::prefs_ui::shortcuts::CONTROL_ID) { + return Some(match req.method.as_str() { + "ui.dialog.cancel" if crate::prefs_ui::shortcuts::cancel(app) => ok(Value::Null), + "ui.dialog.cancel" => err("Keyboard Shortcuts and Menus is not open"), + _ => err("Keyboard Shortcuts and Menus takes its changes as `edit.keyboardShortcuts` params; `ui.dialog.cancel` closes it"), + }); + } + // The unsaved-changes prompt is listed as "discard" and answered by that id. + let id = if p.get("dialog").and_then(Value::as_str) == Some(crate::discard_ui::CONTROL_ID) { + match crate::discard_ui::host_id(app) { + Some(id) => id, + None => return Some(err("no unsaved-changes prompt is open")), + } + } else { + match dialog_id(host(app), p) { + Ok(id) => id, + Err(e) => return Some(err(e)), + } }; Some(match req.method.as_str() { "ui.dialog.set" => set(app, ctx, id, p), diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index b4ac2a24f6..5c71c68dd7 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -87,6 +87,11 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { // The framework host's dialogs in their one stack order (top last). let mut dialogs = craft::automation::dialogs::inspect(&app.framework.dialogs); crate::layer_style::describe_params(app, &mut dialogs); + crate::discard_ui::describe(app, &mut dialogs); + // Keyboard Shortcuts and Menus draws beneath the host's dialogs, outside the host (#15544). + if let (Some(shortcuts), Some(list)) = (crate::prefs_ui::shortcuts::inspect(app), dialogs.as_array_mut()) { + list.insert(0, shortcuts); + } // Last frame's task bar rect, unless the bar can't show now (hidden by `ui.set` before the // next draw). let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index aa8e65df7a..2b6c55355e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -986,11 +986,11 @@ fn preferences_apply_is_available_over_control_without_closing() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = app.ctx().clone(); let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"})); - // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists - // and the reply names it by its key. + // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists, + // and the reply names it by that id (#15544). let listed = dialogs(&mut app, &ctx); let window = listed.iter().find(|d| d["key"] == "preferences").expect("the Preferences window is listed"); - assert_eq!(r["result"]["dialog"], window["key"], "{r}"); + assert_eq!(r["result"]["dialog"], window["id"], "{r}"); let id = window["id"].clone(); let mut values = window["fields"]["values"].clone(); values["interface"]["uiScale"] = json!("200"); @@ -1354,7 +1354,8 @@ fn dirty_close_prompted() -> (Box, egui::Context, std::rc::Rc Result<(), String> { let prompt = top_dialog(app, ctx)["id"].clone(); if synthetic { - let id = craft::automation::dialogs::dialog_id(&app.framework.dialogs, &json!({"dialog": prompt})).expect("the prompt is listed"); + assert_eq!(prompt, crate::discard_ui::CONTROL_ID, "the prompt is listed as discard"); + let id = crate::discard_ui::host_id(app).expect("the prompt is open"); app.automation_input = true; let r = crate::dialogs::confirm(app, ctx, id); app.automation_input = false; @@ -2223,3 +2224,103 @@ fn shift_right_menu_choose_rejects_bad_choices_and_sets_the_tool() { shift_right(&mut app, "magicEraser"); assert!(inspect(&app, &ctx)["brushModeMenu"].is_null()); } + +/// A fresh app with a document, as a control client finds it, and the context the control channel runs on. +fn app_with_document() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// The id `ui.menu.invoke {id, wait: false}` replied for the dialog it opened. +fn invoked_dialog(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) -> Value { + let reply = call(app, ctx, "ui.menu.invoke", json!({"id": id, "wait": false})); + assert_eq!(reply["ok"], true, "{id}: {reply}"); + crate::canvas::testing::frame(app); + reply["result"]["dialog"].clone() +} + +/// #15544: Keyboard Shortcuts and Menus is listed under the id its menu items reply with, and +/// `ui.dialog.cancel` with that id closes it, so a control client is never stuck behind it. +#[test] +fn keyboard_shortcuts_is_listed_and_cancelled_by_the_id_invoke_replies() { + for command in ["edit.keyboardShortcuts", "edit.menus"] { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, command); + assert!(id.is_string(), "{command}: the reply names the dialog: {id}"); + let listed = dialogs(&mut app, &ctx); + assert!(listed.iter().any(|d| d["id"] == id), "{command}: {id} is listed in {listed:?}"); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], false, "{command}: the dialog is modal"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{command}: {cancelled}"); + assert!(!crate::prefs_ui::shortcuts_open(&app), "{command}: Cancel closed it"); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], false, "{command}: nothing left to cancel"); + let next = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"})); + assert_eq!(next["ok"], true, "{command}: commands run again: {next}"); + } +} + +/// #15544: Preferences replies with the id `ui.inspect` lists it under, and cancelling that id closes it. +#[test] +fn preferences_replies_with_the_id_it_is_listed_under() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "edit.preferences.interface"); + let listed = dialogs(&mut app, &ctx); + assert_eq!(listed.len(), 1, "{listed:?}"); + assert_eq!(listed[0]["id"], id, "the reply is the listed id"); + assert_eq!(listed[0]["key"], "preferences"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], true); +} + +/// #15544: Select › Color Range… replies with the bare id, as every other dialog does, not a `Result` around it. +#[test] +fn color_range_replies_with_the_bare_dialog_id() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "select.colorRange"); + assert!(id.is_string(), "a bare id, not a wrapper: {id}"); + assert_eq!(top_dialog(&mut app, &ctx)["id"], id); + assert_eq!(top_dialog(&mut app, &ctx)["key"], "select.colorRange"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + assert!(dialogs(&mut app, &ctx).is_empty()); +} + +/// #15544: the unsaved-changes prompt is listed as `"discard"` with the command it holds back, the document it +/// asks about, how many are left and the choices, and `ui.dialog.confirm` / `ui.dialog.cancel` take that id +/// (docs/control-protocol.md). +#[test] +fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { + let (mut app, ctx) = app_with_document(); + app.run("layer.new.layer", json!({})).unwrap(); + let prompt = |app: &mut PhotocraftApp| dialogs(app, &ctx).into_iter().find(|d| d["id"] == "discard"); + assert!(prompt(&mut app).is_none()); + // Close the changed document: the prompt is listed; Cancel keeps the document. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let listed = prompt(&mut app).unwrap_or_else(|| panic!("listed as discard: {:?}", dialogs(&mut app, &ctx))); + let name = app.session.active().unwrap().doc.name.clone(); + assert_eq!(listed["fields"]["command"], "file.close"); + assert_eq!(listed["fields"]["document"], name.as_str()); + assert_eq!(listed["fields"]["remaining"], 1); + assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(prompt(&mut app).is_none()); + assert_eq!(app.session.documents().len(), 1, "Cancel keeps the document"); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer"); + // Don't Save by that id closes it. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let answered = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"})); + assert_eq!(answered["ok"], true, "{answered}"); + crate::canvas::testing::frame(&mut app); + assert!(app.session.documents().is_empty(), "Don't Save closed the document"); +} diff --git a/crates/ui-egui/src/dialogs/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs index 8ca632d0c7..f96391a6fb 100644 --- a/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/crates/ui-egui/src/dialogs/discard_ui.rs @@ -418,6 +418,43 @@ pub(crate) fn authorize_save(app: &PhotocraftApp, from_control: bool) -> Result< } } +/// The id the control channel knows the prompt by: `ui.inspect` lists it under this id, and `ui.dialog.confirm` and +/// `ui.dialog.cancel` answer it by it (docs/control-protocol.md, #4920, #15544). +pub const CONTROL_ID: &str = "discard"; + +/// The host's id of the open question, for a control request naming [`CONTROL_ID`]. +pub(crate) fn host_id(app: &PhotocraftApp) -> Option { + app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id) +} + +/// Lists the open question in `dialogs` (the host's `ui.inspect` entries) under [`CONTROL_ID`], its fields adding the +/// command it holds back, the document it asks about, how many are left to answer, the choices `ui.dialog.confirm` +/// takes and the default one. +pub(crate) fn describe(app: &PhotocraftApp, dialogs: &mut Value) { + let Some(key) = host_id(app).map(|id| id.value().to_string()) else { return }; + let Some(entry) = dialogs.as_array_mut().and_then(|list| list.iter_mut().find(|d| d["id"] == key.as_str())) else { return }; + entry["id"] = json!(CONTROL_ID); + let Some(p) = app.discard.as_ref() else { return }; + let name = p.docs.first().and_then(|&doc| index_of(app, doc)).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone()); + let reverts = p.id == "file.revert"; + let choices: &[&str] = match (reverts, p.docs.len() > 1) { + (true, _) => &["dontSave", "cancel"], + (false, false) => &["save", "dontSave", "cancel"], + (false, true) => &["save", "saveAll", "dontSave", "dontSaveAll", "cancel"], + }; + let described = json!({ + "command": p.id, + "document": name, + "remaining": p.docs.len(), + "choices": choices, + "default": if reverts { "dontSave" } else { "save" }, + }); + match entry.get_mut("fields").and_then(Value::as_object_mut) { + Some(fields) => fields.extend(described.as_object().cloned().unwrap_or_default()), + None => entry["fields"] = described, + } +} + /// The command the prompt holds back and its params, for the automation policy to see before a /// control client answers it. pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> { diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index c7e1cf2378..5f442d0bc5 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -523,9 +523,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "select.findLayers" => crate::layer_filter_ui::find::invoke(app, params), // Photoshop's "Select and Mask…" is the engine's select.refineEdge. // Select › Color Range… from the menu: the dialog (with params: the engine directly). - "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::color_range_ui::open(app).map(|dialog| dialog.value().to_string())})) - } + "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => crate::color_range_ui::open(app).map(dialog_reply), // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params: // the engine directly). photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => { diff --git a/crates/ui-egui/src/prefs/kys_import.rs b/crates/ui-egui/src/prefs/kys_import.rs index 8d45d3a61f..bdec2dd9f0 100644 --- a/crates/ui-egui/src/prefs/kys_import.rs +++ b/crates/ui-egui/src/prefs/kys_import.rs @@ -14,7 +14,7 @@ use craft::keymap::import::kys; use craft::menu::shortcuts::{ImportOffer, OfferAnswer, OfferRecord}; use craft::ui::dialog::{DialogResult, StartupStage}; -use serde_json::{Value, json}; +use serde_json::Value; use crate::PhotocraftApp; use crate::prefs_ui::shortcuts::{draft_keymap, import_options, kys_text, profiles_of, queue_import, save_keys}; @@ -28,7 +28,7 @@ pub const IMPORTED_PREF: &str = "photoshopShortcuts"; pub fn open_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result { let text = kys_text(name, bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(crate::prefs_ui::shortcuts::control_reply()) } fn remember(app: &mut PhotocraftApp, record: &OfferRecord) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index 1fc4722e94..64a0727d53 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -41,17 +41,20 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } if let Some(section) = id.strip_prefix("edit.preferences.") { open_preferences(app, section); - return Some(Ok(json!({"dialog": "preferences"}))); + // The id `ui.inspect` lists the window under, as every hosted dialog replies (#15544); the status says why it + // did not open. + let opened = app.framework.dialogs.get::().map(|d| json!({"dialog": d.id().value().to_string()})); + return Some(opened.ok_or_else(|| app.ui.status.clone())); } let dialog = |d: Result| Some(d.map(|d| json!({"dialog": d.value().to_string()}))); match id { "edit.keyboardShortcuts" => { super::shortcuts::open(app, 0); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.menus" => { super::shortcuts::open(app, 1); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.toolbar" => { crate::panels::toolbar::open_drawer(app); diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index 282c69dba3..9f14c5ee74 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -117,6 +117,27 @@ pub fn shortcuts_open(app: &PhotocraftApp) -> bool { app.prefs_rt.shortcuts.is_some() } +/// The id the control channel knows the dialog by: Edit › Keyboard Shortcuts and Edit › Menus reply with it, +/// `ui.inspect` lists the dialog under it, and `ui.dialog.cancel` closes it. The dialog draws outside the framework's +/// dialog host, which has no id for it (#15544). +pub(crate) const CONTROL_ID: &str = "shortcuts"; + +/// The reply of a command that opened the dialog. +pub(crate) fn control_reply() -> Value { + json!({"dialog": CONTROL_ID}) +} + +/// The dialog as `ui.inspect` lists it among the dialogs while it is open, in the host's entry shape. +pub(crate) fn inspect(app: &PhotocraftApp) -> Option { + shortcuts_open(app).then(|| json!({"id": CONTROL_ID, "key": "edit.keyboardShortcuts", "parent": null, "fields": {}})) +} + +/// Cancel for a control client, as the dialog's Cancel: the session goes and nothing it edited is saved. False with +/// the dialog closed. +pub(crate) fn cancel(app: &mut PhotocraftApp) -> bool { + app.prefs_rt.shortcuts.take().is_some() +} + /// Whether the dialog is recording a chord: the key goes to the recorder and runs nothing, and the /// native menu bar pauses its key equivalents. pub fn recording(app: &PhotocraftApp) -> bool { @@ -213,7 +234,7 @@ fn ask_import(app: &mut PhotocraftApp, state: &mut DialogState) { let picked = app.pick_file_bytes_filtered(&["kys", "psp", "json"], |app, name, bytes| { let text = kys_text(&name, &bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(control_reply()) }); if let Err(e) = picked { state.show_error(e); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4aed18c1c4..22225621a7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -126,13 +126,13 @@ The transport is the framework's control server (`craft::automation::server` in - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs and the unsaved-changes prompt are listed like any other; the prompt's `ui.dialog.confirm` takes a `choice`). OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) + - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs are listed like any other). A menu item that opens a dialog replies `{"dialog": ""}` with the id it is listed under. Two dialogs have a fixed id instead: the unsaved-changes prompt is `"discard"` (below), and Keyboard Shortcuts and Menus (Edit › Keyboard Shortcuts, Edit › Menus) is `"shortcuts"`, listed first while it is open (it draws beneath the other dialogs); `ui.dialog.cancel {"dialog": "shortcuts"}` closes it without saving, as its Cancel does, and its changes go through `edit.keyboardShortcuts` params rather than `ui.dialog.set` or `ui.dialog.confirm`, which refuse it; `"top"` never names it. OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "saveAll" | "dontSave" | "dontSaveAll" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time. `saveAll` and `dontSaveAll` tick "Apply to All": they answer for every document still to ask about, and are listed in `choices` only while more than one is left. A document whose save is cancelled or fails is asked about again; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. - Gradient Overlay's `params.offset` is the gradient's centre as a fraction of the layer's bounds (`[x, y]`, `[0, 0]` centred, as the renderer takes it). With the dialog on a Gradient Overlay page, a drag on the image moves it by the pointer's movement over the layer's size, as a drag on a shadow page moves the shadow (#10763). - - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. + - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`, which replies with the id `ui.inspect` lists the window under, its `key` being `preferences`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. - Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …). - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. @@ -336,7 +336,7 @@ when it starts); see [Without `--control`](#without---control-preferences--integ | `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key | | `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything. An individual `shortcuts.` or `menus.colors.` reset removes the override and returns `null`, including when it is already absent | | `edit.preferences.
` | the section's values; in the app (no params) it opens the Preferences dialog on that section | -| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus, whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | +| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus (`ui.menu.invoke` replies `{"dialog": "shortcuts"}`, the id `ui.inspect` lists it under and `ui.dialog.cancel` closes it by), whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | | `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` | | `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt | From 4d576ced907488eb6e7f833b06be3dd99d1c1a25 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 11:21:18 -0800 Subject: [PATCH 42/85] Partition the long Windows UI test matrices without reducing coverage --- .config/nextest.toml | 4 +- .../src/input/shortcut_dispatch/tests.rs | 101 ++++++++++------- crates/ui-egui/tests/it/tone_targets.rs | 105 ++++++++++-------- 3 files changed, 123 insertions(+), 87 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index ee1a1a5390..e4d9ee7f15 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -55,8 +55,8 @@ threads-required = 2 platform = 'cfg(target_os = "windows")' # over 200 s filter = ''' - (package(photocraft-ui-egui) & test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is)) | - (package(photocraft-ui-egui) & test(=tone_targets::review_mask_action_context_matches_the_addressed_layer)) | + (package(photocraft-ui-egui) & (test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_canvas) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_layers_row) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_focused_widget) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_opacity_field))) | + (package(photocraft-ui-egui) & (test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_rgb) | test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_cmyk) | test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_lab))) | (package(photocraft-ui-egui) & test(=tone_targets::grayscale_picker_controls_sample_the_plane_and_change_the_visible_curve)) | (package(photocraft-ui-egui) & test(=dialogs::adjust_editors::ui_tests::every_adjustment_layer_edits_through_properties)) | (package(photocraft-ui-egui) & test(=tone_targets::filter_mask_tone_dialogs_preserve_the_target_and_sample_its_own_levels)) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 9d9dd2f319..cc8cf8e468 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -194,54 +194,75 @@ fn displayed(app: &PhotocraftApp) -> Vec<(String, String, bool)> { /// 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 /// links… resolve and check enablement without running.) -#[test] -fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() { +fn every_displayed_shortcut_dispatches_from_where_focus_usually_is_for(place: Place) { let mut failures = Vec::new(); - for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] { - let mut h = harness(); - set_dry_run(&h.ctx, true); - 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}")); - // 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); - press(&mut h, &sc); - let log = take_log(&h.ctx); - if typing && !chord.has_command() && !chord.is_function_key() { - // A focused text field keeps its typing / editing keys: nothing may fire. - if !log.is_empty() { - failures.push(format!("{place:?}: {sc} ({id}) fired {log:?} into a focused field")); - } - continue; - } - let enabled = items.iter().find(|i| i.command.id == id).map_or_else(|| crate::menus::is_enabled(h.state(), &id), |i| i.enabled); - match log.as_slice() { - [] if held || typing => {} - [(bound, Outcome::Ran)] if same(&id, bound) && enabled => {} - [(bound, Outcome::Disabled(why))] if same(&id, bound) && !enabled && !why.is_empty() => {} - other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")), - } + let mut h = harness(); + set_dry_run(&h.ctx, true); + 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; } - // Tool letters from the tools panel tooltips ("Brush Tool (B)"). - if !typing { - for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { - h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; - press(&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)); - } + let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}")); + // 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); + press(&mut h, &sc); + let log = take_log(&h.ctx); + if typing && !chord.has_command() && !chord.is_function_key() { + // A focused text field keeps its typing / editing keys: nothing may fire. + if !log.is_empty() { + failures.push(format!("{place:?}: {sc} ({id}) fired {log:?} into a focused field")); + } + continue; + } + let enabled = items.iter().find(|i| i.command.id == id).map_or_else(|| crate::menus::is_enabled(h.state(), &id), |i| i.enabled); + match log.as_slice() { + [] if held || typing => {} + [(bound, Outcome::Ran)] if same(&id, bound) && enabled => {} + [(bound, Outcome::Disabled(why))] if same(&id, bound) && !enabled && !why.is_empty() => {} + other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")), + } + } + // Tool letters from the tools panel tooltips ("Brush Tool (B)"). + if !typing { + for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') { + h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; + press(&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)); } } } assert!(failures.is_empty(), "{} shortcut failures:\n{}", failures.len(), failures.join("\n")); } +/// The complete displayed shortcut matrix from one ordinary focus location. +#[test] +fn every_displayed_shortcut_dispatches_from_where_focus_usually_is_canvas() { + every_displayed_shortcut_dispatches_from_where_focus_usually_is_for(Place::Canvas); +} + +/// The complete displayed shortcut matrix from one ordinary focus location. +#[test] +fn every_displayed_shortcut_dispatches_from_where_focus_usually_is_layers_row() { + every_displayed_shortcut_dispatches_from_where_focus_usually_is_for(Place::LayersRow); +} + +/// The complete displayed shortcut matrix from one ordinary focus location. +#[test] +fn every_displayed_shortcut_dispatches_from_where_focus_usually_is_focused_widget() { + every_displayed_shortcut_dispatches_from_where_focus_usually_is_for(Place::FocusedWidget); +} + +/// The complete displayed shortcut matrix from one ordinary focus location. +#[test] +fn every_displayed_shortcut_dispatches_from_where_focus_usually_is_opacity_field() { + every_displayed_shortcut_dispatches_from_where_focus_usually_is_for(Place::OpacityField); +} + #[test] fn a_disabled_shortcut_says_why() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index cedcb8a773..2def86ec64 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -1117,57 +1117,72 @@ fn addressed_mask_app(mode: ColorMode, depth: SampleType, filter: bool) -> (Box< /// Named/id mask Actions show, sample, preview and edit the addressed layer's own mask without /// switching the selected layer. The matrix includes native raster and Smart Filter masks. -#[test] -fn review_mask_action_context_matches_the_addressed_layer() { - for mode in MODES { - for depth in DEPTHS { - for kind in ["levels", "curves"] { - for filter in [false, true] { - let (app, layer) = addressed_mask_app(mode, depth, filter); - for selector in [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})] { - let mut app = fixture_for_addressed_replay(&app); - let command = format!("image.adjustments.{kind}"); - let target = if filter { "filterMask" } else { "mask" }; - let raw = json!({"layer":selector,"target":target}); - add_action(&mut app, "Other mask", command.clone(), raw, true); - let original = app.session.active().unwrap().doc.clone(); - let active = app.session.active().unwrap().active_layer; - let expected = - photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); - let mut h = canvas_harness(app); - play(&mut h, "Other mask"); - assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); - let id = top(&h); - arm(&mut h, "white"); - sample_at(&mut h, 4.0, 4.0); - let p = params(&h); - let want = photocraft_engine::adjust_params::adjustment_eyedropper( - kind, - &json!({}), - photocraft_engine::adjust_params::CurvesEyedropper::White, - [expected; 3], - ColorMode::Grayscale, - ) - .unwrap(); - let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); - assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); - let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); - confirm(&mut h, id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.layers, preview.layers); - assert_eq!(doc.layers[0], original.layers[0]); - assert_eq!(doc.channels, original.channels); - assert!( - photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99 - ); - assert_eq!(h.state().session.active().unwrap().active_layer, active); - } +fn review_mask_action_context_matches_the_addressed_layer_for(mode: ColorMode) { + for depth in DEPTHS { + for kind in ["levels", "curves"] { + for filter in [false, true] { + let (app, layer) = addressed_mask_app(mode, depth, filter); + for selector in [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})] { + let mut app = fixture_for_addressed_replay(&app); + let command = format!("image.adjustments.{kind}"); + let target = if filter { "filterMask" } else { "mask" }; + let raw = json!({"layer":selector,"target":target}); + add_action(&mut app, "Other mask", command.clone(), raw, true); + let original = app.session.active().unwrap().doc.clone(); + let active = app.session.active().unwrap().active_layer; + let expected = + photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); + let mut h = canvas_harness(app); + play(&mut h, "Other mask"); + assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); + let id = top(&h); + arm(&mut h, "white"); + sample_at(&mut h, 4.0, 4.0); + let p = params(&h); + let want = photocraft_engine::adjust_params::adjustment_eyedropper( + kind, + &json!({}), + photocraft_engine::adjust_params::CurvesEyedropper::White, + [expected; 3], + ColorMode::Grayscale, + ) + .unwrap(); + let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); + assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); + let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); + confirm(&mut h, id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.layers, preview.layers); + assert_eq!(doc.layers[0], original.layers[0]); + assert_eq!(doc.channels, original.channels); + assert!( + photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99 + ); + assert_eq!(h.state().session.active().unwrap().active_layer, active); } } } } } +/// The addressed-mask Action matrix for one document colour mode. +#[test] +fn review_mask_action_context_matches_the_addressed_layer_rgb() { + review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Rgb); +} + +/// The addressed-mask Action matrix for one document colour mode. +#[test] +fn review_mask_action_context_matches_the_addressed_layer_cmyk() { + review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Cmyk); +} + +/// The addressed-mask Action matrix for one document colour mode. +#[test] +fn review_mask_action_context_matches_the_addressed_layer_lab() { + review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Lab); +} + /// Copy the source document for independent Action cases without carrying modal/UI history. fn fixture_for_addressed_replay(app: &PhotocraftApp) -> Box { let st = app.session.active().unwrap(); From 6294c6fe0067d8513499aee9e8c674d3b453a177 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 11:42:46 -0800 Subject: [PATCH 43/85] Format the partitioned mask assertion --- crates/ui-egui/tests/it/tone_targets.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index 2def86ec64..7444a28d93 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -1155,9 +1155,7 @@ fn review_mask_action_context_matches_the_addressed_layer_for(mode: ColorMode) { assert_eq!(doc.layers, preview.layers); assert_eq!(doc.layers[0], original.layers[0]); assert_eq!(doc.channels, original.channels); - assert!( - photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99 - ); + assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99); assert_eq!(h.state().session.active().unwrap().active_layer, active); } } From 36d05ab93301495cb4b12a49f0d62447304360dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 23:26:31 +0100 Subject: [PATCH 44/85] Toolbar: the rail's version no longer keys on the flyout side, which is fixed now Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/region_versions.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index d99adab582..3ace374c97 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -39,13 +39,12 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { } /// The version of the Toolbar's rail: the toolbar slots (the preferences revision), the remembered group tools, the -/// Edit Toolbar drawer, the side its flyouts open on, Quick Mask and the screen mode. The active tool and the colours -/// are in every version. +/// Edit Toolbar drawer, Quick Mask and the screen mode. Its flyouts always open on the same side. The active tool and +/// the colours are in every version. pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { let quick_mask = app.session.active().is_some_and(|st| st.doc.quick_mask.is_some()); - let opens_start = crate::panel_docking::toolbar_opens(app) == craft::behavior::overlay::Side::Start; let screen_mode = format!("{:?}", app.ui.view.screen_mode); - version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode)) + version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, quick_mask, screen_mode)) } /// What every region may show, joined with `extra`: the commands run (any of them may change anything), the active From ce996788a08554db78d113216718e463540b39e2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 23:44:32 +0100 Subject: [PATCH 45/85] Control channel: rects keys the unsaved-changes prompt as discard, the id dialogs lists it by Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/inspect.rs | 8 +++++++- crates/ui-egui/src/control/tests.rs | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 5c71c68dd7..6b542994c2 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -60,12 +60,18 @@ fn rects(app: &PhotocraftApp, ctx: &egui::Context) -> Value { } for dialog in app.framework.dialogs.open_dialogs() { if let Some(r) = rect(dialog.id) { - out.insert(dialog.id.value().to_string(), r); + out.insert(dialog_key(app, dialog.id), r); } } Value::Object(out) } +/// The key `rects` stores hosted dialog `id` under: the id `dialogs` lists it by, so the unsaved-changes prompt is +/// [`crate::discard_ui::CONTROL_ID`] there too (#15544), any other dialog its host id. +pub(super) fn dialog_key(app: &PhotocraftApp, id: egui::Id) -> String { + if crate::discard_ui::host_id(app) == Some(id) { crate::discard_ui::CONTROL_ID.to_string() } else { id.value().to_string() } +} + /// The notices posted since the last pass and the toast cards on screen in every window. fn notices(app: &PhotocraftApp, ctx: &egui::Context) -> Value { let mut all: Vec = app.ui.notices.iter().map(|notice| serde_json::to_value(notice).unwrap_or_default()).collect(); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 2b6c55355e..f265b281f4 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2310,6 +2310,11 @@ fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { assert_eq!(listed["fields"]["document"], name.as_str()); assert_eq!(listed["fields"]["remaining"], 1); assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + // Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs. + let host = crate::discard_ui::host_id(&app).expect("the prompt is open"); + assert_eq!(super::inspect::dialog_key(&app, host), "discard"); + let other = egui::Id::new("another dialog"); + assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string()); let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); assert_eq!(cancelled["ok"], true, "{cancelled}"); crate::canvas::testing::frame(&mut app); From 4aeb7e7c8da3141c67a8f13a40f7a4aaeeb033ad Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:14:05 +0100 Subject: [PATCH 46/85] 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 47/85] 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 48/85] 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 81e95dfc213c4d6244071027dfc04bc5b21113af Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 49/85] Integration: craft-libs pin to next 04ba41419b (craft-libs#2242, #15540) Moves every craft-libs pin from 18ffc07519 to the current next head, two commits newer: storytold/craft-libs#2242 (a dialog that opens on a text field selects its text). craft-svg keeps its own rev. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 222 +++++++++++++++++++-------------------- Cargo.toml | 68 ++++++------ crates/engine/Cargo.toml | 2 +- 3 files changed, 146 insertions(+), 146 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a52ea4f9a5..a73a50ae2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-automation", "craft-behavior", @@ -1404,7 +1404,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "crc32fast", "flate2", @@ -1425,7 +1425,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rustix 1.1.5", ] @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "base64 0.22.1", "craft-ai-agents", @@ -1459,7 +1459,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1475,7 +1475,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-docpath", @@ -1493,7 +1493,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "egui", ] @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "md-5", "rayon", @@ -1510,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-cms", @@ -1530,17 +1530,17 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "thiserror 2.0.21", ] [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1548,7 +1548,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rayon", ] @@ -1564,7 +1564,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1587,7 +1587,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", ] @@ -1595,7 +1595,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1614,21 +1614,21 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-eps", "craft-idml", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pcraft-bundle", "craft-raw", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "serde", "serde_json", @@ -1637,7 +1637,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "dirs", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1662,7 +1662,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "cap-primitives", "craft-atomic", @@ -1702,12 +1702,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "heic-rs", "rayon", @@ -1716,7 +1716,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "fixed_decimal", @@ -1757,9 +1757,9 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1767,13 +1767,13 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-heif", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "exr", "flate2", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1845,7 +1845,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a0455 [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1861,11 +1861,11 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-host", "craft-i18n", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "egui", "serde", "serde_json", @@ -1874,9 +1874,9 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1884,7 +1884,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -1916,11 +1916,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "quick-xml 0.41.0", "serde", ] @@ -1940,9 +1940,9 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1950,7 +1950,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-text", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "blake3", "craft-atomic", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "serde", @@ -1988,7 +1988,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "flate2", @@ -2003,7 +2003,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "async-channel", "async-io", @@ -2038,7 +2038,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-ui", @@ -2064,7 +2064,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "encoding_rs", "flate2", @@ -2075,7 +2075,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "dispatch2", "egui", @@ -2086,12 +2086,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-host", @@ -2135,9 +2135,9 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "flate2", "kurbo 0.13.1", "quick-xml 0.41.0", @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2208,7 +2208,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "ecolor", @@ -2221,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-theme", @@ -2232,7 +2232,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2265,7 +2265,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2274,7 +2274,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2303,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "craft-behavior", @@ -2331,7 +2331,7 @@ dependencies = [ "craft-platform", "craft-quit", "craft-settings", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-window", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2364,7 +2364,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2403,13 +2403,13 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", "craft-i18n", "craft-platform", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-ui-panels", @@ -2422,7 +2422,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2439,7 +2439,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-host", @@ -2468,7 +2468,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "winsafe", ] @@ -2476,7 +2476,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2506,7 +2506,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2515,7 +2515,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2535,7 +2535,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "hayro-interpret", @@ -4028,7 +4028,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4046,7 +4046,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4070,7 +4070,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "hayro-ccitt", @@ -5154,7 +5154,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6371,10 +6371,10 @@ dependencies = [ "core-graphics2", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "craft-update", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "eframe", "egui", "egui_kittest", @@ -6418,7 +6418,7 @@ name = "photocraft-algo" version = "0.23.1" dependencies = [ "craft", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "criterion", "photocraft-color", "photocraft-geom", @@ -6438,7 +6438,7 @@ dependencies = [ "cap-std", "clap", "craft", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "getrandom 0.3.4", "photocraft-color", @@ -6471,7 +6471,7 @@ dependencies = [ "clap_mangen", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "photocraft-automation", "photocraft-doc", @@ -6535,11 +6535,11 @@ dependencies = [ "craft-affinity", "craft-cms", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-format", "craft-print", "craft-psd", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "exr", "flate2", "photocraft-algo", @@ -6575,7 +6575,7 @@ name = "photocraft-format" version = "0.23.1" dependencies = [ "blake3", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-bundle", "craft-pcraft-format", "craft-zip", @@ -6635,16 +6635,16 @@ dependencies = [ "craft-crs", "craft-docpath", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pdf", "craft-pdn", "craft-psd", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-xcf", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "flate2", "kurbo 0.13.1", @@ -6735,7 +6735,7 @@ dependencies = [ name = "photocraft-raw" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-raw", "flate2", "image", @@ -6797,7 +6797,7 @@ dependencies = [ "craft", "craft-file-formats", "craft-i18n", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-print", "craft-psd", "eframe", @@ -6846,7 +6846,7 @@ dependencies = [ name = "photocraft-web" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "eframe", "egui", @@ -11216,14 +11216,14 @@ source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1c [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" diff --git a/Cargo.toml b/Cargo.toml index eac941937a..2192a12aff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,19 +12,19 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", default-features = false } +craft = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", default-features = false } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -43,34 +43,34 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Keep the shared embedded-image validation API until the framework revision includes it. craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7b8c1eccea0c695a495ab279c9523e6efcc9b8be", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -322,14 +322,14 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 65220283e8..b28eeb44cd 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,7 +16,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } From 248fd87a6a79510ee17b67e1347d2a1733d374ce Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 50/85] Integration: #15504 with #15496: the toolbar's measured height keys on the fixed flyout side #15504 removes panel_docking::toolbar_opens (flyouts always open the same way); #15496's measure cache still read it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/toolbar.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 7690f29d94..f80b73bf9a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -227,7 +227,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } let slots = app.toolbar_slots.get(&app.session.prefs); - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let env = craft::ui::runtime::env::Env::of(ui); let room = ui.available_size(); let key = MeasureKey { From 73b13c8424d2ac12695d207e47aec45cd3d524e3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 51/85] Integration: #15631: Id::unique in place of the deprecated Id::new in the discard-prompt test Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index f265b281f4..dc88c6efed 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2313,7 +2313,7 @@ fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { // Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs. let host = crate::discard_ui::host_id(&app).expect("the prompt is open"); assert_eq!(super::inspect::dialog_key(&app, host), "discard"); - let other = egui::Id::new("another dialog"); + let other = egui::Id::unique("another dialog"); assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string()); let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); assert_eq!(cancelled["ok"], true, "{cancelled}"); From 15321f219e99c74742747c5d9ab85b0f6f67b88f Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 52/85] Integration: #15561: the dialog-title test harness holds the boxed app, as build_eframe returns it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialog_title_ellipsis_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs index d958214bce..014c7dc1c5 100644 --- a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -10,7 +10,7 @@ use crate::PhotocraftApp; /// Opens one dialog. type Open = fn(&mut PhotocraftApp); -fn harness() -> Harness<'static, PhotocraftApp> { +fn harness() -> Harness<'static, Box> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); From 56e818059f43cbdaa66bba5cbe8c18bbd1c5e9eb Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 53/85] Integration: #15585: the Free Transform preview test harness holds the boxed app Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/free_transform_preview_canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index 99681b74e6..0b7ff0eb5b 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -14,7 +14,7 @@ use photocraft_ui_egui::PhotocraftApp; use photocraft_ui_egui::control::{ControlRequest, handle}; use serde_json::{Value, json}; -type Harness = egui_kittest::Harness<'static, PhotocraftApp>; +type Harness = egui_kittest::Harness<'static, Box>; /// The red square on the layer, in document pixels: x 100..200, y 100..200 of a 400 × 300 document. fn square() -> Rect { From eb55919530b2ff523be90c5d9295207b7ccbe552 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:44 +0100 Subject: [PATCH 54/85] Integration: #15608: craft counts as a UI dependency only with its UI features (#15467) Listing craft by name in UI_CRATES flagged photocraft-algo, -io, -text and -engine, which use the facade's non-UI parts (imaging, fonts, keymap, settings), so cargo xtask layers failed on the workspace. The facade brings the craft UI framework (craft-ui, egui) only through `ui` and the features that turn it on (`ui-*`, `screen-testing`), so the guard now reads each dependency's declared features from cargo metadata and flags craft below L6 only with one of those. Tests: craft with ui, ui-app or screen-testing below L6 fails (normal and dev), the features the workspace uses today pass, L6 may use them all, and metadata parsing keeps the features. Both fail with the feature rule empty. Co-Authored-By: Claude Opus 5.5 --- xtask/src/layers.rs | 67 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 9 deletions(-) diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index cc8e282730..c7ed3f95d9 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -98,7 +98,12 @@ fn standalone_exception(from: &str, to: &str) -> bool { /// External crates that constitute a UI toolkit / windowing dependency. /// Entries ending in `*` are prefixes. -pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy*"]; +pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy*"]; + +/// Facade crates that are a UI toolkit dependency only with some of their features (#15467): `craft` carries the +/// whole craft UI framework behind `ui` (and the features that turn it on), while lower layers use its non-UI parts +/// (imaging, fonts, keymap, settings). Feature names ending in `*` are prefixes. +pub const UI_FEATURES: &[(&str, &[&str])] = &[("craft", &["ui", "ui-*", "screen-testing"])]; /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -112,11 +117,17 @@ pub fn classify(pkg: &str) -> Option { TABLE.iter().find(|(n, _)| *n == s).map(|(_, c)| *c) } -fn is_ui_crate(name: &str) -> bool { - UI_CRATES.iter().any(|p| match p.strip_suffix('*') { +fn matches_pattern(name: &str, pattern: &str) -> bool { + match pattern.strip_suffix('*') { Some(prefix) => name.starts_with(prefix), - None => name == *p, - }) + None => name == pattern, + } +} + +/// Whether `dep` brings a UI toolkit: a crate in [`UI_CRATES`], or a [`UI_FEATURES`] facade with one of its UI features. +fn is_ui_dep(dep: &Dep) -> bool { + UI_CRATES.iter().any(|p| matches_pattern(&dep.name, p)) + || UI_FEATURES.iter().any(|(krate, features)| dep.name == *krate && dep.features.iter().any(|f| features.iter().any(|p| matches_pattern(f, p)))) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -132,6 +143,8 @@ pub struct Dep { pub kind: DepKind, /// `true` if the dependency is a workspace member. pub workspace: bool, + /// The features the dependency is declared with (including the ones inherited from the workspace). + pub features: Vec, } #[derive(Debug, Clone)] @@ -214,7 +227,7 @@ pub fn check(crates: &[Crate]) -> Vec { } } } - } else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) { + } else if layer < UI_MIN_LAYER && is_ui_dep(d) { out.push(Violation::UiBelowL6 { krate: c.name.clone(), dep: d.name.clone(), layer }); } } @@ -240,7 +253,8 @@ pub fn from_metadata(meta: &Value) -> Result, String> { _ => DepKind::Normal, }; let workspace = members.contains(&dname.as_str()) || d["path"].is_string(); - deps.push(Dep { name: dname, kind, workspace }); + let features = d["features"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_owned)).collect(); + deps.push(Dep { name: dname, kind, workspace, features }); } out.push(Crate { name, deps }); } @@ -263,7 +277,7 @@ mod tests { use super::*; fn c(name: &str, deps: &[(&str, DepKind, bool)]) -> Crate { - Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w }).collect() } + Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w, features: Vec::new() }).collect() } } use DepKind::*; @@ -340,7 +354,7 @@ mod tests { #[test] fn ui_crates_below_l6_flagged() { - for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy_ecs", "bevy"] { + for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy_ecs", "bevy"] { let v = check(&[c("photocraft-engine", &[(dep, Normal, false)])]); assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 5, .. }]), "{dep}"); } @@ -349,6 +363,41 @@ mod tests { assert!(check(&[c("photocraft-platform", &[("winit", Normal, false)])]).is_empty()); } + fn with_features(name: &str, dep: &str, kind: DepKind, features: &[&str]) -> Crate { + let features = features.iter().map(|f| (*f).to_owned()).collect(); + Crate { name: name.into(), deps: vec![Dep { name: dep.into(), kind, workspace: false, features }] } + } + + #[test] + fn craft_facade_with_ui_features_flagged_below_l6() { + // #15467: the facade's UI features bring the whole craft UI framework. + for features in [&["ui"][..], &["imaging", "ui-app"], &["screen-testing"]] { + let v = check(&[with_features("photocraft-engine", "craft", Normal, features)]); + assert!(matches!(&v[..], [Violation::UiBelowL6 { layer: 5, dep, .. }] if dep == "craft"), "{features:?}"); + let v = check(&[with_features("photocraft-text", "craft", Dev, features)]); + assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 2, .. }]), "dev {features:?}"); + } + // Its non-UI parts stay usable below L6 (what text, io and engine use today), and L6 may use it all. + for features in [&[][..], &["imaging"], &["font-catalog", "font-manager"], &["automation", "color-ui", "keymap", "platform", "settings"]] { + assert!(check(&[with_features("photocraft-engine", "craft", Normal, features)]).is_empty(), "{features:?}"); + } + assert!(check(&[with_features("photocraft-ui-egui", "craft", Normal, &["ui", "screen-testing"])]).is_empty()); + // Only the facade is judged by its features. + assert!(check(&[with_features("photocraft-engine", "craft-imaging", Normal, &["ui"])]).is_empty()); + } + + #[test] + fn metadata_reads_dependency_features() { + let meta: Value = serde_json::from_str( + r#"{"packages":[{"name":"photocraft-engine","dependencies":[ + {"name":"craft","kind":null,"features":["keymap","ui"]}]}]}"#, + ) + .unwrap(); + let g = from_metadata(&meta).unwrap(); + assert_eq!(g[0].deps[0].features, ["keymap", "ui"]); + assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }])); + } + #[test] fn unregistered_crate_is_error() { let v = check(&[c("photocraft-mystery", &[])]); From 9be5f352358dc72558189d4a01099eeae96f1a55 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:44 +0100 Subject: [PATCH 55/85] Integration: regenerate docs/scorecard.md Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 3f01a2ece7..e3fb1e1dbb 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -12,7 +12,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 9 of 202 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 6 | 4 | 2 | 664 of 664 menu items live (100.0%) | -| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 25 of 25 crates; panic_hunt present | +| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 24 of 25 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -280,7 +280,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T ## Reliability -Never-crash attribute on 25 of 25 crate roots. +Never-crash attribute on 24 of 25 crate roots; missing: `crates/ipp/src/lib.rs`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| From 90d9e35affabbf4aeacb1596590b4996820e683d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 02:37:11 +0100 Subject: [PATCH 56/85] Integration: #15480: the Image Size test reads Pixels as the unit selects' value The Width and Height unit selects are labelled "Width unit" and "Height unit" and show Pixels as their value, so looking for a node labelled "Pixels" found none (it failed on Linux and Windows CI too). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/sizing/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index 2f93d1890d..f3cc2fedf7 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -200,8 +200,10 @@ fn image_size_draws_width_and_height_with_values_and_unit() { let shown = value_of(&h, label); assert!(shown.iter().any(|v| v == want), "{label} shows {want}: {shown:?}"); } - let pixels = h.query_all_by_label("Pixels").count(); - assert!(pixels >= 2, "the Width and Height unit selects show Pixels ({pixels} nodes)"); + for label in ["Width unit", "Height unit"] { + let shown = value_of(&h, label); + assert!(shown.iter().any(|v| v == "Pixels"), "the {label} select shows Pixels: {shown:?}"); + } let width = h.query_all_by_label("Width").find(|n| n.accesskit_node().value().is_some()).expect("the Width field"); width.click(); From 13418925ca84db4bb03f4c05e0641352a0414b9d Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 04:00:48 +0100 Subject: [PATCH 57/85] Test: the merge's type-history fixtures build the app like main's test frame The wave merge of main (a1ae1f64b) left one compile error on the branch: unchanged_edit_history_tests.rs returned a PhotocraftApp from its factory while main's PhotocraftApp::new now boxes the app (E0308). Follow main's test-frame convention: the factory returns Box, which every helper call site already derefs. --- .../ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs index 6a67226101..0128acfc0c 100644 --- a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -14,7 +14,7 @@ use crate::PhotocraftApp; use crate::state::Tool; /// A 400x200 document with one committed type layer: that layer active and the Type tool picked. -fn app() -> (PhotocraftApp, LayerId) { +fn app() -> (Box, LayerId) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); app.sync_views(); From 6b207c5b55e9af7426e26c8e9017b46ce4bed00a Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:41:16 +0100 Subject: [PATCH 58/85] Share built-in brush presets across sessions --- crates/engine/examples/abr_memory.rs | 2 +- crates/engine/src/cmd/brush_cmds.rs | 11 ++++++---- crates/engine/src/cmd/brush_key_cmds.rs | 4 ++-- crates/engine/src/cmd/brush_preset_cmds.rs | 20 +++++++++---------- .../engine/src/cmd/brush_preset_cmds/tests.rs | 12 +++++------ crates/engine/src/cmd/edit_menu_cmds.rs | 4 ++-- .../engine/src/cmd/edit_menu_cmds/presets.rs | 4 ++-- crates/engine/src/cmd/preset_import_cmds.rs | 8 ++++---- crates/engine/src/doc_state.rs | 4 ++-- crates/engine/src/preset_store.rs | 6 +++--- crates/engine/src/preset_store/tests.rs | 16 +++++++-------- crates/engine/src/tests.rs | 13 ++++++++++++ crates/paint/src/presets.rs | 6 ++++++ .../src/dialogs/preset_group_prompt/tests.rs | 4 ++-- .../ui-egui/src/panels/brush_panel/tests.rs | 8 ++++---- crates/ui-egui/src/preset_files_ui.rs | 2 +- 16 files changed, 73 insertions(+), 51 deletions(-) diff --git a/crates/engine/examples/abr_memory.rs b/crates/engine/examples/abr_memory.rs index 9cec8ec1de..71c1460664 100644 --- a/crates/engine/examples/abr_memory.rs +++ b/crates/engine/examples/abr_memory.rs @@ -52,7 +52,7 @@ fn library_tip_bytes(s: &Session) -> (usize, u64, u64) { previews += g.data.len() as u64 * 2; } }; - for p in &s.tools.presets { + for p in s.tools.presets.iter() { let b = &p.brush; for t in [&b.tip, &b.dual_brush.tip] { match t { diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index f17b5b28b4..8b25c1d3c6 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -980,9 +980,9 @@ fn name_param(p: &Value, cmd: &str) -> Result { /// Replace the preset of that name, or append it at the end of the list. fn upsert(s: &mut Session, preset: BrushPreset) { - match s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { Some(x) => *x = preset, - None => s.tools.presets.push(preset), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(preset), } s.brush_presets_changed(); } @@ -1010,7 +1010,7 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.delete"; let name = name_param(p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !x.name.eq_ignore_ascii_case(&name)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !x.name.eq_ignore_ascii_case(&name)); if s.tools.presets.len() == before { return Err(bad(cmd, format!("no brush preset named `{name}`"))); } @@ -1043,7 +1043,10 @@ fn presets_update(s: &mut Session, p: &Value) -> Result { Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?, None => s.tools.brush.clone(), }; - let pr = s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets) + .iter_mut() + .find(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; pr.brush = brush; pr.builtin = false; let (name, group) = (pr.name.clone(), pr.group.clone()); diff --git a/crates/engine/src/cmd/brush_key_cmds.rs b/crates/engine/src/cmd/brush_key_cmds.rs index 0cb6f93ff0..a76f15b868 100644 --- a/crates/engine/src/cmd/brush_key_cmds.rs +++ b/crates/engine/src/cmd/brush_key_cmds.rs @@ -263,7 +263,7 @@ mod tests { #[test] fn previous_and_next_brush_walk_the_presets_and_wrap() { let mut s = Session::new(); - s.tools.presets = vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]; + s.tools.presets = std::sync::Arc::new(vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]); s.tools.current_preset = None; let picked = |s: &Session| (s.tools.current_preset.clone().unwrap_or_default(), s.tools.brush.size); s.execute("tools.nextBrush", Value::Null).unwrap(); @@ -284,7 +284,7 @@ mod tests { [Some(","), Some("."), Some("Shift+,"), Some("Shift+.")] ); // No presets: an error, and the brush and the current preset stay as they were. - s.tools.presets.clear(); + std::sync::Arc::make_mut(&mut s.tools.presets).clear(); let (brush, current) = (s.tools.brush.clone(), s.tools.current_preset.clone()); for id in ["tools.previousBrush", "tools.nextBrush", "tools.firstBrush", "tools.lastBrush"] { assert!(s.execute(id, Value::Null).is_err(), "{id}"); diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 6cfe6365c7..34cd2fbb4a 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -153,7 +153,7 @@ fn move_preset(s: &mut Session, p: &Value) -> Result { }; let folder = folder_param(p, cmd)?; let group = group_param(p, "group", cmd)?; - let lib = &mut s.tools.presets; + let lib = std::sync::Arc::make_mut(&mut s.tools.presets); let (Some(moving), before_pr) = (lib.get(i), before.and_then(|b| lib.get(b))) else { return Err(bad(cmd, "no such preset")); }; @@ -233,7 +233,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); // Where the block sits among the other presets (its place when nothing else is in the parent). let start = lib.iter().position(|x| in_folder(x, &g, &f)).unwrap_or(0); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); @@ -252,7 +252,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = subfolder_order(&s.tools.presets, &g, parent).iter().position(|x| x == leaf).unwrap_or(0); Ok(json!({ "group": g, "folder": f, "index": at })) @@ -332,7 +332,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, if deepest > MAX_FOLDER_DEPTH { return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep"))); } - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); let (mut block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); for x in &mut block { let tail = rest_of(x); @@ -352,7 +352,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default(); let at = match &dest { @@ -382,7 +382,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| x.group == g); let order = group_order(&rest); let first = |name: &str, rest: &[BrushPreset]| rest.iter().position(|x| x.group == name).unwrap_or(rest.len()); @@ -394,7 +394,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = group_order(&s.tools.presets).iter().position(|x| *x == g).unwrap_or(0); Ok(json!({ "group": g, "index": at })) @@ -410,7 +410,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a folder named `{new}` already exists there"))); } let depth = parent.len(); - for x in s.tools.presets.iter_mut().filter(|x| in_folder(x, &g, &f)) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| in_folder(x, &g, &f)) { if let Some(n) = x.folder.get_mut(depth) { n.clone_from(&new); } @@ -426,7 +426,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a group named `{new}` already exists"))); } if new != g { - for x in s.tools.presets.iter_mut().filter(|x| x.group == g) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| x.group == g) { x.group = new.clone(); x.builtin = false; } @@ -439,7 +439,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.deleteGroup"; let (g, f) = target_folder(s, p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !in_folder(x, &g, &f)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !in_folder(x, &g, &f)); if s.tools.current_preset.as_ref().is_some_and(|c| !s.tools.presets.iter().any(|x| x.name.eq_ignore_ascii_case(c))) { s.tools.current_preset = None; s.tools.brush_changed(); diff --git a/crates/engine/src/cmd/brush_preset_cmds/tests.rs b/crates/engine/src/cmd/brush_preset_cmds/tests.rs index eeed131bc7..5bb2b6698d 100644 --- a/crates/engine/src/cmd/brush_preset_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_preset_cmds/tests.rs @@ -7,7 +7,7 @@ fn names(s: &Session, g: &str) -> Vec { fn with_groups() -> Session { let mut s = Session::new(); for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -119,7 +119,7 @@ fn with_folders() -> Session { let mut s = Session::new(); for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -226,7 +226,7 @@ fn with_two_groups() -> Session { let mut s = with_folders(); for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -266,7 +266,7 @@ fn bad_moves_into_folders_fail_without_changes() { let mut s = with_two_groups(); // A chain 31 deep under Set/Deep. let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, @@ -274,7 +274,7 @@ fn bad_moves_into_folders_fail_without_changes() { folder: deep.clone(), captures: Default::default(), }); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, @@ -314,7 +314,7 @@ fn bad_moves_into_folders_fail_without_changes() { s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); assert_eq!(folder_of(&s, "F1"), ["Fine"]); // An ungrouped preset's group can't move. - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index fab273a9a6..b9f32b9df0 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -314,9 +314,9 @@ fn export_import(s: &mut Session, p: &Value) -> Result { // absurd tree). b.folder.retain(|f| !f.trim().is_empty()); b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH); - match s.tools.presets.iter_mut().find(|x| x.name == b.name) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name == b.name) { Some(x) => *x = b, - None => s.tools.presets.push(b), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(b), } nb += 1; } diff --git a/crates/engine/src/cmd/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs index abc3a61172..9a73f086db 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/presets.rs @@ -114,7 +114,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { } "delete" => match kind.as_str() { "brushes" => { - let gone = s.tools.presets.remove(i); + let gone = std::sync::Arc::make_mut(&mut s.tools.presets).remove(i); crate::brush_cmds::forget_deleted_preset(s, &gone.name); } "patterns" => drop(s.patterns.items.remove(i)), @@ -123,7 +123,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { "move" => { let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; match kind.as_str() { - "brushes" => crate::move_item(&mut s.tools.presets, i, to), + "brushes" => crate::move_item(std::sync::Arc::make_mut(&mut s.tools.presets), i, to), "patterns" => crate::move_item(&mut s.patterns.items, i, to), _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), }; diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 8b866c3f89..62c786e848 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -155,7 +155,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io // in Photoshop, unless `replace` asks to drop that group's own presets first: the group name // is only the file name, and the library is outside document history (#10640). let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) { - s.tools.presets.retain(|x| x.builtin || x.group != group); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| x.builtin || x.group != group); group } else { // One pass over the library, not one per numbered candidate. @@ -168,7 +168,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io preset.group.clone_from(&group); preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); - s.tools.presets.push(preset); + std::sync::Arc::make_mut(&mut s.tools.presets).push(preset); } s.brush_presets_changed(); if p.get("select").and_then(Value::as_bool).unwrap_or(false) @@ -262,7 +262,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let (v, w, h) = image_paint(&doc, cmd)?; let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); - s.tools.presets.push(photocraft_paint::BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(photocraft_paint::BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, @@ -541,7 +541,7 @@ mod tests { // The user's own brush moved into the group. let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone(); own.name = "My Ink".into(); - s.tools.presets.push(own); + std::sync::Arc::make_mut(&mut s.tools.presets).push(own); let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap(); assert_eq!(r["group"], "Kit (2)"); let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count(); diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 17ac800c97..662d39ecb1 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -183,7 +183,7 @@ pub struct ToolState { pub background: [f32; 4], pub brush: photocraft_paint::BrushSettings, /// Brush presets (built-ins plus user presets; see `brush.presets.*`). - pub presets: Vec, + pub presets: Arc>, /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store /// syncs when it moves. pub presets_rev: u64, @@ -284,7 +284,7 @@ impl Default for ToolState { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..Default::default() }, - presets: photocraft_paint::presets::builtin(), + presets: photocraft_paint::presets::builtin_shared(), presets_rev: 0, mixer: Default::default(), brush_gesture: None, diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index c654de811f..b44a2abdae 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1103,7 +1103,7 @@ impl PresetStore { fn builtin_names() -> &'static [String] { static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); - NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect()) + NAMES.get_or_init(|| photocraft_paint::presets::builtin_shared().iter().map(|p| p.name.clone()).collect()) } impl Session { @@ -1141,7 +1141,7 @@ impl Session { } } } - let lib = &mut self.tools.presets; + let lib = std::sync::Arc::make_mut(&mut self.tools.presets); lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); for p in presets { match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { @@ -1204,7 +1204,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync(&mut self.tools.presets); + st.sync(std::sync::Arc::make_mut(&mut self.tools.presets)); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 368d74e155..3e601f2601 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -119,7 +119,7 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() { let b = sampled("Sixteen", "Inks", tip16(50, 70, 2)); let mut c = sampled("Shared tip", "Other", tip8(64, 48, 1)); c.brush.size = 9.0; - s.tools.presets.extend([a, b, c]); + std::sync::Arc::make_mut(&mut s.tools.presets).extend([a, b, c]); s.brush_presets_changed(); s.sync_preset_store(); let files = dir.files(); @@ -243,7 +243,7 @@ fn startup_with_many_groups_loads_them_all() { let (mut s, _) = session(&dir); for g in 0..25 { for i in 0..4 { - s.tools.presets.push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); } } s.brush_presets_changed(); @@ -267,7 +267,7 @@ fn reordering_presets_and_groups_persists() { let (mut s, _) = session(&dir); for (n, g) in [("Ink 1", "Inks"), ("Ink 2", "Inks"), ("Wash", "Washes")] { s.execute("brush.presets.save", json!({"name": n})).unwrap(); - s.tools.presets.iter_mut().find(|p| p.name == n).unwrap().group = g.into(); + std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|p| p.name == n).unwrap().group = g.into(); } s.brush_presets_changed(); s.sync_preset_store(); @@ -299,8 +299,8 @@ fn reordering_presets_and_groups_persists() { fn corrupt_and_oversized_files_are_skipped_with_a_warning() { let dir = TempDir::new("corrupt"); let (mut s, _) = session(&dir); - s.tools.presets.push(sampled("Good", "Fine", tip8(8, 8, 1))); - s.tools.presets.push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Good", "Fine", tip8(8, 8, 1))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); s.brush_presets_changed(); s.sync_preset_store(); let be = DirBackend::new(&dir.0); @@ -370,7 +370,7 @@ fn bench_load_500_sampled_presets() { // A mix of 8-bit (most .abr tips) and 16-bit tips, 64..319 px. let side = 64 + (i * 37) % 256; let t = if i % 4 == 0 { tip16(side, side, i) } else { tip8(side, side, i) }; - s.tools.presets.push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); } s.brush_presets_changed(); let t0 = std::time::Instant::now(); @@ -411,7 +411,7 @@ fn library(n: u32, side: u32) -> (Session, MemBackend) { let mut s = Session::new(); s.attach_preset_store(open(Box::new(mem.clone()))); for i in 0..n { - s.tools.presets.push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); } s.brush_presets_changed(); s.sync_preset_store(); @@ -519,7 +519,7 @@ fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() { let k0 = key(&t, "Big 0"); mem.remove(&tip_file(&k0)).unwrap(); t.execute("tools.setBrush", json!({"preset": "Hard Round"})).unwrap(); - let broken = t.tools.presets.iter_mut().find(|p| p.name == "Big 0").unwrap(); + let broken = std::sync::Arc::make_mut(&mut t.tools.presets).iter_mut().find(|p| p.name == "Big 0").unwrap(); broken.captures.color = true; broken.brush.color = [1.0, 0.0, 0.0, 1.0]; t.tools.foreground = [0.0, 0.0, 1.0, 1.0]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b15add018c..2e6b02aa32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2063,3 +2063,16 @@ fn the_active_layer_marker_advances_for_a_new_document_and_not_for_a_same_layer_ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert!(s.active_layer_changes() > before, "a new active document advances the marker"); } + +#[test] +fn sessions_share_builtin_brushes_until_edited() { + let mut first = Session::new(); + let second = Session::new(); + assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); + let count = second.tools.presets.len(); + first.execute("brush.presets.save", serde_json::json!({"name": "Session-only test brush"})).unwrap(); + assert_eq!(second.tools.presets.len(), count); + assert!(second.tools.presets.iter().all(|preset| preset.name != "Session-only test brush")); + assert!(first.tools.presets.iter().any(|preset| preset.name == "Session-only test brush")); + assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); +} diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index e40902a78f..0107dfdcfe 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -448,6 +448,12 @@ pub fn builtin() -> Vec { v } +/// The built-in set shared by new sessions until one is edited. +pub fn builtin_shared() -> std::sync::Arc> { + static BUILTIN: std::sync::OnceLock>> = std::sync::OnceLock::new(); + BUILTIN.get_or_init(|| std::sync::Arc::new(builtin())).clone() +} + /// Find a preset by name (case-insensitive). pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPreset> { presets.iter().find(|p| p.name.eq_ignore_ascii_case(name)) diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs index 96de48ce66..160238e8a4 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs @@ -38,7 +38,7 @@ fn group(app: &PhotocraftApp, kind: Kind, name: &str) -> Value { } fn library(app: &PhotocraftApp) -> Value { - json!({"brushes": app.session.tools.presets, "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) + json!({"brushes": app.session.tools.presets.as_ref(), "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) } impl Fixture { @@ -74,7 +74,7 @@ impl Fixture { match kind { Kind::Brushes => { assert_eq!(original.as_array().unwrap().len(), 2); - app.session.tools.presets.iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; + std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; } Kind::Gradients => { assert_eq!(original[0]["items"].as_array().unwrap().len(), 2); diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 6d52d98708..57264f5603 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -487,14 +487,14 @@ fn preset_rows_nest_presets_in_panel_order() { let max = photocraft_engine::brush_preset_cmds::MAX_FOLDER_DEPTH; let deep: Vec<&str> = vec!["d"; max + 5]; let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("Top", "Kit", &[]), kit("Pen", "Kit", &["Inks"]), kit("Chalk", "Kit", &["Dry"]), kit("Nib", "Kit", &["Inks", "Fine"]), kit("Quill", "Kit", &["Inks"]), kit("Deep", "Kit", &deep), - ]; + ]); let out: Vec = rows_of(app, PresetView::List) .iter() .map(|r| match r.count { @@ -509,7 +509,7 @@ fn preset_rows_nest_presets_in_panel_order() { fn fixture() -> Box { let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("A1", "Alpha", &[]), kit("A2", "Alpha", &[]), kit("A3", "Alpha", &[]), @@ -518,7 +518,7 @@ fn fixture() -> Box { kit("Kit Pen", "Kit", &["Inks"]), kit("Kit Nib", "Kit", &["Inks", "Fine"]), kit("Kit Chalk", "Kit", &["Dry"]), - ]; + ]); app } diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 2b84f9de6d..4d7b9cae8b 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -211,7 +211,7 @@ mod tests { assert!(prompt(&app).is_none(), "a new group imports without asking"); assert!(app.ui.status.ends_with("brushes from Kit"), "{}", app.ui.status); // The user edits one of its brushes. - let edited = app.session.tools.presets.iter_mut().find(|p| p.group == "Kit").unwrap(); + let edited = std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == "Kit").unwrap(); edited.brush.size = 77.0; let edited = edited.name.clone(); From 0ef7ab1450e941383ee93e417746f2d8fac65801 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 08:52:41 +0100 Subject: [PATCH 59/85] Fix: a Layers panel range that excludes the edited type layer is a switch (#12050) The panel sends layer.select with a "layers" list when a Shift-click selects several rows, so run_actions read no "layer" key and commit_before_selecting got no target: it counted the click as an in-place commit, and an unchanged session ended by selecting other rows added an "Edit Type" state, while the same gesture on one other row added nothing. It now passes every id the payload names, and a selection that does not include the edited layer counts as the layer switch (#6483) it is. A range that still names the edited layer keeps the row click a commit (#5584), which the new neighbour test pins from the other side. Red first: the new multi-layer test failed on this head before the fix, the history list left with an extra "Edit Type" entry. --- crates/ui-egui/src/panels/layers_events.rs | 14 +++++- crates/ui-egui/src/tools/type_tool/editing.rs | 11 +++-- .../type_tool/unchanged_edit_history_tests.rs | 47 ++++++++++++++++++- 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index 8762e7da4d..bfcbdffb6d 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -594,13 +594,23 @@ pub(crate) fn selection_actions(change: SelectionChange, selected: &[La } } +/// The layer ids a `layer.select` payload names: the single `layer`, or every id of the `layers` +/// list a multi-row selection carries. +fn select_param_ids(p: &Value) -> Vec { + match p.get("layer").and_then(Value::as_u64) { + Some(id) => vec![id], + None => p.get("layers").and_then(Value::as_array).map(|ids| ids.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(), + } +} + /// Runs the actions in order: a type session commits before a select, the mask targets switch, /// `Value::Null` params (and the fill layers that open a dialog) run as the menu item does. pub(crate) fn run_actions(app: &mut PhotocraftApp, ctx: &egui::Context, actions: Vec) { for (id, p) in actions { - // A row click commits even when it selects the layer already being edited (#5584). + // A row click commits even when it selects the layer already being edited (#5584); a + // multi-row selection that leaves the edited layer out is a layer switch (#6483). if id == "layer.select" && app.ui.text_edit.is_some() { - crate::type_tool::commit_before_selecting(app, p.get("layer").and_then(serde_json::Value::as_u64)); + crate::type_tool::commit_before_selecting(app, &select_param_ids(&p)); } if id == "ui.maskTarget" { app.end_filter_mask_view(); diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index 6813903a1b..8f53ed8d8c 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -234,11 +234,12 @@ pub fn commit_with(app: &mut PhotocraftApp, _mods: egui::Modifiers) { commit_ending(app, true); } -/// The commit a Layers panel row click makes before it selects `layer` (#5584): a click on another -/// layer's row is a layer switch (#6483), so an unchanged session records nothing (#12050); a click -/// on the edited layer's own row ends the edit like any other commit. -pub(crate) fn commit_before_selecting(app: &mut PhotocraftApp, layer: Option) { - let switches = app.ui.text_edit.as_ref().is_some_and(|ed| layer.is_some_and(|l| l != ed.layer)); +/// The commit a Layers panel row click makes before it selects `selected` (#5584): a click on +/// another layer's row is a layer switch (#6483), so an unchanged session records nothing (#12050); +/// a click on the edited layer's own row ends the edit like any other commit. A multi-row selection +/// names all its rows, so it is a switch too unless the edited layer is one of them. +pub(crate) fn commit_before_selecting(app: &mut PhotocraftApp, selected: &[u64]) { + let switches = app.ui.text_edit.as_ref().is_some_and(|ed| !selected.is_empty() && !selected.contains(&ed.layer)); commit_ending(app, !switches); } diff --git a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs index 0128acfc0c..fe61d5b98a 100644 --- a/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/unchanged_edit_history_tests.rs @@ -7,6 +7,8 @@ //! The Cancel button discards the session and adds no state. An edit that did change something //! still gives one state, not two. +use craft::behavior::SelectionChange; +use craft::layers::ui::panel::{LayerSelect, LayersEvent}; use photocraft_doc::{LayerContent, LayerId}; use serde_json::json; @@ -57,6 +59,14 @@ fn click_into(app: &mut PhotocraftApp, id: LayerId) { assert!(!ed.created, "it is an existing layer"); } +/// The Layers panel selecting several rows at once (its Shift-click range): one pass of panel +/// events, which sends `layer.select` with a `layers` list rather than a single `layer`. +fn select_rows(app: &mut PhotocraftApp, ids: &[LayerId]) { + let ctx = app.ctx().clone(); + let event = LayersEvent::Select(LayerSelect::new(SelectionChange::Set(ids.to_vec()), None)); + crate::panels::layers_events::apply_layers_events(app, &ctx, vec![event]); +} + /// What ending the session with `how` left behind: exactly one state, named like any other edit /// of an existing type layer, on an unchanged layer. fn ended(app: &PhotocraftApp, id: LayerId, before: &[String], how: &str) { @@ -238,7 +248,7 @@ fn an_unchanged_edit_ended_by_a_layers_panel_click_on_another_layer_records_noth click_into(&mut app, id); let before = history(&app); // The panel's order: commit first, then select. - crate::type_tool::commit_before_selecting(&mut app, Some(other.0)); + crate::type_tool::commit_before_selecting(&mut app, &[other.0]); app.run("layer.select", json!({"layer": other.0})).unwrap(); assert!(app.ui.text_edit.is_none(), "the row click ends the session"); assert_eq!(history(&app), before, "a layer switch adds no state"); @@ -252,10 +262,43 @@ fn a_layers_panel_click_on_the_edited_layers_row_records_one_state() { let (mut app, id) = app(); click_into(&mut app, id); let before = history(&app); - crate::type_tool::commit_before_selecting(&mut app, Some(id.0)); + crate::type_tool::commit_before_selecting(&mut app, &[id.0]); ended(&app, id, &before, "click on the edited layer's row"); } +/// A Shift-click range selects several rows at once, so the panel sends `layer.select` with a +/// `layers` list instead of a single `layer`. While layer A is being edited, a range of other +/// rows excludes A and leaves A inactive, so it is a layer switch (#6483) and an unchanged +/// session records nothing - as the single-row click on another layer's row does. +#[test] +fn an_unchanged_edit_ended_by_a_multi_layer_selection_that_excludes_the_edited_layer_records_nothing() { + let (mut app, id) = app(); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + let c = LayerId(app.run("layer.new.layer", json!({"name": "C"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + select_rows(&mut app, &[b, c]); + assert!(app.ui.text_edit.is_none(), "the multi-layer selection ends the session"); + assert_eq!(app.session.active().unwrap().active_layer, Some(c), "and the last row of the range becomes active"); + assert_eq!(history(&app), before, "a selection that excludes the edited layer is a switch: no state"); + assert_eq!(text_of(&app, id), "Hello"); +} + +/// The neighbour of that case: a range that names the edited layer among its rows keeps the row +/// click a commit (#5584), so it records the state. Guard test, it pins the boundary. +#[test] +fn a_multi_layer_selection_that_includes_the_edited_layer_records_one_state() { + let (mut app, id) = app(); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + click_into(&mut app, id); + let before = history(&app); + select_rows(&mut app, &[b, id]); + assert_eq!(app.session.active().unwrap().active_layer, Some(id), "the edited layer stays active in the range"); + ended(&app, id, &before, "multi-layer selection that includes the edited layer"); +} + /// Another document becoming active ends the edit in its own document (#6483), which is made /// active again for the commit: that is a document switch, and an unchanged session records /// nothing there. From bd3fce78c58ed68d2d90b7cce987eda588f57464 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 08:53:18 +0100 Subject: [PATCH 60/85] Docs: what keeps a document switch from recording an unchanged edit (#12050) The comment on worked_on_layer still said a document switch "still records". commit_ending identifies that switch before worked_on_layer is read: it makes the edit's own document active, calls commit_here with by_user false, and restores the document that was active before, so ends_an_edit is false and nothing records. That is the behaviour the family's another-document test pins. Comment only, no behaviour change. --- crates/ui-egui/src/tools/type_tool/editing.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index 8f53ed8d8c..936d9fc497 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -387,9 +387,10 @@ fn user_ends_the_edit(app: &PhotocraftApp) -> bool { /// Is the session's layer still the one worked on? Selecting another layer or document commits the /// session (#6483); #12050 does not measure that, so it records nothing. A background document's -/// edit is checked in its own document, where `commit_with` has just made it active - which is why -/// a document switch cannot be told from an in-place commit here, and still records (#12050 review -/// c4502824764). +/// edit is checked in its own document, where [`commit_ending`] has just made it active, so a +/// document switch cannot be told from an in-place commit here: [`commit_ending`] already found the +/// switch and passes `by_user` false, which is what keeps the unchanged edit from recording there +/// (#12050 review c4502824764). fn worked_on_layer(app: &PhotocraftApp, ed: &TextEdit) -> bool { app.session.active().is_some_and(|st| st.active_layer == Some(LayerId(ed.layer))) } From 16935087ab25952cca3a74eb18ac4a713ad3aa5e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:30:24 +0100 Subject: [PATCH 61/85] Fix shared preset mutation and sync --- crates/engine/src/cmd/brush_preset_cmds.rs | 2 +- crates/engine/src/preset_store.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 34cd2fbb4a..8965d1d658 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -120,7 +120,7 @@ pub(crate) fn rename_at(s: &mut Session, i: usize, new: &str, cmd: &str) -> Resu if index_of(&s.tools.presets, new).is_some_and(|j| j != i) { return Err(bad(cmd, format!("a brush preset named `{new}` already exists"))); } - let pr = s.tools.presets.get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets).get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; if pr.name != new { let was_current = s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&pr.name)); pr.name = new.to_string(); diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index b44a2abdae..174c99281d 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1204,7 +1204,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync(std::sync::Arc::make_mut(&mut self.tools.presets)); + st.sync(std::sync::Arc::make_mut(&mut self.tools.presets).as_mut_slice()); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush From b43ffa380f185169056b251861867bf649874b0b Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:48:31 +0100 Subject: [PATCH 62/85] Borrow shared presets as a vector --- crates/ui-egui/src/panels/brush_panel/brushes.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/brush_panel/brushes.rs b/crates/ui-egui/src/panels/brush_panel/brushes.rs index e851181931..f4ae4a302c 100644 --- a/crates/ui-egui/src/panels/brush_panel/brushes.rs +++ b/crates/ui-egui/src/panels/brush_panel/brushes.rs @@ -109,7 +109,7 @@ pub(crate) fn tip_paint(b: &BrushSettings) -> impl Fn(&ContentPainterCx, Rect) + /// The rows of every preset in the engine's panel order (the order `,` and `.` step through): a /// group row before the first preset of each group and each folder, with its count. pub(crate) fn preset_rows(app: &PhotocraftApp, env: &Env, parts: BrushCardParts) -> Vec> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); let mut counts: std::collections::HashMap<(&str, &[String]), usize> = std::collections::HashMap::new(); for p in presets { let path = path_of(p); @@ -204,7 +204,7 @@ pub(crate) fn apply_events(app: &mut PhotocraftApp, events: Vec, rows: &[BrushKey]) -> Option<(&'static str, Value)> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); match event { PresetEvent::Select { key: BrushKey::Preset(name), .. } => Some(("tools.setBrush", json!({ "preset": name }))), // The double click's first click already picked it. From 587f5e5dab4eaea4dc745565b89e2d39d4eb0e0b Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 10:09:05 +0000 Subject: [PATCH 63/85] Section store syncs by per-section revisions (#15704) PrefSections tracks the sections a component wrote and the revision it last saw of each section, so a sync no longer compares or clones the whole section map. --- crates/engine/src/prefs.rs | 6 ++ crates/ui-egui/src/app/framework.rs | 105 +++++++++++++++++++++++----- 2 files changed, 94 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d193d89c34..23a0a97042 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1946,6 +1946,12 @@ impl Session { self.prefs.get() } + /// Revision of the framework preference section `key`: it moves when an edit changes that + /// section. + pub fn section_rev(&self, key: &str) -> u64 { + self.prefs.section_rev(key) + } + /// Change preferences and apply the engine-side ones. pub fn edit_prefs(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { let r = self.prefs.edit(f); diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 4adf2e7624..c367a6821f 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -10,7 +10,7 @@ //! The `craft` facade features PhotoCraft enables for this: `text`, `text-font-picker`, //! `font-manager`, `menu`, `timeline` and `print`, plus `dialogs` on native targets. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex, PoisonError}; use craft::host::target::{Backend, ShellInfo}; @@ -603,27 +603,53 @@ struct PrefSections(Mutex); #[derive(Default)] struct Tables { tables: BTreeMap, - /// A component wrote since the last sync. - written: bool, - /// The preferences' sections as last synced, to notice a change from elsewhere (a reset, - /// the control channel). - seen: BTreeMap, + /// The sections a component wrote since the last sync. + written: BTreeSet, + /// Each section's preference revision as last synced, to notice a change from elsewhere (a + /// reset, the control channel) without comparing the sections. + seen: BTreeMap, + /// How many sections a sync has read from the preferences. + #[cfg(test)] + loaded: usize, } impl PrefSections { - /// Writes the components' changes into the preferences, or takes a change made there. + /// Writes the sections the components wrote into the preferences, and takes the sections whose + /// preference revision moved. fn sync(&self, session: &mut Session) { let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner); - if std::mem::take(&mut t.written) { - let json: BTreeMap = t.tables.iter().filter_map(|(key, table)| Some((key.clone(), serde_json::to_value(table).ok()?))).collect(); - if session.prefs().sections != json { - session.edit_prefs(|p| p.sections = json.clone()); + let written = std::mem::take(&mut t.written); + if !written.is_empty() { + let changed: Vec<(String, Value)> = written + .iter() + .filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?))) + .filter(|(key, value)| session.prefs().sections.get(key) != Some(value)) + .collect(); + if !changed.is_empty() { + session.edit_prefs(|p| p.sections.extend(changed)); } - t.seen = json; - } else if session.prefs().sections != t.seen { - let seen = session.prefs().sections.clone(); - t.tables = seen.iter().filter_map(|(key, value)| Some((key.clone(), serde_json::from_value(value.clone()).ok()?))).collect(); - t.seen = seen; + for key in written { + let rev = session.section_rev(&key); + t.seen.insert(key, rev); + } + } + let sections = &session.prefs().sections; + let moved: Vec<&String> = sections.keys().filter(|key| t.seen.get(*key) != Some(&session.section_rev(key))).collect(); + let gone: Vec = t.seen.keys().filter(|key| !sections.contains_key(*key)).cloned().collect(); + for key in moved { + match serde_json::from_value(sections[key].clone()) { + Ok(table) => t.tables.insert(key.clone(), table), + Err(_) => t.tables.remove(key), + }; + t.seen.insert(key.clone(), session.section_rev(key)); + #[cfg(test)] + { + t.loaded += 1; + } + } + for key in gone { + t.tables.remove(&key); + t.seen.remove(&key); } } } @@ -636,7 +662,7 @@ impl SectionStore for PrefSections { fn write(&self, key: &str, table: toml::Table) { let mut t = self.0.lock().unwrap_or_else(PoisonError::into_inner); t.tables.insert(key.to_owned(), table); - t.written = true; + t.written.insert(key.to_owned()); } } @@ -689,6 +715,51 @@ pub(crate) fn keys_pass(app: &mut PhotocraftApp, ctx: &egui::Context, input: egu #[cfg(test)] mod tests { + use super::*; + + fn table(n: i64) -> toml::Table { + let mut t = toml::Table::new(); + t.insert("n".into(), toml::Value::Integer(n)); + t + } + + /// A sync reads and writes only the sections that changed, one revision per section. + #[test] + fn section_sync_touches_only_changed_sections() { + let store = PrefSections::default(); + let mut session = Session::new(); + store.write("one", table(1)); + store.write("two", table(2)); + store.sync(&mut session); + assert_eq!(session.prefs().sections.len(), 2); + let (one, two) = (session.section_rev("one"), session.section_rev("two")); + let loaded = store.0.lock().unwrap().loaded; + + store.sync(&mut session); + assert_eq!((session.section_rev("one"), session.section_rev("two")), (one, two)); + assert_eq!(store.0.lock().unwrap().loaded, loaded, "an idle sync reads nothing"); + + store.write("two", table(3)); + store.sync(&mut session); + assert_eq!(session.section_rev("one"), one, "a section nobody wrote keeps its revision"); + assert_eq!(session.section_rev("two"), two.wrapping_add(1)); + assert_eq!(store.0.lock().unwrap().loaded, loaded, "a component's own write is not read back"); + + session.edit_prefs(|p| { + p.sections.insert("one".into(), serde_json::json!({ "n": 9 })); + }); + store.sync(&mut session); + assert_eq!(store.0.lock().unwrap().loaded, loaded + 1, "only the changed section is read"); + assert_eq!(store.read("one"), Some(table(9))); + assert_eq!(store.read("two"), Some(table(3))); + + session.edit_prefs(|p| { + p.sections.remove("one"); + }); + store.sync(&mut session); + assert_eq!(store.read("one"), None); + } + /// Every theme PhotoCraft has a palette for names a framework built-in. #[test] fn every_palette_theme_is_a_builtin() { From d53d6002582c0026052ba0b594ac51a6044b1304 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:24:19 +0100 Subject: [PATCH 64/85] Keep shared presets on empty store attachment --- crates/engine/src/preset_store.rs | 84 +++++++++++++++++++------ crates/engine/src/preset_store/tests.rs | 14 +++++ 2 files changed, 78 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 174c99281d..268cfa1899 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -822,6 +822,29 @@ pub fn open_dir_async(root: std::path::PathBuf) -> std::sync::mpsc::Receiver &[BrushPreset]; + fn view_mut(&mut self) -> &mut [BrushPreset]; +} + +impl PresetList for [BrushPreset] { + fn view(&self) -> &[BrushPreset] { + self + } + fn view_mut(&mut self) -> &mut [BrushPreset] { + self + } +} + +impl PresetList for std::sync::Arc> { + fn view(&self) -> &[BrushPreset] { + self.as_slice() + } + fn view_mut(&mut self) -> &mut [BrushPreset] { + std::sync::Arc::make_mut(self).as_mut_slice() + } +} + impl PresetStore { /// `actions.json` exists but could not be read: it is left as it is and never written. pub fn actions_load_failed(&self) -> bool { @@ -880,9 +903,17 @@ impl PresetStore { /// removed ones and their unreferenced tips, update the index. The bitmaps of every group /// written become stored tiles (#1843): the files hold them, so the presets keep previews only. pub fn sync(&mut self, presets: &mut [BrushPreset]) { + self.sync_inner(presets); + } + + fn sync_shared(&mut self, presets: &mut std::sync::Arc>) { + self.sync_inner(presets); + } + + fn sync_inner(&mut self, presets: &mut P) { // User presets by group, in first-appearance order. let mut order: Vec<(String, Vec)> = Vec::new(); - for (i, p) in presets.iter().enumerate().filter(|(_, p)| !p.builtin) { + for (i, p) in presets.view().iter().enumerate().filter(|(_, p)| !p.builtin) { match order.iter_mut().find(|(g, _)| *g == p.group) { Some((_, v)) => v.push(i), None => order.push((p.group.clone(), vec![i])), @@ -895,7 +926,7 @@ impl PresetStore { let unchanged = self .groups .get(&file) - .is_some_and(|s| !s.stale && s.presets.len() == idx.len() && s.presets.iter().zip(idx).all(|(a, &i)| presets.get(i) == Some(a))); + .is_some_and(|s| !s.stale && s.presets.len() == idx.len() && s.presets.view().iter().zip(idx).all(|(a, &i)| presets.view().get(i) == Some(a))); if unchanged { continue; } @@ -906,7 +937,7 @@ impl PresetStore { )); continue; } - let mut items: Vec<&mut BrushPreset> = presets.iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); + let mut items: Vec<&mut BrushPreset> = presets.view_mut().iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); if let Err(e) = self.write_group(&file, group, &mut items) { self.warnings.push(format!("Couldn't save brush presets `{}`: {e}", if group.is_empty() { "(ungrouped)" } else { group })); } @@ -929,14 +960,16 @@ impl PresetStore { } } // Index: group order and deleted built-ins. - let hidden: Vec = builtin_names().iter().filter(|n| !presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); + let hidden: Vec = + builtin_names().iter().filter(|n| !presets.view().iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); let groups: Vec = files.into_iter().filter(|f| self.groups.contains_key(f)).collect(); // The full order is only saved once it differs from the default (built-ins, then the rest). - let order: Vec = presets.iter().map(|p| p.name.clone()).collect(); - let default_order: Vec = presets.iter().filter(|p| p.builtin).chain(presets.iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); + let order: Vec = presets.view().iter().map(|p| p.name.clone()).collect(); + let default_order: Vec = + presets.view().iter().filter(|p| p.builtin).chain(presets.view().iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); let builtins_in_order = { let names = builtin_names(); - let mut it = presets.iter().filter(|p| p.builtin).map(|p| names.iter().position(|n| *n == p.name)); + let mut it = presets.view().iter().filter(|p| p.builtin).map(|p| names.iter().position(|n| *n == p.name)); let first = it.next().flatten(); it.try_fold(first, |prev, cur| match (prev, cur) { (Some(a), Some(b)) if b > a => Some(Some(b)), @@ -1141,19 +1174,30 @@ impl Session { } } } - let lib = std::sync::Arc::make_mut(&mut self.tools.presets); - lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); - for p in presets { - match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { - Some(x) if x.builtin => *x = p, - Some(_) => {} - None => lib.push(p), + let order_changes = if order.is_empty() { + false + } else { + let pos: HashMap = order.iter().enumerate().map(|(i, name)| (name.to_lowercase(), i)).collect(); + !self.tools.presets.iter().map(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)).is_sorted() + }; + let changes_presets = order_changes + || self.tools.presets.iter().any(|p| p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name))) + || presets.iter().any(|p| self.tools.presets.iter().find(|x| x.name.eq_ignore_ascii_case(&p.name)).is_none_or(|x| x.builtin && x != p)); + if changes_presets { + let lib = std::sync::Arc::make_mut(&mut self.tools.presets); + lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); + for p in presets { + match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { + Some(x) if x.builtin => *x = p, + Some(_) => {} + None => lib.push(p), + } + } + // The saved panel order (stable: presets it doesn't name keep their order, at the end). + if !order.is_empty() { + let pos: HashMap = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect(); + lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)); } - } - // The saved panel order (stable: presets it doesn't name keep their order, at the end). - if !order.is_empty() { - let pos: HashMap = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect(); - lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)); } self.preset_store = Some(store); // Clear All, Reset or Replace before the store loaded made the session's list the whole @@ -1204,7 +1248,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync(std::sync::Arc::make_mut(&mut self.tools.presets).as_mut_slice()); + st.sync_shared(&mut self.tools.presets); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 3e601f2601..02f91075d3 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -52,6 +52,20 @@ fn user(s: &Session) -> Vec { s.tools.presets.iter().filter(|p| !p.builtin).cloned().collect() } +#[test] +fn empty_stores_preserve_shared_builtin_presets() { + let first_dir = TempDir::new("shared-first"); + let second_dir = TempDir::new("shared-second"); + let (mut first, warnings) = session(&first_dir); + assert!(warnings.is_empty(), "{warnings:?}"); + let (second, warnings) = session(&second_dir); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); + first.execute("brush.presets.save", json!({"name": "Only first"})).unwrap(); + assert!(second.tools.presets.iter().all(|p| p.name != "Only first")); + assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); +} + #[test] fn sessions_have_no_store_by_default() { let mut s = Session::new(); From 252773ce8caecd6c4148f99783ab588cdf79a020 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 13:35:20 +0100 Subject: [PATCH 65/85] Address CodeRabbit review: stale transform picture, setup panics, UI feature check - A pass that cancels Free Transform no longer hands the canvas the captured preview picture, so the moved pixels are not painted over the restored document in that frame (new GPU/CPU canvas test fails without it). - The preview canvas test skips only when the GPU harness fails before the app callback; a panic in the app's own setup now fails the test. - The layering check treats craft's keymap-egui as a UI feature and counts dependency features turned on by a crate's own [features] table. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/tools/transform_tool/draw.rs | 4 ++ .../tests/it/free_transform_preview_canvas.rs | 43 +++++++++++++++- xtask/src/layers.rs | 50 +++++++++++++++++-- 3 files changed, 93 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index a8723af30e..dc7d45275b 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -91,6 +91,10 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re if let Some(t) = app.ui.transform.as_mut() { t.session.settle(now, busy); } + // A pass that ended the session (Cancel, or a commit that finished at once) hands back no picture: its moving + // pixels would paint over the restored document. A commit still running in the background keeps the preview, and + // with it the picture. + let picture = if app.transform_preview.is_some() { picture } else { Vec::new() }; SessionShown { shown: true, snapped, picture } } diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index 0b7ff0eb5b..f5890874b7 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -22,8 +22,13 @@ fn square() -> Rect { } fn harness(gpu_canvas: bool) -> Option { - let built = std::panic::catch_unwind(|| { + // Only a panic before the app callback runs (no adapter, no render state) is a skip; one from the app's own setup + // is a failure. + let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = entered.clone(); + let built = std::panic::catch_unwind(move || { egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move |cc| { + flag.store(true, std::sync::atomic::Ordering::SeqCst); PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if gpu_canvas && let Some(rs) = cc.wgpu_render_state.as_ref() { @@ -34,6 +39,7 @@ fn harness(gpu_canvas: bool) -> Option { }); match built { Ok(h) => Some(h), + Err(panic) if entered.load(std::sync::atomic::Ordering::SeqCst) => std::panic::resume_unwind(panic), Err(_) => { eprintln!("skipping: no GPU adapter"); None @@ -137,3 +143,38 @@ fn free_transform_shows_the_layer_inside_its_box_on_the_gpu_canvas() { fn free_transform_shows_the_layer_inside_its_box_on_the_cpu_canvas() { shows_the_layer_inside_the_box(false); } + +/// Escape after a move puts the square back in the frame that cancels: the cancelled preview's moving pixels are not +/// painted over the restored document where the box had taken them. +fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(gpu_canvas) else { return }; + setup(&mut h); + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + let (from, to) = (screen(&h, 150.0, 150.0), screen(&h, 210.0, 150.0)); + pointer_move(&mut h, from); + button(&mut h, from, true); + for i in 1..=6 { + pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); + } + button(&mut h, to, false); + assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square"); + + h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.step(); + assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform"); + let moved = rgb_at(&mut h, 230.5, 130.5); + assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}"); + let back = rgb_at(&mut h, 150.5, 130.5); + assert!(is_red(back), "the square is back in its place: {back:?}"); +} + +#[test] +fn cancelling_free_transform_shows_no_moved_pixels_on_the_gpu_canvas() { + cancelling_shows_no_moved_pixels(true); +} + +#[test] +fn cancelling_free_transform_shows_no_moved_pixels_on_the_cpu_canvas() { + cancelling_shows_no_moved_pixels(false); +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index c7ed3f95d9..825a35daa3 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -102,8 +102,9 @@ pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "cra /// Facade crates that are a UI toolkit dependency only with some of their features (#15467): `craft` carries the /// whole craft UI framework behind `ui` (and the features that turn it on), while lower layers use its non-UI parts -/// (imaging, fonts, keymap, settings). Feature names ending in `*` are prefixes. -pub const UI_FEATURES: &[(&str, &[&str])] = &[("craft", &["ui", "ui-*", "screen-testing"])]; +/// (imaging, fonts, keymap, settings). `keymap-egui` adds the keymap's egui key conversions, which bring egui itself. +/// Feature names ending in `*` are prefixes. +pub const UI_FEATURES: &[(&str, &[&str])] = &[("craft", &["ui", "ui-*", "screen-testing", "keymap-egui"])]; /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -253,7 +254,11 @@ pub fn from_metadata(meta: &Value) -> Result, String> { _ => DepKind::Normal, }; let workspace = members.contains(&dname.as_str()) || d["path"].is_string(); - let features = d["features"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_owned)).collect(); + let mut features: Vec = d["features"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_owned)).collect(); + // The package's own `[features]` can turn on a dependency's features (`default = ["craft/ui"]`), named by + // the dependency's key, which is its rename when it has one. Any of them may be on, so all count. + let key = d["rename"].as_str().unwrap_or(&dname); + features.extend(forwarded_features(&p["features"], key)); deps.push(Dep { name: dname, kind, workspace, features }); } out.push(Crate { name, deps }); @@ -262,6 +267,15 @@ pub fn from_metadata(meta: &Value) -> Result, String> { Ok(out) } +/// The features of dependency `key` that the package's `[features]` table (`features` in `cargo metadata`) turns on: +/// `key/feat` and `key?/feat` entries. +fn forwarded_features<'a>(table: &'a Value, key: &'a str) -> impl Iterator + 'a { + table.as_object().into_iter().flat_map(|t| t.values()).filter_map(Value::as_array).flatten().filter_map(Value::as_str).filter_map(move |entry| { + let (dep, feature) = entry.split_once('/')?; + (dep.strip_suffix('?').unwrap_or(dep) == key).then(|| feature.to_owned()) + }) +} + pub fn describe(class: Option) -> String { match class { Some(Class::Layer(l)) => format!("L{l}"), @@ -398,6 +412,36 @@ mod tests { assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }])); } + /// The keymap's egui conversions bring egui; the plain keymap does not. + #[test] + fn keymap_egui_is_a_ui_feature() { + assert!(matches!(check(&[with_features("photocraft-engine", "craft", Normal, &["keymap-egui"])])[..], [Violation::UiBelowL6 { .. }])); + assert!(check(&[with_features("photocraft-engine", "craft", Normal, &["keymap"])]).is_empty()); + } + + /// A UI feature turned on by the package's own `[features]` (also through a renamed dependency) counts; other + /// forwarded features don't. + #[test] + fn metadata_reads_features_forwarded_by_the_package() { + let meta = |features: &str, rename: &str| -> Value { + serde_json::from_str(&format!( + r#"{{"packages":[{{"name":"photocraft-engine","features":{features},"dependencies":[ + {{"name":"craft","kind":null,"features":["keymap"]{rename}}}]}}]}}"# + )) + .unwrap() + }; + for (features, rename) in [(r#"{"default":["craft/ui"]}"#, ""), (r#"{"gui":["c?/ui"]}"#, r#","rename":"c""#)] { + let g = from_metadata(&meta(features, rename)).unwrap(); + assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }]), "{features}"); + } + for (features, rename) in + [(r#"{"default":["craft/imaging"]}"#, ""), (r#"{"gui":["other/ui","dep:craft"]}"#, ""), (r#"{"gui":["craft/ui"]}"#, r#","rename":"c""#)] + { + let g = from_metadata(&meta(features, rename)).unwrap(); + assert!(check(&g).is_empty(), "{features} {rename}: {:?}", check(&g)); + } + } + #[test] fn unregistered_crate_is_error() { let v = check(&[c("photocraft-mystery", &[])]); From d01b09d7e7c3222afa45e25193b36fdd746285a6 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 15:14:20 +0100 Subject: [PATCH 66/85] Initialize built-in presets once --- crates/paint/src/presets.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index 0107dfdcfe..f7411fcc82 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -438,8 +438,10 @@ impl Texture { } } -/// The built-in preset set, in display order (grouped by [`GROUPS`]). -pub fn builtin() -> Vec { +#[cfg(test)] +static BUILTIN_INITIALIZATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn build_builtin() -> Vec { let base = BrushSettings { pressure_size: false, spacing: 0.25, ..Default::default() }; let mut v = general(&base); v.extend(dry_media(&base)); @@ -448,10 +450,21 @@ pub fn builtin() -> Vec { v } +/// An owned copy of the built-in preset set, in display order (grouped by [`GROUPS`]). +pub fn builtin() -> Vec { + builtin_shared().as_ref().clone() +} + /// The built-in set shared by new sessions until one is edited. pub fn builtin_shared() -> std::sync::Arc> { static BUILTIN: std::sync::OnceLock>> = std::sync::OnceLock::new(); - BUILTIN.get_or_init(|| std::sync::Arc::new(builtin())).clone() + BUILTIN + .get_or_init(|| { + #[cfg(test)] + BUILTIN_INITIALIZATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::sync::Arc::new(build_builtin()) + }) + .clone() } /// Find a preset by name (case-insensitive). @@ -463,6 +476,16 @@ pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPrese mod tests { use super::*; + #[test] + fn builtins_initialize_once_across_owned_and_shared_calls() { + let first = builtin_shared(); + let owned = builtin(); + let second = builtin_shared(); + assert!(std::sync::Arc::ptr_eq(&first, &second)); + assert_eq!(*first, owned); + assert_eq!(BUILTIN_INITIALIZATIONS.load(std::sync::atomic::Ordering::Relaxed), 1); + } + #[test] fn builtins_are_grouped_and_unique() { let v = builtin(); From 81fe85e318d7aaffb2fd57df68ce5f4483ba8b6d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 15:19:27 +0100 Subject: [PATCH 67/85] Regenerate docs/scorecard.md after merging main Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index e3fb1e1dbb..3f01a2ece7 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -12,7 +12,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 9 of 202 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 6 | 4 | 2 | 664 of 664 menu items live (100.0%) | -| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 24 of 25 crates; panic_hunt present | +| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 25 of 25 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -280,7 +280,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T ## Reliability -Never-crash attribute on 24 of 25 crate roots; missing: `crates/ipp/src/lib.rs`. +Never-crash attribute on 25 of 25 crate roots. | Id | Target | Status | Issue | Note | |---|---|---|---|---| From 2f911f85e0e31f5114dcc14c8169ed62a125f0fd Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:26:19 +0000 Subject: [PATCH 68/85] raster: assign Surface generations lazily --- crates/raster/src/lib.rs | 43 +++++++++++++++++++++++++++++++------- crates/raster/src/shift.rs | 4 ++-- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 9ccf9e67e7..59474e6ab5 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -309,14 +309,27 @@ impl PruneCursor { } } -#[derive(Clone)] pub struct Surface { - generation: u64, + /// 0 means no number assigned yet; see [`Surface::generation`]. + generation: std::sync::atomic::AtomicU64, format: PixelFormat, default_pixel: Box<[u8]>, tiles: BTreeMap>, } +impl Clone for Surface { + fn clone(&self) -> Self { + // Read first so the clone and the original share one number: they hold the same pixels. + let generation = self.generation(); + Self { + generation: std::sync::atomic::AtomicU64::new(generation), + format: self.format, + default_pixel: self.default_pixel.clone(), + tiles: self.tiles.clone(), + } + } +} + impl std::fmt::Debug for Surface { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // The generation identifies an edit history. Independently opened copies of the same @@ -601,14 +614,29 @@ fn fresh_surface_generation() -> u64 { NEXT_SURFACE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// A generation slot with no number yet; the first [`Surface::generation`] read assigns one. +fn unassigned_generation() -> std::sync::atomic::AtomicU64 { + std::sync::atomic::AtomicU64::new(0) +} + impl Surface { - /// Equal generations identify the same pixel state, including across clones. + /// Equal generations identify the same pixel state, including across clones. Numbers are + /// assigned on first read after a mutation, so writes never touch the shared counter. pub fn generation(&self) -> u64 { - self.generation + use std::sync::atomic::Ordering::Relaxed; + let current = self.generation.load(Relaxed); + if current != 0 { + return current; + } + let fresh = fresh_surface_generation(); + match self.generation.compare_exchange(0, fresh, Relaxed, Relaxed) { + Ok(_) => fresh, + Err(assigned) => assigned, + } } fn note_mutation(&mut self) { - self.generation = fresh_surface_generation(); + *self.generation.get_mut() = 0; } /// Reads a region into a newly allocated buffer, returning an error instead of aborting if @@ -672,7 +700,7 @@ impl Surface { /// Transparent/zero surface. pub fn new(format: PixelFormat) -> Self { - Self { generation: fresh_surface_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } + Self { generation: unassigned_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } } /// Surface whose untouched pixels read as `pixel` (normalised channel values). @@ -1397,8 +1425,7 @@ impl Surface { /// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only /// tiles it reaches are kept. pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface { - let mut out = - Surface { generation: fresh_surface_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; + let mut out = Surface { generation: unassigned_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; let sources = || self.tiles.iter().filter(move |(c, _)| !c.rect().intersect(&content).is_empty()); if dx % TILE_SIZE == 0 && dy % TILE_SIZE == 0 { let (tx, ty) = (dx / TILE_SIZE, dy / TILE_SIZE); diff --git a/crates/raster/src/shift.rs b/crates/raster/src/shift.rs index c75ebf3401..9320db8cc1 100644 --- a/crates/raster/src/shift.rs +++ b/crates/raster/src/shift.rs @@ -222,7 +222,7 @@ impl TranslateSteps { let tiles: Vec<(TileCoord, Arc)> = if whole_tiles { Vec::new() } else { ShiftBuilder::sources(&src, content).map(|(c, t)| (*c, Arc::clone(t))).collect() }; let out = - Surface { generation: super::fresh_surface_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; + Surface { generation: super::unassigned_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; Self { sources: tiles.len(), scan: tiles.into_iter(), @@ -276,7 +276,7 @@ impl TranslateSteps { return Some(std::mem::replace( &mut self.out, Surface { - generation: super::fresh_surface_generation(), + generation: super::unassigned_generation(), format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default(), From aeabe8e2bef0638b2d9b83375843161cc8e1cd29 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:28:20 +0000 Subject: [PATCH 69/85] engine: drop an unused re-export --- crates/engine/src/cmd/retouch_cmds.rs | 4 +--- crates/engine/src/cmd/retouch_cmds/content_aware_move.rs | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 4bb8496fa5..868a5428ba 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -35,9 +35,7 @@ pub use pattern_stamp::{ }; mod periodic; mod remove; -pub use content_aware_move::{ - ContentAwarePreview, preview as content_aware_move_preview, preview_with_pixel_budget as content_aware_move_preview_with_pixel_budget, -}; +pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; pub use patch::preview as patch_preview; fn bad(cmd: &str, msg: impl Into) -> EngineError { diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index 89eca9973a..fa7b82ad72 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -700,7 +700,7 @@ pub fn preview(s: &Session, p: &Value) -> Result { } /// Prepare a preview with a bound on the number of pixels solved at full resolution. -pub fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result { +pub(crate) fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result { let captured = crate::channel_cmds::inject_target(s, CMD, p.clone()); let p = &captured; let plan = plan(s, p, PREVIEW_MARGIN)?; From 3d76829fd37f9fbd3c7b795e2b67dfcb466b513e Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:57:23 +0000 Subject: [PATCH 70/85] Preset store: sync takes the shared list directly --- crates/engine/src/preset_store.rs | 49 ++++++------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 268cfa1899..0a109b736b 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -822,29 +822,6 @@ pub fn open_dir_async(root: std::path::PathBuf) -> std::sync::mpsc::Receiver &[BrushPreset]; - fn view_mut(&mut self) -> &mut [BrushPreset]; -} - -impl PresetList for [BrushPreset] { - fn view(&self) -> &[BrushPreset] { - self - } - fn view_mut(&mut self) -> &mut [BrushPreset] { - self - } -} - -impl PresetList for std::sync::Arc> { - fn view(&self) -> &[BrushPreset] { - self.as_slice() - } - fn view_mut(&mut self) -> &mut [BrushPreset] { - std::sync::Arc::make_mut(self).as_mut_slice() - } -} - impl PresetStore { /// `actions.json` exists but could not be read: it is left as it is and never written. pub fn actions_load_failed(&self) -> bool { @@ -902,18 +879,10 @@ impl PresetStore { /// Bring the files in line with `presets` (built-ins skipped): write changed groups, delete /// removed ones and their unreferenced tips, update the index. The bitmaps of every group /// written become stored tiles (#1843): the files hold them, so the presets keep previews only. - pub fn sync(&mut self, presets: &mut [BrushPreset]) { - self.sync_inner(presets); - } - - fn sync_shared(&mut self, presets: &mut std::sync::Arc>) { - self.sync_inner(presets); - } - - fn sync_inner(&mut self, presets: &mut P) { + pub fn sync(&mut self, presets: &mut std::sync::Arc>) { // User presets by group, in first-appearance order. let mut order: Vec<(String, Vec)> = Vec::new(); - for (i, p) in presets.view().iter().enumerate().filter(|(_, p)| !p.builtin) { + for (i, p) in presets.iter().enumerate().filter(|(_, p)| !p.builtin) { match order.iter_mut().find(|(g, _)| *g == p.group) { Some((_, v)) => v.push(i), None => order.push((p.group.clone(), vec![i])), @@ -926,7 +895,7 @@ impl PresetStore { let unchanged = self .groups .get(&file) - .is_some_and(|s| !s.stale && s.presets.len() == idx.len() && s.presets.view().iter().zip(idx).all(|(a, &i)| presets.view().get(i) == Some(a))); + .is_some_and(|s| !s.stale && s.presets.len() == idx.len() && s.presets.iter().zip(idx).all(|(a, &i)| presets.get(i) == Some(a))); if unchanged { continue; } @@ -937,7 +906,7 @@ impl PresetStore { )); continue; } - let mut items: Vec<&mut BrushPreset> = presets.view_mut().iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); + let mut items: Vec<&mut BrushPreset> = std::sync::Arc::make_mut(presets).iter_mut().filter(|p| !p.builtin && p.group == *group).collect(); if let Err(e) = self.write_group(&file, group, &mut items) { self.warnings.push(format!("Couldn't save brush presets `{}`: {e}", if group.is_empty() { "(ungrouped)" } else { group })); } @@ -961,15 +930,15 @@ impl PresetStore { } // Index: group order and deleted built-ins. let hidden: Vec = - builtin_names().iter().filter(|n| !presets.view().iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); + builtin_names().iter().filter(|n| !presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); let groups: Vec = files.into_iter().filter(|f| self.groups.contains_key(f)).collect(); // The full order is only saved once it differs from the default (built-ins, then the rest). - let order: Vec = presets.view().iter().map(|p| p.name.clone()).collect(); + let order: Vec = presets.iter().map(|p| p.name.clone()).collect(); let default_order: Vec = - presets.view().iter().filter(|p| p.builtin).chain(presets.view().iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); + presets.iter().filter(|p| p.builtin).chain(presets.iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); let builtins_in_order = { let names = builtin_names(); - let mut it = presets.view().iter().filter(|p| p.builtin).map(|p| names.iter().position(|n| *n == p.name)); + let mut it = presets.iter().filter(|p| p.builtin).map(|p| names.iter().position(|n| *n == p.name)); let first = it.next().flatten(); it.try_fold(first, |prev, cur| match (prev, cur) { (Some(a), Some(b)) if b > a => Some(Some(b)), @@ -1248,7 +1217,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync_shared(&mut self.tools.presets); + st.sync(&mut self.tools.presets); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush From 977617f26856daaa23d49ad2f3e6acc05177ea6c Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:57:35 +0000 Subject: [PATCH 71/85] Brush preset moves: take the shared list without copying it first --- crates/engine/src/cmd/brush_preset_cmds.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 8965d1d658..6e8d2e1d76 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -233,7 +233,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); // Where the block sits among the other presets (its place when nothing else is in the parent). let start = lib.iter().position(|x| in_folder(x, &g, &f)).unwrap_or(0); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); @@ -332,7 +332,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, if deepest > MAX_FOLDER_DEPTH { return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep"))); } - let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); let (mut block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); for x in &mut block { let tail = rest_of(x); @@ -382,7 +382,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); + let lib = std::sync::Arc::unwrap_or_clone(std::mem::take(&mut s.tools.presets)); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| x.group == g); let order = group_order(&rest); let first = |name: &str, rest: &[BrushPreset]| rest.iter().position(|x| x.group == name).unwrap_or(rest.len()); From 3194ea5bae8eb52d7b8f384aa15dddf3bfc5a909 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:58:08 +0000 Subject: [PATCH 72/85] Preset store attach: one copy of the merge rule, copy the list only on a write --- crates/engine/src/preset_store.rs | 46 ++++++++++++++----------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 0a109b736b..dff99794fc 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -929,13 +929,11 @@ impl PresetStore { } } // Index: group order and deleted built-ins. - let hidden: Vec = - builtin_names().iter().filter(|n| !presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); + let hidden: Vec = builtin_names().iter().filter(|n| !presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect(); let groups: Vec = files.into_iter().filter(|f| self.groups.contains_key(f)).collect(); // The full order is only saved once it differs from the default (built-ins, then the rest). let order: Vec = presets.iter().map(|p| p.name.clone()).collect(); - let default_order: Vec = - presets.iter().filter(|p| p.builtin).chain(presets.iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); + let default_order: Vec = presets.iter().filter(|p| p.builtin).chain(presets.iter().filter(|p| !p.builtin)).map(|p| p.name.clone()).collect(); let builtins_in_order = { let names = builtin_names(); let mut it = presets.iter().filter(|p| p.builtin).map(|p| names.iter().position(|n| *n == p.name)); @@ -1143,29 +1141,25 @@ impl Session { } } } - let order_changes = if order.is_empty() { - false - } else { - let pos: HashMap = order.iter().enumerate().map(|(i, name)| (name.to_lowercase(), i)).collect(); - !self.tools.presets.iter().map(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)).is_sorted() - }; - let changes_presets = order_changes - || self.tools.presets.iter().any(|p| p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name))) - || presets.iter().any(|p| self.tools.presets.iter().find(|x| x.name.eq_ignore_ascii_case(&p.name)).is_none_or(|x| x.builtin && x != p)); - if changes_presets { - let lib = std::sync::Arc::make_mut(&mut self.tools.presets); - lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); - for p in presets { - match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { - Some(x) if x.builtin => *x = p, - Some(_) => {} - None => lib.push(p), - } + // The list stays shared (`make_mut` is taken at the first write) when the store changes nothing. + let hide = |p: &BrushPreset| p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)); + if self.tools.presets.iter().any(hide) { + std::sync::Arc::make_mut(&mut self.tools.presets).retain(|p| !hide(p)); + } + for p in presets { + let found = self.tools.presets.iter().position(|x| x.name.eq_ignore_ascii_case(&p.name)); + match found { + Some(i) if self.tools.presets[i].builtin && self.tools.presets[i] != p => std::sync::Arc::make_mut(&mut self.tools.presets)[i] = p, + Some(_) => {} + None => std::sync::Arc::make_mut(&mut self.tools.presets).push(p), } - // The saved panel order (stable: presets it doesn't name keep their order, at the end). - if !order.is_empty() { - let pos: HashMap = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect(); - lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)); + } + // The saved panel order (stable: presets it doesn't name keep their order, at the end). + if !order.is_empty() { + let pos: HashMap = order.iter().enumerate().map(|(i, n)| (n.to_lowercase(), i)).collect(); + let key = |p: &BrushPreset| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX); + if !self.tools.presets.iter().map(key).is_sorted() { + std::sync::Arc::make_mut(&mut self.tools.presets).sort_by_key(key); } } self.preset_store = Some(store); From 129c4e5e6ad7a698203dd74b354f632cf40a8bfd Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:58:08 +0000 Subject: [PATCH 73/85] Test: reordering only built-in presets persists --- crates/engine/src/preset_store/tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 02f91075d3..18f5f96182 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -309,6 +309,22 @@ fn reordering_presets_and_groups_persists() { assert!(t.tools.presets.iter().all(|p| p.group != "Washes" && p.group != "Inks")); } +#[test] +fn reordering_only_built_in_presets_persists() { + let names = |s: &Session| s.tools.presets.iter().map(|p| p.name.clone()).collect::>(); + let dir = TempDir::new("reorder-builtin"); + let (mut s, _) = session(&dir); + let group = s.tools.presets[0].group.clone(); + let last = s.tools.presets.iter().rfind(|p| p.builtin && p.group == group).unwrap().name.clone(); + let first = s.tools.presets[0].name.clone(); + assert_ne!(last, first); + s.execute("brush.presets.move", json!({"name": last, "before": first})).unwrap(); + assert_eq!(s.tools.presets[0].name, last); + let (t, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(names(&t), names(&s), "the new built-in order survives a restart"); +} + #[test] fn corrupt_and_oversized_files_are_skipped_with_a_warning() { let dir = TempDir::new("corrupt"); From 40bd3e7e73beb34e796b3ad870d55b5faa3325d2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:05:43 +0000 Subject: [PATCH 74/85] 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 75/85] 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 76/85] 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 77/85] 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 78/85] 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 79/85] 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 1d391ce10ff823abdad6802433189eb97045d542 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 17:50:13 +0100 Subject: [PATCH 80/85] Integration: #15429: the caret font test checks the typed text and the pending font before the commit CodeRabbit on #15429: the family check alone passed if the IME inserted other characters in the same fonts, and the cleanup check passed if the pending font was already gone before the check mark. Co-Authored-By: Claude Opus 5.5 --- .../src/tools/type_tool/font_commit_tests.rs | 6 +- crates/ui-egui/tests/it/tone_targets.rs | 110 ++++++++---------- 2 files changed, 54 insertions(+), 62 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index 3f2c6f7103..cfc131d5e6 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -180,10 +180,14 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { let mut expected = families(&before); expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); + let mut expected_text: Vec = text.chars().collect(); + expected_text.splice(caret..caret, "éXZ".chars()); let typed = saved(&h, id); + assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); + assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); checkmark(&mut h); assert_eq!(saved(&h, id), typed, "{label:?}"); - assert!(h.state().ui.type_insertion_style.is_none(), "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); } } } diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index a5c6da8247..b0060e0728 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -27,7 +27,7 @@ const TARGETS: [ChannelTarget; 3] = [ChannelTarget::Alpha(0), ChannelTarget::Lay /// these tests run every kind and target on [`RGB_8`] and visit the other modes once. Sampling the right plane at /// every colour mode x native depth is `destructive_eyedropper`'s, tested without the app in the engine's /// `tone_target_picker.rs` (#15648). The full cross product ran a single test past nextest's 600 s limit on -/// Windows (#15636). The addressed-mask Action regressions below retain their full matrix in separate per-mode tests. +/// Windows (#15636). const RGB_8: (ColorMode, SampleType) = (ColorMode::Rgb, SampleType::U8); /// The keys the hosted adjustment dialog lists beside its engine parameters. @@ -1201,69 +1201,57 @@ fn addressed_mask_session(mode: ColorMode, depth: SampleType, filter: bool) -> ( /// Named/id mask Actions show, sample, preview and edit the addressed layer's own mask without /// switching the selected layer. The matrix includes native raster and Smart Filter masks. -fn review_mask_action_context_matches_the_addressed_layer_for(mode: ColorMode) { +#[test] +fn review_mask_action_context_matches_the_addressed_layer() { let mut h = bench(); - for depth in DEPTHS { - for kind in ["levels", "curves"] { - for filter in [false, true] { - let (source, layer) = addressed_mask_session(mode, depth, filter); - let selectors = [json!(layer.0), json!("Receiver"), json!({"name":"Receiver"})]; - for selector in selectors { - next_case(&mut h, &source, None); - let command = format!("image.adjustments.{kind}"); - let target = if filter { "filterMask" } else { "mask" }; - let raw = json!({"layer":selector,"target":target}); - add_action(h.state_mut(), "Other mask", command.clone(), raw, true); - let original = h.state().session.active().unwrap().doc.clone(); - let active = h.state().session.active().unwrap().active_layer; - let expected = - photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); - play(&mut h, "Other mask"); - assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); - let id = top(&h); - arm(&mut h, "white"); - sample_at(&mut h, 4.0, 4.0); - let p = params(&h); - let want = photocraft_engine::adjust_params::adjustment_eyedropper( - kind, - &json!({}), - photocraft_engine::adjust_params::CurvesEyedropper::White, - [expected; 3], - ColorMode::Grayscale, - ) - .unwrap(); - let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); - assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); - let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); - confirm(&mut h, id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.layers, preview.layers); - assert_eq!(doc.layers[0], original.layers[0]); - assert_eq!(doc.channels, original.channels); - assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99); - assert_eq!(h.state().session.active().unwrap().active_layer, active); - } - } + // Both dialogs with both mask kinds on an RGB document, and a CMYK and a Lab document once. Resolving the address is + // the engine's (`review_picker_reads_the_addressed_mask_layer` runs every selector form in every mode and depth); + // here every form runs on the first layer-mask and filter-mask cases, the name form on the rest. + let mut cases = Vec::new(); + for kind in ["levels", "curves"] { + for filter in [false, true] { + cases.push((RGB_8, kind, filter)); + } + } + cases.extend([((ColorMode::Cmyk, SampleType::U16), "curves", true), ((ColorMode::Lab, SampleType::F32), "levels", false)]); + for (case, ((mode, depth), kind, filter)) in cases.into_iter().enumerate() { + let (source, layer) = addressed_mask_session(mode, depth, filter); + let selectors = [json!("Receiver"), json!(layer.0), json!({"name":"Receiver"})]; + for selector in selectors.into_iter().take(if case < 2 { 3 } else { 1 }) { + next_case(&mut h, &source, None); + let command = format!("image.adjustments.{kind}"); + let target = if filter { "filterMask" } else { "mask" }; + let raw = json!({"layer":selector,"target":target}); + add_action(h.state_mut(), "Other mask", command.clone(), raw, true); + let original = h.state().session.active().unwrap().doc.clone(); + let active = h.state().session.active().unwrap().active_layer; + let expected = photocraft_engine::mask_view_cmds::viewed_mask(original.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0); + play(&mut h, "Other mask"); + assert_eq!(names(&h), [if filter { "Receiver Filter Mask" } else { "Receiver Mask" }]); + let id = top(&h); + arm(&mut h, "white"); + sample_at(&mut h, 4.0, 4.0); + let p = params(&h); + let want = photocraft_engine::adjust_params::adjustment_eyedropper( + kind, + &json!({}), + photocraft_engine::adjust_params::CurvesEyedropper::White, + [expected; 3], + ColorMode::Grayscale, + ) + .unwrap(); + let got = photocraft_engine::adjust_params::from_params(kind, &p, None, ColorMode::Grayscale).unwrap(); + assert_eq!(got, want, "{mode:?} {depth:?} {kind} {target}"); + let preview = filter_dialog::preview_document(&original, active, &command, &p, 1).unwrap(); + confirm(&mut h, id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.layers, preview.layers); + assert_eq!(doc.layers[0], original.layers[0]); + assert_eq!(doc.channels, original.channels); + assert!(photocraft_engine::mask_view_cmds::viewed_mask(doc.layer(layer).unwrap(), filter).unwrap().surface.sample_channel(8, 8, 0) > 0.99); + assert_eq!(h.state().session.active().unwrap().active_layer, active); } } -} - -/// The addressed-mask Action matrix for one document colour mode. -#[test] -fn review_mask_action_context_matches_the_addressed_layer_rgb() { - review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Rgb); -} - -/// The addressed-mask Action matrix for one document colour mode. -#[test] -fn review_mask_action_context_matches_the_addressed_layer_cmyk() { - review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Cmyk); -} - -/// The addressed-mask Action matrix for one document colour mode. -#[test] -fn review_mask_action_context_matches_the_addressed_layer_lab() { - review_mask_action_context_matches_the_addressed_layer_for(ColorMode::Lab); } /// Repairing a missing Action address re-seeds its recorded alias without losing modal context. From ca87f95aec16125bc32f184e6aaf8d75d6decc5b Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 17:50:13 +0100 Subject: [PATCH 81/85] Integration: #15417: keep main's addressed-mask Action cases #15417 brought back the full 108-case addressed-mask matrix, which main trimmed for test time (#15636, #15648); selector forms in every mode and depth stay covered by the engine's review_picker_reads_the_addressed_mask_layer. That is outside #15379's two worker rows, so tone_targets.rs and its nextest entry go back to main. The shortcut matrix split stays. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 90dbe567bb..1217276221 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -68,7 +68,7 @@ threads-required = 2 # over 200 s filter = ''' (package(photocraft-ui-egui) & (test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_canvas) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_layers_row) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_focused_widget) | test(=input::shortcut_dispatch::tests::every_displayed_shortcut_dispatches_from_where_focus_usually_is_opacity_field))) | - (package(photocraft-ui-egui) & (test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_rgb) | test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_cmyk) | test(=tone_targets::review_mask_action_context_matches_the_addressed_layer_lab))) | + (package(photocraft-ui-egui) & test(=tone_targets::review_mask_action_context_matches_the_addressed_layer)) | (package(photocraft-ui-egui) & test(=tone_targets::grayscale_picker_controls_sample_the_plane_and_change_the_visible_curve)) | (package(photocraft-ui-egui) & test(=dialogs::adjust_editors::ui_tests::every_adjustment_layer_edits_through_properties)) | (package(photocraft-ui-egui) & test(=tone_targets::filter_mask_tone_dialogs_preserve_the_target_and_sample_its_own_levels)) From cc31e60bd48803d65d16bcaec5583556d5f66261 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:01:54 +0100 Subject: [PATCH 82/85] Integration: #15429: the arrow-key case accepts whichever row ArrowDown reaches ArrowDown steps to the row below the typed match. Where JetBrains Mono NL is installed (Windows), that row is NL, so the case failed on the font list rather than on the caret path. The test now takes the pending font as the accepted row, checks it matches the typed name and differs from the text's font, and keeps the exact font for Enter and click. Co-Authored-By: Claude Opus 5.5 --- .../src/tools/type_tool/font_commit_tests.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index cfc131d5e6..8b47bc69d3 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -161,8 +161,22 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { h.run(); let before = saved(&h, id); let steps = h.state().session.active().unwrap().history.entries().len(); - let font = FONTS[1 - original]; - choose(&mut h, font, accept); + let requested = FONTS[1 - original]; + choose(&mut h, requested, accept); + // ArrowDown steps to the row below the typed match, which depends on the installed fonts + // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. + let font = h + .state() + .ui + .type_insertion_style + .as_ref() + .map(|s| s.style.font_family.clone()) + .unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); + let font = font.as_str(); + assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); + if accept != "arrow-enter" { + assert_eq!(font, requested, "{label:?}"); + } assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); crate::type_font_preview::set(h.state_mut(), font.into()); From 7bffc1d27149f4f2fea73e205a8643a0b3e4913a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 17:02:37 +0000 Subject: [PATCH 83/85] 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 84/85] 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. From fb372c60110c87107049df8d578987120cddce55 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 19:46:17 +0100 Subject: [PATCH 85/85] Paint tool tests: smoothing off where the measured lag is not under test (#15803) #12246 made the default 10 % smoothing lag the measured one and stopped zero-time repeats from moving the brush. The Mixer release test and the pen tilt preview test painted with that default on real frame times, so the brush no longer reached the release point and the tail landed inside the compared region. Neither test is about smoothing. --- crates/ui-egui/src/canvas/paint_tool/tests.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/paint_tool/tests.rs b/crates/ui-egui/src/canvas/paint_tool/tests.rs index 4498653fda..fb37337064 100644 --- a/crates/ui-egui/src/canvas/paint_tool/tests.rs +++ b/crates/ui-egui/src/canvas/paint_tool/tests.rs @@ -215,7 +215,12 @@ fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { #[test] fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { for failed in [false, true] { - let mut h = harness(mixer_app()); + let mut app = mixer_app(); + // Smoothing off: this is about which points reach the commit, and the Mixer Brush's + // first-use 10 % lag (measured, #11888) would hold the brush short of the release point. + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap(); + let mut h = harness(app); let before = h.state().session.active().unwrap().doc.clone(); let p = |h: &Harness<'static, Box>, x: f64| at(h, x, 30.0); let start = p(&h, 20.0); @@ -371,7 +376,10 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); let ctx = app.ctx().clone(); app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); - let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); + // Smoothing off: the default 10 % lag (measured, #11888) on wall-clock times would leave the + // preview's tail anywhere short of the release, so the comparison below couldn't hold. + let tilt = + json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "smoothing": {"amount": 0.0}, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); app.ui.tool = Tool::Brush; let mut seen = composite_revision(&mut app, &ctx, 0, None); @@ -390,7 +398,6 @@ fn live_stroke_uses_pen_tilt_and_redraws_partially() { let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); - // (The smoothed tail catches up to the end point only when the stroke finishes.) assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); }