From e8c30125539f4f3fe75cc9335a21b729d2c85f48 Mon Sep 17 00:00:00 2001 From: admiralronton Date: Sat, 31 Oct 2026 10:46:53 -0700 Subject: [PATCH 001/385] 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 d487711f1927d82ff391321d27a260f60f869dc7 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:01:33 +0100 Subject: [PATCH 002/385] fix(ui): close canvas menu when the active document changes Reuse the existing document identity reset so Zoom In and Zoom Out cannot apply a point from the previous document. Same-document edits keep the menu. --- crates/ui-egui/src/app/commands.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 9a5621c5be..188a9426ae 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -291,9 +291,9 @@ impl PhotocraftApp { } pub fn sync_views(&mut self) { - // The Paths panel selection belongs to the active document. Ordinary edits replace the - // snapshot and advance its revision; a replaced snapshot without a newer revision is a - // reopened document, even with the same ID. + // The Paths panel selection and canvas context menu belong to the active document. + // Ordinary edits replace the snapshot and advance its revision; a replaced snapshot + // without a newer revision is a reopened document, even with the same ID. let document = self.session.active().map(|st| (st.doc.id, st.revision, std::sync::Arc::downgrade(&st.doc))); let same_document = match (&self.path_document, &document) { (Some((old_id, old_revision, old_source)), Some((id, revision, source))) => old_id == id && (revision > old_revision || old_source.ptr_eq(source)), @@ -302,6 +302,7 @@ impl PhotocraftApp { }; if !same_document { self.ui.selected_path = None; + self.ui.canvas_tool_menu = None; } self.path_document = document; vector_ui::cancel_stale_pen(self); From 20c7feb37bff6d40b0ebf55264f7cb11e0b3d7c4 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:02:01 +0100 Subject: [PATCH 003/385] test(ui): cover canvas menu document switching and tab closure Cover Zoom and Hand menus, ordinary edits in the owning document, replacement of the active slot, and an owning document that survives another tab closing. --- crates/ui-egui/src/view_sync_tests.rs | 38 +++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/ui-egui/src/view_sync_tests.rs b/crates/ui-egui/src/view_sync_tests.rs index 0cae764e62..120715f0b3 100644 --- a/crates/ui-egui/src/view_sync_tests.rs +++ b/crates/ui-egui/src/view_sync_tests.rs @@ -44,3 +44,41 @@ fn every_document_keeps_its_own_view_through_syncs() { assert_eq!(app.ui.views[0].zoom, 3.2, "the first document's view is untouched"); assert_eq!(app.ui.views[1].zoom, 4.0, "the last document's view follows it to its new index"); } + +/// #11325: Zoom In/Out must never use a point right-clicked in another document. +#[test] +fn switching_documents_closes_the_canvas_view_menu() { + for tool in [crate::Tool::Zoom, crate::Tool::Hand] { + let mut app = app_with_two_documents(); + app.ui.tool = tool; + let ctx = egui::Context::default(); + assert!(crate::canvas_tool_menu::open_view(&mut app, &ctx, tool, [10.0, 10.0], [20.0, 20.0])); + app.sync_views(); + assert!(app.ui.canvas_tool_menu.is_some(), "ordinary sync keeps the menu"); + app.run("layer.new.layer", json!({})).unwrap(); + assert!(app.ui.canvas_tool_menu.is_some(), "an edit in the same document keeps the menu"); + assert!(app.session.set_active(0)); + app.sync_views(); + assert!(app.ui.canvas_tool_menu.is_none(), "a document switch closes the old document's menu"); + } +} + +/// A tab closing can put another document at the same index, or move the menu's own document +/// to another index. Follow its identity, not its slot. +#[test] +fn closing_a_tab_keeps_the_canvas_menu_only_for_its_own_document() { + for close_menu_document in [false, true] { + let mut app = app_with_two_documents(); + if close_menu_document { + assert!(app.session.set_active(0)); + app.sync_views(); + } + app.ui.tool = crate::Tool::Hand; + let document = app.session.active().unwrap().doc.id; + assert!(crate::canvas_tool_menu::open_view(&mut app, &egui::Context::default(), crate::Tool::Hand, [10.0, 10.0], [20.0, 20.0])); + app.run("file.close", json!({"document": 0})).unwrap(); + assert_eq!(app.session.active_index(), Some(0), "the survivor occupies the first slot"); + assert_eq!(app.session.active().unwrap().doc.id == document, !close_menu_document); + assert_eq!(app.ui.canvas_tool_menu.is_some(), !close_menu_document, "only a menu for the surviving document stays open"); + } +} From 91dcb83fa64e45ce2c9803bcc2a7eb15426c0b02 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:02:25 +0100 Subject: [PATCH 004/385] docs(ui): record canvas menu dismissal on document changes Updated the context-menu parity contract to reflect changes in canvas menus closing on active document changes. --- docs/context-menu-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 1ef971ef33..56004900e6 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -1,13 +1,13 @@ # Context-menu parity contract -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-21 · **Change:** minor (Crop tool menu on a pending crop, #6561; Zoom tool menu order, #6005; Type tool menu over committed type, #7324; earlier: Path Selection canvas menu, #1056; pasteboard row: the menu exists, #2462) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-04 · **Change:** minor (canvas menus close when the active document changes, #11325; Crop tool menu on a pending crop, #6561; Zoom tool menu order, #6005; Type tool menu over committed type, #7324; earlier: Path Selection canvas menu, #1056; pasteboard row: the menu exists, #2462) · **Target:** Adobe Photoshop 2026 Status: implementation contract, updated 2026-10-09. Scope: canvas, document tabs, and panels. “Right-click” means a secondary pointer click; macOS Control-click should also open the same menu where the platform sends a context-menu gesture. Photoshop changes a context menu with the active tool, selection, and panel item. Adobe documents that principle but does not publish a complete current menu catalog. **Documented** means an Adobe source explicitly names the gesture or action. **Inferred** means a PhotoCraft design target or an item known from a main menu whose presence in a Photoshop context menu still needs a current-product capture. Do not present inferred rows as exact Photoshop menus. [Adobe: panels and menus](https://helpx.adobe.com/photoshop/using/panels-menus.html), [Adobe: shortcuts and context menus](https://helpx.adobe.com/sa_en/photoshop/using/customizing-keyboard-shortcuts.html). ## Dispatch contract 1. Hit-test the target before opening: modal operation/handle, text selection, canvas content, panel row or icon, tab, then empty workspace. A generic canvas menu must not swallow a more specific target. -2. Snapshot the target and selection when the menu opens. A row in an existing multiselection acts on that set; a row outside it becomes the target before its command runs. Apply the same rule to layers, channels, paths, and presets. +2. Snapshot the target and selection when the menu opens. A row in an existing multiselection acts on that set; a row outside it becomes the target before its command runs. Apply the same rule to layers, channels, paths, and presets. Canvas menus close when the active document changes, including when a closed tab leaves another document in its slot (#11325); ordinary edits in the same document keep the menu open. 3. Resolve items from a pure menu model keyed by target kind, active tool, document state, platform, and active operation. The model supplies label, command id, params, enabled state, and reason. Every mutating item dispatches an engine command; view-only items may update shell state. An unavailable feature is disabled with a reason or omitted, never a clickable no-op. 4. Preserve primary-button tool behavior. Secondary click only opens a menu unless a right-button drag gesture or the user's explicit right-erase preference owns the gesture. A drag must not briefly open a menu, and opening a menu must never paint, transform, sample, or commit. 5. Anchor at the pointer and clamp to the viewport; support keyboard context-menu key/Shift+F10 where available, Escape/outside click, separators only between nonempty groups, checked/radio state, keyboard navigation, and screen-reader labels. @@ -100,6 +100,7 @@ Each slice needs pure model tests (including every item dispatching a known comm | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Canvas menus close on an active-document change, so Zoom In/Out cannot reuse another document's clicked point (#11325) | | 2026-10-21 | minor | Crop tool menu on a pending crop (#6561) | | 2026-10-20 | trivial | Zoom tool menu order (#6005) | | 2026-10-18 | minor | Type tool menu over committed type (#7324) | From d06b24f96bd3898d0f4da594ebe07ba49ae85804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 09:02:57 +0100 Subject: [PATCH 005/385] fix(io): GIF export keeps the indexed palette, unused entries and all Saving an Indexed Color document as GIF went through the generic image encoder, which rebuilt the colour table from the colours present in the image. The entries no pixel used were dropped, the survivors changed index and the transparent index moved, so a pixel-art palette did not survive a save even though the picture looked the same. PNG and PSD already wrote the document's own table. Take the GIF save through export_mode_specific next to the palette PNG and BMP, which have the document and its colour table in hand, and encode with the codec's existing indexed GIF writer. Indices come from the document's table, so they pass through unchanged rather than being nearest-colour remapped into a new one. A GIF colour table holds 2^n entries: the writer pads the slots past the document's last entry with black, the way the palette BMP's table is padded, so no used index moves. An RGB-mode document still takes the quantizing path, and an indexed document with no usable table falls back to it rather than failing the save. The indexed route encodes from the document instead of through encode_image, so it now reports the metadata a GIF cannot hold in the words the generic encoder's fidelity warnings use. Tests (crates/io/tests/it/modes.rs): unused entries survive a save and reopening; a 200-entry palette lands in a 256-entry table with its indices intact; every pixel keeps its index at 8/16/32 bits; the transparent index is kept; a saved GIF round-trips unchanged; the metadata warnings; an RGB GIF still quantizes; no usable table falls back; a table with no opaque entry errors instead of writing a blank. --- crates/io/src/flat.rs | 51 ++++++++++-- crates/io/tests/it/modes.rs | 161 ++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 5 +- 3 files changed, 208 insertions(+), 9 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 859ec01eb9..c4fe7f2cd1 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -1673,11 +1673,11 @@ pub fn export_flat_with_renderer( mut renderer: Option<&mut dyn BandRenderer>, ) -> Result { if let Some(mut r) = export_mode_specific(doc, format, opts)? { - // Palette PNG/BMP and Duotone exports render on their own paths before the renderer + // Palette PNG/BMP/GIF and Duotone exports render on their own paths before the renderer // branch: say so, or `--gpu` would silently do nothing for them. if let Some(renderer) = &mut renderer { let why = match doc.mode { - ColorMode::Indexed => "palette (Indexed Color) PNG/BMP export uses the CPU compositor", + ColorMode::Indexed => "palette (Indexed Color) PNG/BMP/GIF export uses the CPU compositor", ColorMode::Duotone => "Duotone export uses the CPU compositor", _ => "this export uses the CPU compositor", }; @@ -2258,16 +2258,44 @@ fn cmyk_image_to_srgb(img: &Image) -> Result { Ok(Image::from_normalized(w, h, layout, sample, &out)?.with_icc(Some(dst.to_bytes().to_vec())).with_meta(img.meta.clone())) } -/// Indexed Color → PNG-8 or an 8-bit BMP with its colour table; Duotone → the inks rendered as RGB. +/// The metadata a GIF cannot hold, worded as the generic encoder's fidelity warnings word it. +/// The indexed route encodes straight from the document instead of through [`encode_image`], so it +/// has to report what that check would have warned about. +fn gif_dropped_metadata(doc: &Document, opts: &ExportOptions) -> Vec { + let mut w = Vec::new(); + if !opts.encode.embed_metadata { + return w; + } + if doc.icc_profile.is_some() && opts.encode.embed_icc { + w.push("ICC profile not supported; it will be dropped".into()); + } + if doc.metadata.exif.is_some() { + w.push("EXIF not supported; it will be dropped".into()); + } + // Export As ▸ Metadata: None already dropped these before the generic encoder got to say so. + if opts.xmp != XmpEmbed::None { + if doc.metadata.xmp.is_some() { + w.push("XMP not supported; it will be dropped".into()); + } + if !doc.metadata.text.is_empty() { + w.push("text metadata not supported; it will be dropped".into()); + } + } + w.push("resolution (DPI) not supported; it will be dropped".into()); + w +} + +/// Indexed Color → PNG-8, an 8-bit BMP or a GIF with the document's colour table; Duotone → the +/// inks rendered as RGB. fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> Result, IoError> { match doc.mode { - ColorMode::Indexed if matches!(format, Format::Png | Format::Bmp) => { + ColorMode::Indexed if matches!(format, Format::Png | Format::Bmp | Format::Gif) => { let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) }; - // PNG transparency belongs to a palette index, not its RGB value. Keep the + // PNG and GIF transparency belongs to a palette index, not its RGB value. Keep the // transparent entry out of opaque lookup, even when it duplicates an opaque colour. - let png_transparent_index = table.transparent.map(usize::from).filter(|_| format == Format::Png); + let transparent_index = table.transparent.map(usize::from).filter(|_| format != Format::Bmp); let (opaque_indices, colors): (Vec, Vec<_>) = - table.colors.iter().copied().enumerate().filter(|(i, _)| Some(*i) != png_transparent_index).map(|(i, c)| (i as u8, c)).unzip(); + table.colors.iter().copied().enumerate().filter(|(i, _)| Some(*i) != transparent_index).map(|(i, c)| (i as u8, c)).unzip(); let opaque = photocraft_doc::ColorTable { colors, transparent: None }; let mut idx = try_buffer(doc.size.area() as usize, 1)?; photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), IoError> { @@ -2290,6 +2318,15 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> } return Ok(Some(ExportResult { bytes, warnings })); } + if format == Format::Gif { + // The whole table in its original order, as the palette PNG and BMP write it: a + // GIF colour table holds 2^n entries, and the writer pads the ones past the + // document's last entry with black, so no used index moves (#11824). + let bytes = codecs::web::encode_gif_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, false)?; + let mut warnings = vec![format!("written as a GIF with the document's colour table ({} colours)", table.colors.len())]; + warnings.extend(gif_dropped_metadata(doc, opts)); + return Ok(Some(ExportResult { bytes, warnings })); + } // Same rule as the ordinary PNG encoder: the resolution goes into `pHYs` with the metadata. let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi)); let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi, opts.encode.png_stereo)?; diff --git a/crates/io/tests/it/modes.rs b/crates/io/tests/it/modes.rs index b1bfff3d30..720ea85beb 100644 --- a/crates/io/tests/it/modes.rs +++ b/crates/io/tests/it/modes.rs @@ -209,3 +209,164 @@ fn indexed_bmp_without_a_usable_table_falls_back_to_rgb() { assert_eq!(u16::from_le_bytes([r.bytes[28], r.bytes[29]]), 24); } } + +/// Entry `i` of `palette` as the normalized RGB an Indexed Color document holds, plus its alpha. +fn entry_rgb(palette: &[[u8; 3]], i: usize) -> [f32; 4] { + let c = palette.get(i).copied().unwrap_or([0, 0, 0]); + [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0] +} + +/// An Indexed Color document, one pixel per palette entry, each holding that entry's colour. +fn indexed_doc(palette: &[[u8; 3]], transparent: Option, depth: SampleType) -> Document { + let mut d = Document::with_background("m", Size::new(palette.len() as u32, 1), ColorMode::Rgb, depth, Color::rgba(0.0, 0.0, 0.0, 1.0)); + d.mode = ColorMode::Indexed; + d.color_table = Some(ColorTable { colors: palette.to_vec(), transparent }); + { + let s = d.layers[0].surface_mut().unwrap(); + for x in 0..palette.len() { + s.write_pixel(x as i32, 0, &entry_rgb(palette, x)); + } + } + d +} + +#[test] +fn indexed_gif_keeps_unused_palette_entries() { + // #11824: a GIF save rebuilt the colour table from the colours present in the image, so the + // entries no pixel used vanished and the rest changed index. Palette PNG and BMP keep the + // document's table; GIF now does the same. + let mut palette = vec![[10, 20, 30], [200, 100, 50]]; + // Reserved entries no pixel uses: pixel art keeps them for later edits and palette swaps. + palette.extend((2..8u8).map(|i| [i, i * 16, 255 - i])); + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: palette.clone(), transparent: None }); + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + assert_eq!(photocraft_codecs::gif_palette(&r.bytes).unwrap().0, palette, "every entry, in the original order"); + let back = photocraft_io::import("x.gif", &r.bytes).unwrap().document; + assert_eq!(back.mode, ColorMode::Indexed); + assert_eq!(back.color_table.as_ref().map(|t| t.colors.clone()), Some(palette), "reopened with the same table"); + let px = back.layers[0].surface().unwrap().rgba(1, 1); + assert_eq!(&px[..3], &[200.0 / 255.0, 100.0 / 255.0, 50.0 / 255.0], "{px:?}"); + assert!(r.warnings.iter().any(|w| w.contains("colour table")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("quantiz")), "the palette was not rebuilt: {:?}", r.warnings); +} + +#[test] +fn indexed_gif_keeps_the_palette_index_of_every_pixel() { + // Each pixel was drawn as one palette entry, so after the save its index must still mean that + // entry rather than the nearest colour of a freshly built table. + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let palette: Vec<[u8; 3]> = (0..9u8).map(|i| [i * 28, (9 - i) * 24, i * 7 + 3]).collect(); + let d = indexed_doc(&palette, None, depth); + let r = photocraft_io::export(&d, "out.gif", &Default::default()).unwrap(); + let table = photocraft_codecs::gif_palette(&r.bytes).unwrap(); + assert_eq!(table.0.get(..palette.len()), Some(&palette[..]), "{depth:?}"); + let back = photocraft_io::import("out.gif", &r.bytes).unwrap().document; + let s = back.layers[0].surface().unwrap(); + for (x, c) in palette.iter().enumerate() { + let px = s.rgba(x as i32, 0); + for k in 0..3 { + assert!((px[k] - f32::from(c[k]) / 255.0).abs() < 1.0 / 255.0, "{depth:?}, index {x}: {px:?} vs {c:?}"); + } + } + } +} + +#[test] +fn indexed_gif_pads_a_200_entry_palette_to_256_entries() { + // A GIF colour table holds 2^n entries. The document's 200 entries keep their slots and the + // rest is padded with black (the palette BMP writer's convention too), so no used index moves. + let palette: Vec<[u8; 3]> = (0..200u16).map(|i| [(i * 7 % 256) as u8, (i * 13 % 256) as u8, (255 - i % 256) as u8]).collect(); + let mut d = Document::with_background("m", Size::new(2, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(0.0, 0.0, 0.0, 1.0)); + d.mode = ColorMode::Indexed; + d.color_table = Some(ColorTable { colors: palette.clone(), transparent: None }); + { + let s = d.layers[0].surface_mut().unwrap(); + s.write_pixel(0, 0, &entry_rgb(&palette, 0)); + s.write_pixel(1, 0, &entry_rgb(&palette, 199)); + } + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + let (colors, _) = photocraft_codecs::gif_palette(&r.bytes).unwrap(); + assert_eq!(colors.len(), 256, "padded to the next power of two"); + assert_eq!(&colors[..200], &palette[..], "the document's entries, in their original order"); + assert!(colors[200..].iter().all(|c| *c == [0, 0, 0]), "the padding holds no palette colours"); + let px = photocraft_io::import("x.gif", &r.bytes).unwrap().document.layers[0].surface().unwrap().rgba(1, 0); + let want = entry_rgb(&palette, 199); + for k in 0..3 { + assert!((px[k] - want[k]).abs() < 1.0 / 255.0, "index 199 still means entry 199: {px:?} vs {:?}", palette[199]); + } +} + +#[test] +fn indexed_gif_keeps_the_transparent_index() { + let mut d = Document::with_background("m", Size::new(2, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(1.0, 0.0, 0.0, 1.0)); + d.mode = ColorMode::Indexed; + d.color_table = Some(ColorTable { colors: vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], transparent: Some(2) }); + d.layers[0].surface_mut().unwrap().write_pixel(1, 0, &[0.0, 0.0, 1.0, 0.0]); + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + assert_eq!(photocraft_codecs::gif_palette(&r.bytes).unwrap().1, Some(2), "the designated transparent index"); + let back = photocraft_io::import("x.gif", &r.bytes).unwrap().document; + assert_eq!(back.color_table.as_ref().unwrap().transparent, Some(2)); + let s = back.layers[0].surface().unwrap(); + assert_eq!(s.rgba(1, 0)[3], 0.0, "the transparent entry stays transparent"); + assert_eq!(s.rgba(0, 0)[3], 1.0, "the opaque pixel keeps entry 0"); +} + +#[test] +fn indexed_gif_round_trips_a_saved_gif() { + // Regression: a GIF opened and saved again keeps its table and its decoded pixels. + let palette = [[10, 20, 30], [200, 100, 50], [7, 8, 9], [0, 255, 0]]; + let bytes = photocraft_codecs::web::encode_gif_indexed(4, 1, &[0, 1, 2, 3], &palette, Some(2), false).unwrap(); + let d = photocraft_io::import("in.gif", &bytes).unwrap().document; + let before = d.color_table.clone(); + let r = photocraft_io::export(&d, "out.gif", &Default::default()).unwrap(); + assert_eq!(photocraft_codecs::gif_palette(&r.bytes), photocraft_codecs::gif_palette(&bytes)); + assert_eq!(photocraft_codecs::decode(&r.bytes).unwrap().data(), photocraft_codecs::decode(&bytes).unwrap().data()); + let back = photocraft_io::import("out.gif", &r.bytes).unwrap().document; + assert_eq!(back.color_table, before, "reopening the save changes nothing"); + assert_eq!(d.color_table, before, "export must not edit the document's table"); +} + +#[test] +fn indexed_gif_warns_about_the_metadata_it_cannot_hold() { + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0]], transparent: None }); + d.metadata.text = vec![("Comment".into(), "kept".into())]; + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("text metadata")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("resolution (DPI)")), "{:?}", r.warnings); +} + +#[test] +fn rgb_gif_still_quantizes_its_colors() { + // Only an Indexed Color document keeps its table: an RGB GIF is still quantized as before. + let d = doc(ColorMode::Rgb); + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("quantized")), "{:?}", r.warnings); + assert!(photocraft_codecs::gif_palette(&r.bytes).unwrap().0.contains(&[255, 0, 0]), "a table of the colours present"); + assert_eq!(photocraft_io::import("x.gif", &r.bytes).unwrap().document.mode, ColorMode::Indexed); +} + +#[test] +fn indexed_gif_without_a_usable_table_falls_back_to_rgb() { + // As with the palette BMP: no table (or one past 256 entries) keeps the quantizing path + // rather than failing the save. + for table in [None, Some(ColorTable { colors: vec![[0; 3]; 257], transparent: None })] { + let mut d = doc(ColorMode::Indexed); + d.color_table = table; + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + assert!(!r.bytes.is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("quantized")), "{:?}", r.warnings); + } +} + +#[test] +fn indexed_gif_rejects_opaque_pixels_without_an_opaque_entry() { + // Same rule as the palette PNG: with only the transparent entry left, an opaque pixel has + // nothing to point at, and the save says so instead of writing a GIF that shows nothing. + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: vec![[255, 0, 0]], transparent: Some(0) }); + let err = photocraft_io::export(&d, "out.gif", &Default::default()).unwrap_err(); + assert!(matches!(err, photocraft_io::IoError::Unsupported(_)), "{err}"); + assert!(err.to_string().contains("no opaque entry"), "{err}"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bc3c84a524..daaa0f1523 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-07 · **Change:** minor (GIF: Indexed Color documents save with the document's own colour table, unused entries and transparent index included, #11824; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -29,7 +29,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, YCbCr read as RGB (JPEG-compressed with subsampled chroma, or uncompressed without subsampling; #10316), BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); TIFF Options on Save As and Save a Copy (Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency, Discard Layers and Save a Copy; scripts pass `tiffCompression`, `tiffTransparency`, `tiffPyramid`, `tiffLayers`; #8827), no JPEG compression, Pixel Order or Byte Order (the encoder writes interleaved samples in the machine's byte order); undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); Save Transparency on keeps the transparency as the first extra sample ahead of the channels (a layered file marks it with `MTrn`, as Photoshop does), off mattes on white; unset, it is kept only without alpha or spot channels | | JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); File › Save, Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte, progressive Scans (3–5) or size preview | | PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) | -| GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done | +| GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Indexed Color documents save with the document's own colour table, unused entries and transparent index included, and pixel indices unchanged (#11824). Per-frame delays and keeping the frames in `.pcraft` are not done | | BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode and Indexed Color documents save as palette BMPs (no transparency) | | WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP; Save keeps an opened file lossy (at its quality) or lossless (#2399); Save for Web (Legacy) writes it too, lossy at its Quality or lossless, a format Photoshop's legacy dialog lacks (#6391). File › Open keeps an animation's first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the durations (#1198) | | AVIF | R/W | no (#463) | optional feature, off by default | | @@ -151,6 +151,7 @@ The original reference entry retains its source date and historical totals; curr | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | GIF: an Indexed Color document saves with its own colour table instead of a palette rebuilt from the colours present, so unused entries, the entry order, the index-to-colour relationship and the transparent index survive File › Save As and Save a Copy (#11824). GIF colour tables hold 2^n entries: the document's entries keep their slots and the rest is padded with black, as the palette BMP table is. An RGB document's GIF still quantizes, and Save for Web still rebuilds the palette when asked | | 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). | | 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | | 2026-11-01 | minor | Recorded direct Gradient Map and Lab-range Replace Color load, play and retain their measured settings on save; unsupported forms remain preserved (part of #10607). | From dbc4a78147719cc1bd52192995ac6e795d842456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 13:40:52 +0100 Subject: [PATCH 006/385] docs: regenerate the scorecard after merging main `cargo xtask scorecard` on the merged tree counts 193 `Preferences` leaves where the committed doc still says 192: main's #11322 added the pref `group_tools` without regenerating. The shell reads it, so only the total moves and the ten unread entries stay as they were. Nothing in this PR touches preferences; the regenerated file has the same line count and two changed numbers, and CI checks that the committed one matches the tree. --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index c199c30e90..f27b45b9fb 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 192 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 193 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 192** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 193** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 348af93e09698bbf24202b01537cab49492a1006 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 15:40:22 +0100 Subject: [PATCH 007/385] Regenerate the scorecard after merging main --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index f27b45b9fb..7e92243bf8 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 193 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 193** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 194** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 9bf5fb17d180e121b9657b7bdd0e96be1f25d12e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 07:48:38 -0800 Subject: [PATCH 008/385] Add a contextual task bar to Free Transform --- crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/control/inspect.rs | 2 +- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/tools.rs | 1 + .../ui-egui/src/tools/transform_task_bar.rs | 89 ++++++++++ .../ui-egui/src/transform_task_bar_tests.rs | 166 ++++++++++++++++++ 6 files changed, 261 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/tools/transform_task_bar.rs create mode 100644 crates/ui-egui/src/transform_task_bar_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ac471a9269..eca78e6779 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1430,6 +1430,7 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut // above, the stored camera wins over this frame's copy, or the write-back drops it. let before = app.ui.views.get(idx).cloned(); crate::crop_task_bar::draw(app, ui, xf); + crate::transform_task_bar::draw(app, ui, xf); if let Some(now) = app.ui.views.get(idx) && Some(now) != before.as_ref() { diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 9522088656..a9fc910edf 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -31,7 +31,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { dialogs.extend(crate::discard_ui::inspect(app)); // 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)); + let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app) || crate::transform_task_bar::eligible(app)); json!({ "window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()}, "scratch": photocraft_raster::spill::stats(), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 81b981fa55..b8ec40aec2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -320,6 +320,7 @@ pub use tools::stroke_trail; pub use tools::symmetry_ui; use tools::tool_reset; pub use tools::transform_fx; +pub use tools::transform_task_bar; pub use tools::transform_tex; pub use tools::transform_tool; use tools::type_font_preview; @@ -836,6 +837,8 @@ mod transform_fx_tests; #[cfg(test)] mod transform_commit_click_tests; +#[cfg(test)] +mod transform_task_bar_tests; #[cfg(test)] mod layer_props_ui_tests; diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 9878bf41a4..f9967bb036 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -47,6 +47,7 @@ pub mod stroke_trail; pub mod symmetry_ui; pub(super) mod tool_reset; pub mod transform_fx; +pub mod transform_task_bar; pub mod transform_tex; pub mod transform_tool; pub(super) mod type_font_preview; diff --git a/crates/ui-egui/src/tools/transform_task_bar.rs b/crates/ui-egui/src/tools/transform_task_bar.rs new file mode 100644 index 0000000000..4cf3e4545d --- /dev/null +++ b/crates/ui-egui/src/tools/transform_task_bar.rs @@ -0,0 +1,89 @@ +//! The contextual task bar for an open Free Transform box (#11104). + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::{Tool, TransformSession}; +use crate::widgets::{self, task_bar}; + +enum Action { + Preset(&'static str), + Cancel, + Done, +} + +/// Crop keeps its own bar. Warp, Transform Selection and Content-Aware Scale use their own controls. +fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { + if !app.ui.panels.context_task_bar + || app.ui.tool == Tool::Crop + || !app.ui.dialogs.is_empty() + || app.session.active().is_none() + || crate::transform_tool::committing(app).is_some() + { + return None; + } + app.ui.transform.as_ref().filter(|t| t.warp.is_none() && !t.selection && t.content_aware.is_none()) +} + +/// Whether the shared task-bar rect belongs to an open Free Transform box. +pub fn eligible(app: &PhotocraftApp) -> bool { + open_box(app).is_some() +} + +/// Place the shared bar below the box's current screen bounds on the active canvas tile. +pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { + let Some(transform) = open_box(app) else { return }; + let corners = transform.quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); + let anchor = egui::Rect::from_points(&corners); + let ctx = ui.ctx().clone(); + let mut place = app.ui.panels.task_bar; + let shown = task_bar::show(&ctx, &mut place, anchor, xf.rect, contents); + app.ui.panels.task_bar = place; + let Some(shown) = shown else { return }; + if shown.hide { + app.ui.panels.context_task_bar = false; + return; + } + match shown.inner { + Some(Action::Preset(id)) => { + if let Err(error) = crate::menus::invoke(app, &ctx, id, json!({})) { + app.ui.status = error; + app.ui.status_error = true; + } + } + Some(Action::Cancel) => crate::transform_tool::cancel(app), + Some(Action::Done) => crate::transform_tool::commit(app), + None => {} + } + if eligible(app) { + let r = shown.rect; + app.ui.task_bar_shown = Some([r.min.x, r.min.y, r.max.x, r.max.y]); + } +} + +/// Draw presets in the measured order, with the shared menu before Cancel and Done. +fn contents(ui: &mut egui::Ui, more: &mut task_bar::MoreMenu) -> Option { + let mut action = None; + for (icon, label, id) in [ + ("rotate-ccw", tl!("Rotate 90° Counter Clockwise"), "edit.transform.rotate90Ccw"), + ("rotate-cw", tl!("Rotate 90° Clockwise"), "edit.transform.rotate90Cw"), + ] { + if crate::icons::button_with_icon_size_tip(ui, icon, task_bar::BUTTON, 14.0, false, label, false).clicked() { + action = Some(Action::Preset(id)); + } + } + for (label, id) in [(tl!("Flip Horizontal"), "edit.transform.flipHorizontal"), (tl!("Flip Vertical"), "edit.transform.flipVertical")] { + if ui.button(label).clicked() { + action = Some(Action::Preset(id)); + } + } + more.show(ui); + if widgets::secondary_button(ui, tl!("Cancel"), 0.0).clicked() { + action = Some(Action::Cancel); + } + if widgets::primary_button(ui, tl!("Done"), 0.0).clicked() { + action = Some(Action::Done); + } + action +} diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs new file mode 100644 index 0000000000..1f01f537ca --- /dev/null +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -0,0 +1,166 @@ +//! Free Transform's contextual task bar through the real canvas and existing commands. + +use egui::{Key, Rect, pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::transform_undo_tests::{begin, harness}; + +type AppHarness = Harness<'static, PhotocraftApp>; + +/// Settle the floating area's measured size before exercising its controls. +fn open_box() -> AppHarness { + let mut h = harness(); + begin(&mut h); + h.run_steps(4); + h +} + +/// Send a synchronous command through the same control path as the offscreen example. +fn control(h: &mut AppHarness, method: &str, params: Value) -> Value { + let ctx = h.ctx.clone(); + let (request, _reply) = ControlRequest::new(method, params); + let Outcome::Done(reply) = handle(h.state_mut(), &ctx, &request) else { panic!("{method} should reply immediately") }; + assert_eq!(reply["ok"], true, "{method}: {reply}"); + reply["result"].clone() +} + +/// Read the bar's current visibility and position through the public inspection route. +fn bar(h: &mut AppHarness) -> Value { + control(h, "ui.inspect", json!({}))["taskBar"].clone() +} + +/// Count committed document edits, excluding changes made only inside the open box. +fn history(h: &AppHarness) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// Click the actual accessible widget and allow the canvas to redraw. +fn click(h: &mut AppHarness, label: &str) { + h.get_by_label(label).click(); + h.run_steps(4); +} + +/// Each preset must match the real right-click entry and keep the document history untouched. +#[test] +fn transform_task_bar_presets_match_the_context_menu() { + for (label, id) in [ + ("Rotate 90° Counter Clockwise", "edit.transform.rotate90Ccw"), + ("Rotate 90° Clockwise", "edit.transform.rotate90Cw"), + ("Flip Horizontal", "edit.transform.flipHorizontal"), + ("Flip Vertical", "edit.transform.flipVertical"), + ] { + let mut toolbar = open_box(); + let mut menu = open_box(); + let before = toolbar.state().ui.transform.as_ref().unwrap().quad; + let (toolbar_history, menu_history) = (history(&toolbar), history(&menu)); + click(&mut toolbar, label); + control(&mut menu, "ui.pointer", json!({"button": "secondary", "events": [{"kind": "down", "x": 150, "y": 130}, {"kind": "up", "x": 150, "y": 130}]})); + control(&mut menu, "ui.context.choose", json!({"id": id})); + let quad = toolbar.state().ui.transform.as_ref().unwrap().quad; + assert_ne!(quad, before, "{label}"); + assert_eq!(quad, menu.state().ui.transform.as_ref().unwrap().quad, "{label}"); + assert_eq!(history(&toolbar), toolbar_history); + assert_eq!(history(&menu), menu_history); + } +} + +/// Done commits once like Enter, while Cancel discards the box like Escape. +#[test] +fn transform_task_bar_done_and_cancel_match_the_keys() { + for (label, key, edits) in [("Done", Key::Enter, 1), ("Cancel", Key::Escape, 0)] { + let mut toolbar = open_box(); + let mut keys = open_box(); + for h in [&mut toolbar, &mut keys] { + click(h, "Rotate 90° Clockwise"); + } + let (toolbar_history, key_history) = (history(&toolbar), history(&keys)); + click(&mut toolbar, label); + keys.key_press(key); + keys.run_steps(4); + assert!(toolbar.state().ui.transform.is_none() && keys.state().ui.transform.is_none(), "{label}"); + assert_eq!(history(&toolbar), toolbar_history + edits); + assert_eq!(history(&keys), key_history + edits); + assert_eq!(bar(&mut toolbar)["visible"], false); + } +} + +/// The unpinned bar stays centered eleven points below the actual quad on screen. +#[test] +fn transform_task_bar_tracks_the_rotated_quad() { + let mut h = open_box(); + for turn in [false, true] { + if turn { + click(&mut h, "Rotate 90° Clockwise"); + } + let app = h.state(); + let view = &app.ui.views[0]; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: view.zoom, + center: view.center, + flip: app.ui.view.flip_horizontal, + rotation: view.rotation, + aspect: app.ui.view.display_aspect(), + }; + let quad = app.ui.transform.as_ref().unwrap().quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); + let anchor = Rect::from_points(&quad); + let [x0, y0, x1, y1] = app.ui.task_bar_shown.unwrap(); + let shown = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)); + assert!((shown.center().x - anchor.center().x).abs() <= 1.0, "{shown:?} below {anchor:?}"); + assert!((shown.top() - anchor.bottom() - crate::widgets::task_bar::GAP).abs() <= 1.0, "{shown:?} below {anchor:?}"); + assert_eq!(bar(&mut h)["visible"], true); + } +} + +/// Warp and Content-Aware Scale keep their own controls, and the Crop bar still draws. +#[test] +fn transform_task_bar_keeps_warp_content_aware_scale_and_crop_separate() { + let mut warp = open_box(); + control(&mut warp, "ui.menu.invoke", json!({"id": "edit.transform.warp"})); + warp.run_steps(4); + assert!(warp.state().ui.transform.as_ref().unwrap().warp.is_some()); + assert_eq!(bar(&mut warp)["visible"], false); + + let mut scale = harness(); + control(&mut scale, "ui.menu.invoke", json!({"id": "edit.contentAwareScale"})); + scale.run_steps(4); + assert!(scale.state().ui.transform.as_ref().unwrap().content_aware.is_some()); + assert_eq!(bar(&mut scale)["visible"], false); + + let mut crop = harness(); + control(&mut crop, "ui.set", json!({"tool": "crop"})); + crop.state_mut().ui.crop_rect = Some([100.0, 100.0, 200.0, 160.0]); + crop.run_steps(4); + assert!(crate::crop_task_bar::eligible(crop.state())); + assert!(!crate::transform_task_bar::eligible(crop.state())); + assert_eq!(bar(&mut crop)["visible"], true); +} + +/// The shared menu pins, resets and hides the bar, and the Window command restores it. +#[test] +fn transform_task_bar_uses_the_shared_menu_and_window_toggle() { + let mut h = open_box(); + click(&mut h, "More options"); + click(&mut h, "Pin bar position"); + assert_eq!(bar(&mut h)["pinned"], true); + assert!(h.state().ui.panels.task_bar.at.is_some()); + + click(&mut h, "More options"); + click(&mut h, "Reset bar position"); + assert_eq!(bar(&mut h)["pinned"], false); + assert!(h.state().ui.panels.task_bar.at.is_none()); + + click(&mut h, "More options"); + click(&mut h, "Hide bar"); + assert_eq!(bar(&mut h)["enabled"], false); + assert_eq!(bar(&mut h)["visible"], false); + assert!(h.state().ui.transform.is_some()); + control(&mut h, "ui.menu.invoke", json!({"id": "window.panel.contextualTaskBar"})); + h.run_steps(4); + assert_eq!(bar(&mut h)["visible"], true); +} 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 009/385] 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 ff22990c027f9833c305546d29441b18da10886a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 08:43:20 -0800 Subject: [PATCH 010/385] Keep Free Transform task bar state tied to its action and document --- .../ui-egui/src/tools/transform_task_bar.rs | 18 +++--- .../ui-egui/src/transform_task_bar_tests.rs | 62 +++++++++++++++++++ 2 files changed, 72 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_task_bar.rs b/crates/ui-egui/src/tools/transform_task_bar.rs index 4cf3e4545d..efda04fadc 100644 --- a/crates/ui-egui/src/tools/transform_task_bar.rs +++ b/crates/ui-egui/src/tools/transform_task_bar.rs @@ -15,10 +15,12 @@ enum Action { /// Crop keeps its own bar. Warp, Transform Selection and Content-Aware Scale use their own controls. fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { + let active = app.session.active()?; + let preview = app.transform_preview.as_ref()?; if !app.ui.panels.context_task_bar || app.ui.tool == Tool::Crop || !app.ui.dialogs.is_empty() - || app.session.active().is_none() + || preview.doc.id != active.doc.id || crate::transform_tool::committing(app).is_some() { return None; @@ -41,10 +43,6 @@ pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { let shown = task_bar::show(&ctx, &mut place, anchor, xf.rect, contents); app.ui.panels.task_bar = place; let Some(shown) = shown else { return }; - if shown.hide { - app.ui.panels.context_task_bar = false; - return; - } match shown.inner { Some(Action::Preset(id)) => { if let Err(error) = crate::menus::invoke(app, &ctx, id, json!({})) { @@ -56,10 +54,14 @@ pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { Some(Action::Done) => crate::transform_tool::commit(app), None => {} } - if eligible(app) { - let r = shown.rect; - app.ui.task_bar_shown = Some([r.min.x, r.min.y, r.max.x, r.max.y]); + if shown.hide { + app.ui.panels.context_task_bar = false; } + // An action in an extra window can invalidate the rect written by the main canvas. + app.ui.task_bar_shown = eligible(app).then(|| { + let r = shown.rect; + [r.min.x, r.min.y, r.max.x, r.max.y] + }); } /// Draw presets in the measured order, with the shared menu before Cancel and Done. diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 1f01f537ca..9f1bba829a 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -164,3 +164,65 @@ fn transform_task_bar_uses_the_shared_menu_and_window_toggle() { h.run_steps(4); assert_eq!(bar(&mut h)["visible"], true); } + +/// A switch before the next canvas pass must not expose the previous document's Done action. +#[test] +fn transform_task_bar_ignores_a_foreign_preview_after_a_document_switch() { + let mut h = harness(); + h.state_mut().run("file.new", json!({"width": 400, "height": 300})).unwrap(); + h.state_mut().run("document.activate", json!({"document": 0})).unwrap(); + begin(&mut h); + h.run_steps(4); + let owner = h.state().transform_preview.as_ref().unwrap().doc.id; + let quad = h.state().ui.transform.as_ref().unwrap().quad; + assert_eq!(bar(&mut h)["visible"], true); + + control(&mut h, "ui.menu.invoke", json!({"id": "window.nextDocument"})); + assert_ne!(h.state().session.active().unwrap().doc.id, owner); + assert_eq!(h.state().transform_preview.as_ref().unwrap().doc.id, owner); + assert_eq!(bar(&mut h)["visible"], false); + + // Deliver a click to the old widget before the harness redraws the new document's canvas. + h.get_by_label("Done").click_accesskit(); + h.run_steps(1); + assert_eq!(h.state().transform_preview.as_ref().unwrap().doc.id, owner); + assert_eq!(h.state().ui.transform.as_ref().unwrap().quad, quad); +} + +/// Accessibility can deliver Hide and Done during the same pass. +#[test] +fn transform_task_bar_commits_when_done_and_hide_arrive_together() { + let mut h = open_box(); + click(&mut h, "Rotate 90° Clockwise"); + let edits = history(&h); + click(&mut h, "More options"); + + h.get_by_label("Hide bar").click_accesskit(); + h.get_by_label("Done").click_accesskit(); + h.run_steps(4); + + assert!(!h.state().ui.panels.context_task_bar); + assert!(h.state().ui.transform.is_none()); + assert_eq!(history(&h), edits + 1); +} + +/// A Crop frame created synchronously after Cancel cannot inherit the Transform rect. +#[test] +fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { + let mut h = open_box(); + assert!(bar(&mut h)["rect"].is_array()); + h.get_by_label("Cancel").click_accesskit(); + h.run_steps(1); + assert!(h.state().ui.transform.is_none()); + + // No UI pass between the Crop request and inspection. + control( + &mut h, + "ui.pointer", + json!({"tool": "crop", "events": [{"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]}), + ); + assert!(crate::crop_task_bar::eligible(h.state())); + let crop_bar = bar(&mut h); + assert_eq!(crop_bar["visible"], false); + assert!(crop_bar["rect"].is_null()); +} From f3cd0002407f7bee5bf3a2ab51a0deae78edcf96 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 08:47:59 -0800 Subject: [PATCH 011/385] Test Free Transform task bar at the action pass boundary --- .../ui-egui/src/transform_task_bar_tests.rs | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 9f1bba829a..eb462bd835 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -182,10 +182,6 @@ fn transform_task_bar_ignores_a_foreign_preview_after_a_document_switch() { assert_eq!(h.state().transform_preview.as_ref().unwrap().doc.id, owner); assert_eq!(bar(&mut h)["visible"], false); - // Deliver a click to the old widget before the harness redraws the new document's canvas. - h.get_by_label("Done").click_accesskit(); - h.run_steps(1); - assert_eq!(h.state().transform_preview.as_ref().unwrap().doc.id, owner); assert_eq!(h.state().ui.transform.as_ref().unwrap().quad, quad); } @@ -210,9 +206,32 @@ fn transform_task_bar_commits_when_done_and_hide_arrive_together() { #[test] fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { let mut h = open_box(); - assert!(bar(&mut h)["rect"].is_array()); - h.get_by_label("Cancel").click_accesskit(); - h.run_steps(1); + let prior_rect = h.state().ui.task_bar_shown.unwrap(); + let cancel = h.get_by_label("Cancel").rect().center(); + let ctx = h.ctx.clone(); + let mut input = h.input().clone(); + input.events = vec![ + egui::Event::PointerMoved(cancel), + egui::Event::PointerButton { pos: cancel, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerButton { pos: cancel, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ]; + let app = h.state_mut(); + let view = &app.ui.views[0]; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: view.zoom, + center: view.center, + flip: app.ui.view.flip_horizontal, + rotation: view.rotation, + aspect: app.ui.view.display_aspect(), + }; + let _ = ctx.run_ui(input, |ui| { + if app.ui.transform.is_some() { + // Model the main canvas recording its rect before the extra window handles Cancel. + app.ui.task_bar_shown = Some(prior_rect); + crate::transform_task_bar::draw(app, ui, &xf); + } + }); assert!(h.state().ui.transform.is_none()); // No UI pass between the Crop request and inspection. From 3fb7a01e89df2df123c5d991696d05ecc25eb444 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 18:26:58 -0800 Subject: [PATCH 012/385] Document Free Transform task bar eligibility and actions --- crates/ui-egui/src/tools/transform_task_bar.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_task_bar.rs b/crates/ui-egui/src/tools/transform_task_bar.rs index efda04fadc..bb8e159698 100644 --- a/crates/ui-egui/src/tools/transform_task_bar.rs +++ b/crates/ui-egui/src/tools/transform_task_bar.rs @@ -1,4 +1,11 @@ //! The contextual task bar for an open Free Transform box (#11104). +//! +//! The active document must own the transform preview. The bar is hidden when the shared +//! task bar is disabled, a dialog is open, or the transform is committing. Crop, Warp, +//! Transform Selection and Content-Aware Scale keep their own controls. +//! +//! The bar follows the box's screen bounds on the active canvas. It uses the same placement +//! and pin, reset and hide menu as Crop. The Window menu can show the shared bar again. use serde_json::json; @@ -28,12 +35,15 @@ fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { app.ui.transform.as_ref().filter(|t| t.warp.is_none() && !t.selection && t.content_aware.is_none()) } -/// Whether the shared task-bar rect belongs to an open Free Transform box. +/// Whether the inspector may report the shared task-bar rectangle for Free Transform. +/// This checks current eligibility without changing placement or the transform. pub fn eligible(app: &PhotocraftApp) -> bool { open_box(app).is_some() } -/// Place the shared bar below the box's current screen bounds on the active canvas tile. +/// Draw the shared bar, persist its placement and apply the selected action before Hide. +/// Report failed preset commands in the status bar. After the action, publish the rectangle +/// for inspection while Free Transform remains eligible, or clear it if the action closed or hid it. pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { let Some(transform) = open_box(app) else { return }; let corners = transform.quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); From 33c2c1128ab99b81df7356f1d06a3527792d01fd Mon Sep 17 00:00:00 2001 From: kirubhakaran12 <27127513+kirubhakaran12@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:35:08 +0530 Subject: [PATCH 013/385] fix(engine): stack duplicated layers above the originals (#11915) Duplicating several selected layers inserted each copy directly above its own original, interleaving copies with originals. The copies of sibling layers now form one block above the topmost selected original, in the originals' order, as Photoshop does. A selection spanning groups keeps a copy above each original so no copy leaves its group, and artboard copies keep their existing placement beside their boards. Layer via Copy shares this path, so its multi-layer ordering changes with it; its test now asserts the new order. --- crates/engine/src/cmd/edit_cmds/tests.rs | 13 +++--- .../src/cmd/layer_multi_cmds/structure.rs | 32 +++++++++++-- .../engine/src/cmd/layer_multi_cmds/tests.rs | 46 +++++++++++++++++++ 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/edit_cmds/tests.rs b/crates/engine/src/cmd/edit_cmds/tests.rs index 089a9873ba..f668efcfeb 100644 --- a/crates/engine/src/cmd/edit_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_cmds/tests.rs @@ -715,8 +715,9 @@ fn layer_via_copy_and_cut_deselect_in_one_step() { } /// #2777: with several layers selected and no pixel selection, Layer via Copy (Cmd+J) copies -/// every selected layer in one step, each copy above its original and the copies selected. -/// With a pixel selection it still copies the active layer's selected pixels only. +/// every selected layer in one step, the copies stacked above the topmost selected original in +/// the originals' order (#11915), and the copies selected. With a pixel selection it still copies +/// the active layer's selected pixels only. #[test] fn layer_via_copy_duplicates_every_selected_layer() { let mut s = session(); @@ -728,11 +729,9 @@ fn layer_via_copy_duplicates_every_selected_layer() { s.execute("layer.new.layerViaCopy", json!({})).unwrap(); let st = s.active().unwrap(); let ids: Vec = st.doc.layers.iter().map(|l| l.id).collect(); - assert_eq!(ids.len(), 5, "background, a, a copy, b, b copy"); - assert_eq!((ids[1], ids[3]), (a, b), "each copy sits above its original"); - let mut selected = st.selected_layers(); - selected.sort_by_key(|l| l.0); - assert_eq!(selected, vec![ids[2], ids[4]], "the copies become the selection"); + assert_eq!(ids.len(), 5, "background, a, b, a copy, b copy"); + assert_eq!((ids[1], ids[2]), (a, b), "the originals keep their order"); + assert_eq!(st.selected_layers(), vec![ids[3], ids[4]], "the copies become the selection, in document order"); assert_eq!(st.history.past_len(), steps + 1, "one undo step"); assert!(s.undo()); s.execute("layer.select", json!({"layer": b.0})).unwrap(); diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 66974e1dd2..5d0cc3ace2 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -264,7 +264,9 @@ pub fn delete_selected(s: &mut Session) -> Result { Ok(json!({"deleted": sel.len()})) } -/// Duplicate Layer with several layers selected: each copy goes above its original and the +/// Duplicate Layer with several layers selected: the copies of sibling layers form one block above +/// the topmost selected original, in the originals' order, as Photoshop does (#11915); a selection +/// spanning groups keeps each copy directly above its original, so no copy leaves its group. The /// copies become the selection. Artboard copies go beside their boards unless `in_place` /// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses /// this path, #2777). @@ -273,13 +275,23 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul let old_active = s.active().and_then(|d| d.active_layer); let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); let (copies, active) = s.edit(label, |doc, active| { + let ids = top_level(doc, &sel); + // Copies of sibling layers go above the topmost selected original as one block, keeping + // their originals' order, as Photoshop does (#11915). Layers from different groups keep a + // copy directly above each original, so no copy leaves its group; artboard copies are + // placed beside their boards one by one (below). + let block = same_siblings(doc, &ids) && !ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())); + let mut above = ids.last().copied(); let mut copies = Vec::new(); let mut new_active = None; - for id in top_level(doc, &sel) { + for id in ids { // Match the single-layer duplicate path: Background copies become // ordinary layers, while normal copies retain their original locks. let dup = crate::commands::layer_copy(doc, id, add_copy)?; - let nid = doc.insert_above(Some(id), dup); + let nid = if block { doc.insert_above(above, dup) } else { doc.insert_above(Some(id), dup) }; + if block { + above = Some(nid); + } if !in_place { crate::artboard_cmds::place_copy(doc, nid)?; } @@ -298,6 +310,20 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) } +/// True when two or more layers in `ids` all share one parent (they are siblings), so copies of +/// them can be inserted as one block above the topmost of them (#11915). Fewer than two ids, or an +/// id that is not in `doc`, means false. +fn same_siblings(doc: &Document, ids: &[LayerId]) -> bool { + let [first, rest @ ..] = ids else { return false }; + let Some(mut parent) = doc.path_of(*first) else { return false }; + parent.pop(); + rest.iter().all(|id| { + let Some(mut path) = doc.path_of(*id) else { return false }; + path.pop(); + path == parent + }) +} + /// Link groups of fresh copies, as the reference application does (measured, #11217): a copy of /// one layer alone (Duplicate, Layer via Copy) joins its original's link group. With several /// layers copied, the copies of several layers of one link group are linked to each other under a diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index fc39d25f5d..5e6fa43cd8 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -1401,6 +1401,52 @@ fn selection_pruned_after_delete_and_undo() { assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); } +/// #11915: duplicating several layers stacks the copies above the topmost selected original, in +/// the originals' order, as Photoshop does, instead of putting each copy directly above its own +/// original (which interleaved copies and originals). +#[test] +fn duplicating_several_layers_stacks_the_copies_above_the_originals() { + let mut s = session(8); + let background = doc(&s).layers[0].id; + let lower = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let upper = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + // Bottom to top: Background, lower, upper. + select_all(&mut s, &[background, lower]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + let copies: Vec = r["layers"].as_array().unwrap().iter().map(|v| LayerId(v.as_u64().unwrap())).collect(); + assert_eq!(copies.len(), 2); + // The copies keep the originals' order and sit as one block above the topmost selected + // original; upper, which is not selected, stays on top. + let stack: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); + assert_eq!(stack, vec![background, lower, copies[0], copies[1], upper], "the copies are a block above the originals"); + assert_eq!(sel(&s).len(), 2); + assert!(sel(&s).iter().all(|id| copies.contains(id))); + // One undo puts the stack back. + assert!(s.undo()); + assert_eq!(doc(&s).layers.iter().map(|l| l.id).collect::>(), vec![background, lower, upper]); +} + +/// #11915: only sibling layers get one block of copies. A selected layer inside a group keeps its +/// copy in that group, directly above the original, even when a top-level layer is selected too, +/// so no copy ever leaves its group. +#[test] +fn duplicating_layers_from_different_parents_keeps_each_copy_in_its_group() { + let mut s = session(8); + let background = doc(&s).layers[0].id; + let inner = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let gid = LayerId(s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().unwrap()); + let outer = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[inner, outer]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + let copies: Vec = r["layers"].as_array().unwrap().iter().map(|v| LayerId(v.as_u64().unwrap())).collect(); + assert_eq!(copies.len(), 2); + let children: Vec = doc(&s).layer(gid).unwrap().children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![inner, copies[0]], "the grouped layer's copy stays in the group"); + let stack: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); + assert_eq!(stack, vec![background, gid, outer, copies[1]], "the top-level layer's copy stays at the root"); + assert!(sel(&s).iter().all(|id| copies.contains(id))); +} + #[test] fn duplicate_hide_lock_and_reverse_selected() { let mut s = session(8); From 0284ab27dd06809f38d3393df81d5414ed1f0f4a Mon Sep 17 00:00:00 2001 From: kirubhakaran12 <27127513+kirubhakaran12@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:35:08 +0530 Subject: [PATCH 014/385] Credit kirubhakaran12 by their GitHub profile name --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index a2ead57598..20b8aabd8c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -315,3 +315,6 @@ sync_github_name = false [people.davidvhk] real_name = "David Vanhoucke" sync_github_name = true + +[people.kirubhakaran12] +sync_github_name = true From 8d1a37a6f81d28a52eaf302f61ece229abe35dc1 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 22:17:09 -0600 Subject: [PATCH 015/385] Mixer Brush: a load lasts for a length of stroke, not a number of dabs (#11943) Below 100 % Load the reservoir now paints at full strength for a stroke length set by Load (390 px at 1 %, 570 px at 5 %, a power law between and above), then steps down to about 68 % alpha and fades with the distance travelled. Load 100 % never runs out. The distance is measured between dab centres and restarts with each stroke. --- .../src/cmd/brush_cmds/mixer_live_tests.rs | 4 +- crates/engine/src/cmd/brush_cmds/tests.rs | 18 ++-- crates/paint/src/lib.rs | 2 + crates/paint/src/mixer.rs | 57 +++++++++++- crates/paint/src/mixer/reference_tests.rs | 12 ++- crates/paint/src/mixer_load_supply_tests.rs | 90 +++++++++++++++++++ 6 files changed, 169 insertions(+), 14 deletions(-) create mode 100644 crates/paint/src/mixer_load_supply_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs index af8e754ce2..ce2c28ce88 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs @@ -255,7 +255,9 @@ fn mixer_rejects_malformed_load_and_retains_or_reloads_paint() { } assert!(s.execute("brush.mixer.load", json!({"color":[1e300,0,0,1]})).is_err()); s.execute("brush.mixer.load", json!({"color":"#ff0000"})).unwrap(); - s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":10,"loadAfterStroke":false,"cleanAfterStroke":false,"load":10})).unwrap(); + // The load lasts for a length of stroke (390 px at Load 1 %), so the stroke runs back and forth. + let long = json!([[10, 40], [180, 40], [10, 40], [180, 40], [10, 40]]); + s.execute("paint.mixerBrush", json!({"points":long,"size":10,"loadAfterStroke":false,"cleanAfterStroke":false,"load":1})).unwrap(); assert!(s.tools.mixer.amount > 0.0 && s.tools.mixer.amount < 1.0); s.execute("paint.mixerBrush", json!({"points":[[40,40],[80,40]],"size":10,"loadAfterStroke":true,"load":10})).unwrap(); assert_eq!(s.tools.mixer.amount, 1.0); diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 3abf932823..9cd59d1e60 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -214,14 +214,15 @@ fn pencil_is_aliased_and_auto_erases() { #[test] fn mixer_brush_reservoir_and_cleaning() { - let mut s = session(200, 30); + // The load lasts for a length of stroke (390 px at the lowest Load), so the stroke is longer. + let mut s = session(800, 30); s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); s.execute( "paint.mixerBrush", - json!({"points": [[5, 15], [195, 15]], "size": 8, "wet": 0, "load": 0, "mix": 0, "brush": {"pressureSize": false, "spacing": 0.25}}), + json!({"points": [[5, 15], [795, 15]], "size": 8, "wet": 0, "load": 0, "mix": 0, "brush": {"pressureSize": false, "spacing": 0.25}}), ) .unwrap(); - assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 190, 15)[3] < 0.5, "low load dries out"); + assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 790, 15)[3] < 0.5, "low load dries out"); assert!(s.tools.mixer.pickup.is_none(), "cleaned after stroke"); // Wet, not cleaned: the pickup persists into the session. s.execute("paint.mixerBrush", json!({"points": [[5, 5], [100, 5]], "size": 8, "wet": 100, "mix": 80, "cleanAfterStroke": false})).unwrap(); @@ -982,15 +983,16 @@ fn new_brush_controls_round_trip_through_set_brush() { #[test] fn mixer_brush_uses_the_brush_mixer_settings() { - let mut s = session(200, 30); + // The load lasts for a length of stroke (390 px at the lowest Load), so the stroke is longer. + let mut s = session(800, 30); s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); // No wet/load params: the brush's Mixer settings (a dry brush with 0 % Load) apply. s.execute("tools.setBrush", json!({"brush": {"pressureSize": false, "spacing": 0.25, "mixer": {"wet": 0, "load": 0, "mix": 0}}})).unwrap(); - s.execute("paint.mixerBrush", json!({"points": [[5, 15], [195, 15]], "size": 8})).unwrap(); - assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 190, 15)[3] < 0.5, "the brush's 0 % Load dries out"); + s.execute("paint.mixerBrush", json!({"points": [[5, 15], [795, 15]], "size": 8})).unwrap(); + assert!(rgba(&s, 10, 15)[3] > 0.95 && rgba(&s, 790, 15)[3] < 0.5, "the brush's 0 % Load dries out"); // A param still overrides the brush. - s.execute("paint.mixerBrush", json!({"points": [[5, 5], [195, 5]], "size": 8, "load": 100})).unwrap(); - assert!(rgba(&s, 190, 5)[3] > 0.95); + s.execute("paint.mixerBrush", json!({"points": [[5, 5], [795, 5]], "size": 8, "load": 100})).unwrap(); + assert!(rgba(&s, 790, 5)[3] > 0.95); } /// A red image with an empty layer above it, a blue foreground, and a Mixer Brush that samples all diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 7054e11492..a090d9dcb3 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -408,3 +408,5 @@ mod tests { #[cfg(test)] mod brush_tests; +#[cfg(test)] +mod mixer_load_supply_tests; diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index bb34749065..5e30513b0d 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -3,7 +3,10 @@ //! Model (behavioural, our own): each dab samples the canvas colour under its footprint. The pickup //! colour `P` moves towards it by `wet`. The deposited colour mixes the reservoir `R` (weight //! `amount × (1 − mix·wet)`) with the pickup (weight `mix·wet`); it lands at `flow` times the total -//! weight. The reservoir amount drains per dab unless `load` is 100 %, so low Load strokes dry out. +//! weight. Below 100 % Load the reservoir lasts for a length of stroke (390 px at Load 1 %, 570 px +//! at 5 %, measured; a power law between and above), not a number of dabs: it paints at full +//! strength that far, then the amount steps down to [`DRY_STEP`] and fades with the distance +//! travelled ([`DRY_FADE_PX`]), so low Load strokes dry out. Load 100 % never runs out. //! A dry brush (`wet = 0`) paints only reservoir colour; an empty, wet brush smears canvas colour. use photocraft_raster::{Surface, from_rgba, from_rgba_into, to_rgba}; @@ -16,6 +19,32 @@ use photocraft_geom::Rect; /// Fraction of the way the pickup colour moves towards the canvas colour per dab at 100 % Wet. pub const PICKUP_RATE: f32 = 0.25; +/// Stroke length a load lasts at Load 1 %; the reference application paints solid for about 390 px +/// (35 px tip at 25 % spacing). Lower Load values last as long as 1 %. +pub const SUPPLY_AT_1_PERCENT_PX: f32 = 390.0; +/// Exponent of the supply's power law in Load, from the measured 570 px at Load 5 %. +pub const SUPPLY_EXPONENT: f32 = 0.2357; +/// The reservoir amount once the supply runs out: a 35 px soft tip at 25 % spacing then lays down +/// about 68 % alpha, as measured. +pub const DRY_STEP: f32 = 0.45; +/// Stroke length over which a run-out load fades by a factor of e (the measured alpha falls by +/// about × 0.85–0.88 per 30 px). +pub const DRY_FADE_PX: f32 = 170.0; + +/// Stroke length a load at `load` (0..1) lasts at full strength; infinite at 100 %. +pub fn supply_length(load: f32) -> f32 { + if load >= 1.0 { + return f32::INFINITY; + } + SUPPLY_AT_1_PERCENT_PX * (load * 100.0).max(1.0).powf(SUPPLY_EXPONENT) +} + +/// The share of a full load left after `travelled` px of stroke at `load`. +pub fn supply_left(load: f32, travelled: f32) -> f32 { + let length = supply_length(load); + if travelled < length { 1.0 } else { DRY_STEP * (-(travelled - length) / DRY_FADE_PX).exp() } +} + /// Mixer Brush options (all 0..1). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -69,6 +98,13 @@ pub struct MixerState { /// The color recorded by the last stroke (its color) or the last Load Brush or Clean Brush /// (the foreground). None = no stroke, load or clean yet. pub color: Option<[f32; 4]>, + /// Stroke length travelled so far in the current stroke, in px (the load's supply is measured + /// in stroke length). + #[serde(skip)] + pub travelled: f32, + /// The last dab of the current stroke: its index and centre. + #[serde(skip)] + pub last_dab: Option<(usize, f64, f64)>, } impl MixerState { @@ -307,7 +343,16 @@ pub fn apply_mixer_dab_region( } } } - amount *= 1.0 - 0.08 * (1.0 - load); + let (x, y) = (fp.dab.center.x, fp.dab.center.y); + let before = match state.last_dab { + Some((index, ..)) if fp.index > index => state.travelled, + _ => 0.0, + }; + let step = state.last_dab.filter(|(index, ..)| fp.index > *index).map_or(0.0, |(_, lx, ly)| (x - lx).hypot(y - ly) as f32); + let after = before + if step.is_finite() { step } else { 0.0 }; + amount *= supply_left(load, after) / supply_left(load, before); + state.travelled = after; + state.last_dab = Some((fp.index, x, y)); state.amount = amount; state.pickup = pickup.map(|p| to_rgba(&fmt, &p)); } @@ -327,12 +372,16 @@ mod tests { #[test] fn low_load_runs_dry_and_full_load_does_not() { + // The load lasts for a length of stroke (390 px at the lowest Load), so the stroke is longer + // than that. + let mut long = stroke(10.0); + long.points[1].x = 796.0; for (load, expect_dry) in [(0.0, true), (1.0, false)] { let mut s = Surface::new(PixelFormat::RGBA8); let mut st = MixerState::default(); st.load([1.0, 0.0, 0.0, 1.0]); - apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, &mut st, None, false); - let (start, end) = (s.rgba(10, 10)[3], s.rgba(190, 10)[3]); + apply_mixer_stroke(&mut s, None, &long, &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, &mut st, None, false); + let (start, end) = (s.rgba(10, 10)[3], s.rgba(790, 10)[3]); assert!(start > 0.95, "{start}"); if expect_dry { assert!(end < start * 0.6, "load {load}: {start} → {end}"); diff --git a/crates/paint/src/mixer/reference_tests.rs b/crates/paint/src/mixer/reference_tests.rs index 2071f60f01..4c6a5ef2d8 100644 --- a/crates/paint/src/mixer/reference_tests.rs +++ b/crates/paint/src/mixer/reference_tests.rs @@ -101,7 +101,17 @@ fn reference( } } } - amount *= 1.0 - 0.08 * (1.0 - load); + // The supply drain (#11943) is shared with the optimized kernel; it is not pickup or blending. + let (x, y) = (fp.dab.center.x, fp.dab.center.y); + let before = match state.last_dab { + Some((index, ..)) if fp.index > index => state.travelled, + _ => 0.0, + }; + let step = state.last_dab.filter(|(index, ..)| fp.index > *index).map_or(0.0, |(_, lx, ly)| (x - lx).hypot(y - ly) as f32); + let after = before + if step.is_finite() { step } else { 0.0 }; + amount *= supply_left(load, after) / supply_left(load, before); + state.travelled = after; + state.last_dab = Some((fp.index, x, y)); state.amount = amount; state.pickup = pickup.map(|p| to_rgba(&fmt, &p)); } diff --git a/crates/paint/src/mixer_load_supply_tests.rs b/crates/paint/src/mixer_load_supply_tests.rs new file mode 100644 index 0000000000..af946f4795 --- /dev/null +++ b/crates/paint/src/mixer_load_supply_tests.rs @@ -0,0 +1,90 @@ +//! A loaded Mixer Brush lasts for a length of stroke, not a number of dabs (#11943): measured with +//! Wet 0, Mix 0, Flow 100, a black load and a 35 px soft round tip at 25 % spacing, a stroke from +//! x 30 to 770 on an empty layer paints solid (alpha 252 or more) to about x 420 at Load 1 %, x 600 +//! at Load 5 % and to the end at Load 50 %; then the alpha steps down to about 68 % and fades. + +use crate::mixer::{MixerSettings, MixerState, apply_mixer_stroke}; +use crate::{BrushSettings, Stroke, StrokePoint}; +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +const Y: f64 = 100.0; + +fn stroke(x0: f64, x1: f64, spacing: f32) -> Stroke { + Stroke { + brush: BrushSettings { size: 35.0, hardness: 0.0, spacing, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(x0, Y, 1.0), StrokePoint::new(x1, Y, 1.0)], + } +} + +/// Paints the stroke with a fresh black load and returns the alpha (0–255) along its centre line, +/// and the reservoir amount left. +fn paint(load: f32, x0: f64, x1: f64, spacing: f32) -> (impl Fn(i32) -> i32, f32) { + let mut s = Surface::new(PixelFormat::RGBA8); + let mut st = MixerState::default(); + st.load([0.0, 0.0, 0.0, 1.0]); + let m = MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }; + apply_mixer_stroke(&mut s, None, &stroke(x0, x1, spacing), &m, &mut st, None, false); + (move |x: i32| (s.rgba(x, Y as i32)[3] * 255.0).round() as i32, st.amount) +} + +/// The first x at or after `from` whose alpha falls below 250. +fn runs_out(alpha: &impl Fn(i32) -> i32, from: i32) -> Option { + (from..=770).find(|&x| alpha(x) < 250) +} + +#[test] +fn the_measured_strokes_stay_solid_as_far_as_the_reference_and_then_drop() { + for (load, solid_to) in [(0.5, 760), (0.05, 590), (0.01, 410)] { + let (alpha, _) = paint(load, 30.0, 770.0, 0.25); + for x in 40..=solid_to { + assert!(alpha(x) >= 250, "Load {load}: alpha {} at x {x}", alpha(x)); + } + } + // After the supply runs out the alpha steps down to 60–75 % and then fades. + let (alpha, amount) = paint(0.01, 30.0, 770.0, 0.25); + assert!((150..=200).contains(&alpha(450)), "Load 1 %: alpha {} at x 450", alpha(450)); + assert!((25..=55).contains(&alpha(750)), "Load 1 %: alpha {} at x 750", alpha(750)); + assert!(alpha(480) > alpha(570) && alpha(570) > alpha(690), "it keeps fading"); + assert!(amount < 0.2, "{amount}"); + let (alpha, _) = paint(0.05, 30.0, 770.0, 0.25); + assert!((153..=191).contains(&alpha(640)), "Load 5 %: alpha {} at x 640", alpha(640)); + assert!(alpha(760) < alpha(640), "Load 5 % fades towards the end"); +} + +#[test] +fn the_supply_is_a_length_of_stroke() { + // A 470 px stroke at Load 5 % stays solid to its end. + let (alpha, amount) = paint(0.05, 300.0, 770.0, 0.25); + for x in 310..=760 { + assert!(alpha(x) >= 250, "alpha {} at x {x}", alpha(x)); + } + assert_eq!(amount, 1.0); + // At spacing 10 % (two and a half times the dabs) the load runs out at the same place. + for load in [0.01, 0.05] { + let wide = runs_out(&paint(load, 30.0, 770.0, 0.25).0, 40).unwrap(); + let dense = runs_out(&paint(load, 30.0, 770.0, 0.10).0, 40).unwrap(); + assert!((wide - dense).abs() <= 30, "Load {load}: spacing 25 % runs out at x {wide}, 10 % at x {dense}"); + } +} + +#[test] +fn load_100_never_runs_out() { + let (alpha, amount) = paint(1.0, 30.0, 770.0, 0.25); + assert_eq!(runs_out(&alpha, 40).filter(|&x| x < 765), None); + assert_eq!(amount, 1.0); +} + +#[test] +fn each_stroke_measures_its_own_length() { + // With the automatic Load off, a second stroke starts from what the first left and measures + // its supply from its own start. + let mut s = Surface::new(PixelFormat::RGBA8); + let mut st = MixerState::default(); + st.load([0.0, 0.0, 0.0, 1.0]); + let m = MixerSettings { wet: 0.0, load: 0.05, mix: 0.0, flow: 1.0, ..Default::default() }; + apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false); + assert_eq!(st.amount, 1.0, "300 px of a 570 px supply"); + apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false); + assert_eq!(st.amount, 1.0, "the second stroke starts its own 570 px"); +} From 20f566779f7e879a7c8de5f7d3c4e82c56aa2381 Mon Sep 17 00:00:00 2001 From: kirubhakaran12 <27127513+kirubhakaran12@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:47:50 +0530 Subject: [PATCH 016/385] Keep a duplicated clipped layer's base when it is not copied (#11915) A block of copies would place a clipped layer's copy above an unrelated sibling, making it clip to that sibling instead of its original base and changing its pixels. A clipped layer whose own base is not part of the selection now keeps its copy directly above the original, as before. Cover nested siblings (copies stack inside their group), the clipped-base case, and the source of each Layer via Copy copy. --- crates/engine/src/cmd/edit_cmds/tests.rs | 3 ++ .../src/cmd/layer_multi_cmds/structure.rs | 12 ++++-- .../engine/src/cmd/layer_multi_cmds/tests.rs | 37 +++++++++++++++++++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/edit_cmds/tests.rs b/crates/engine/src/cmd/edit_cmds/tests.rs index f668efcfeb..1296db71dd 100644 --- a/crates/engine/src/cmd/edit_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_cmds/tests.rs @@ -732,6 +732,9 @@ fn layer_via_copy_duplicates_every_selected_layer() { assert_eq!(ids.len(), 5, "background, a, b, a copy, b copy"); assert_eq!((ids[1], ids[2]), (a, b), "the originals keep their order"); assert_eq!(st.selected_layers(), vec![ids[3], ids[4]], "the copies become the selection, in document order"); + let surface = |id: LayerId| st.doc.layer(id).unwrap().surface().unwrap(); + assert_eq!(surface(ids[3]), surface(a), "the first copy came from a"); + assert_eq!(surface(ids[4]), surface(b), "the second copy came from b"); assert_eq!(st.history.past_len(), steps + 1, "one undo step"); assert!(s.undo()); s.execute("layer.select", json!({"layer": b.0})).unwrap(); diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 5d0cc3ace2..1b176c243a 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -266,8 +266,9 @@ pub fn delete_selected(s: &mut Session) -> Result { /// Duplicate Layer with several layers selected: the copies of sibling layers form one block above /// the topmost selected original, in the originals' order, as Photoshop does (#11915); a selection -/// spanning groups keeps each copy directly above its original, so no copy leaves its group. The -/// copies become the selection. Artboard copies go beside their boards unless `in_place` +/// spanning groups keeps each copy directly above its original, so no copy leaves its group, and a +/// clipped layer copied without its base keeps its copy above the original so the copy keeps that +/// base. The copies become the selection. Artboard copies go beside their boards unless `in_place` /// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses /// this path, #2777). pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { @@ -279,8 +280,11 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul // Copies of sibling layers go above the topmost selected original as one block, keeping // their originals' order, as Photoshop does (#11915). Layers from different groups keep a // copy directly above each original, so no copy leaves its group; artboard copies are - // placed beside their boards one by one (below). - let block = same_siblings(doc, &ids) && !ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())); + // placed beside their boards one by one (below). So does a clipped copy whose own base is + // not copied with it: the block would give it a different base and change its pixels. + let block = same_siblings(doc, &ids) + && !ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) + && ids.iter().all(|id| doc.layer(*id).is_none_or(|l| !l.clipped || crate::clip_group::base_of(doc, *id).is_some_and(|base| ids.contains(&base)))); let mut above = ids.last().copied(); let mut copies = Vec::new(); let mut new_active = None; diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index 5e6fa43cd8..35d95cf326 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -1447,6 +1447,43 @@ fn duplicating_layers_from_different_parents_keeps_each_copy_in_its_group() { assert!(sel(&s).iter().all(|id| copies.contains(id))); } +/// #11915: sibling copies stack as one block inside their own group too, not only at the root. +#[test] +fn duplicating_nested_siblings_stacks_their_copies_above_them() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, b]); + let gid = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + select_all(&mut s, &[a, b]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + let copies: Vec = r["layers"].as_array().unwrap().iter().map(|v| LayerId(v.as_u64().unwrap())).collect(); + assert_eq!(copies.len(), 2); + let children: Vec = doc(&s).layer(gid).unwrap().children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![a, b, copies[0], copies[1]], "the copies are one block above the originals inside the group"); +} + +/// #11915: a copy never takes a different clipping base. A clipped layer copied without its base +/// stays directly above its original (clipped to the same base) rather than joining the block and +/// clipping to an unrelated sibling. +#[test] +fn duplicating_a_clipped_layer_without_its_base_keeps_its_base() { + let mut s = session(8); + let background = doc(&s).layers[0].id; + let base = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let clipped = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + let other = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + assert_eq!(crate::clip_group::base_of(doc(&s), clipped), Some(base)); + select_all(&mut s, &[clipped, other]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + let copies: Vec = r["layers"].as_array().unwrap().iter().map(|v| LayerId(v.as_u64().unwrap())).collect(); + assert_eq!(copies.len(), 2); + let stack: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); + assert_eq!(stack, vec![background, base, clipped, copies[0], other, copies[1]], "each copy is above its original"); + assert_eq!(crate::clip_group::base_of(doc(&s), copies[0]), Some(base), "the copy still clips to the original base"); +} + #[test] fn duplicate_hide_lock_and_reverse_selected() { let mut s = session(8); From 427aadecb1410687d30dacd22e339445c86a17c9 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 23:17:23 -0600 Subject: [PATCH 017/385] Mixer Brush: the load swatch shows a checkerboard or the sampled tip image (#11953) The Current Brush Load swatch now shows what the reservoir holds: the loaded colour after Load Brush, the 64 x 64 sampled tip image after an Alt+click (over the usual transparency checker), and a checkerboard when the brush is clean. The image's texture is uploaded again only when the load changes. --- crates/ui-egui/src/mixer_load_swatch_tests.rs | 121 ++++++++++++++++++ crates/ui-egui/src/panels/brush_controls.rs | 56 ++++++-- 2 files changed, 167 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/mixer_load_swatch_tests.rs diff --git a/crates/ui-egui/src/mixer_load_swatch_tests.rs b/crates/ui-egui/src/mixer_load_swatch_tests.rs new file mode 100644 index 0000000000..4e15f6d916 --- /dev/null +++ b/crates/ui-egui/src/mixer_load_swatch_tests.rs @@ -0,0 +1,121 @@ +//! The Mixer Brush's Current Brush Load swatch shows what the reservoir holds (#11953): a solid +//! colour after Load Brush, the sampled 64 × 64 tip image after an ⌥-click (an edge between green +//! and blue shows green on the left and blue on the right), and a checkerboard after Clean Brush. + +use egui::{Modifiers, Rect, Shape, TextureId, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use super::mixer_load_image; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + +/// A pixel layer green left of x 100 and blue from there on, with the Mixer Brush active. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": GREEN})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": BLUE})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#ffffff"})).unwrap(); + app.ui.tool = Tool::MixerBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap(); + app +} + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 120.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app(), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn flatten<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) { + if let Shape::Vec(v) = shape { + v.iter().for_each(|s| flatten(s, out)); + } else { + out.push(shape); + } +} + +/// What the swatch draws this frame: the fill colours of its rectangles and the textures of its +/// images, inside the swatch's chip. +fn swatch(h: &Harness<'static, PhotocraftApp>) -> (Vec, Vec) { + let r = h.get_by_label("Current Brush Load").rect(); + let chip = Rect::from_min_size(egui::pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)).expand(0.5); + let (mut fills, mut textures) = (Vec::new(), Vec::new()); + for clipped in &h.output().shapes { + let mut all = Vec::new(); + flatten(&clipped.shape, &mut all); + for s in all { + match s { + Shape::Rect(rs) if chip.contains_rect(rs.rect) => fills.push(rs.fill), + Shape::Mesh(m) if m.texture_id != TextureId::default() && chip.contains_rect(m.calc_bounds()) => textures.push(m.texture_id), + _ => {} + } + } + } + (fills, textures) +} + +fn has_fonts(h: &Harness<'static, PhotocraftApp>) -> bool { + h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +#[test] +fn the_sampled_image_keeps_its_left_and_right() { + let load: Vec<[f32; 4]> = (0..64 * 64).map(|i| if i % 64 < 32 { GREEN } else { BLUE }).collect(); + let image = mixer_load_image(&load); + assert_eq!(image.size, [64, 64]); + assert_eq!(image[(10, 32)], egui::Color32::from_rgb(0, 255, 0)); + assert_eq!(image[(54, 32)], egui::Color32::from_rgb(0, 0, 255)); +} + +#[test] +fn the_swatch_shows_the_load_the_tip_image_or_a_checkerboard() { + let mut h = harness(); + if !has_fonts(&h) { + return; + } + // Load Brush: one solid red, no image. + h.state_mut().run("brush.mixer.load", json!({})).unwrap(); + h.run_steps(3); + let (fills, textures) = swatch(&h); + assert!(fills.contains(&egui::Color32::from_rgb(255, 0, 0)) && textures.is_empty(), "{fills:?} {textures:?}"); + + // ⌥-click on the green/blue edge: the sampled tip image, green left and blue right. + tool_event(h.state_mut(), ToolEvent::Down { x: 100.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(h.state_mut(), ToolEvent::Up { x: 100.0, y: 50.0 }, Modifiers::ALT); + h.run_steps(3); + let load = h.state().session.tools.mixer.spatial.clone().expect("the ⌥-click loads the tip image"); + let (_, textures) = swatch(&h); + assert_eq!(textures.len(), 1, "the swatch draws the tip image"); + let image = mixer_load_image(&load); + let (left, right) = (image[(16, 32)], image[(48, 32)]); + assert!(left.g() > 200 && left.b() < 50, "left of the image {left:?}"); + assert!(right.b() > 200 && right.g() < 50, "right of the image {right:?}"); + + // Clean Brush: a checkerboard of two greys, no image. + h.state_mut().run("brush.mixer.clean", json!({})).unwrap(); + h.run_steps(3); + let (fills, textures) = swatch(&h); + let greys: std::collections::BTreeSet<_> = fills.iter().filter(|c| c.r() == c.g() && c.g() == c.b() && c.r() > 150).map(|c| c.r()).collect(); + assert!(greys.len() >= 2 && textures.is_empty(), "checkerboard {fills:?} {textures:?}"); +} diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index ddd45f38ba..9c58d0927a 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -64,8 +64,36 @@ pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::Br }); } -/// Mixer Brush: the Current Brush Load swatch shows the paint the next stroke starts with (an -/// empty swatch when the brush is clean). Its menu holds Load Brush and Clean Brush. +/// The sampled tip image of a Mixer Brush load (64 × 64 straight RGBA cells, row by row) as the +/// Current Brush Load swatch draws it. +pub(crate) fn mixer_load_image(load: &[[f32; 4]]) -> egui::ColorImage { + let bytes: Vec = load.iter().flat_map(|c| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + egui::ColorImage::from_rgba_unmultiplied([64, 64], &bytes) +} + +/// The swatch's texture of `load`, uploaded again only when the load changes. +fn mixer_load_texture(ctx: &egui::Context, load: &[[f32; 4]]) -> egui::TextureHandle { + use std::hash::{Hash, Hasher}; + let image = mixer_load_image(load); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + image.as_raw().hash(&mut hasher); + let hash = hasher.finish(); + let key = egui::Id::unique("mixer-load-swatch-image"); + if let Some((_, tex)) = ctx.data(|d| d.get_temp::<(u64, egui::TextureHandle)>(key)).filter(|(h, _)| *h == hash) { + return tex; + } + let tex = ctx.load_texture("mixer-load-swatch", image, egui::TextureOptions::LINEAR); + ctx.data_mut(|d| d.insert_temp(key, (hash, tex.clone()))); + tex +} + +#[cfg(test)] +#[path = "../mixer_load_swatch_tests.rs"] +mod mixer_load_swatch_tests; + +/// Mixer Brush: the Current Brush Load swatch shows the paint the next stroke starts with: the +/// loaded colour, the sampled tip image after an ⌥-click, or a transparency checkerboard when the +/// brush is clean. Its menu holds Load Brush and Clean Brush. pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(40.0, 26.0), Sense::hover()); @@ -75,14 +103,22 @@ pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let chip = Rect::from_min_size(pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)); let p = ui.painter(); - match app.session.tools.mixer.next_load(app.session.tools.foreground) { - Some(c) => { - p.rect_filled(chip, 2.0, c32(c)); - } - None => { - p.rect_filled(chip, 2.0, t.field); - p.line_segment([chip.left_bottom(), chip.right_top()], Stroke::new(1.0, t.text_faint)); - } + // What the reservoir holds (#11953): the loaded colour, the sampled tip image of an ⌥-click + // (kept while the foreground stays), or a transparency checkerboard when the brush is clean. + let mixer = &app.session.tools.mixer; + let foreground = app.session.tools.foreground; + match mixer.next_load(foreground) { + Some(c) => match mixer.spatial.as_deref().filter(|load| load.len() == 64 * 64 && mixer.color == Some(foreground)) { + Some(load) => { + widgets::checker(p, chip, 4.0); + let tex = mixer_load_texture(ui.ctx(), load); + p.image(tex.id(), chip, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + None => { + p.rect_filled(chip, 2.0, c32(c)); + } + }, + None => widgets::checker(p, chip, 4.0), } p.rect_stroke(chip, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); From 2bb585dd6f4d604c8e8886cb565fca02f6566942 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 8 Nov 2026 04:47:04 -0800 Subject: [PATCH 018/385] Mirror the outside Free Transform rotation test drag --- crates/ui-egui/src/transform_undo_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index b863eb8fff..c99323f82b 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -218,7 +218,7 @@ fn a_press_just_off_a_corner_scales_rather_than_rotates() { assert!(q[2][0] > 230.0, "via controls {via_controls}: scaled: {q:?}"); // Well outside the box still rotates. let before = quad(&h); - drag(&mut h, [before[2][0] + 30.0, before[2][1] + 30.0], [before[2][0] - 10.0, before[2][1] + 60.0]); + drag(&mut h, [before[1][0] + 30.0, before[1][1] - 30.0], [before[1][0] - 10.0, before[1][1] - 60.0]); let r = quad(&h); assert!((r[0][1] - r[1][1]).abs() > 1.0, "via controls {via_controls}: rotated: {r:?}"); } From 46db44b6fbde738bf01c4d86d012b6580aac7e0c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 8 Nov 2026 08:53:29 -0800 Subject: [PATCH 019/385] Run paired transform actions in one test frame --- crates/ui-egui/src/transform_task_bar_tests.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index eb462bd835..3123f00359 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -2,7 +2,7 @@ use egui::{Key, Rect, pos2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use crate::PhotocraftApp; @@ -193,8 +193,12 @@ fn transform_task_bar_commits_when_done_and_hide_arrive_together() { let edits = history(&h); click(&mut h, "More options"); - h.get_by_label("Hide bar").click_accesskit(); - h.get_by_label("Done").click_accesskit(); + // The harness runs queued clicks in separate frames. Deliver both actions in one input. + let events = ["Hide bar", "Done"].map(|label| { + let (target_node, target_tree) = h.get_by_label(label).accesskit_node().locate(); + egui::Event::AccessKitActionRequest(egui::accesskit::ActionRequest { action: egui::accesskit::Action::Click, target_node, target_tree, data: None }) + }); + h.input_mut().events.extend(events); h.run_steps(4); assert!(!h.state().ui.panels.context_task_bar); @@ -225,13 +229,15 @@ fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { rotation: view.rotation, aspect: app.ui.view.display_aspect(), }; - let _ = ctx.run_ui(input, |ui| { + ctx.run_ui(input, |ui| { if app.ui.transform.is_some() { // Model the main canvas recording its rect before the extra window handles Cancel. app.ui.task_bar_shown = Some(prior_rect); crate::transform_task_bar::draw(app, ui, &xf); } - }); + }) + .textures_delta + .clear(); assert!(h.state().ui.transform.is_none()); // No UI pass between the Crop request and inspection. From cadfede3b1e4feb39ef2f1eb64b6a0b3385b2325 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 8 Nov 2026 10:14:56 -0800 Subject: [PATCH 020/385] Keep Free Transform task bar inspection tied to its draw --- crates/ui-egui/src/control/inspect.rs | 2 +- .../ui-egui/src/tools/transform_task_bar.rs | 34 +++++++++-- .../ui-egui/src/transform_task_bar_tests.rs | 59 +++++++++++++++++-- 3 files changed, 86 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index a9fc910edf..e092b0063a 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -31,7 +31,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { dialogs.extend(crate::discard_ui::inspect(app)); // 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) || crate::transform_task_bar::eligible(app)); + let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)).or_else(|| crate::transform_task_bar::shown_rect(app, ctx)); json!({ "window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()}, "scratch": photocraft_raster::spill::stats(), diff --git a/crates/ui-egui/src/tools/transform_task_bar.rs b/crates/ui-egui/src/tools/transform_task_bar.rs index bb8e159698..c646e882ec 100644 --- a/crates/ui-egui/src/tools/transform_task_bar.rs +++ b/crates/ui-egui/src/tools/transform_task_bar.rs @@ -20,6 +20,17 @@ enum Action { Done, } +#[derive(Clone, Copy)] +struct ShownRect { + session: u64, + pass: u64, + rect: [f32; 4], +} + +fn shown_id() -> egui::Id { + egui::Id::unique("free-transform-task-bar-rect") +} + /// Crop keeps its own bar. Warp, Transform Selection and Content-Aware Scale use their own controls. fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { let active = app.session.active()?; @@ -27,6 +38,7 @@ fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { if !app.ui.panels.context_task_bar || app.ui.tool == Tool::Crop || !app.ui.dialogs.is_empty() + || app.ui.shell.dialog.is_some() || preview.doc.id != active.doc.id || crate::transform_tool::committing(app).is_some() { @@ -35,17 +47,28 @@ fn open_box(app: &PhotocraftApp) -> Option<&TransformSession> { app.ui.transform.as_ref().filter(|t| t.warp.is_none() && !t.selection && t.content_aware.is_none()) } -/// Whether the inspector may report the shared task-bar rectangle for Free Transform. +/// Whether Free Transform can show its bar. /// This checks current eligibility without changing placement or the transform. pub fn eligible(app: &PhotocraftApp) -> bool { open_box(app).is_some() } +/// The current or last painted rectangle of this transform session. Crop keeps its own rectangle. +pub(crate) fn shown_rect(app: &PhotocraftApp, ctx: &egui::Context) -> Option<[f32; 4]> { + let session = open_box(app)?.session; + let shown = ctx.data(|data| data.get_temp::(shown_id()))?; + // Extra document windows draw within the root pass. Inspection also runs between passes, + // when egui has already incremented the counter for the last drawn rectangle. + let pass = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT); + (shown.session == session && pass.checked_sub(shown.pass).is_some_and(|age| age <= 1)).then_some(shown.rect) +} + /// Draw the shared bar, persist its placement and apply the selected action before Hide. /// Report failed preset commands in the status bar. After the action, publish the rectangle /// for inspection while Free Transform remains eligible, or clear it if the action closed or hid it. pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { let Some(transform) = open_box(app) else { return }; + let session = transform.session; let corners = transform.quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); let anchor = egui::Rect::from_points(&corners); let ctx = ui.ctx().clone(); @@ -68,10 +91,13 @@ pub fn draw(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { app.ui.panels.context_task_bar = false; } // An action in an extra window can invalidate the rect written by the main canvas. - app.ui.task_bar_shown = eligible(app).then(|| { + let pass = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT); + if open_box(app).is_some_and(|transform| transform.session == session) { let r = shown.rect; - [r.min.x, r.min.y, r.max.x, r.max.y] - }); + ctx.data_mut(|data| data.insert_temp(shown_id(), ShownRect { session, pass, rect: [r.min.x, r.min.y, r.max.x, r.max.y] })); + } else { + ctx.data_mut(|data| data.remove::(shown_id())); + } } /// Draw presets in the measured order, with the shared menu before Cancel and Done. diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 3123f00359..fff723ab1b 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -72,9 +72,14 @@ fn transform_task_bar_presets_match_the_context_menu() { /// Done commits once like Enter, while Cancel discards the box like Escape. #[test] fn transform_task_bar_done_and_cancel_match_the_keys() { + let pixels = |h: &AppHarness| { + let st = h.state().session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) + }; for (label, key, edits) in [("Done", Key::Enter, 1), ("Cancel", Key::Escape, 0)] { let mut toolbar = open_box(); let mut keys = open_box(); + let original = pixels(&toolbar); for h in [&mut toolbar, &mut keys] { click(h, "Rotate 90° Clockwise"); } @@ -85,6 +90,9 @@ fn transform_task_bar_done_and_cancel_match_the_keys() { assert!(toolbar.state().ui.transform.is_none() && keys.state().ui.transform.is_none(), "{label}"); assert_eq!(history(&toolbar), toolbar_history + edits); assert_eq!(history(&keys), key_history + edits); + let actual = pixels(&toolbar); + assert!(actual == pixels(&keys), "{label} should produce the same pixels as the key"); + assert_eq!(actual != original, edits != 0, "{label}"); assert_eq!(bar(&mut toolbar)["visible"], false); } } @@ -109,7 +117,7 @@ fn transform_task_bar_tracks_the_rotated_quad() { }; let quad = app.ui.transform.as_ref().unwrap().quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); let anchor = Rect::from_points(&quad); - let [x0, y0, x1, y1] = app.ui.task_bar_shown.unwrap(); + let [x0, y0, x1, y1] = crate::transform_task_bar::shown_rect(app, &h.ctx).unwrap(); let shown = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)); assert!((shown.center().x - anchor.center().x).abs() <= 1.0, "{shown:?} below {anchor:?}"); assert!((shown.top() - anchor.bottom() - crate::widgets::task_bar::GAP).abs() <= 1.0, "{shown:?} below {anchor:?}"); @@ -185,6 +193,50 @@ fn transform_task_bar_ignores_a_foreign_preview_after_a_document_switch() { assert_eq!(h.state().ui.transform.as_ref().unwrap().quad, quad); } +#[test] +fn transform_task_bar_hides_while_a_shell_dialog_is_open() { + let mut h = open_box(); + let session = h.state().ui.transform.as_ref().unwrap().session; + assert_eq!(bar(&mut h)["visible"], true); + control(&mut h, "ui.menu.invoke", json!({"id": "window.workspace.newWorkspace"})); + assert!(h.state().ui.shell.dialog.is_some() && h.state().ui.dialogs.is_empty()); + assert_eq!(bar(&mut h)["visible"], false); + h.run_steps(2); + assert!(h.query_by_label("Rotate 90° Clockwise").is_none()); + control(&mut h, "ui.dialog.cancel", json!({"dialog": "shell"})); + assert!(bar(&mut h)["rect"].is_null(), "the last pass did not draw the bar"); + h.run_steps(4); + assert_eq!(h.state().ui.transform.as_ref().unwrap().session, session); + assert_eq!(bar(&mut h)["visible"], true); +} + +#[test] +fn transform_task_bar_inspection_keeps_crop_and_free_transform_rects_separate_before_redraw() { + let mut h = open_box(); + assert_eq!(bar(&mut h)["visible"], true); + control( + &mut h, + "ui.pointer", + json!({"tool": "crop", "events": [{"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]}), + ); + assert!(crate::crop_task_bar::eligible(h.state())); + assert!(bar(&mut h)["rect"].is_null(), "Crop must wait for its own draw"); + h.run_steps(4); + assert_eq!(bar(&mut h)["visible"], true); + + // An untouched Crop frame can leave the tool without committing a document edit. + let mut h = harness(); + control(&mut h, "ui.set", json!({"tool": "crop"})); + h.run_steps(4); + assert_eq!(bar(&mut h)["visible"], true); + control(&mut h, "ui.set", json!({"tool": "move"})); + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(crate::transform_task_bar::eligible(h.state())); + assert!(bar(&mut h)["rect"].is_null(), "Free Transform must wait for its own draw"); + h.run_steps(4); + assert_eq!(bar(&mut h)["visible"], true); +} + /// Accessibility can deliver Hide and Done during the same pass. #[test] fn transform_task_bar_commits_when_done_and_hide_arrive_together() { @@ -210,7 +262,7 @@ fn transform_task_bar_commits_when_done_and_hide_arrive_together() { #[test] fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { let mut h = open_box(); - let prior_rect = h.state().ui.task_bar_shown.unwrap(); + let prior_rect = crate::transform_task_bar::shown_rect(h.state(), &h.ctx).unwrap(); let cancel = h.get_by_label("Cancel").rect().center(); let ctx = h.ctx.clone(); let mut input = h.input().clone(); @@ -231,8 +283,7 @@ fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { }; ctx.run_ui(input, |ui| { if app.ui.transform.is_some() { - // Model the main canvas recording its rect before the extra window handles Cancel. - app.ui.task_bar_shown = Some(prior_rect); + assert_eq!(crate::transform_task_bar::shown_rect(app, ui.ctx()), Some(prior_rect)); crate::transform_task_bar::draw(app, ui, &xf); } }) From d5246412294ab087c81c3107b07725f9e54a18c7 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 8 Nov 2026 12:37:48 -0600 Subject: [PATCH 021/385] Mixer Brush load swatch tests: the sampled image keeps its top and bottom rows, its alpha and clamps out-of-range values (eliets2 review 5818990460 on mixer_load_swatch_tests.rs) --- crates/ui-egui/src/mixer_load_swatch_tests.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/mixer_load_swatch_tests.rs b/crates/ui-egui/src/mixer_load_swatch_tests.rs index 4e15f6d916..6b58687b4f 100644 --- a/crates/ui-egui/src/mixer_load_swatch_tests.rs +++ b/crates/ui-egui/src/mixer_load_swatch_tests.rs @@ -80,12 +80,18 @@ fn has_fonts(h: &Harness<'static, PhotocraftApp>) -> bool { } #[test] -fn the_sampled_image_keeps_its_left_and_right() { +fn the_sampled_image_keeps_its_left_right_top_and_bottom() { let load: Vec<[f32; 4]> = (0..64 * 64).map(|i| if i % 64 < 32 { GREEN } else { BLUE }).collect(); let image = mixer_load_image(&load); assert_eq!(image.size, [64, 64]); assert_eq!(image[(10, 32)], egui::Color32::from_rgb(0, 255, 0)); assert_eq!(image[(54, 32)], egui::Color32::from_rgb(0, 0, 255)); + // Row 0 is the tip's top, as `load_at` reads it; alpha is kept and values past 0..1 clamp. + let load: Vec<[f32; 4]> = (0..64 * 64).map(|i| if i < 32 * 64 { [1.0, 0.0, 0.0, 0.5] } else { [1.5, -0.2, 0.0, 1.0] }).collect(); + let image = mixer_load_image(&load); + let (top, bottom) = (image[(32, 10)], image[(32, 54)]); + assert_eq!((top.r() > 0, top.g(), top.b(), top.a()), (true, 0, 0, 128), "top of the image {top:?}"); + assert_eq!(bottom, egui::Color32::from_rgb(255, 0, 0), "bottom of the image"); } #[test] From 88b467095902d78e3c3b87e00ecc871317b571e9 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 8 Nov 2026 12:37:49 -0600 Subject: [PATCH 022/385] Mixer Brush load swatch tests: the swatch draws the sampled load's own texture, keeps it while the load stays and uploads a new one when it changes (eliets2 review 5818990460 on brush_controls.rs mixer_load_texture) --- crates/ui-egui/src/mixer_load_swatch_tests.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/mixer_load_swatch_tests.rs b/crates/ui-egui/src/mixer_load_swatch_tests.rs index 6b58687b4f..f23d9bf7bc 100644 --- a/crates/ui-egui/src/mixer_load_swatch_tests.rs +++ b/crates/ui-egui/src/mixer_load_swatch_tests.rs @@ -7,7 +7,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use super::mixer_load_image; +use super::{mixer_load_image, mixer_load_texture}; use crate::PhotocraftApp; use crate::canvas::{ToolEvent, tool_event}; use crate::state::Tool; @@ -112,11 +112,22 @@ fn the_swatch_shows_the_load_the_tip_image_or_a_checkerboard() { h.run_steps(3); let load = h.state().session.tools.mixer.spatial.clone().expect("the ⌥-click loads the tip image"); let (_, textures) = swatch(&h); - assert_eq!(textures.len(), 1, "the swatch draws the tip image"); + let sampled = mixer_load_texture(&h.ctx, &load).id(); + assert_eq!(textures, [sampled], "the swatch draws the texture of the sampled load"); let image = mixer_load_image(&load); let (left, right) = (image[(16, 32)], image[(48, 32)]); assert!(left.g() > 200 && left.b() < 50, "left of the image {left:?}"); assert!(right.b() > 200 && right.g() < 50, "right of the image {right:?}"); + h.run_steps(3); + assert_eq!(swatch(&h).1, [sampled], "an unchanged load keeps its texture"); + + // ⌥-click in the green: a new load, uploaded again. + tool_event(h.state_mut(), ToolEvent::Down { x: 30.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(h.state_mut(), ToolEvent::Up { x: 30.0, y: 50.0 }, Modifiers::ALT); + h.run_steps(3); + let green = h.state().session.tools.mixer.spatial.clone().expect("the second ⌥-click loads the tip image"); + let (_, textures) = swatch(&h); + assert!(textures != [sampled] && textures == [mixer_load_texture(&h.ctx, &green).id()], "the new load's texture {textures:?}"); // Clean Brush: a checkerboard of two greys, no image. h.state_mut().run("brush.mixer.clean", json!({})).unwrap(); From 06498888f8cbcae85d06fbbfd5cac8f8d8c1f3a6 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 8 Nov 2026 12:37:49 -0600 Subject: [PATCH 023/385] Mixer Brush load swatch tests: a new foreground after an Alt+click shows its colour, not the sampled image (eliets2 review 5818990460 on mixer_load_swatch_tests.rs) --- crates/ui-egui/src/mixer_load_swatch_tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/mixer_load_swatch_tests.rs b/crates/ui-egui/src/mixer_load_swatch_tests.rs index f23d9bf7bc..7885e52cbc 100644 --- a/crates/ui-egui/src/mixer_load_swatch_tests.rs +++ b/crates/ui-egui/src/mixer_load_swatch_tests.rs @@ -129,6 +129,12 @@ fn the_swatch_shows_the_load_the_tip_image_or_a_checkerboard() { let (_, textures) = swatch(&h); assert!(textures != [sampled] && textures == [mixer_load_texture(&h.ctx, &green).id()], "the new load's texture {textures:?}"); + // A new foreground: the next stroke loads it, so the swatch shows that colour, not the image. + h.state_mut().run("tools.setColors", json!({"foreground": "#ffff00"})).unwrap(); + h.run_steps(3); + let (fills, textures) = swatch(&h); + assert!(fills.contains(&egui::Color32::from_rgb(255, 255, 0)) && textures.is_empty(), "the new foreground {fills:?} {textures:?}"); + // Clean Brush: a checkerboard of two greys, no image. h.state_mut().run("brush.mixer.clean", json!({})).unwrap(); h.run_steps(3); From 50eef3dd9b67a4804c994d681b7ec332fe690dd3 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 8 Nov 2026 13:35:09 -0800 Subject: [PATCH 024/385] Give the Free Transform bar priority over raw Type presses --- crates/ui-egui/src/canvas.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3451b48cba..c1317757f1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -900,8 +900,13 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: let press_mods = crate::workspace_ui::sticky_mods(app, press_mods); ctx.data_mut(|d| d.insert_temp(tool_press, press_mods)); if tool.is_type() && press_mods.command && app.ui.text_edit.is_some() { - let d = xf.to_doc(p); - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); + // This raw press bypasses egui's widget ownership. Leave presses on the Free Transform bar to its controls. + let on_transform_bar = app.session.active_index() == Some(idx) + && crate::transform_task_bar::shown_rect(app, ctx).is_some_and(|[x0, y0, x1, y1]| Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)).contains(p)); + if !on_transform_bar { + let d = xf.to_doc(p); + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods); + } } } From e5049c3eee1116b4ce0a905255a6e37b26244bdf Mon Sep 17 00:00:00 2001 From: PhotoCraft Priority scratch Date: Tue, 10 Nov 2026 20:11:32 -0800 Subject: [PATCH 025/385] docs: show the Free Transform task bar before and after --- docs/images/free-transform-task-bar-after.png | Bin 0 -> 134004 bytes docs/images/free-transform-task-bar-before.png | Bin 0 -> 126057 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/images/free-transform-task-bar-after.png create mode 100644 docs/images/free-transform-task-bar-before.png diff --git a/docs/images/free-transform-task-bar-after.png b/docs/images/free-transform-task-bar-after.png new file mode 100644 index 0000000000000000000000000000000000000000..11c270e951f75c4511fd7fce975bb8863de2d8dc GIT binary patch literal 134004 zcmcG%3s{up+BQ6hO1X*D%F={#6U!{IOwk0!-fWqfvC37J8>p;UMv98Y0K*JsrDjTL zM(&tat+Mh(a+v}O42p_79Lp39WZ0u3%nq0t80PuU^CB&KbG`p}e8+bjD|NA%dFHwA z``VnF>sj@;XD0XVF`$P^rRqK9$w|+tRNX#TseIqPsXM+hW7?-bsk-!>FlEwXf7kdl z7WjTX^rcS^+m!gGHAhZtTRe5{j`^i~e*NFP57R$=Dl`4z(Sw`ZZ)d%k`1OhjF=sOK zFO=qO&AI&D_8oiw{14^Dt~2H=J@fpZ|IredT5;pw-R`aKGy8_WyY!4c^!`78S^SRD z!{Od?=+(zEHf;AQpMAZmcJa|ScUL_zsrH6%_rxOx)1~(G_NINQ_~GXj{R4OOd}iyT z-3s`76Kl;CYyI@MYeJ)H>P?3F zO))!O**()X_#W2`%`ZcY8@GkF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1&Qf@bT6f^;0-2|5)d`hVY4AL9z71lS6B+>qwION;@n)cJmmcW_h%g zRUPd!GN7{~?RRpTaG-cRJGppo47TnGi3U%F~Z@5ee`k+)r3S>&{|2g&eWj zO4tdr)yBw6m8hO@+%)oLWcSb!AMzy+GJsYQFFkl6lH(9PXM>wD4YZCF6Mu@K!EDcp zr7x8+GHiQ0ih~rkXC5r%h9kfsGe7Hmd*oE-p9SpLJ{u%OS!fhVc$k*x5oShx#PMkD!V3ikKGv* z{AO3zu^ub!j$^GuUf#Lc@m=H(C+A1R?d@khdW{j(aejzv+x;J%j9jtMn!dTPsAuSd zff;934b;ru84)$AYw}+rk0W@h3~~M~@`r*;ZD$sR&)#(Bp|y_MA^p?do??U^FWndJ zE_!89?BcnH<9^A^y2n+PvVWs>mD_i(HFmSWDtr@fDr_(1Z^NSN_Syo;iK4hFDD=fLP*Bw#Se~FqDal!b*8y~xo zwnK<1%}xMp;LZWL?%(;xtpA$6h;=tqn*hU^Z9$=a;e}ndz19LWjp(f^^^T&*r@D`% oSyXeuT;1>79nRB~W41e6RT^^gmhs~a{NJd%9vHFVjwk2+f8_Zxod5s; literal 0 HcmV?d00001 From 3b17eab9cc56b49572384a7a40280ab4afccf820 Mon Sep 17 00:00:00 2001 From: PhotoCraft Priority private Date: Wed, 11 Nov 2026 00:00:00 +0000 Subject: [PATCH 026/385] Fix contextual task-bar frame drag ownership --- .../ui-egui/src/transform_task_bar_tests.rs | 100 ++++++++++++++++++ crates/ui-egui/src/widgets/task_bar.rs | 2 +- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index fff723ab1b..914b34be01 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -302,3 +302,103 @@ fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { assert_eq!(crop_bar["visible"], false); assert!(crop_bar["rect"].is_null()); } + +/// The frame owns its press even when egui gives the underlying canvas the drag sense. +#[test] +fn transform_task_bar_frame_drag_preserves_the_open_transform() { + for edge in ["top", "bottom", "right"] { + let mut h = open_box(); + let app = h.state(); + let transform = app.ui.transform.as_ref().unwrap(); + let before = (transform.session, transform.pivot, transform.quad); + let before_history = history(&h); + let [x0, y0, x1, y1] = crate::transform_task_bar::shown_rect(app, &h.ctx).unwrap(); + let frame = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)); + let from = match edge { + "top" => pos2(frame.center().x, frame.top() + 1.0), + "bottom" => pos2(frame.center().x, frame.bottom() - 1.0), + _ => pos2(frame.right() - 1.0, frame.center().y), + }; + let to = from + egui::vec2(35.0, 25.0); + let xf = ViewXform::active(app).unwrap(); + assert!(xf.rect.contains(from) && xf.rect.contains(to), "frame drag must stay on canvas"); + assert!(frame.contains(from), "frame drag must begin inside the visible bar"); + let hit = crate::transform_tool::box_hit(app, transform, xf.to_doc(from), crate::transform_tool::handle_tolerance(app)); + assert!(matches!(hit, crate::transform_tool::Hit::Outside), "frame sample must be outside transform controls: {edge} {hit:?}"); + task_bar_screen_drag(&mut h, from, to); + let after = h.state().ui.transform.as_ref().map(|t| (t.session, t.pivot, t.quad)); + assert_eq!(after, Some(before), "dragging the bar's {edge} frame must leave the open transform unchanged"); + assert_eq!(history(&h), before_history, "frame drag must not commit an edit"); + } +} + +/// The frame guard must still allow a canvas rotation gesture with an outside-bar origin. +#[test] +fn transform_task_bar_frame_guard_preserves_off_bar_rotation() { + let mut h = open_box(); + let app = h.state(); + let transform = app.ui.transform.as_ref().unwrap(); + let before = (transform.session, transform.pivot, transform.quad); + let before_history = history(&h); + let xf = ViewXform::active(app).unwrap(); + let corner = xf.to_screen(transform.quad[1][0] as f32, transform.quad[1][1] as f32); + let from = corner + egui::vec2(20.0, -20.0); + let to = corner + egui::vec2(45.0, 0.0); + let [x0, y0, x1, y1] = crate::transform_task_bar::shown_rect(app, &h.ctx).unwrap(); + assert!(!Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)).contains(from)); + assert!(xf.rect.contains(from) && xf.rect.contains(to)); + let hit = crate::transform_tool::box_hit(app, transform, xf.to_doc(from), crate::transform_tool::handle_tolerance(app)); + assert!(matches!(hit, crate::transform_tool::Hit::Outside), "control must start in the rotation zone: {hit:?}"); + task_bar_screen_drag(&mut h, from, to); + let after = h.state().ui.transform.as_ref().unwrap(); + assert_eq!((after.session, after.pivot), (before.0, before.1)); + assert_ne!(after.quad, before.2, "a real off-bar canvas drag must rotate the transform"); + assert_eq!(history(&h), before_history); +} + +fn task_bar_screen_drag(h: &mut AppHarness, from: egui::Pos2, to: egui::Pos2) { + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for step in 1..=6 { + h.event(egui::Event::PointerMoved(from + (to - from) * (step as f32 / 6.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +/// Crop uses the same floating frame and canvas drag routing as Free Transform. +#[test] +fn crop_task_bar_frame_drag_preserves_crop_but_off_bar_drag_rotates() { + for on_bar in [true, false] { + let mut h = harness(); + control(&mut h, "ui.set", json!({"tool": "crop"})); + h.state_mut().ui.crop_rect = Some([100.0, 100.0, 200.0, 160.0]); + h.run_steps(4); + let app = h.state(); + assert!(crate::crop_task_bar::eligible(app)); + let before = (app.ui.crop_rect, app.ui.crop_angle); + let before_history = history(&h); + let [x0, y0, x1, y1] = app.ui.task_bar_shown.expect("Crop bar must be visible"); + let frame = Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)); + let xf = ViewXform::active(app).unwrap(); + let (from, to) = if on_bar { + let from = pos2(frame.center().x, frame.bottom() - 1.0); + (from, from + egui::vec2(35.0, 25.0)) + } else { + (xf.to_screen(250.0, 130.0), xf.to_screen(150.0, 230.0)) + }; + assert_eq!(frame.contains(from), on_bar, "origin must identify the intended owner"); + assert!(xf.rect.contains(from) && xf.rect.contains(to)); + task_bar_screen_drag(&mut h, from, to); + let after = (h.state().ui.crop_rect, h.state().ui.crop_angle); + if on_bar { + assert_eq!(after, before, "dragging the Crop bar frame must not edit the crop"); + } else { + assert_ne!(after.1, before.1, "the off-bar Crop rotation control must still work"); + } + assert_eq!(history(&h), before_history, "an uncommitted crop drag must not edit document history"); + } +} diff --git a/crates/ui-egui/src/widgets/task_bar.rs b/crates/ui-egui/src/widgets/task_bar.rs index 1d8e48c4ed..2493a55828 100644 --- a/crates/ui-egui/src/widgets/task_bar.rs +++ b/crates/ui-egui/src/widgets/task_bar.rs @@ -105,7 +105,7 @@ pub fn show( let t = Tokens::get(ctx); let mut moved = None; let mut menu = MoreMenu { place: *place, shown: false, hide: false, picked: None }; - let out = egui::Area::new(area_id()).order(egui::Order::Middle).fixed_pos(at).constrain(false).show(ctx, |ui| { + let out = egui::Area::new(area_id()).order(egui::Order::Middle).fixed_pos(at).sense(Sense::click_and_drag()).constrain(false).show(ctx, |ui| { egui::Frame::NONE .fill(t.card) .stroke(Stroke::new(1.0, t.field_border)) From 4c80e88cc8848c080eb27f515eacad207bee7356 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 07:56:10 +0000 Subject: [PATCH 027/385] fix(retouch): match measured Sponge color response --- crates/algo/src/retouch.rs | 47 +++++++++ .../src/retouch_sponge_desaturate_tests.rs | 98 +++++++++++++++++++ .../algo/src/retouch_sponge_saturate_tests.rs | 30 ++++++ crates/engine/src/cmd/retouch_cmds/dab.rs | 8 +- crates/engine/src/cmd/retouch_cmds/tests.rs | 48 +++++++++ 5 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 crates/algo/src/retouch_sponge_desaturate_tests.rs create mode 100644 crates/algo/src/retouch_sponge_saturate_tests.rs diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 78b588f787..75a71c0eaf 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -109,6 +109,46 @@ pub fn sponge(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; compress_gamut([l + (c[0] - l) * k, l + (c[1] - l) * k, l + (c[2] - l) * k], l) } +/// Adjust a normalized RGB dab using the measured RGB Sponge response (#12972, #12973). +/// `amount` is the spacing-adjusted dab coverage from the brush engine. +pub fn sponge_rgb(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; 3] { + let [r, g, b] = c; + let lo = r.min(g).min(b); + let hi = r.max(g).max(b); + let chroma = hi - lo; + if amount <= 0.0 || chroma <= f32::EPSILON { + return c; + } + + // Express the dab in units of the reference 25%-spacing brush. At that spacing the brush + // passes 1 - (1 - flow / 2)^(1/4). Factor its inverse to retain precision at low coverage. + let amount = amount.min(1.0); + let remaining = 1.0 - amount; + let flow = 2.0 * amount * (1.0 + remaining) * (1.0 + remaining * remaining); + let grey = luma(c); + if !vibrance { + let gain = 1.0 + flow * if saturate { 0.4 } else { -0.2 }; + return compress_gamut(c.map(|v| grey + (v - grey) * gain), grey); + } + + // Vibrance changes the channel extrema asymmetrically. The shadow response tapers near + // black and near grey. The highlight response is limited by headroom in Saturate and by + // brightness and chroma in Desaturate. Fit those bounds to the measured single dabs. + let mid = r.min(g).max(r.max(g).min(b)); + let shadow = (((lo - 0.125).max(0.0) / 12.0) + (mid - lo) * 0.025).min(chroma / 6.0).min(lo); + let (low, high) = if saturate { + let highlight = (0.4 * (1.0 - hi)).min(0.5 * (hi - grey)); + ((lo - flow * shadow).max(0.0), hi + flow * highlight) + } else { + let weight = (0.5 * lo / hi).max(0.2); + let highlight = (0.06 * hi + 0.03 * lo).min(weight * (hi - grey)); + (lo + flow * shadow, hi - flow * highlight) + }; + // One affine map keeps the intermediate channel in the same position within the span. + let gain = (high - low).max(0.0) / chroma; + c.map(|v| low + (v - lo) * gain) +} + /// Gaussian blur of the window `[x0, x1) × [y0, y1)` of an interleaved `w × h × ch` buffer, reading /// neighbours with edge clamping. With an alpha channel (`alpha = Some(index)`), colour is blurred /// premultiplied so transparent pixels don't bleed their (meaningless) colour. Returns the window's @@ -372,3 +412,10 @@ mod tests { } } } + +#[cfg(test)] +#[path = "retouch_sponge_desaturate_tests.rs"] +mod sponge_desaturate_tests; +#[cfg(test)] +#[path = "retouch_sponge_saturate_tests.rs"] +mod sponge_saturate_tests; diff --git a/crates/algo/src/retouch_sponge_desaturate_tests.rs b/crates/algo/src/retouch_sponge_desaturate_tests.rs new file mode 100644 index 0000000000..f81b32dc5f --- /dev/null +++ b/crates/algo/src/retouch_sponge_desaturate_tests.rs @@ -0,0 +1,98 @@ +use super::sponge_rgb; + +const COLORS: [[u8; 3]; 9] = + [[200, 40, 40], [40, 160, 60], [40, 60, 200], [220, 170, 140], [230, 200, 40], [90, 50, 30], [180, 200, 230], [128, 64, 192], [255, 0, 0]]; + +fn dab_amount(flow: f32) -> f32 { + 1.0 - (1.0 - flow * 0.5).powf(0.25) +} + +pub(super) fn check_reference(saturate: bool, vibrance: bool, flow: f32, expected: [[u8; 3]; 9]) { + for (input, expected) in COLORS.into_iter().zip(expected) { + let actual = sponge_rgb(input.map(|v| f32::from(v) / 255.0), dab_amount(flow), saturate, vibrance).map(|v| (v * 255.0).round() as u8); + assert!( + actual.into_iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2), + "RGB {input:?}, Flow {flow}, Vibrance {vibrance}: {actual:?} vs {expected:?}" + ); + } +} + +#[test] +fn desaturate_matches_measured_single_dabs() { + // One 40 px hard round dab at 25% spacing, measured in #12972. + check_reference( + false, + true, + 0.5, + [[193, 40, 40], [41, 155, 60], [40, 59, 193], [213, 170, 144], [226, 197, 42], [87, 49, 31], [184, 200, 225], [126, 66, 185], [248, 0, 0]], + ); + check_reference( + false, + true, + 1.0, + [[187, 40, 40], [42, 149, 60], [40, 59, 187], [206, 170, 149], [223, 195, 44], [83, 48, 31], [187, 200, 219], [123, 69, 178], [240, 0, 0]], + ); + check_reference( + false, + false, + 0.5, + [[189, 44, 44], [47, 155, 65], [43, 61, 188], [216, 171, 144], [226, 199, 54], [87, 51, 33], [182, 200, 227], [125, 67, 183], [237, 7, 7]], + ); + check_reference( + false, + false, + 1.0, + [[178, 49, 49], [54, 151, 70], [46, 62, 175], [212, 172, 147], [222, 198, 69], [84, 52, 36], [183, 199, 223], [122, 71, 174], [220, 15, 15]], + ); +} + +#[test] +fn greys_are_fixed_for_both_modes_and_every_flow() { + for level in 0..=255u8 { + let grey = [f32::from(level) / 255.0; 3]; + for flow in 0..=100u8 { + for saturate in [false, true] { + for vibrance in [false, true] { + assert_eq!(sponge_rgb(grey, dab_amount(f32::from(flow) / 100.0), saturate, vibrance), grey); + } + } + } + } +} + +#[test] +fn flow_changes_chroma_monotonically_and_preserves_hue_in_the_rgb_gamut() { + let levels: [f32; 9] = [0.0, 0.02, 0.12, 0.3, 0.5, 0.7, 0.9, 0.99, 1.0]; + for r in levels { + for g in levels { + for b in levels { + let input = [r, g, b]; + let lo = r.min(g).min(b); + let hi = r.max(g).max(b); + let chroma = hi - lo; + if chroma == 0.0 { + continue; + } + let hue = input.map(|v| (v - lo) / chroma); + for saturate in [false, true] { + for vibrance in [false, true] { + assert_eq!(sponge_rgb(input, 0.0, saturate, vibrance), input); + let mut previous = chroma; + for amount in [dab_amount(0.1), dab_amount(0.5), dab_amount(1.0), 0.5, 1.0] { + let actual = sponge_rgb(input, amount, saturate, vibrance); + assert!(actual.into_iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(&v)), "{input:?} became {actual:?}"); + let lo = actual.into_iter().fold(1.0, f32::min); + let hi = actual.into_iter().fold(0.0, f32::max); + let span = hi - lo; + assert!(if saturate { span >= previous - 1e-6 } else { span <= previous + 1e-6 }); + for (out, normalized) in actual.into_iter().zip(hue) { + assert!((out - lo - normalized * span).abs() < 1e-6, "{input:?} became {actual:?}"); + } + previous = span; + } + } + } + } + } + } +} diff --git a/crates/algo/src/retouch_sponge_saturate_tests.rs b/crates/algo/src/retouch_sponge_saturate_tests.rs new file mode 100644 index 0000000000..ec3a165536 --- /dev/null +++ b/crates/algo/src/retouch_sponge_saturate_tests.rs @@ -0,0 +1,30 @@ +use super::sponge_desaturate_tests::check_reference; + +#[test] +fn saturate_matches_measured_single_dabs() { + // One 40 px hard round dab at 25% spacing, measured in #12973. + check_reference( + true, + true, + 0.5, + [[211, 40, 40], [40, 172, 62], [40, 61, 211], [227, 169, 135], [235, 204, 38], [97, 52, 30], [176, 199, 235], [133, 62, 204], [255, 0, 0]], + ); + check_reference( + true, + true, + 1.0, + [[222, 39, 39], [39, 184, 64], [39, 62, 222], [234, 169, 130], [240, 207, 36], [105, 55, 30], [171, 199, 240], [138, 60, 217], [255, 0, 0]], + ); + check_reference( + true, + false, + 0.5, + [[222, 31, 31], [25, 169, 49], [34, 58, 225], [228, 168, 132], [238, 202, 11], [96, 48, 24], [177, 201, 237], [134, 57, 210], [255, 1, 1]], + ); + check_reference( + true, + false, + 1.0, + [[244, 21, 21], [11, 178, 39], [28, 56, 251], [235, 166, 124], [240, 202, 1], [102, 46, 18], [173, 201, 243], [140, 51, 229], [255, 1, 1]], + ); +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index a0fe5da71b..c3eb9b5f58 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -4,6 +4,8 @@ use super::{ Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, blend_from_str, damage_json, dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, }; +use photocraft_algo::retouch::sponge_rgb; +use photocraft_color::{ColorMode, SampleType}; // --------------------------------------------------------------------------------------------- // Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge @@ -232,7 +234,11 @@ impl DabTool { let sp = spacing; match self.clone() { Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), - // Flow is already in each dab's coverage; a full-flow pass moves colours half-way. + // Flow is already in the dab's coverage. The reference RGB response applies to integer + // RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve. + Self::Sponge { saturate, vibrance } if fmt.mode == ColorMode::Rgb && fmt.sample != SampleType::F32 => { + Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge_rgb(c, k, saturate, vibrance))) + } Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), Self::Focus { sharpen, strength, protect, sigma } => { let a = alpha_index(&fmt); diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index c96b153fb7..6354958cc2 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -456,6 +456,54 @@ fn sponge_reduces_and_increases_saturation() { } } +#[test] +fn sponge_rgb_single_dab_matches_reference_at_integer_depths() { + for depth in [8, 16] { + for (mode, flow, vibrance, input, expected) in [ + ("desaturate", 50, true, [220, 170, 140], [213, 170, 144]), + ("desaturate", 100, false, [200, 40, 40], [178, 49, 49]), + ("saturate", 50, false, [230, 200, 40], [238, 202, 11]), + ("saturate", 100, true, [40, 160, 60], [39, 184, 64]), + ] { + let [r, g, b] = input.map(|v| v as f32 / 255.0); + let mut s = session(64, 64, depth, "rgb"); + paint_layer(&mut s, |_, _| [r, g, b, 1.0]); + let before = rgba(&s, 32, 32); + s.execute( + "paint.sponge", + json!({"points": [[32, 32]], "size": 40, "hardness": 100, "spacing": 25, "flow": flow, "mode": mode, "vibrance": vibrance}), + ) + .unwrap(); + let [r, g, b, a] = rgba(&s, 32, 32); + let actual = [r, g, b].map(|v| (v * 255.0).round() as i32); + assert!(actual.into_iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2), "{depth}-bit {mode}, Flow {flow}, Vibrance {vibrance}: {actual:?}"); + assert_eq!(a, before[3]); + assert_eq!(rgba(&s, 0, 0), before); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Sponge Tool")); + assert!(s.undo()); + assert_eq!(rgba(&s, 32, 32), before); + } + } +} + +#[test] +fn sponge_float_rgb_and_lab_keep_the_existing_transfer() { + for (depth, mode) in [(32, "rgb"), (8, "lab")] { + let mut s = session(64, 64, depth, mode); + paint_layer(&mut s, |_, _| [200.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0, 1.0]); + let [r, g, b, a] = rgba(&s, 32, 32); + let [r, g, b] = sponge([r, g, b], 1.0 - 0.75f32.powf(0.25), false, true); + let doc = &s.active().unwrap().doc; + let fmt = doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().format(); + let mut expected = Surface::new(fmt); + expected.write_region(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [r, g, b, a])); + s.execute("paint.sponge", json!({"points": [[32, 32]], "size": 40, "hardness": 100, "spacing": 25, "flow": 50})).unwrap(); + for (actual, expected) in rgba(&s, 32, 32).into_iter().zip(expected.rgba(0, 0)) { + assert!((actual - expected).abs() <= 1e-6, "{mode} {depth}-bit: {actual} vs {expected}"); + } + } +} + #[test] fn blur_reduces_local_variance_and_sharpen_increases_it() { for depth in [8u64, 16] { From b40ce02ea906ace01298f056a7cd98e969490138 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 08:37:03 +0000 Subject: [PATCH 028/385] perf(retouch): bound Sponge gain before mapping channels --- crates/algo/src/retouch.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 75a71c0eaf..9cb159f5a2 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -127,8 +127,20 @@ pub fn sponge_rgb(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [ let flow = 2.0 * amount * (1.0 + remaining) * (1.0 + remaining * remaining); let grey = luma(c); if !vibrance { - let gain = 1.0 + flow * if saturate { 0.4 } else { -0.2 }; - return compress_gamut(c.map(|v| grey + (v - grey) * gain), grey); + let mut gain = 1.0 - 0.2 * flow; + if saturate { + gain = 1.0 + 0.4 * flow; + // Limit the gain before applying it to all three channels, using the same luma pivot. + let shadow = grey - lo; + if gain * shadow > grey { + gain = grey / shadow; + } + let highlight = hi - grey; + if gain * highlight > 1.0 - grey { + gain = (1.0 - grey) / highlight; + } + } + return c.map(|v| grey + (v - grey) * gain); } // Vibrance changes the channel extrema asymmetrically. The shadow response tapers near From ead29a0f58f70b0a73a0b9cda18660724d1fd682 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:33:51 +0100 Subject: [PATCH 029/385] #12284: keep the Mixer Brush amount finite when the remaining supply underflows to zero (0/0 was NaN) Co-Authored-By: Hector Villarreal Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/mixer.rs | 4 +++- crates/paint/src/mixer_load_supply_tests.rs | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index 9ecd4ae2b1..571614aa85 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -354,7 +354,9 @@ pub fn apply_mixer_dab_region( }; let step = state.last_dab.filter(|(index, ..)| fp.index > *index).map_or(0.0, |(_, lx, ly)| (x - lx).hypot(y - ly) as f32); let after = before + if step.is_finite() { step } else { 0.0 }; - amount *= supply_left(load, after) / supply_left(load, before); + // Far enough past the supply both shares underflow to zero; the load is then simply used up. + let left = supply_left(load, before); + amount = if left > 0.0 { amount * supply_left(load, after) / left } else { 0.0 }; state.travelled = after; state.last_dab = Some((fp.index, x, y)); state.amount = amount; diff --git a/crates/paint/src/mixer_load_supply_tests.rs b/crates/paint/src/mixer_load_supply_tests.rs index af946f4795..2deb0290e3 100644 --- a/crates/paint/src/mixer_load_supply_tests.rs +++ b/crates/paint/src/mixer_load_supply_tests.rs @@ -88,3 +88,11 @@ fn each_stroke_measures_its_own_length() { apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false); assert_eq!(st.amount, 1.0, "the second stroke starts its own 570 px"); } + +#[test] +fn a_very_long_stroke_keeps_the_amount_finite() { + // Thousands of px past the supply the remaining share underflows to zero; the amount must not + // turn into NaN (0 / 0). + let (_, amount) = paint(0.01, 0.0, 20_000.0, 1.0); + assert!(amount.is_finite() && amount >= 0.0, "{amount}"); +} From 602d2b89b0e438e548280807c74bb994934bd717 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:46:16 +0100 Subject: [PATCH 030/385] #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 d29eb78ffddc8a967909d63440e57e045f52c65b Mon Sep 17 00:00:00 2001 From: PhotoCraft contribution Date: Wed, 11 Nov 2026 04:49:04 -0800 Subject: [PATCH 031/385] Test real task-bar grip drags in Free Transform and Crop --- .../ui-egui/src/transform_task_bar_tests.rs | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 914b34be01..84df54f416 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -369,6 +369,82 @@ fn task_bar_screen_drag(h: &mut AppHarness, from: egui::Pos2, to: egui::Pos2) { h.run_steps(3); } +fn task_bar_screen_rect(h: &mut AppHarness) -> Rect { + let shown = bar(h); + assert_eq!(shown["visible"], true); + let [x0, y0, x1, y1]: [f32; 4] = serde_json::from_value(shown["rect"].clone()).unwrap(); + Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)) +} + +/// Hit the real 12-point child grip, not the surrounding Area or an inspection command. +fn drag_task_bar_grip(h: &mut AppHarness) -> Rect { + let before = task_bar_screen_rect(h); + let grip = h.get_by_label("Move bar").rect(); + assert!((grip.width() - 12.0).abs() <= 0.1, "the shared grip remains twelve points wide: {grip:?}"); + assert!(before.contains_rect(grip), "the pointer must hit the grip inside the visible bar"); + assert!(h.state().ui.panels.task_bar.at.is_none(), "a fresh bar follows its frame before the drag"); + let area = ViewXform::active(h.state()).unwrap().rect; + let from = grip.center(); + let delta = egui::vec2(40.0, -24.0); + assert!(area.contains(from) && area.contains(from + delta)); + let document = h.state().session.active().unwrap().doc.clone(); + let edits = history(h); + task_bar_screen_drag(h, from, from + delta); + let after = task_bar_screen_rect(h); + let movement = after.min - before.min; + assert!(movement.length() > 12.0 && movement.dot(delta) > 0.0, "the grip must move the bar: {before:?} -> {after:?}"); + let place = h.state().ui.panels.task_bar; + let [x, y] = place.at.expect("a grip drag stores the canvas-relative bar position"); + assert!((after.min - (area.min + egui::vec2(x, y))).length() <= 1.0, "the displayed bar must use the saved position"); + assert_eq!(bar(h)["at"], json!([x, y])); + // This is the same serialized panel-layout field used across restarts, not a transient Area rect. + let restored: crate::state::TaskBarPlace = serde_json::from_value(serde_json::to_value(place).unwrap()).unwrap(); + assert_eq!(restored, place); + h.run_steps(4); + assert_eq!(h.state().ui.panels.task_bar, place, "the drop stays saved on later canvas passes"); + assert!((task_bar_screen_rect(h).min - after.min).length() <= 1.0); + assert!(std::sync::Arc::ptr_eq(&document, &h.state().session.active().unwrap().doc)); + assert_eq!(history(h), edits, "moving the bar must not commit a document edit"); + after +} + +#[test] +fn transform_task_bar_grip_drag_moves_the_saved_bar_without_changing_the_box() { + let mut h = open_box(); + let transform = h.state().ui.transform.as_ref().unwrap(); + let before = (transform.session, transform.pivot, transform.quad); + let edits = history(&h); + let shown = drag_task_bar_grip(&mut h); + let transform = h.state().ui.transform.as_ref().expect("the same transform stays open"); + assert_eq!((transform.session, transform.pivot, transform.quad), before); + // A real pointer click after the grip drop still reaches a child button through the Area sense. + let button = h.get_by_label("Rotate 90° Clockwise").rect().center(); + assert!(shown.contains(button)); + task_bar_screen_drag(&mut h, button, button); + let transform = h.state().ui.transform.as_ref().unwrap(); + assert_eq!((transform.session, transform.pivot), (before.0, before.1)); + assert_ne!(transform.quad, before.2, "the relocated rotation button still works"); + assert_eq!(history(&h), edits); +} + +#[test] +fn crop_task_bar_grip_drag_moves_the_saved_bar_without_changing_the_crop() { + let mut h = harness(); + control(&mut h, "ui.set", json!({"tool": "crop"})); + h.state_mut().ui.crop_rect = Some([100.0, 100.0, 200.0, 160.0]); + h.run_steps(4); + assert!(crate::crop_task_bar::eligible(h.state())); + let before = (h.state().ui.crop_rect, h.state().ui.crop_angle); + let edits = history(&h); + let shown = drag_task_bar_grip(&mut h); + assert_eq!((h.state().ui.crop_rect, h.state().ui.crop_angle), before); + let cancel = h.get_by_label("Cancel").rect().center(); + assert!(shown.contains(cancel)); + task_bar_screen_drag(&mut h, cancel, cancel); + assert!(h.state().ui.crop_rect.is_none(), "the relocated Cancel button still dismisses the crop"); + assert_eq!(history(&h), edits); +} + /// Crop uses the same floating frame and canvas drag routing as Free Transform. #[test] fn crop_task_bar_frame_drag_preserves_crop_but_off_bar_drag_rotates() { From 8399b767d2a3a004ed3c4a689da7d6de93bef8f8 Mon Sep 17 00:00:00 2001 From: PhotoCraft contribution Date: Wed, 11 Nov 2026 05:25:15 -0800 Subject: [PATCH 032/385] Use real short pointer clicks after task-bar grip drags --- crates/ui-egui/src/transform_task_bar_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 84df54f416..46199a45e9 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -420,7 +420,7 @@ fn transform_task_bar_grip_drag_moves_the_saved_bar_without_changing_the_box() { // A real pointer click after the grip drop still reaches a child button through the Area sense. let button = h.get_by_label("Rotate 90° Clockwise").rect().center(); assert!(shown.contains(button)); - task_bar_screen_drag(&mut h, button, button); + click(&mut h, "Rotate 90° Clockwise"); let transform = h.state().ui.transform.as_ref().unwrap(); assert_eq!((transform.session, transform.pivot), (before.0, before.1)); assert_ne!(transform.quad, before.2, "the relocated rotation button still works"); @@ -440,7 +440,7 @@ fn crop_task_bar_grip_drag_moves_the_saved_bar_without_changing_the_crop() { assert_eq!((h.state().ui.crop_rect, h.state().ui.crop_angle), before); let cancel = h.get_by_label("Cancel").rect().center(); assert!(shown.contains(cancel)); - task_bar_screen_drag(&mut h, cancel, cancel); + click(&mut h, "Cancel"); assert!(h.state().ui.crop_rect.is_none(), "the relocated Cancel button still dismisses the crop"); assert_eq!(history(&h), edits); } From 944d0b67d610021094ed9adf1e29ec8cad4bf744 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Wed, 11 Nov 2026 07:50:25 -0600 Subject: [PATCH 033/385] #12284: a Mixer dab deposits the supply left at its own distance (CodeRabbit, mixer.rs:350) The load's supply is a length of stroke, but the dab used the amount left at the dab before: depletion ran after the deposit. With a wide spacing (35 px tip at 1000 %: dabs at 30, 380, 730) the dab 700 px into a 390 px supply still painted solid. The distance update now runs before the dab deposits; the first dab is still at distance zero. Test: a_dab_deposits_the_supply_left_at_its_own_distance (254 at x 730 before). --- crates/paint/src/mixer.rs | 26 +++++++++++---------- crates/paint/src/mixer_load_supply_tests.rs | 10 ++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index 571614aa85..8c667d31c1 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -271,9 +271,21 @@ pub fn apply_mixer_dab_region( v }; let res = state.reservoir.map(native); - let mut amount = if res.is_some() { state.amount.clamp(0.0, 1.0) } else { 0.0 }; - let mut pickup: Option> = state.pickup.map(native); let (mix, flow, load) = (m.mix.clamp(0.0, 1.0), m.flow.clamp(0.0, 1.0), m.load.clamp(0.0, 1.0)); + let mut amount = if res.is_some() { state.amount.clamp(0.0, 1.0) } else { 0.0 }; + // The supply is a length of stroke (#11943): the dab deposits what is left at its own + // distance from the stroke start, the first dab at none. + let (x, y) = (fp.dab.center.x, fp.dab.center.y); + let before = match state.last_dab { + Some((index, ..)) if fp.index > index => state.travelled, + _ => 0.0, + }; + let step = state.last_dab.filter(|(index, ..)| fp.index > *index).map_or(0.0, |(_, lx, ly)| (x - lx).hypot(y - ly) as f32); + let after = before + if step.is_finite() { step } else { 0.0 }; + // Far enough past the supply both shares underflow to zero; the load is then simply used up. + let left = supply_left(load, before); + amount = if left > 0.0 { amount * supply_left(load, after) / left } else { 0.0 }; + let mut pickup: Option> = state.pickup.map(native); let mut paint = vec![0.0f32; n]; // Transfer › Wetness / Mix Jitter scale the settings per dab. let (wet, mix) = (m.effective_wet(&fp.dab), mix * fp.dab.mix.clamp(0.0, 1.0)); @@ -347,16 +359,6 @@ pub fn apply_mixer_dab_region( } } } - let (x, y) = (fp.dab.center.x, fp.dab.center.y); - let before = match state.last_dab { - Some((index, ..)) if fp.index > index => state.travelled, - _ => 0.0, - }; - let step = state.last_dab.filter(|(index, ..)| fp.index > *index).map_or(0.0, |(_, lx, ly)| (x - lx).hypot(y - ly) as f32); - let after = before + if step.is_finite() { step } else { 0.0 }; - // Far enough past the supply both shares underflow to zero; the load is then simply used up. - let left = supply_left(load, before); - amount = if left > 0.0 { amount * supply_left(load, after) / left } else { 0.0 }; state.travelled = after; state.last_dab = Some((fp.index, x, y)); state.amount = amount; diff --git a/crates/paint/src/mixer_load_supply_tests.rs b/crates/paint/src/mixer_load_supply_tests.rs index 2deb0290e3..7da317db92 100644 --- a/crates/paint/src/mixer_load_supply_tests.rs +++ b/crates/paint/src/mixer_load_supply_tests.rs @@ -96,3 +96,13 @@ fn a_very_long_stroke_keeps_the_amount_finite() { let (_, amount) = paint(0.01, 0.0, 20_000.0, 1.0); assert!(amount.is_finite() && amount >= 0.0, "{amount}"); } + +#[test] +fn a_dab_deposits_the_supply_left_at_its_own_distance() { + // A 35 px tip at spacing 1000 % lays dabs at x 30, 380 and 730. At Load 1 % the supply is 390 + // px of stroke: the dab 350 px in is solid, the one 700 px in is past it and already fading, + // not painted with the supply left at the dab before. + let (alpha, _) = paint(0.01, 30.0, 770.0, 10.0); + assert!(alpha(380) >= 250, "alpha {} at x 380, inside the supply", alpha(380)); + assert!(alpha(730) < 250, "alpha {} at x 730, 700 px into a 390 px supply", alpha(730)); +} From 36e4c166100de2fc7c08e58ef6ec1d5b7cd07706 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 11 Nov 2026 09:06:11 -0800 Subject: [PATCH 034/385] Keep Type options control identities stable while fonts load --- .../src/tools/type_tool/options_bar.rs | 62 ++++++++++--------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index 4a1687dbd4..56f8157c25 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -26,37 +26,41 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } // Font family and style menus (one placeholder in their place while the fonts load). - if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { - if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { - app.ui.tool_options.type_font = fam.clone(); - let st = styles(&fam); - let picked = picked.filter(|s| st.contains(s)); - style = match &picked { - Some(s) => s.clone(), - None if st.contains(&style) => style, - None => st.first().cloned().unwrap_or_else(|| "Regular".into()), - }; - app.ui.tool_options.type_style = style.clone(); - // Only a style picked under the family's ">" is set: otherwise each selected layer - // keeps its own face in the new family (#3556). - match picked { - Some(s) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": s})), - None => apply(app, ui.ctx(), json!({"font": fam})), + // Keep the following controls' positional IDs stable when the font menus replace the + // loading placeholder: both states occupy one slot in the parent UI. + ui.scope(|ui| { + if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { + if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { + app.ui.tool_options.type_font = fam.clone(); + let st = styles(&fam); + let picked = picked.filter(|s| st.contains(s)); + style = match &picked { + Some(s) => s.clone(), + None if st.contains(&style) => style, + None => st.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + app.ui.tool_options.type_style = style.clone(); + // Only a style picked under the family's ">" is set: otherwise each selected layer + // keeps its own face in the new family (#3556). + match picked { + Some(s) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": s})), + None => apply(app, ui.ctx(), json!({"font": fam})), + } + } + font_picker_tip(ui, tl!("Search and select fonts")); + let style_family = if fam.is_empty() { styles_at(app).map(|(c, _)| c.font_family).unwrap_or_default() } else { fam.clone() }; + let opts: Vec<(String, String)> = styles(&style_family).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); + let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); + if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"fontStyle": style})); + } + // The menu's button, by the id its combo box takes from "type-style"; "Style" stays its name. + if let Some(menu) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("type-style"))) { + menu.on_hover_text(tl!("Set font style")); } } - font_picker_tip(ui, tl!("Search and select fonts")); - let style_family = if fam.is_empty() { styles_at(app).map(|(c, _)| c.font_family).unwrap_or_default() } else { fam.clone() }; - let opts: Vec<(String, String)> = styles(&style_family).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); - let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); - if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { - app.ui.tool_options.type_style = style.clone(); - apply(app, ui.ctx(), json!({"fontStyle": style})); - } - // The menu's button, by the id its combo box takes from "type-style"; "Style" stays its name. - if let Some(menu) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("type-style"))) { - menu.on_hover_text(tl!("Set font style")); - } - } + }); let (r, icon) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover()); crate::icons::paint(ui, r, "type", 13.0, t.icon); icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tl!("Font size"))); From 72f1e618ad560f4475194eec24cf27eb1c390823 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 11 Nov 2026 13:21:19 -0800 Subject: [PATCH 035/385] Remove PR-only FT screenshot evidence from repository --- docs/images/free-transform-task-bar-after.png | Bin 134004 -> 0 bytes docs/images/free-transform-task-bar-before.png | Bin 126057 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 docs/images/free-transform-task-bar-after.png delete mode 100644 docs/images/free-transform-task-bar-before.png diff --git a/docs/images/free-transform-task-bar-after.png b/docs/images/free-transform-task-bar-after.png deleted file mode 100644 index 11c270e951f75c4511fd7fce975bb8863de2d8dc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 134004 zcmcG%3s{up+BQ6hO1X*D%F={#6U!{IOwk0!-fWqfvC37J8>p;UMv98Y0K*JsrDjTL zM(&tat+Mh(a+v}O42p_79Lp39WZ0u3%nq0t80PuU^CB&KbG`p}e8+bjD|NA%dFHwA z``VnF>sj@;XD0XVF`$P^rRqK9$w|+tRNX#TseIqPsXM+hW7?-bsk-!>FlEwXf7kdl z7WjTX^rcS^+m!gGHAhZtTRe5{j`^i~e*NFP57R$=Dl`4z(Sw`ZZ)d%k`1OhjF=sOK zFO=qO&AI&D_8oiw{14^Dt~2H=J@fpZ|IredT5;pw-R`aKGy8_WyY!4c^!`78S^SRD z!{Od?=+(zEHf;AQpMAZmcJa|ScUL_zsrH6%_rxOx)1~(G_NINQ_~GXj{R4OOd}iyT z-3s`76Kl;CYyI@MYeJ)H>P?3F zO))!O**()X_#W2`%`ZcY8@GkFC0*KA(aoKnN1^&V@;;ql72bn zklg*Tz8~$}|5d-tq8ls(?^y8P68db-Yt73xPc{BL)p{wj+40tb`S$vv@O7~{4aq9a zhFyXC4P{G))SIGebQa~Yz`{UJtI4r9N^r8VirE4@$80*DqR-Yx^rcS$ugykX~`>O}um4y*>MQMikoz8=Nm0 z4hDK{23u8X@@>H_&jmm8Wqn$B#U*X?WZgZn?mJ=+E-jhkTQJvPd*$vy54tnVUfQKc7$6T;h|Zkw*NL&J+5wk+?}QQG9+{pQ&GjrH}*)vo346DH5o z-i+|Z)8T9U6{~;!)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v+x;J%j9jtMn!dTPsAuSd zff;934b;ru84)$AYw}+rk0W@h3~~M~@`r*;ZD$sR&)#(Bp|y_MA^p?do??U^FWndJ zE_!89?BcnH<9^A^y2n+PvVWs>mD_i(HFmSWDtr@fDr_(1Z^NSN_Syo;iK4hFDD=fLP*Bw#Se~FqDal!b*8y~xo zwnK<1%}xMp;LZWL?%(;xtpA$6h;=tqn*hU^Z9$=a;e}ndz19LWjp(f^^^T&*r@D`% oSyXeuT;1>79nRB~W41e6RT^^gmhs~a{NJd%9vHFVjwk2+f8_Zxod5s; From c6c562b3a11a6615c94b70d3a7d71b78cb1f918c Mon Sep 17 00:00:00 2001 From: Omar Saidahmed Date: Wed, 28 Oct 2026 18:57:08 -0400 Subject: [PATCH 036/385] 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 037/385] 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 038/385] 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 1d425bbf5e850fc5f9cef5dd7831de826b936c48 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 12 Nov 2026 11:59:08 +0000 Subject: [PATCH 039/385] Normalize Sponge strength across brush spacing --- crates/algo/src/retouch.rs | 28 ++++++---- .../src/retouch_sponge_desaturate_tests.rs | 51 +++++++++++++++---- crates/engine/src/cmd/retouch_cmds/dab.rs | 10 ++-- crates/engine/src/cmd/retouch_cmds/tests.rs | 20 ++++++++ 4 files changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 9cb159f5a2..a2d208dd85 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -110,26 +110,25 @@ pub fn sponge(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; } /// Adjust a normalized RGB dab using the measured RGB Sponge response (#12972, #12973). -/// `amount` is the spacing-adjusted dab coverage from the brush engine. -pub fn sponge_rgb(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; 3] { +/// `coverage` includes Flow and the brush falloff. `spacing` is in brush diameters. +pub fn sponge_rgb(c: [f32; 3], coverage: f32, spacing: f32, saturate: bool, vibrance: bool) -> [f32; 3] { let [r, g, b] = c; let lo = r.min(g).min(b); let hi = r.max(g).max(b); let chroma = hi - lo; - if amount <= 0.0 || chroma <= f32::EPSILON { + if coverage <= 0.0 || chroma <= f32::EPSILON { return c; } - // Express the dab in units of the reference 25%-spacing brush. At that spacing the brush - // passes 1 - (1 - flow / 2)^(1/4). Factor its inverse to retain precision at low coverage. - let amount = amount.min(1.0); - let remaining = 1.0 - amount; - let flow = 2.0 * amount * (1.0 + remaining) * (1.0 + remaining * remaining); + let flow = coverage.min(1.0); + // The measured dab covers a quarter of a brush diameter along the stroke. Scale its gain + // multiplicatively so the same distance gets the same strength from more or fewer dabs. + let steps = 4.0 * spacing.clamp(0.01, 1.0); let grey = luma(c); if !vibrance { - let mut gain = 1.0 - 0.2 * flow; + let reference_gain = if saturate { 1.0 + 0.4 * flow } else { 1.0 - 0.2 * flow }; + let mut gain = if steps == 1.0 { reference_gain } else { reference_gain.powf(steps) }; if saturate { - gain = 1.0 + 0.4 * flow; // Limit the gain before applying it to all three channels, using the same luma pivot. let shadow = grey - lo; if gain * shadow > grey { @@ -156,6 +155,15 @@ pub fn sponge_rgb(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [ let highlight = (0.06 * hi + 0.03 * lo).min(weight * (hi - grey)); (lo + flow * shadow, hi - flow * highlight) }; + // Compose the measured affine response for this dab's distance, holding its locally + // computed coefficients fixed. Use expm1 for small changes and cap at the RGB gamut. + let (low, high) = if steps == 1.0 { + (low, high) + } else { + let change = ((high - hi) - (low - lo)) / chroma; + let scale = if change == 0.0 { steps } else { (steps * change.ln_1p()).exp_m1() / change }; + ((lo + (low - lo) * scale).max(0.0), (hi + (high - hi) * scale).min(1.0)) + }; // One affine map keeps the intermediate channel in the same position within the span. let gain = (high - low).max(0.0) / chroma; c.map(|v| low + (v - lo) * gain) diff --git a/crates/algo/src/retouch_sponge_desaturate_tests.rs b/crates/algo/src/retouch_sponge_desaturate_tests.rs index f81b32dc5f..3461065274 100644 --- a/crates/algo/src/retouch_sponge_desaturate_tests.rs +++ b/crates/algo/src/retouch_sponge_desaturate_tests.rs @@ -3,13 +3,9 @@ use super::sponge_rgb; const COLORS: [[u8; 3]; 9] = [[200, 40, 40], [40, 160, 60], [40, 60, 200], [220, 170, 140], [230, 200, 40], [90, 50, 30], [180, 200, 230], [128, 64, 192], [255, 0, 0]]; -fn dab_amount(flow: f32) -> f32 { - 1.0 - (1.0 - flow * 0.5).powf(0.25) -} - pub(super) fn check_reference(saturate: bool, vibrance: bool, flow: f32, expected: [[u8; 3]; 9]) { for (input, expected) in COLORS.into_iter().zip(expected) { - let actual = sponge_rgb(input.map(|v| f32::from(v) / 255.0), dab_amount(flow), saturate, vibrance).map(|v| (v * 255.0).round() as u8); + let actual = sponge_rgb(input.map(|v| f32::from(v) / 255.0), flow, 0.25, saturate, vibrance).map(|v| (v * 255.0).round() as u8); assert!( actual.into_iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2), "RGB {input:?}, Flow {flow}, Vibrance {vibrance}: {actual:?} vs {expected:?}" @@ -53,7 +49,7 @@ fn greys_are_fixed_for_both_modes_and_every_flow() { for flow in 0..=100u8 { for saturate in [false, true] { for vibrance in [false, true] { - assert_eq!(sponge_rgb(grey, dab_amount(f32::from(flow) / 100.0), saturate, vibrance), grey); + assert_eq!(sponge_rgb(grey, f32::from(flow) / 100.0, 0.25, saturate, vibrance), grey); } } } @@ -76,10 +72,10 @@ fn flow_changes_chroma_monotonically_and_preserves_hue_in_the_rgb_gamut() { let hue = input.map(|v| (v - lo) / chroma); for saturate in [false, true] { for vibrance in [false, true] { - assert_eq!(sponge_rgb(input, 0.0, saturate, vibrance), input); + assert_eq!(sponge_rgb(input, 0.0, 0.25, saturate, vibrance), input); let mut previous = chroma; - for amount in [dab_amount(0.1), dab_amount(0.5), dab_amount(1.0), 0.5, 1.0] { - let actual = sponge_rgb(input, amount, saturate, vibrance); + for amount in [0.1, 0.5, 1.0] { + let actual = sponge_rgb(input, amount, 0.25, saturate, vibrance); assert!(actual.into_iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(&v)), "{input:?} became {actual:?}"); let lo = actual.into_iter().fold(1.0, f32::min); let hi = actual.into_iter().fold(0.0, f32::max); @@ -96,3 +92,40 @@ fn flow_changes_chroma_monotonically_and_preserves_hue_in_the_rgb_gamut() { } } } + +#[test] +fn equal_distance_non_vibrance_passes_have_equal_strength() { + let input = [0.58, 0.51, 0.42]; + for flow in [0.2, 0.5, 1.0] { + for saturate in [false, true] { + let pass = |spacing, dabs| (0..dabs).fold(input, |rgb, _| sponge_rgb(rgb, flow, spacing, saturate, false)); + let reference = pass(0.25, 4); + for (spacing, dabs) in [(0.125, 8), (0.5, 2), (1.0, 1)] { + for (actual, expected) in pass(spacing, dabs).into_iter().zip(reference) { + assert!((actual - expected).abs() < 1e-6, "Flow {flow}, spacing {spacing}, saturate {saturate}: {actual} vs {expected}"); + } + } + } + } +} + +#[test] +fn vibrance_at_other_spacings_stays_in_gamut_and_preserves_hue() { + for input in COLORS.map(|rgb| rgb.map(|v| f32::from(v) / 255.0)) { + let lo = input.into_iter().fold(1.0, f32::min); + let hi = input.into_iter().fold(0.0, f32::max); + let hue = input.map(|v| (v - lo) / (hi - lo)); + for spacing in [0.01, 0.125, 0.5, 1.0] { + for saturate in [false, true] { + let out = sponge_rgb(input, 1.0, spacing, saturate, true); + let a = out.into_iter().fold(1.0, f32::min); + let b = out.into_iter().fold(0.0, f32::max); + assert!(out.into_iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(&v)), "{input:?} became {out:?}"); + assert!(if saturate { b - a >= hi - lo - 1e-6 } else { b - a <= hi - lo + 1e-6 }); + for (v, h) in out.into_iter().zip(hue) { + assert!((v - a - h * (b - a)).abs() < 1e-6, "{input:?} became {out:?}"); + } + } + } + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 9560cf1223..a4c04d287b 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -20,13 +20,13 @@ fn per_dab(e: f32, spacing: f32) -> f32 { /// Apply an RGB colour transform `f(rgb, strength)` to each covered pixel of a dab (through straight /// RGBA, so it works for Gray/CMYK/Lab too; untouched pixels are never round-tripped). -fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32, spacing: f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) { +fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: impl Fn(f32) -> f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) { let r = fp.rect.intersect(&work.rect); let n = fmt.channels(); let mut enc = [0.0f32; 8]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let k = per_dab(fp.at(x, y) * strength, spacing); + let k = strength(fp.at(x, y)); if k <= 0.0 { continue; } @@ -237,9 +237,11 @@ impl DabTool { // Flow is already in the dab's coverage. The reference RGB response applies to integer // RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve. Self::Sponge { saturate, vibrance } if fmt.mode == ColorMode::Rgb && fmt.sample != SampleType::F32 => { - Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge_rgb(c, k, saturate, vibrance))) + Box::new(move |work, fp| color_dab(&fmt, work, fp, |k| k, |c, k| sponge_rgb(c, k, sp, saturate, vibrance))) + } + Self::Sponge { saturate, vibrance } => { + Box::new(move |work, fp| color_dab(&fmt, work, fp, |k| per_dab(k * 0.5, sp), |c, k| sponge(c, k, saturate, vibrance))) } - Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), Self::Focus { sharpen, strength, protect, sigma } => { let a = alpha_index(&fmt); Box::new(move |work, fp| { diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 53d9ea69ee..1309c7110f 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -502,6 +502,26 @@ fn sponge_rgb_single_dab_matches_reference_at_integer_depths() { } } +#[test] +fn sponge_single_dab_uses_the_requested_spacing() { + for depth in [8, 16] { + for spacing in [25, 50, 100] { + let mut s = session(64, 64, depth, "rgb"); + paint_layer(&mut s, |_, _| [0.8, 0.4, 0.2, 1.0]); + let [r0, _, b0, a0] = rgba(&s, 32, 32); + s.execute( + "paint.sponge", + json!({"points": [[32, 32]], "size": 40, "hardness": 100, "spacing": spacing, "flow": 100, "mode": "desaturate", "vibrance": false}), + ) + .unwrap(); + let [r, _, b, a] = rgba(&s, 32, 32); + let expected = (r0 - b0) * 0.8f32.powf(spacing as f32 / 25.0); + assert!(((r - b) - expected).abs() < 2.0 / 255.0, "{depth}-bit, spacing {spacing}: {} vs {expected}", r - b); + assert_eq!(a, a0); + } + } +} + #[test] fn sponge_float_rgb_and_lab_keep_the_existing_transfer() { for (depth, mode) in [(32, "rgb"), (8, "lab")] { From d5f410ce5c5cbf7980866fe467a750849e115b86 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 12 Nov 2026 13:10:14 +0000 Subject: [PATCH 040/385] Avoid costly Sponge exponentials at common spacings --- crates/algo/src/retouch.rs | 38 +++++++++++++++++-- .../src/retouch_sponge_desaturate_tests.rs | 14 ++++++- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index a2d208dd85..260ee8e9df 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -109,6 +109,38 @@ pub fn sponge(c: [f32; 3], amount: f32, saturate: bool, vibrance: bool) -> [f32; compress_gamut([l + (c[0] - l) * k, l + (c[1] - l) * k, l + (c[2] - l) * k], l) } +/// Compound a reference dab's gain, with closed forms for common spacings. +#[inline] +fn sponge_gain(gain: f32, steps: f32) -> f32 { + match steps { + 0.5 => gain.sqrt(), + 1.0 => gain, + 2.0 => gain * gain, + 4.0 => { + let squared = gain * gain; + squared * squared + } + _ => gain.powf(steps), + } +} + +/// Sum the local affine response over the dab's fractional number of reference steps. +#[inline] +fn sponge_affine_scale(change: f32, steps: f32) -> f32 { + let gain = 1.0 + change; + match steps { + 0.5 => 1.0 / (gain.sqrt() + 1.0), + 2.0 => gain + 1.0, + 4.0 => (gain + 1.0) * (gain * gain + 1.0), + // The first terms of ((1 + change)^steps - 1) / change avoid cancellation near zero. + _ if change.abs() < 0.001 => { + let second = (steps - 1.0) * (steps - 2.0) / 6.0; + steps * (1.0 + change * (0.5 * (steps - 1.0) + change * second)) + } + _ => (gain.powf(steps) - 1.0) / change, + } +} + /// Adjust a normalized RGB dab using the measured RGB Sponge response (#12972, #12973). /// `coverage` includes Flow and the brush falloff. `spacing` is in brush diameters. pub fn sponge_rgb(c: [f32; 3], coverage: f32, spacing: f32, saturate: bool, vibrance: bool) -> [f32; 3] { @@ -127,7 +159,7 @@ pub fn sponge_rgb(c: [f32; 3], coverage: f32, spacing: f32, saturate: bool, vibr let grey = luma(c); if !vibrance { let reference_gain = if saturate { 1.0 + 0.4 * flow } else { 1.0 - 0.2 * flow }; - let mut gain = if steps == 1.0 { reference_gain } else { reference_gain.powf(steps) }; + let mut gain = sponge_gain(reference_gain, steps); if saturate { // Limit the gain before applying it to all three channels, using the same luma pivot. let shadow = grey - lo; @@ -156,12 +188,12 @@ pub fn sponge_rgb(c: [f32; 3], coverage: f32, spacing: f32, saturate: bool, vibr (lo + flow * shadow, hi - flow * highlight) }; // Compose the measured affine response for this dab's distance, holding its locally - // computed coefficients fixed. Use expm1 for small changes and cap at the RGB gamut. + // computed coefficients fixed, then cap the endpoints at the RGB gamut. let (low, high) = if steps == 1.0 { (low, high) } else { let change = ((high - hi) - (low - lo)) / chroma; - let scale = if change == 0.0 { steps } else { (steps * change.ln_1p()).exp_m1() / change }; + let scale = sponge_affine_scale(change, steps); ((lo + (low - lo) * scale).max(0.0), (hi + (high - hi) * scale).min(1.0)) }; // One affine map keeps the intermediate channel in the same position within the span. diff --git a/crates/algo/src/retouch_sponge_desaturate_tests.rs b/crates/algo/src/retouch_sponge_desaturate_tests.rs index 3461065274..3c6ef0c664 100644 --- a/crates/algo/src/retouch_sponge_desaturate_tests.rs +++ b/crates/algo/src/retouch_sponge_desaturate_tests.rs @@ -1,4 +1,4 @@ -use super::sponge_rgb; +use super::{sponge_affine_scale, sponge_rgb}; const COLORS: [[u8; 3]; 9] = [[200, 40, 40], [40, 160, 60], [40, 60, 200], [220, 170, 140], [230, 200, 40], [90, 50, 30], [180, 200, 230], [128, 64, 192], [255, 0, 0]]; @@ -129,3 +129,15 @@ fn vibrance_at_other_spacings_stays_in_gamut_and_preserves_hue() { } } } + +#[test] +fn fractional_vibrance_gain_stays_accurate_near_zero() { + for steps in [0.04, 0.5, 0.68, 1.32, 2.0, 3.0, 4.0] { + for change in [-0.3, -0.002, -0.0001, 0.0, 0.0001, 0.002, 0.3] { + let (x, n) = (f64::from(change), f64::from(steps)); + let expected = if x == 0.0 { n } else { (n * x.ln_1p()).exp_m1() / x }; + let actual = f64::from(sponge_affine_scale(change, steps)); + assert!((actual - expected).abs() < 0.0001, "change {change}, steps {steps}: {actual} vs {expected}"); + } + } +} From 34ba1fc39ab269d3b09b6ae33fb3ada39775de62 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 18:22:20 +0000 Subject: [PATCH 041/385] Convert Point and Curvature Pen: Delete edits the path, never the layer (#12734, #12695) With Convert Point and one anchor selected (Ctrl+click), or the idle Curvature Pen with an anchor clicked, Delete and Backspace fell through to Edit > Clear and deleted the active layer. They now take the route Add and Delete Anchor Point already use (#12703): path.deleteAnchor with its two segments, one History step, Delete Anchor Point. A closed subpath opens at the anchor. With the Curvature Pen, no path being drawn and no anchor selected, Delete removes the shown Work Path, as with the Pen (#5702). --- crates/ui-egui/src/input/shortcuts.rs | 8 +- crates/ui-egui/src/tools/direct_select.rs | 3 + .../convert_point_delete_key_tests.rs | 95 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui.rs | 3 + .../vector_ui/curvature_delete_key_tests.rs | 86 +++++++++++++++++ .../ui-egui/src/tools/vector_ui/path_ops.rs | 21 ++-- 6 files changed, 202 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/tools/direct_select/convert_point_delete_key_tests.rs create mode 100644 crates/ui-egui/src/tools/vector_ui/curvature_delete_key_tests.rs diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 51970cbe3b..86e119e633 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -724,8 +724,8 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f crate::shape_bounds_box::cancel(app); return true; } - // An anchor selected with the Add Anchor Point tool: ⌫/Delete removes it and its two segments, - // as in Photoshop (#12703), never the active layer. + // An anchor selected with an anchor point tool, Convert Point or the Curvature Pen: ⌫/Delete + // removes it and its two segments, as in Photoshop (#12703, #12734, #12695), never the active layer. if focus != crate::shortcut_dispatch::Focus::DeletingWidget && let Some((target, [s, k])) = crate::vector_ui::delete_key_deletes_anchor(app) { @@ -747,8 +747,8 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f return true; } } - // A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in - // Photoshop (#5702), never Edit › Clear on the pixels under it. + // A finished work path shown by a Pen or Path Selection: ⌫/Delete deletes it, as in + // Photoshop (#5702, #12695), never Edit › Clear on the pixels under it. if focus != crate::shortcut_dispatch::Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { let mods = ctx.input(|i| i.modifiers); if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 62b85a77c5..a78a9ae627 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -989,6 +989,9 @@ mod convert_point_tolerance_tests; #[cfg(test)] mod convert_point_drag_segment_tests; +#[cfg(test)] +mod convert_point_delete_key_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_delete_key_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_delete_key_tests.rs new file mode 100644 index 0000000000..3c2ab85a93 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/convert_point_delete_key_tests.rs @@ -0,0 +1,95 @@ +//! #12734: with the Convert Point tool, ⌫/Delete on an anchor selected with ⌘/Ctrl+click removes +//! the anchor and its two segments (a closed subpath opens there), never the active layer. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// 800 x 600 on white, pixel layer Red active, saved path Path 1 (a closed corner square) +/// targeted in the Paths panel, the Convert Point tool on. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": square})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.ui.tool = Tool::ConvertPoint; + app +} + +fn path1(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +fn layer_names(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect() +} + +fn ctrl_click(app: &mut PhotocraftApp, at: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, Modifiers::COMMAND); + tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::COMMAND); +} + +/// A key through the app's shortcut handling, as the canvas gets it. +fn press(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let m = Modifiers::NONE; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn anchors(path: &Path) -> Vec<[f64; 2]> { + path.subpaths.iter().flat_map(|sp| sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y])).collect() +} + +#[test] +fn delete_on_a_selected_anchor_removes_it_and_its_segments_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let (before, names) = (path1(&app), layer_names(&app)); + let n = app.session.active().unwrap().history.past_len(); + ctrl_click(&mut app, [300.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "{key:?}: Ctrl+click selects the anchor"); + press(&mut app, key); + assert_eq!(layer_names(&app), names, "{key:?}: every layer is still there"); + let p = path1(&app); + assert_eq!((p.subpaths.len(), p.subpaths[0].closed), (1, false), "{key:?}: the square opens"); + assert_eq!(anchors(&p), vec![[300.0, 500.0], [100.0, 500.0], [100.0, 300.0]], "{key:?}"); + let st = app.session.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.undo_label()), (n + 1, Some("Delete Anchor Point")), "{key:?}: one step"); + assert!(app.session.undo()); + assert_eq!(path1(&app), before, "{key:?}: Undo restores the closed square"); + } +} + +#[test] +fn without_a_selected_anchor_delete_keeps_its_usual_route() { + let mut app = app(); + let before = path1(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(path1(&app), before, "no anchor selected: the path stays"); + assert_ne!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); +} + +#[test] +fn the_pen_tools_and_path_selection_keep_their_delete() { + for tool in [Tool::Pen, Tool::FreeformPen, Tool::PathSelection] { + let mut app = app(); + ctrl_click(&mut app, [300.0, 300.0]); + app.ui.tool = tool; + let before = path1(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(path1(&app), before, "{tool:?}: no anchor is deleted"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 558d7a60f0..e88ed97d66 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -241,6 +241,9 @@ mod pen_mode_menu_tests; #[cfg(test)] mod ellipse_path_menus_tests; +#[cfg(test)] +mod curvature_delete_key_tests; + pub(crate) use pen::freeform_locked_shape; #[cfg(test)] use pen_resume::pen_finish_on_redo; diff --git a/crates/ui-egui/src/tools/vector_ui/curvature_delete_key_tests.rs b/crates/ui-egui/src/tools/vector_ui/curvature_delete_key_tests.rs new file mode 100644 index 0000000000..257fe38a94 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/curvature_delete_key_tests.rs @@ -0,0 +1,86 @@ +//! #12695: with the Curvature Pen and a finished path, ⌫/Delete on the selected anchor removes it, +//! and with no anchor selected deletes the Work Path, as the Pen does (#5702); never the layer. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// 800 x 600 on white, pixel layer Red active, and a Work Path drawn with the Curvature Pen +/// through (100,300), (250,150), (400,300), ended with Esc. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + app.ui.tool = Tool::CurvaturePen; + app.ui.tool_options.vector_mode = "path".into(); + for p in [[100.0, 300.0], [250.0, 150.0], [400.0, 300.0]] { + click(&mut app, p); + } + press(&mut app, egui::Key::Escape); + assert!(app.ui.pen.is_none(), "Esc ended the path"); + assert_eq!(work(&app).map(|p| anchors(&p).len()), Some(3), "the Work Path has the three anchors"); + app +} + +fn work(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.work_path.clone() +} + +fn layer_names(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect() +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::NONE); +} + +/// A key through the app's shortcut handling, as the canvas gets it. +fn press(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let m = Modifiers::NONE; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn anchors(path: &Path) -> Vec<[f64; 2]> { + path.subpaths.iter().flat_map(|sp| sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y])).collect() +} + +#[test] +fn delete_on_the_selected_anchor_removes_it_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let names = layer_names(&app); + click(&mut app, [400.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 2]], "{key:?}: the click selects the anchor"); + let n = app.session.active().unwrap().history.past_len(); + press(&mut app, key); + assert_eq!(layer_names(&app), names, "{key:?}: every layer is still there"); + assert_eq!(work(&app).map(|p| anchors(&p)), Some(vec![[100.0, 300.0], [250.0, 150.0]]), "{key:?}: two anchors are left"); + let st = app.session.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.undo_label()), (n + 1, Some("Delete Anchor Point")), "{key:?}: one step"); + } +} + +#[test] +fn without_a_selected_anchor_delete_removes_the_work_path_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + assert!(app.ui.direct_selection.anchors.is_empty(), "{key:?}: no anchor selected"); + let names = layer_names(&app); + press(&mut app, key); + assert_eq!(layer_names(&app), names, "{key:?}: every layer is still there"); + assert!(work(&app).is_none(), "{key:?}: the Work Path is deleted, as with the Pen"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index 6c86c1d287..b9b6b95ab1 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -203,27 +203,28 @@ pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { } } -/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen or Path Selection tool, no -/// path being drawn and the work path the one these tools show and edit (no shape layer or -/// targeted vector mask in front of it), as in Photoshop (#5702). It was drawn whenever one of -/// these tools was active, but the key reached Edit › Clear, so it looked impossible to delete. -/// Direct Selection and the Curvature Pen delete selected anchors in Photoshop, not the path. +/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen, Curvature Pen or Path +/// Selection tool, no path being drawn and the work path the one these tools show and edit (no +/// shape layer or targeted vector mask in front of it), as in Photoshop (#5702, #12695). It was +/// drawn whenever one of these tools was active, but the key reached Edit › Clear, so it looked +/// impossible to delete. A selected anchor goes first (`delete_key_deletes_anchor`). pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { - matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::PathSelection) + matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::PathSelection) && app.ui.pen.is_none() && app.ui.transform.is_none() && app.ui.view.shows(app.ui.view.show.target_path) && matches!(target_path(app), Some((PathTarget::Work, _))) } -/// The anchor ⌫ / Delete removes, with its two segments: with the Add or Delete Anchor Point tool, the one -/// anchor selected on it (⌘/Ctrl+click) while that selection still holds and its path is shown, -/// as in Photoshop (#12703). The key reached Edit › Clear and deleted the active layer. Several +/// The anchor ⌫ / Delete removes, with its two segments: with the Add or Delete Anchor Point tool, +/// Convert Point or the idle Curvature Pen, the one anchor selected on it (⌘/Ctrl+click, or a +/// Curvature Pen click) while that selection still holds and its path is shown, as in Photoshop +/// (#12703, #12734, #12695). The key reached Edit › Clear and deleted the active layer. Several /// selected anchors weren't measured and keep the key's other routes. pub(crate) fn delete_key_deletes_anchor(app: &PhotocraftApp) -> Option<(crate::direct_select::PathRef, [usize; 2])> { let ds = &app.ui.direct_selection; let ([[s, k]], Some(target)) = (ds.anchors.as_slice(), ds.target) else { return None }; - let usable = matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) + let usable = matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint | Tool::CurvaturePen) && app.ui.pen.is_none() && ds.drag.is_none() && app.ui.view.shows(app.ui.view.show.target_path) From 0a3bbcbb23c6d064b07b24034779e7606e24b341 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 12 Nov 2026 13:34:21 -0800 Subject: [PATCH 042/385] Backport the six upstream Rust 1.100 lint repairs Use the applicable e660b490 hunks without main or dependency changes. --- apps/photocraft/src/external_svg.rs | 7 ++----- crates/algo/src/photo_util.rs | 4 ++-- crates/cms/src/synth.rs | 4 ++-- crates/engine/src/cmd/multichannel_cmds/tests.rs | 4 ++-- crates/format/src/noreplace.rs | 5 +---- crates/ui-egui/src/home_recent_ui.rs | 9 ++------- 6 files changed, 11 insertions(+), 22 deletions(-) diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f552573..c34dd88bd0 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434..8f1e436d53 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce..c86bedc9bd 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/engine/src/cmd/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd6..99ad72d673 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/format/src/noreplace.rs b/crates/format/src/noreplace.rs index 75a54350c5..60d74d29c8 100644 --- a/crates/format/src/noreplace.rs +++ b/crates/format/src/noreplace.rs @@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { /// Use fallback only when the exclusive rename primitive itself is unsupported. fn unsupported_rename(error: &io::Error) -> bool { - if error.kind() == io::ErrorKind::Unsupported { - return true; - } #[cfg(unix)] if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { return true; } - false + error.kind() == io::ErrorKind::Unsupported } /// Linking claims an absent destination atomically; a later unlink failure is already published. diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 0c0a770276..81569b8ea0 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } } From 92db56ab6a7d93aa9060a2586b0395e59981ba35 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Thu, 12 Nov 2026 23:40:44 +0100 Subject: [PATCH 043/385] Floating selection: a refused command leaves it floating (#13169) Session::dispatch dropped a floating piece before it checked whether the command may run, so a refused command still placed the piece, moved the selection and added a History step. dispatch now runs admit before the drop for every command that would drop the piece, and again after it. --- crates/engine/src/cmd/float_cmds.rs | 13 ++++++ crates/engine/src/cmd/float_cmds/tests.rs | 56 +++++++++++++++++++++++ crates/engine/src/jobs.rs | 6 +++ crates/engine/src/session/execute.rs | 6 +-- 4 files changed, 78 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs index f5dfa28d2f..2853788b02 100644 --- a/crates/engine/src/cmd/float_cmds.rs +++ b/crates/engine/src/cmd/float_cmds.rs @@ -376,6 +376,19 @@ fn keeps_floating(id: &str) -> bool { ) || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p)) } +/// Commands that step the history over a floating piece instead of dropping it: Undo, Redo and +/// the History panel's steps and states ([`before_command`] puts the piece back or keeps it). +fn steps_over_piece(id: &str) -> bool { + matches!(id, "edit.undo" | "history.stepBackward" | "edit.redo" | "history.stepForward" | "history.selectState") +} + +/// Will [`before_command`] drop a floating piece for command `id`? `Session::dispatch` checks +/// whether such a command may run before the drop, so a refused one leaves the piece floating: +/// no drop, no History step, the selection where it was (#13169). +pub(crate) fn drops_for(s: &Session, id: &str) -> bool { + s.active().is_some_and(|st| floating(st).is_some()) && !steps_over_piece(id) && !keeps_floating(id) +} + /// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up: /// returns its result); every other command but the floating ones drops it first. pub(crate) fn before_command(s: &mut Session, id: &str) -> Result> { diff --git a/crates/engine/src/cmd/float_cmds/tests.rs b/crates/engine/src/cmd/float_cmds/tests.rs index 1fec9630b7..4883d79850 100644 --- a/crates/engine/src/cmd/float_cmds/tests.rs +++ b/crates/engine/src/cmd/float_cmds/tests.rs @@ -551,3 +551,59 @@ fn nudging_away_and_back_keeps_the_moved_pixels_selection() { assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(Rect::new(2, 2, 42, 42)), "a click keeps the marquee"); assert_eq!(st.history.past_len(), steps, "and adds no step"); } + +/// After a refused command the piece of [`session`], floated 15 px right, still floats: the +/// document, its selection and its History are as they were before the command (#13169). +fn assert_still_floating(s: &Session, id: LayerId, steps: usize, what: &str) { + let st = s.active().unwrap(); + assert_eq!(floating(st).map(|f| f.offset), Some((15, 0)), "{what}: the piece still floats"); + assert!(alpha(&st.doc, id, 12, 12) == 1.0 && alpha(&st.doc, id, 35, 12) == 0.0, "{what}: nothing dropped"); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(10, 10, 30, 30), "{what}: the selection did not move"); + assert_eq!(st.history.past_len(), steps, "{what}: no History step"); +} + +#[test] +fn a_disabled_command_leaves_the_piece_floating() { + let (mut s, id) = session(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.float", json!({"dx": 15, "dy": 0})).unwrap(); + let refused = s.execute("layer.ungroupLayers", json!({})); + assert!(matches!(refused, Err(EngineError::Disabled(..))), "a pixel layer is not a group: {refused:?}"); + assert_still_floating(&s, id, steps, "Ungroup Layers"); + // The piece drops as before once a command may run. + s.execute("select.drop", json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(floating(st).is_none() && alpha(&st.doc, id, 12, 12) == 0.0 && alpha(&st.doc, id, 35, 12) == 1.0); + assert_eq!(st.history.past_len(), steps + 1); +} + +#[test] +fn a_command_refused_on_a_hidden_layer_leaves_the_piece_floating() { + let (mut s, id) = session(); + s.edit("hide", |doc, _| { + doc.layer_mut(id).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.float", json!({"dx": 15, "dy": 0})).unwrap(); + let refused = s.execute("paint.stroke", json!({"points": [[40, 40], [50, 50]], "color": "#00ff00"})); + assert!(refused.unwrap_err().to_string().contains(crate::hidden_target::HIDDEN)); + assert_still_floating(&s, id, steps, "Brush on a hidden layer"); +} + +#[test] +fn a_command_refused_for_the_colour_mode_leaves_the_piece_floating() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap(); + let refused = s.execute("filter.other.colorToAlpha", json!({})); + assert!(matches!(refused, Err(EngineError::Disabled(..))), "no Color to Alpha in Indexed Color: {refused:?}"); + let st = s.active().unwrap(); + assert_eq!(floating(st).map(|f| f.offset), Some((5, 0)), "the piece still floats"); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(5, 5, 15, 15)); + assert_eq!(st.history.past_len(), steps, "no History step"); +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 31e29abe23..1a3fcb1ddd 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1760,6 +1760,12 @@ impl Session { } crate::param_check::check(spec, ¶ms)?; crate::filters::validate_params(id, ¶ms)?; + // A command that may not run leaves a floating selection floating (#13169): it is refused + // before the piece drops, without a History step. One that may run is checked again + // below, once the piece has dropped, on the pixels and selection it will change. + if crate::float_cmds::drops_for(self, id) { + self.admit(id, spec, ¶ms)?; + } // A floating selection drops before any other command (Undo puts it back instead). if let Some(v) = crate::float_cmds::before_command(self, id)? { return Ok(Started::Done(v)); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index a94504da4f..751bd05746 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -93,9 +93,9 @@ impl Session { self.admit(id, spec, params).map(|_| ()) } - /// What `dispatch` checks once the params are valid and a floating selection has dropped: - /// the precondition (on a named layer for commands that take one), a job running on the - /// document, a hidden target. The run params (the Channels panel's target filled in) when it + /// What `dispatch` checks once the params are valid, before a floating selection drops (so a + /// refused command leaves it floating) and again after: the precondition (on a named layer + /// for commands that take one), a job running on the document, a hidden target. The run params (the Channels panel's target filled in) when it /// may run. pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); From 701b6dd39bdfcbb124711ebbff63fd324f19478d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 12 Nov 2026 16:45:26 -0800 Subject: [PATCH 044/385] Keep Type options font fields in a distinct ID scope --- crates/ui-egui/src/tools/type_tool/options_bar.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index a02025bcbc..530732410e 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -28,7 +28,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Font family and style menus (one placeholder in their place while the fonts load). // Keep the following controls' positional IDs stable when the font menus replace the // loading placeholder: both states occupy one slot in the parent UI. - ui.scope(|ui| { + ui.scope_builder(egui::UiBuilder::new().id_salt("type-options-fonts"), |ui| { if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { app.ui.tool_options.type_font = fam.clone(); From 9dab50358fccfd798fdf145e66b9984019c4832f Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 13 Nov 2026 12:03:46 +0530 Subject: [PATCH 045/385] Object Selection: gear menu with Object Subtract and Object Finder Mode, and a Refresh button (#12857) The options bar loses the Object Finder checkbox and the rectangle hint and gains a Refresh button and a gear menu: Object Finder, Object Subtract (stored only) and Object Finder Mode (Auto Refresh, the default, or Manual Refresh). Reset Tool restores all three. With Manual Refresh the finder keeps the pixels it analysed: selection-only changes and the pointer leaving keep the highlight, and after a pixel edit it starts no lookup until Refresh is clicked. Auto Refresh is unchanged. --- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/state/tool_options.rs | 16 +++ crates/ui-egui/src/tools.rs | 2 + crates/ui-egui/src/tools/object_finder.rs | 76 ++++++++++- .../src/tools/object_selection_gear_tests.rs | 118 ++++++++++++++++++ crates/ui-egui/src/tools/retouch_ui.rs | 7 +- crates/ui-egui/src/tools/tool_reset.rs | 2 +- 7 files changed, 214 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/tools/object_selection_gear_tests.rs diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 138d995469..ebe1229753 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -18,7 +18,7 @@ pub use panel_state::{ PointCurveDrag, PointCurveState, }; pub use tool::Tool; -pub use tool_options::{SampleAllLayers, ToolOptions}; +pub use tool_options::{ObjectFinderMode, SampleAllLayers, ToolOptions}; use tool_options::{default_brush_tool, default_layer_filter_mode, layer_filter_mode_or_normal, yes}; pub use transform::{ BoxResize, CamTransform, ContentAwareOptions, Extras, MadeLayer, TextEdit, TransformMode, TransformSession, TypeInsertionStyle, TypeTransform, diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index ea741e4b97..77d0ca31d7 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -1,6 +1,16 @@ use super::tool::Tool; use super::{Deserialize, Serialize}; +/// Object Selection › gear › Object Finder Mode (#12857). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ObjectFinderMode { + /// Auto Refresh: the finder re-analyses the document after every edit. + #[default] + Auto, + /// Manual Refresh: the finder re-analyses only when Refresh is clicked. + Manual, +} + /// Options-bar state for tools (Photoshop keeps these per tool). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -13,6 +23,10 @@ pub struct ToolOptions { pub sample_all: SampleAllLayers, /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087). pub object_finder: bool, + /// Object Selection › gear › Object Subtract; stored only, today's subtract behaviour is unchanged (#12857). + pub object_subtract: bool, + /// Object Selection › gear › Object Finder Mode: when the finder re-analyses (#12857). + pub object_finder_mode: ObjectFinderMode, /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer). pub remove_new_layer: bool, /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes @@ -464,6 +478,8 @@ impl Default for ToolOptions { anti_alias: true, sample_all: SampleAllLayers::default(), object_finder: true, + object_subtract: true, + object_finder_mode: ObjectFinderMode::Auto, remove_new_layer: false, remove_after_each_stroke: true, feather: 0.0, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 721057faac..27d2054ed0 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -63,6 +63,8 @@ pub mod zoom_tool; #[cfg(test)] mod gradient_mode_greyed_tests; +#[cfg(test)] +mod object_selection_gear_tests; #[cfg(test)] mod object_selection_mode_tests; diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 267c326775..ec78019397 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -10,6 +10,12 @@ //! so an edit drops it. The preview itself is keyed by document revision, sampled layer and //! Sample All Layers, and clears when the pointer leaves the canvas, the tool changes, a button //! goes down or the option is off. Quality of the object found is out of scope here (#2788). +//! +//! The options bar has a Refresh button and a gear menu (#12857): Object Finder on/off, Object +//! Subtract (stored only) and Object Finder Mode. Auto Refresh re-analyses after every edit, as +//! above. Manual Refresh keeps the analysed pixels (`Finder::basis`) across the pointer leaving, +//! a tool switch and selection-only changes, and after a pixel edit highlights nothing until +//! Refresh is clicked ([`refresh`]). use std::sync::Arc; @@ -20,7 +26,7 @@ use photocraft_engine::smartselect_cmds::{empty_sampled_area, find_object, sampl use crate::PhotocraftApp; use crate::canvas::ViewXform; -use crate::state::Tool; +use crate::state::{ObjectFinderMode, Tool, ToolOptions}; /// Seconds the pointer must rest before an object is looked up. pub const DEBOUNCE: f64 = 0.12; @@ -48,6 +54,8 @@ pub(crate) struct Finder { misses: Vec<[i32; 2]>, shown: Option>, texture: Option<(usize, egui::TextureHandle)>, + /// The document whose pixels were last analysed (Manual Refresh compares against it). + basis: Arc, } /// What [`update`] decided. @@ -81,7 +89,7 @@ fn active(app: &PhotocraftApp, pressed: bool) -> bool { pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: bool, now: f64) -> Update { let at = at.filter(|p| p[0].is_finite() && p[1].is_finite()); let (Some(at), true) = (at, active(app, pressed)) else { - app.object_finder = None; + idle(app); return Update::default(); }; let Some(st) = app.session.active() else { return Update::default() }; @@ -90,10 +98,35 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo let (doc, revision, layer) = (st.doc.id, st.revision, st.active_layer); let px = [at[0].floor() as i32, at[1].floor() as i32]; let fresh = app.object_finder.as_ref().is_some_and(|f| f.doc == doc && f.revision == revision && f.target == target && f.all_layers == all_layers); - if !fresh { - app.object_finder = Some(Finder { doc, revision, target, all_layers, at: px, since: now, job: None, misses: Vec::new(), shown: None, texture: None }); - } let doc_arc = Arc::clone(&st.doc); + if !fresh { + let manual = app.ui.tool_options.object_finder_mode == ObjectFinderMode::Manual; + match app.object_finder.as_mut() { + // Manual Refresh: a selection-only change keeps the analysis, a pixel edit makes it stale. + Some(f) if manual && f.doc == doc => { + if f.target == target && f.all_layers == all_layers && photocraft_engine::layer_multi_cmds::same_pixels(&f.basis, &doc_arc) { + f.revision = revision; + } else { + return Update::default(); + } + } + _ => { + app.object_finder = Some(Finder { + doc, + revision, + target, + all_layers, + at: px, + since: now, + job: None, + misses: Vec::new(), + shown: None, + texture: None, + basis: Arc::clone(&doc_arc), + }); + } + } + } // The click reports an empty sampled layer; the hover says so too instead of showing nothing. let here = photocraft_geom::Rect::from_xywh(px[0], px[1], 1, 1); if doc_arc.bounds().contains(px[0], px[1]) && empty_sampled_area(&doc_arc, layer, all_layers, here).is_some() { @@ -156,11 +189,44 @@ fn spawn(doc: Arc, layer: Option, all_layers: bool, px: [i32; Job { at: px, doc, rx } } +/// Drops the preview. Auto Refresh forgets the finder; Manual Refresh keeps the analysed +/// pixels so the pointer leaving or a tool switch doesn't lose them. +fn idle(app: &mut PhotocraftApp) { + if app.ui.tool_options.object_finder_mode == ObjectFinderMode::Manual + && let Some(f) = app.object_finder.as_mut() + { + f.shown = None; + f.job = None; + f.texture = None; + f.misses.clear(); + } else { + app.object_finder = None; + } +} + /// Clears the preview (a tool switch or an edit made elsewhere is caught by [`update`] too). pub(crate) fn clear(app: &mut PhotocraftApp) { + idle(app); +} + +/// The options bar's Refresh button: the next [`update`] analyses the current pixels. +pub(crate) fn refresh(app: &mut PhotocraftApp) { app.object_finder = None; } +/// The options bar's gear button and its menu (#12857). +pub(crate) fn gear(o: &mut ToolOptions, ui: &mut egui::Ui) { + let r = crate::icons::button(ui, "settings", 24.0, false, tl!("Set additional options")); + egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder")); + crate::widgets::checkbox(ui, &mut o.object_subtract, tl!("Object Subtract")); + ui.separator(); + ui.label(tl!("Object Finder Mode")); + ui.radio_value(&mut o.object_finder_mode, ObjectFinderMode::Auto, tl!("Auto Refresh")); + ui.radio_value(&mut o.object_finder_mode, ObjectFinderMode::Manual, tl!("Manual Refresh")); + }); +} + /// The overlay colour: the theme accent, translucent (Photoshop tints the object it finds). fn overlay(accent: Color32, cov: f32, edge: bool) -> Color32 { let a = if edge { 0.95 } else { 0.42 * cov.clamp(0.0, 1.0) }; diff --git a/crates/ui-egui/src/tools/object_selection_gear_tests.rs b/crates/ui-egui/src/tools/object_selection_gear_tests.rs new file mode 100644 index 0000000000..0e67af2cc2 --- /dev/null +++ b/crates/ui-egui/src/tools/object_selection_gear_tests.rs @@ -0,0 +1,118 @@ +//! Object Selection's Refresh button and gear menu (#12857): Object Finder, Object Subtract and +//! Object Finder Mode are options that Reset Tool restores; Manual Refresh keeps the analysed +//! pixels until Refresh is clicked, Auto Refresh re-analyses after every edit. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::object_finder::{Update, refresh, update}; +use crate::state::{ObjectFinderMode, Tool, ToolOptions}; + +const DISC: [f64; 2] = [100.0, 80.0]; + +/// A 200 x 160 document: a red disc (centre 100,80, radius 45) on blue, nothing selected. +fn app(mode: ObjectFinderMode) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 160})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#3366cc"})).unwrap(); + app.run("select.rect", json!({"x": 55, "y": 35, "width": 90, "height": 90, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#e63319"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::ObjectSelection; + app.ui.tool_options.object_finder = true; + app.ui.tool_options.object_finder_mode = mode; + app +} + +/// Hovers at `at` until the lookup settles (time advances past the debounce). +fn hover(app: &mut PhotocraftApp, at: [f64; 2]) -> Update { + let mut t = 100.0; + loop { + let u = update(app, Some(at), false, t); + if !u.busy || t > 130.0 { + return u; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + t += 0.05; + } +} + +/// A pixel edit away from the disc. +fn edit_pixels(app: &mut PhotocraftApp) { + app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); +} + +#[test] +fn defaults_and_old_settings() { + let d = ToolOptions::default(); + assert!(d.object_finder && d.object_subtract); + assert_eq!(d.object_finder_mode, ObjectFinderMode::Auto); + let o: ToolOptions = serde_json::from_value(json!({})).unwrap(); + assert!(o.object_finder && o.object_subtract); + assert_eq!(o.object_finder_mode, ObjectFinderMode::Auto); + let mut v = serde_json::to_value(&d).unwrap(); + let m = v.as_object_mut().unwrap(); + m.remove("object_subtract"); + m.remove("object_finder_mode"); + let o: ToolOptions = serde_json::from_value(v).unwrap(); + assert_eq!(o, d); +} + +#[test] +fn options_round_trip() { + let mut o = ToolOptions::default(); + o.object_subtract = false; + o.object_finder_mode = ObjectFinderMode::Manual; + let back: ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); + assert!(!back.object_subtract); + assert_eq!(back.object_finder_mode, ObjectFinderMode::Manual); +} + +#[test] +fn reset_tool_restores_them() { + let mut o = ToolOptions::default(); + o.object_finder = false; + o.object_subtract = false; + o.object_finder_mode = ObjectFinderMode::Manual; + crate::tools::tool_reset::reset_options(&mut o, Tool::Lasso); + assert!(!o.object_finder && !o.object_subtract && o.object_finder_mode == ObjectFinderMode::Manual); + crate::tools::tool_reset::reset_options(&mut o, Tool::ObjectSelection); + assert_eq!(o, ToolOptions::default()); +} + +#[test] +fn manual_refresh_waits_for_refresh_after_a_pixel_edit() { + let mut app = app(ObjectFinderMode::Manual); + assert!(hover(&mut app, DISC).shown.is_some()); + edit_pixels(&mut app); + let u = hover(&mut app, DISC); + assert!(u.shown.is_none() && !u.busy); + // Still nothing after the debounce: no lookup was started. + let u = update(&mut app, Some(DISC), false, 500.0); + assert!(u.shown.is_none() && !u.busy); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn manual_refresh_survives_selection_changes_and_leaving() { + let mut app = app(ObjectFinderMode::Manual); + assert!(hover(&mut app, DISC).shown.is_some()); + assert!(update(&mut app, None, false, 200.0).shown.is_none()); + app.run("select.all", json!({})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn auto_refresh_reanalyses_after_a_pixel_edit() { + let mut app = app(ObjectFinderMode::Auto); + assert!(hover(&mut app, DISC).shown.is_some()); + edit_pixels(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 233db18f85..266fb8edb3 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1145,10 +1145,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo Tool::ObjectSelection => { crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); crate::widgets::vline(ui, 22.0); - crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder")); crate::widgets::checkbox(ui, &mut o.sample_all.object_selection, tl!("Sample All Layers")); - opt(ui, tl!("Drag a rectangle around the object")); + let refresh = crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Click to refresh object finder.")).clicked(); + crate::object_finder::gear(o, ui); crate::widgets::vline(ui, 22.0); + if refresh { + crate::object_finder::refresh(app); + } if crate::widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { let r = app.run("select.subject", json!({})); report_smart_result(app, r, tl!("No subject found — try a rectangle around the object")); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 4caae361a1..e04ad6f45c 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -211,7 +211,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::MagneticLasso => reset!(feather, anti_alias, magnetic_width, magnetic_contrast, magnetic_frequency, magnetic_pressure), Tool::MagicWand => reset!(tolerance, anti_alias, contiguous), Tool::QuickSelection => reset!(enhance_edge), - Tool::ObjectSelection => reset!(enhance_edge, object_finder), + Tool::ObjectSelection => reset!(enhance_edge, object_finder, object_subtract, object_finder_mode), Tool::Crop => reset!( crop_ratio, crop_delete, From 0783289bb89b351fef9e596e70a640ea548a2a59 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 13 Nov 2026 13:12:04 +0530 Subject: [PATCH 046/385] Object Selection gear tests: build options with struct update syntax (clippy) --- crates/ui-egui/src/tools/object_selection_gear_tests.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/tools/object_selection_gear_tests.rs b/crates/ui-egui/src/tools/object_selection_gear_tests.rs index 0e67af2cc2..6ce77c645f 100644 --- a/crates/ui-egui/src/tools/object_selection_gear_tests.rs +++ b/crates/ui-egui/src/tools/object_selection_gear_tests.rs @@ -65,9 +65,7 @@ fn defaults_and_old_settings() { #[test] fn options_round_trip() { - let mut o = ToolOptions::default(); - o.object_subtract = false; - o.object_finder_mode = ObjectFinderMode::Manual; + let o = ToolOptions { object_subtract: false, object_finder_mode: ObjectFinderMode::Manual, ..ToolOptions::default() }; let back: ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); assert!(!back.object_subtract); assert_eq!(back.object_finder_mode, ObjectFinderMode::Manual); @@ -75,10 +73,7 @@ fn options_round_trip() { #[test] fn reset_tool_restores_them() { - let mut o = ToolOptions::default(); - o.object_finder = false; - o.object_subtract = false; - o.object_finder_mode = ObjectFinderMode::Manual; + let mut o = ToolOptions { object_finder: false, object_subtract: false, object_finder_mode: ObjectFinderMode::Manual, ..ToolOptions::default() }; crate::tools::tool_reset::reset_options(&mut o, Tool::Lasso); assert!(!o.object_finder && !o.object_subtract && o.object_finder_mode == ObjectFinderMode::Manual); crate::tools::tool_reset::reset_options(&mut o, Tool::ObjectSelection); From 99012b539e7739bca200d0ec6655896b5681e70b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 06:23:38 -0500 Subject: [PATCH 047/385] Batch: a file that fails doesn't use up a serial number (#13664) A folder input the opener refuses (a non-image file with Include Non-Images) fails before its action starts. It now takes no serial number and no serial letter, so the next good file gets the next one. Batches without failures keep their names. Files that fail after their action started are not measured and keep today's numbering. The startingSerial params doc no longer says failed inputs count. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 queued; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/file_cmds.rs | 6 +- .../engine/src/cmd/file_cmds/batch_naming.rs | 14 +++- crates/engine/src/cmd/file_cmds/batch_run.rs | 11 ++- .../batch_serial_skip_failed_tests.rs | 67 +++++++++++++++++++ 4 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index d61919070c..3fb780f8e5 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, + r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (position among the inputs that give an output; a failed input does not use up a number),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, native, batch ), @@ -444,6 +444,10 @@ mod place_job_tests; #[path = "file_cmds/open_as_smart_object_tests.rs"] mod open_as_smart_object_tests; +#[cfg(test)] +#[path = "file_cmds/batch_serial_skip_failed_tests.rs"] +mod batch_serial_skip_failed_tests; + #[cfg(test)] mod aces_exr_tests { use super::*; diff --git a/crates/engine/src/cmd/file_cmds/batch_naming.rs b/crates/engine/src/cmd/file_cmds/batch_naming.rs index 8f7c579a69..8b29be8495 100644 --- a/crates/engine/src/cmd/file_cmds/batch_naming.rs +++ b/crates/engine/src/cmd/file_cmds/batch_naming.rs @@ -240,6 +240,13 @@ fn expand(parts: &[Part<'_>], name: &str, ext: &str, serial: u32, date: Date) -> /// An absent or empty template preserves the old filename path exactly. An explicit template /// determines the whole filename. Recorded components retain their separate format choice. pub fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) -> Result>> { + plan_counting(inputs, output, format, params, &|_| true) +} + +/// [`plan`] where only the inputs `counts` accepts use up a serial number and a serial letter: an +/// input known to fail before its action starts still gets a name (reported with its error) but +/// the next input reuses the number it would have taken. +pub fn plan_counting(inputs: &[BatchInput], output: &str, format: &str, params: &Value, counts: &dyn Fn(&BatchInput) -> bool) -> Result>> { let structured = components(params)?; let compat = compatibility(params)?; let flat = match params.get("flatOutput") { @@ -286,7 +293,9 @@ pub fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) - None }; let mut outputs = Vec::with_capacity(inputs.len()); - for (index, BatchInput { path, rel_dir }) in inputs.iter().enumerate() { + let mut index = 0usize; + for input in inputs { + let BatchInput { path, rel_dir } = input; let serial = if has_serial { u32::try_from(index).ok().and_then(|index| start.checked_add(index)).ok_or_else(|| bad("startingSerial plus the input count exceeds 4294967295"))? } else { @@ -313,6 +322,9 @@ pub fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) - // Preserve the recorded structured routing; ordinary native templates use main's flat output. let subfolder = if structured.is_some() && !flat { rel_dir.as_str() } else { "" }; outputs.push(join(&join(output, subfolder), &name)); + if counts(input) { + index += 1; + } } // Renaming within the source folder could replace a later input before it is read. Resolve // existing paths so aliases such as `source/./001.png` cannot bypass the check. The default diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 5eb6543c86..a73f5245b1 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -901,7 +901,16 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { return result; } let check_duplicates = recorded_output_guard(p); - let names = if save_and_close { None } else { batch_naming::plan(&inputs, &output, &format, p)? }; + // A folder input the opener will refuse fails before its action starts, so it takes no serial. + let counts = |input: &BatchInput| { + #[cfg(not(target_arch = "wasm32"))] + if check_folder_format && !super::paths::openable_name(&input.path) { + return false; + } + let _ = (input, check_folder_format); + true + }; + let names = if save_and_close { None } else { batch_naming::plan_counting(&inputs, &output, &format, p, &counts)? }; let mut save = SaveOpts::from_params(s, p, cmd)?; if save_and_close { save.tiff_layers = save_close_tiff_layers; diff --git a/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs new file mode 100644 index 0000000000..fd553a6090 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs @@ -0,0 +1,67 @@ +//! File › Automate › Batch: an input that fails does not use up a serial number or letter (#13664). + +use super::*; + +fn tmp(name: &str) -> String { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let d = std::env::temp_dir().join(format!("photocraft-batch-serial-{}-{name}-{id}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +fn write_png(path: &str) { + let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![200; 48]).unwrap(); + let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// The issue's folder: `a.png`, `aa.txt`, `b.png`, `c.png`, `notes.txt`, `sub/a.png`, `sub/deeper/d.png`. +fn issue_folder(label: &str, with_text: bool) -> (String, String) { + let dir = tmp(label); + let input = join(&dir, "in"); + std::fs::create_dir_all(join(&input, "sub/deeper")).unwrap(); + for name in ["a.png", "b.png", "c.png", "sub/a.png", "sub/deeper/d.png"] { + write_png(&join(&input, name)); + } + if with_text { + for name in ["aa.txt", "notes.txt"] { + std::fs::write(join(&input, name), b"not an image").unwrap(); + } + } + (input, join(&dir, "out")) +} + +fn run(input: &str, output: &str, with_text: bool, naming: Value) -> Vec { + let mut s = Session::new(); + let p = json!({ + "input": input, "output": output, "steps": [], "format": "same", "startingSerial": 5, + "includeSubfolders": true, "includeNonImages": with_text, "flatOutput": true, "namingComponents": naming + }); + let result = s.execute("file.automate.batch", p).unwrap(); + let failed = result["errors"].as_array().unwrap().len(); + assert_eq!(failed, if with_text { 2 } else { 0 }, "{result}"); + result["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap()).to_string()).collect() +} + +#[test] +fn a_failed_file_does_not_use_up_a_serial_number() { + let (input, output) = issue_folder("gap", true); + let names = run(&input, &output, true, json!([{"component":"serial3"}, {"component":"extension"}, {"text":"_x"}])); + assert_eq!(names, ["005png_x", "006png_x", "007png_x", "008png_x", "009png_x"]); +} + +#[test] +fn a_batch_without_failures_keeps_its_names() { + let (input, output) = issue_folder("clean", false); + let names = run(&input, &output, false, json!([{"component":"serial3"}, {"component":"extension"}, {"text":"_x"}])); + assert_eq!(names, ["005png_x", "006png_x", "007png_x", "008png_x", "009png_x"]); +} + +#[test] +fn serial_letters_follow_the_same_counter() { + let (input, output) = issue_folder("letters", true); + let names = run(&input, &output, true, json!([{"component":"letter"}, {"text":"_x"}])); + assert_eq!(names, ["a_x", "b_x", "c_x", "d_x", "e_x"]); +} From 23827b92852226b88c525322f33e497fbf2ebd3a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 06:38:35 -0500 Subject: [PATCH 048/385] Batch: the error log is UTF-16 big-endian with Start Batch / End Batch and native paths (#13665) Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 queued; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- apps/photocraft-cli/tests/it/cli.rs | 12 +-- crates/engine/src/cmd/file_cmds.rs | 4 + .../cmd/file_cmds/batch_log_format_tests.rs | 76 +++++++++++++++++++ crates/engine/src/cmd/file_cmds/batch_run.rs | 14 +++- crates/engine/src/cmd/file_cmds/tests.rs | 10 +-- docs/atn.md | 15 ++-- 6 files changed, 109 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/batch_log_format_tests.rs diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 4713ae2a20..1a87d99380 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -515,11 +515,11 @@ fn batch_applies_actions_to_directory() { .stdout; assert!(out.contains("2 succeeded, 0 failed"), "{out}"); let clean_log = std::fs::read(&log).unwrap(); - assert!(clean_log.starts_with(&[0xff, 0xfe])); + assert!(clean_log.starts_with(&[0xfe, 0xff])); let (pairs, remainder) = clean_log[2..].as_chunks::<2>(); assert!(remainder.is_empty()); - let body = String::from_utf16(&pairs.iter().map(|pair| u16::from_le_bytes(*pair)).collect::>()).unwrap(); - assert_eq!(body, "Batch Start\r\n\r\nBatch End\r\n"); + let body = String::from_utf16(&pairs.iter().map(|pair| u16::from_be_bytes(*pair)).collect::>()).unwrap(); + assert_eq!(body, "Start Batch\r\n\r\nEnd Batch\r\n"); for n in ["one", "two"] { let info = ok(bin().arg("info").arg(outp.join(format!("{n}.pcraft")))).stdout; let v: Value = serde_json::from_str(&info).unwrap(); @@ -557,11 +557,11 @@ fn batch_recursive_naming_stop_and_error_log() { assert!(output.join(file).is_file(), "{file}: {stdout}"); } let bytes = std::fs::read(log).unwrap(); - assert!(bytes.starts_with(&[0xff, 0xfe])); + assert!(bytes.starts_with(&[0xfe, 0xff])); let (pairs, remainder) = bytes[2..].as_chunks::<2>(); assert!(remainder.is_empty()); - let errors = String::from_utf16(&pairs.iter().map(|pair| u16::from_le_bytes(*pair)).collect::>()).unwrap(); - assert!(errors.contains("Batch Start\r\n") && errors.contains("b.png") && errors.ends_with("Batch End\r\n"), "{errors}"); + let errors = String::from_utf16(&pairs.iter().map(|pair| u16::from_be_bytes(*pair)).collect::>()).unwrap(); + assert!(errors.contains("Start Batch\r\n") && errors.contains("b.png") && errors.ends_with("End Batch\r\n"), "{errors}"); let stopped = root.join("stopped"); let result = run(&stopped, &["--recursive", "--stop-on-error"]); diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index d61919070c..92303878bb 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -436,6 +436,10 @@ pub fn specs() -> Vec { #[path = "file_cmds/tests.rs"] mod tests; +#[cfg(test)] +#[path = "file_cmds/batch_log_format_tests.rs"] +mod batch_log_format_tests; + #[cfg(test)] #[path = "file_cmds/place_job_tests.rs"] mod place_job_tests; diff --git a/crates/engine/src/cmd/file_cmds/batch_log_format_tests.rs b/crates/engine/src/cmd/file_cmds/batch_log_format_tests.rs new file mode 100644 index 0000000000..02fb5cd32a --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/batch_log_format_tests.rs @@ -0,0 +1,76 @@ +//! The Batch error log format (#13665): UTF-16 big-endian with BOM `FE FF`, CRLF line ends, the +//! first line `Start Batch`, the last line `End Batch` plus CRLF, and `File:` paths with the +//! platform's separators. + +use super::*; + +#[cfg(windows)] +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-batch-log-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +fn utf16_be(text: &str) -> Vec { + let mut bytes = vec![0xfe, 0xff]; + for word in text.encode_utf16() { + bytes.extend_from_slice(&word.to_be_bytes()); + } + bytes +} + +fn decode_be(bytes: &[u8]) -> String { + assert_eq!(&bytes[..2], &[0xfe, 0xff], "BOM"); + let (pairs, remainder) = bytes[2..].as_chunks::<2>(); + assert!(remainder.is_empty(), "even length"); + String::from_utf16(&pairs.iter().map(|pair| u16::from_be_bytes(*pair)).collect::>()).unwrap() +} + +#[test] +fn the_log_has_a_big_endian_bom_and_big_endian_code_units() { + let bytes = encode_batch_error_log([("a.png", "boom")]); + assert_eq!(&bytes[..4], &[0xfe, 0xff, 0x00, b'S'], "BOM then the big-endian S of `Start Batch`"); +} + +#[test] +fn the_log_starts_with_start_batch_and_ends_with_end_batch_and_crlf() { + let text = decode_be(&encode_batch_error_log([("a.png", "boom"), ("b.png", "bang")])); + assert!(text.starts_with("Start Batch\r\n\r\n"), "{text:?}"); + assert!(text.ends_with("\r\nEnd Batch\r\n"), "{text:?}"); + assert_eq!(text, "Start Batch\r\n\r\nFile: \"a.png\"\r\nError: boom\r\n\r\nFile: \"b.png\"\r\nError: bang\r\n\r\nEnd Batch\r\n"); +} + +#[test] +fn an_error_free_log_is_exactly_bom_start_blank_end() { + let no_errors: [(&str, &str); 0] = []; + assert_eq!(encode_batch_error_log(no_errors), utf16_be("Start Batch\r\n\r\nEnd Batch\r\n")); +} + +#[cfg(windows)] +#[test] +fn a_folder_given_with_slashes_is_written_with_backslashes_on_windows() { + let dir = tmp("batch-log-slashes").replace('\\', "/"); + let missing = format!("{dir}/in/missing.png"); + let log = format!("{dir}/errors.txt"); + let result = + Session::new().execute("file.automate.batch", json!({"steps": [], "input": [missing], "output": format!("{dir}/out"), "errorLog": log})).unwrap(); + assert_eq!(result["errors"].as_array().map(Vec::len), Some(1), "{result}"); + let text = decode_be(&std::fs::read(&log).unwrap()); + let expected = format!("File: \"{}\"\r\n", missing.replace('/', "\\")); + assert!(text.contains(&expected), "{text:?} should contain {expected:?}"); +} + +#[cfg(windows)] +#[test] +fn the_encoder_writes_windows_separators_for_every_file_line() { + let text = decode_be(&encode_batch_error_log([("C:/pc/in\\notes.txt", "x")])); + assert!(text.contains("File: \"C:\\pc\\in\\notes.txt\"\r\n"), "{text:?}"); +} + +#[cfg(not(windows))] +#[test] +fn slashes_are_kept_off_windows() { + let text = decode_be(&encode_batch_error_log([("/pc/in/notes.txt", "x")])); + assert!(text.contains("File: \"/pc/in/notes.txt\"\r\n"), "{text:?}"); +} diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 5eb6543c86..871ef94d92 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -427,18 +427,24 @@ impl BatchPolicy { /// Photoshop-compatible Batch log encoding, shared by the desktop command and CLI. pub fn encode_batch_error_log<'a>(errors: impl IntoIterator) -> Vec { - let mut body = String::from("Batch Start\r\n\r\n"); + let mut body = String::from("Start Batch\r\n\r\n"); for (input, reason) in errors { + let input = native_separators(input); body.push_str(&format!("File: \"{input}\"\r\nError: {reason}\r\n\r\n")); } - body.push_str("Batch End\r\n"); - let mut bytes = vec![0xff, 0xfe]; + body.push_str("End Batch\r\n"); + let mut bytes = vec![0xfe, 0xff]; for word in body.encode_utf16() { - bytes.extend_from_slice(&word.to_le_bytes()); + bytes.extend_from_slice(&word.to_be_bytes()); } bytes } +/// Paths in the log use the platform's separators: backslashes on Windows, also for a folder given with `/`. +fn native_separators(path: &str) -> String { + if cfg!(windows) { path.replace('/', "\\") } else { path.to_string() } +} + fn write_error_log(path: &str, errors: &[Value]) -> Result<()> { let bytes = encode_batch_error_log(errors.iter().map(|error| { (error.get("file").or_else(|| error.get("document")).and_then(Value::as_str).unwrap_or("?"), error.get("error").and_then(Value::as_str).unwrap_or("?")) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 9b3207a8ee..5a33627f7d 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -802,10 +802,10 @@ fn composite(s: &Session, x: i32, y: i32) -> [f32; 4] { fn batch_log(path: &str) -> String { let bytes = std::fs::read(path).unwrap(); - assert!(bytes.starts_with(&[0xff, 0xfe]), "Batch log needs a UTF-16 LE BOM"); + assert!(bytes.starts_with(&[0xfe, 0xff]), "Batch log needs a UTF-16 BE BOM"); let (pairs, remainder) = bytes[2..].as_chunks::<2>(); assert!(remainder.is_empty(), "UTF-16 bytes must have even length"); - let words: Vec = pairs.iter().map(|pair| u16::from_le_bytes(*pair)).collect(); + let words: Vec = pairs.iter().map(|pair| u16::from_be_bytes(*pair)).collect(); String::from_utf16(&words).unwrap() } @@ -824,8 +824,8 @@ fn batch_stop_on_error_reports_skipped_inputs_and_writes_the_error_log() { assert_eq!(result["stopped"], json!(missing), "{result}"); assert_eq!(result["skipped"], json!([good]), "{result}"); let text = batch_log(&log); - assert!(text.starts_with("Batch Start\r\n\r\n") && text.contains("missing.png") && text.contains("File: \"") && text.contains("Error: "), "{text}"); - assert!(text.ends_with("Batch End\r\n"), "{text}"); + assert!(text.starts_with("Start Batch\r\n\r\n") && text.contains("missing.png") && text.contains("File: \"") && text.contains("Error: "), "{text}"); + assert!(text.ends_with("End Batch\r\n"), "{text}"); assert!(!std::path::Path::new(&join(&output, "good.png")).exists()); } @@ -838,7 +838,7 @@ fn batch_writes_a_utf16_error_log_even_when_every_file_succeeds() { let result = Session::new().execute("file.automate.batch", json!({"steps": [], "input": [input], "output": output, "errorLog": log})).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); assert_eq!(result["errorLog"], json!(log)); - assert_eq!(batch_log(&log), "Batch Start\r\n\r\nBatch End\r\n"); + assert_eq!(batch_log(&log), "Start Batch\r\n\r\nEnd Batch\r\n"); } #[test] diff --git a/docs/atn.md b/docs/atn.md index 85a0c1eb21..eaffd71577 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -1137,17 +1137,18 @@ Measured with a folder `in` holding `a.png`, `b.png`, `notes.txt` and `sub/a.png - **Errors, Stop For Errors** (no `Log ` key): the batch stops at the failing file; files before it are saved, nothing after it is processed. - **Errors, Log Errors To File:** the batch goes on, and at the end a message says an error occurred and - the details are in the log. The log file is **UTF-16 LE with BOM and CRLF**, and is written even when - nothing failed. In German the lines are (the application's own language): + the details are in the log. The log file is **UTF-16 BE with BOM (`FE FF`) and CRLF**, and is written even when + nothing failed. The first line is `Start Batch` and the last is `End Batch` followed by CRLF; `File:` paths + use the platform separators (backslashes on Windows). The measured layout: ``` - Stapelanfang + Start Batch - Datei: "" - Fehler: () + File: "" + Error: …one pair per failed file… - Stapelende + End Batch ``` - **Cancel:** Esc during a batch stops the running command and asks "A command was cancelled or stopped during batch processing. Continue with the next file or stop?" (Continue / Stop). Stop ends the batch @@ -1165,7 +1166,7 @@ Batch cancellation conformance (Photoshop 2026 observation above; PhotoCraft's p | Ask Continue or Stop | Continue skips the interrupted input; Stop returns prior outputs and skips the rest | Implemented and tested in engine and UI | | Keep headless cancellation direct | `jobs.cancel` returns partial results without an interactive question | Implemented and tested, including a worker waiting for a desktop decision | | No progress bar | The desktop Batch preview is the visible feedback | Implemented, UI tested and visually checked | -| Preserve error policy and log | Continue retains earlier errors and writes one final UTF-16 LE log | Implemented and tested with errors before and after Esc | +| Preserve error policy and log | Continue retains earlier errors and writes one final UTF-16 BE log | Implemented and tested with errors before and after Esc | - **Return value:** when any file failed, the Batch step itself reports "cancelled" (the dialog returns no descriptor); a script run with Stop For Errors reports success even though it stopped. From 5eed4141d3a7745a800a9d9e6022449e2bd635ea Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 13 Nov 2026 04:38:32 -0800 Subject: [PATCH 049/385] Right-click the transform box instead of its overlaid task bar in the menu test --- .../ui-egui/src/paint_bucket_right_click_menu_tests.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs index eff0ec017f..c1a72e51b4 100644 --- a/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs +++ b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs @@ -153,7 +153,14 @@ fn a_real_right_click_on_a_free_transform_box_opens_only_the_transform_menu() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); h.run_steps(2); - let c = h.state().last_canvas_rect.center(); + // The small top-left transform box is not at the canvas centre, where its bar can sit. + let app = h.state(); + let xf = crate::canvas::ViewXform::active(app).unwrap(); + let quad = app.ui.transform.as_ref().unwrap().quad.map(|[x, y]| xf.to_screen(x as f32, y as f32)); + let c = egui::Rect::from_points(&quad).center(); + let [x0, y0, x1, y1] = crate::transform_task_bar::shown_rect(app, &ctx).expect("the transform bar remains visible"); + assert!(xf.rect.contains(c), "the click remains on the canvas"); + assert!(!egui::Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1)).contains(c), "the click targets the box, not its bar"); mouse_right_click(&mut h, c, Modifiers::NONE); assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.transform), "the transform menu"); assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); From 3c545d4167134bfad52288755f3067fa67554be5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 08:38:15 -0500 Subject: [PATCH 050/385] Batch: the startingSerial doc names the one failure that uses up no number (#13664) Only a folder input the opener refuses by name, with includeNonImages, leaves its number for the next input. An input that fails later, in its import, action or save, still uses one up, as before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file_cmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 3fb780f8e5..4ac36c4f9f 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (position among the inputs that give an output; a failed input does not use up a number),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, + r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (position among the inputs; a folder input the opener refuses by name, with includeNonImages, does not use up a number, while an input that fails later, in its import, action or save, still does),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, native, batch ), From 66a2916dfb175f9ef7ac19c2bed13f77fbeaf94f Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 13 Nov 2026 19:30:37 +0530 Subject: [PATCH 051/385] Object Selection: Manual Refresh analyses nothing until Refresh is clicked The first hover, or a hover on another document, no longer starts an analysis under Manual Refresh; Refresh creates the finder for the current pixels. --- crates/ui-egui/src/tools/object_finder.rs | 48 +++++++++++-------- .../src/tools/object_selection_gear_tests.rs | 40 ++++++++++++++-- 2 files changed, 64 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index ec78019397..3764578a6e 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -14,8 +14,8 @@ //! The options bar has a Refresh button and a gear menu (#12857): Object Finder on/off, Object //! Subtract (stored only) and Object Finder Mode. Auto Refresh re-analyses after every edit, as //! above. Manual Refresh keeps the analysed pixels (`Finder::basis`) across the pointer leaving, -//! a tool switch and selection-only changes, and after a pixel edit highlights nothing until -//! Refresh is clicked ([`refresh`]). +//! a tool switch and selection-only changes; it analyses nothing until Refresh is clicked +//! ([`refresh`]): not on the first hover, on another document, or after a pixel edit. use std::sync::Arc; @@ -110,21 +110,10 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo return Update::default(); } } - _ => { - app.object_finder = Some(Finder { - doc, - revision, - target, - all_layers, - at: px, - since: now, - job: None, - misses: Vec::new(), - shown: None, - texture: None, - basis: Arc::clone(&doc_arc), - }); - } + // Manual Refresh analyses nothing until Refresh is clicked: no finder yet, or one kept + // for another document, waits for [`refresh`] (#12857). + _ if manual => return Update::default(), + _ => app.object_finder = start(app), } } // The click reports an empty sampled layer; the hover says so too instead of showing nothing. @@ -209,9 +198,30 @@ pub(crate) fn clear(app: &mut PhotocraftApp) { idle(app); } -/// The options bar's Refresh button: the next [`update`] analyses the current pixels. +/// The options bar's Refresh button: the next [`update`] analyses the current pixels. Under +/// Manual Refresh this is the only way a finder starts. pub(crate) fn refresh(app: &mut PhotocraftApp) { - app.object_finder = None; + app.object_finder = start(app); +} + +/// A new finder for the active document's current pixels, sampled layer and Sample All Layers. +/// Its pointer position is unset, so the first hover starts the debounce. +fn start(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let all_layers = app.ui.tool_options.sample_all.object_selection; + Some(Finder { + doc: st.doc.id, + revision: st.revision, + target: sampled_target(&st.doc, st.active_layer, all_layers), + all_layers, + at: [i32::MIN, i32::MIN], + since: 0.0, + job: None, + misses: Vec::new(), + shown: None, + texture: None, + basis: Arc::clone(&st.doc), + }) } /// The options bar's gear button and its menu (#12857). diff --git a/crates/ui-egui/src/tools/object_selection_gear_tests.rs b/crates/ui-egui/src/tools/object_selection_gear_tests.rs index 6ce77c645f..47f511da2b 100644 --- a/crates/ui-egui/src/tools/object_selection_gear_tests.rs +++ b/crates/ui-egui/src/tools/object_selection_gear_tests.rs @@ -80,16 +80,45 @@ fn reset_tool_restores_them() { assert_eq!(o, ToolOptions::default()); } +/// Hovers long past the debounce and checks nothing was shown or started. +fn assert_idle(app: &mut PhotocraftApp) { + let u = hover(app, DISC); + assert!(u.shown.is_none() && !u.busy); + let u = update(app, Some(DISC), false, 500.0); + assert!(u.shown.is_none() && !u.busy); +} + +#[test] +fn manual_refresh_analyses_nothing_before_refresh() { + let mut app = app(ObjectFinderMode::Manual); + assert_idle(&mut app); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn manual_refresh_needs_refresh_on_another_document() { + let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); + app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 55, "y": 35, "width": 90, "height": 90, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#e63319"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert_idle(&mut app); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + #[test] fn manual_refresh_waits_for_refresh_after_a_pixel_edit() { let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); assert!(hover(&mut app, DISC).shown.is_some()); edit_pixels(&mut app); - let u = hover(&mut app, DISC); - assert!(u.shown.is_none() && !u.busy); - // Still nothing after the debounce: no lookup was started. - let u = update(&mut app, Some(DISC), false, 500.0); - assert!(u.shown.is_none() && !u.busy); + assert_idle(&mut app); refresh(&mut app); assert!(hover(&mut app, DISC).shown.is_some()); } @@ -97,6 +126,7 @@ fn manual_refresh_waits_for_refresh_after_a_pixel_edit() { #[test] fn manual_refresh_survives_selection_changes_and_leaving() { let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); assert!(hover(&mut app, DISC).shown.is_some()); assert!(update(&mut app, None, false, 200.0).shown.is_none()); app.run("select.all", json!({})).unwrap(); From 07e43045f9877842648a56360efd7bb994bc52c8 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:52:35 +0100 Subject: [PATCH 052/385] Paths to Illustrator: lower-case c / l for segments that end on a smooth anchor (#13781) The operator of each segment now follows the knot it ends on: c / l when that knot is smooth, C / L when it is a corner. The closing segment of a closed subpath ends on the first knot, so it follows that knot's flag. --- crates/engine/src/cmd/print_cmds.rs | 15 ++- .../paths_export_path_blocks_tests.rs | 9 +- .../paths_export_smooth_operators_tests.rs | 99 +++++++++++++++++++ 3 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/cmd/print_cmds/paths_export_smooth_operators_tests.rs diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index d0f1fd9cd9..694282ad36 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -1583,16 +1583,21 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { s.push_str("1 XR\n"); let (x, y) = pt(sp.knots[0].anchor.x, sp.knots[0].anchor.y); s.push_str(&format!("{x:.4} {y:.4} m\n")); - for seg in sp.segments() { + for (i, seg) in sp.segments().into_iter().enumerate() { let [a, c1, c2, b] = seg; let straight = c1 == a && c2 == b; + // The operator follows the anchor the segment ends on: lower case for a smooth + // one. The closing segment of a closed subpath ends on the first knot. + let smooth_end = sp.knots[(i + 1) % sp.knots.len()].smooth; let (bx, by) = pt(b.x, b.y); if straight { - s.push_str(&format!("{bx:.4} {by:.4} L\n")); + let op = if smooth_end { 'l' } else { 'L' }; + s.push_str(&format!("{bx:.4} {by:.4} {op}\n")); } else { + let op = if smooth_end { 'c' } else { 'C' }; let (x1, y1) = pt(c1.x, c1.y); let (x2, y2) = pt(c2.x, c2.y); - s.push_str(&format!("{x1:.4} {y1:.4} {x2:.4} {y2:.4} {bx:.4} {by:.4} C\n")); + s.push_str(&format!("{x1:.4} {y1:.4} {x2:.4} {y2:.4} {bx:.4} {by:.4} {op}\n")); } } // Unpainted: `n` closes the path, `N` leaves it open. @@ -1704,3 +1709,7 @@ mod tests; #[cfg(test)] #[path = "print_cmds/paths_export_path_blocks_tests.rs"] mod paths_export_path_blocks_tests; + +#[cfg(test)] +#[path = "print_cmds/paths_export_smooth_operators_tests.rs"] +mod paths_export_smooth_operators_tests; diff --git a/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs b/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs index 44d606b000..f1f9b77a95 100644 --- a/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs +++ b/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs @@ -32,7 +32,8 @@ fn circle(cx: f64, cy: f64, r: f64) -> Subpath { sp } -fn doc_with(paths: Vec<(&str, Vec)>) -> Document { +/// A 300 x 200 px document at 72 ppi holding each `(name, subpaths)` pair as a saved path. +pub(super) fn doc_with(paths: Vec<(&str, Vec)>) -> Document { let mut s = Session::new(); s.execute("file.new", json!({"width": 300, "height": 200, "background": "#ffffff", "name": "Blocks.psd"})).unwrap(); s.edit("paths", |d, _| { @@ -47,7 +48,7 @@ fn doc_with(paths: Vec<(&str, Vec)>) -> Document { } /// The text after the file's setup section: just the path blocks and the trailer. -fn body(ai: &str) -> &str { +pub(super) fn body(ai: &str) -> &str { let from = ai.find("%%EndSetup\n").map(|i| i + "%%EndSetup\n".len()).unwrap(); &ai[from..ai.find("%%PageTrailer").unwrap()] } @@ -81,10 +82,10 @@ fn a_two_subpath_path_is_one_block_with_two_groups() { assert_eq!(b.matches("Path_End").count(), 1); let lines: Vec<&str> = b.lines().collect(); let first_end = lines.iter().position(|l| *l == "*U").unwrap(); - // Group one: *u, note, XR, the circle (move plus four curves), n. + // Group one: *u, note, XR, the circle (move plus four curves ending on smooth knots), n. assert_eq!(&lines[1..4], ["*u", XOR.trim_end(), "1 XR"]); assert!(lines[4].ends_with(" m")); - assert!(lines[5..9].iter().all(|l| l.ends_with(" C")), "{lines:?}"); + assert!(lines[5..9].iter().all(|l| l.ends_with(" c")), "{lines:?}"); assert_eq!(&lines[9..=first_end], ["n", "*U"]); // Group two: the open line, ending with N. assert_eq!(&lines[first_end + 1..], ["*u", XOR.trim_end(), "1 XR", "150.0000 30.0000 m", "280.0000 30.0000 L", "N", "*U", "%Adobe_Photoshop_Path_End"]); diff --git a/crates/engine/src/cmd/print_cmds/paths_export_smooth_operators_tests.rs b/crates/engine/src/cmd/print_cmds/paths_export_smooth_operators_tests.rs new file mode 100644 index 0000000000..3844bcddf1 --- /dev/null +++ b/crates/engine/src/cmd/print_cmds/paths_export_smooth_operators_tests.rs @@ -0,0 +1,99 @@ +//! Paths to Illustrator: a segment's operator follows the anchor it ends on. `c` / `l` when that +//! knot is smooth, `C` / `L` when it is a corner; the closing segment ends on the first knot. + +use super::paths_export_path_blocks_tests::{body, doc_with}; +use super::*; +use photocraft_doc::{Knot, Subpath}; +use photocraft_geom::Point; + +/// A smooth knot at `(ax, ay)` with its incoming and outgoing handles. +fn smooth(ax: f64, ay: f64, ix: f64, iy: f64, ox: f64, oy: f64) -> Knot { + Knot::smooth(Point::new(ax, ay), Point::new(ix, iy), Point::new(ox, oy)) +} + +/// A smooth knot whose handles are retracted onto its anchor, so its segments stay straight. +fn smooth_straight(x: f64, y: f64) -> Knot { + smooth(x, y, x, y, x, y) +} + +/// A subpath made of exactly `knots`, closed or open. +fn subpath(knots: Vec, closed: bool) -> Subpath { + let mut sp = Subpath::polyline(&[(0.0, 0.0), (1.0, 1.0)]); + sp.knots = knots; + sp.closed = closed; + sp +} + +/// The path-construction lines of the only exported path: the `m` line through `n` / `N`. +fn drawing(ai: &str) -> Vec<&str> { + let lines: Vec<&str> = body(ai).lines().collect(); + let from = lines.iter().position(|l| *l == "1 XR").unwrap() + 1; + let to = lines.iter().position(|l| *l == "*U").unwrap(); + lines[from..to].to_vec() +} + +#[test] +fn the_measured_smooth_circle_is_four_lower_case_curves() { + // The issue's test document: 300 x 200 px at 72 ppi, a closed smooth circle centred on + // 200,100 with radius 50, drawn from its top anchor clockwise; handles 27.615 long. + let (cx, cy, r, k) = (200.0, 100.0, 50.0, 27.615); + let circle = subpath( + vec![ + smooth(cx, cy - r, cx - k, cy - r, cx + k, cy - r), + smooth(cx + r, cy, cx + r, cy - k, cx + r, cy + k), + smooth(cx, cy + r, cx + k, cy + r, cx - k, cy + r), + smooth(cx - r, cy, cx - r, cy + k, cx - r, cy - k), + ], + true, + ); + let doc = doc_with(vec![("Circle", vec![circle])]); + let (ai, n) = paths_to_ai(&doc, "Circle").unwrap(); + assert_eq!(n, 1); + let want = "%Adobe_Photoshop_Path_Begin:<< /defaultFill false >>\n*u\n%AI3_Note:<< /operation /union >>\n1 XR\n\ + 200.0000 150.0000 m\n\ + 227.6150 150.0000 250.0000 127.6150 250.0000 100.0000 c\n\ + 250.0000 72.3850 227.6150 50.0000 200.0000 50.0000 c\n\ + 172.3850 50.0000 150.0000 72.3850 150.0000 100.0000 c\n\ + 150.0000 127.6150 172.3850 150.0000 200.0000 150.0000 c\n\ + n\n*U\n%Adobe_Photoshop_Path_End\n"; + assert_eq!(body(&ai), want); +} + +#[test] +fn an_open_path_writes_each_operator_from_its_end_knot() { + let knots = vec![ + Knot::corner(10.0, 100.0), + smooth(60.0, 50.0, 40.0, 50.0, 80.0, 50.0), + Knot::corner(110.0, 100.0), + smooth_straight(160.0, 100.0), + Knot::corner(210.0, 100.0), + ]; + let doc = doc_with(vec![("Open", vec![subpath(knots, false)])]); + let (ai, _) = paths_to_ai(&doc, "Open").unwrap(); + assert_eq!( + drawing(&ai), + [ + "10.0000 100.0000 m", + // Curve onto the smooth knot, curve onto a corner, straight onto a smooth knot, + // straight onto a corner. + "10.0000 100.0000 40.0000 150.0000 60.0000 150.0000 c", + "80.0000 150.0000 110.0000 100.0000 110.0000 100.0000 C", + "160.0000 100.0000 l", + "210.0000 100.0000 L", + "N", + ] + ); +} + +#[test] +fn the_closing_segment_follows_the_first_knot() { + // First knot smooth, the others corners: only the closing segment is lower case. + let smooth_first = subpath(vec![smooth_straight(10.0, 10.0), Knot::corner(110.0, 10.0), Knot::corner(110.0, 110.0)], true); + // First knot a corner, the others smooth: only the closing segment is upper case. + let corner_first = subpath(vec![Knot::corner(10.0, 10.0), smooth_straight(110.0, 10.0), smooth_straight(110.0, 110.0)], true); + let doc = doc_with(vec![("Smooth first", vec![smooth_first]), ("Corner first", vec![corner_first])]); + let (ai, _) = paths_to_ai(&doc, "Smooth first").unwrap(); + assert_eq!(drawing(&ai), ["10.0000 190.0000 m", "110.0000 190.0000 L", "110.0000 90.0000 L", "10.0000 190.0000 l", "n"]); + let (ai, _) = paths_to_ai(&doc, "Corner first").unwrap(); + assert_eq!(drawing(&ai), ["10.0000 190.0000 m", "110.0000 190.0000 l", "110.0000 90.0000 l", "10.0000 190.0000 L", "n"]); +} From efb127ad0646df43cb6297f0bf6a30c868117569 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Fri, 13 Nov 2026 18:42:34 +0100 Subject: [PATCH 053/385] fix(io): GIF export pads the palette through a transparent index beyond the last entry --- crates/io/src/flat.rs | 10 ++++++++-- crates/io/tests/it/modes.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 522234f944..7a4050eddd 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -2387,8 +2387,14 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> if format == Format::Gif { // The whole table in its original order, as the palette PNG and BMP write it: a // GIF colour table holds 2^n entries, and the writer pads the ones past the - // document's last entry with black, so no used index moves (#11824). - let bytes = codecs::web::encode_gif_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, false)?; + // document's last entry with black, so no used index moves (#11824). A + // transparent index past the last entry needs a slot too: pad through it, or a + // transparent pixel fails the export of an API-created table (#11861 review). + let mut colors = table.colors.clone(); + if let Some(t) = table.transparent.filter(|t| usize::from(*t) >= colors.len()) { + colors.resize(usize::from(t) + 1, [0, 0, 0]); + } + let bytes = codecs::web::encode_gif_indexed(doc.size.width, doc.size.height, &idx, &colors, table.transparent, false)?; let mut warnings = vec![format!("written as a GIF with the document's colour table ({} colours)", table.colors.len())]; warnings.extend(gif_dropped_metadata(doc, opts)); return Ok(Some(ExportResult { bytes, warnings })); diff --git a/crates/io/tests/it/modes.rs b/crates/io/tests/it/modes.rs index 720ea85beb..07e23a5aed 100644 --- a/crates/io/tests/it/modes.rs +++ b/crates/io/tests/it/modes.rs @@ -297,6 +297,26 @@ fn indexed_gif_pads_a_200_entry_palette_to_256_entries() { } } +#[test] +fn indexed_gif_pads_the_palette_through_a_transparent_index_beyond_it() { + // #11861 review: a table created through the API can designate a transparent index past its + // last entry. The index needs a table slot, so the palette pads through it (black, the same + // padding as the unused entries) instead of the export failing on a transparent pixel. + let palette: Vec<[u8; 3]> = vec![[10, 20, 30], [200, 100, 50], [7, 7, 7]]; + let mut d = Document::with_background("m", Size::new(2, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(1.0, 0.0, 0.0, 1.0)); + d.mode = ColorMode::Indexed; + d.color_table = Some(ColorTable { colors: palette.clone(), transparent: Some(5) }); + d.layers[0].surface_mut().unwrap().write_pixel(1, 0, &[0.0, 0.0, 0.0, 0.0]); + let r = photocraft_io::export(&d, "x.gif", &Default::default()).unwrap(); + let (colors, transparent) = photocraft_codecs::gif_palette(&r.bytes).unwrap(); + assert_eq!(colors.len(), 8, "padded through index 5, then to the next power of two"); + assert_eq!(&colors[..3], &palette[..], "the document's entries keep their slots"); + assert!(colors[3..].iter().all(|c| *c == [0, 0, 0]), "the padding is black"); + assert_eq!(transparent, Some(5), "the transparency keeps its index"); + let back = photocraft_io::import("x.gif", &r.bytes).unwrap().document; + assert_eq!(back.color_table.as_ref().unwrap().transparent, Some(5)); +} + #[test] fn indexed_gif_keeps_the_transparent_index() { let mut d = Document::with_background("m", Size::new(2, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(1.0, 0.0, 0.0, 1.0)); From c9132969444274bb914a845df813bb43f7b34552 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 15:15:38 -0500 Subject: [PATCH 054/385] Layers to Files: PNG file names use dashes for spaces (#13963) For PNG exports, spaces in the prefix and in the layer name become dashes in the file name, applied on top of sanitize. Other formats keep their spaces, sanitize is unchanged, and the skipped report keeps the original layer name. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/file_cmds.rs | 4 ++ crates/engine/src/cmd/file_cmds/export.rs | 4 +- .../layers_to_files_png_names_tests.rs | 56 +++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 633b25ff11..17bfbaf32d 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -440,6 +440,10 @@ mod tests; #[path = "file_cmds/export_clut_cube_header_tests.rs"] mod export_clut_cube_header_tests; +#[cfg(test)] +#[path = "file_cmds/layers_to_files_png_names_tests.rs"] +mod layers_to_files_png_names_tests; + #[cfg(test)] #[path = "file_cmds/place_job_tests.rs"] mod place_job_tests; diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 404930f917..98f20dd40d 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -95,7 +95,9 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } } - let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); + // PNG file names use dashes for spaces (measured); the other formats keep them. + let part = |text: &str| if format == "png" { sanitize(text).replace(' ', "-") } else { sanitize(text) }; + let name = format!("{}_{:04}_{}.{format}", part(&prefix), index, part(&l.name)); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs new file mode 100644 index 0000000000..38dc68a270 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs @@ -0,0 +1,56 @@ +//! Layers to Files: PNG file names turn spaces in the prefix and the layer name into dashes; the +//! other formats keep them (#13963). + +use super::*; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-l2f-png-names-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +/// Background, `Blue Half`, and a hidden layer `Hid den` on top. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Blue Half"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Hid den"})).unwrap(); + s.execute("layer.setProps", json!({"visible": false})).unwrap(); + s +} + +fn export(test: &str, format: &str) -> serde_json::Value { + let dir = tmp(&format!("{test}-{format}")); + let mut s = session(); + s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "p 1", "format": format})).unwrap() +} + +fn file_names(result: &serde_json::Value) -> Vec { + result["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().rsplit(['/', '\\']).next().unwrap().to_string()).collect() +} + +#[test] +fn png_names_use_dashes_for_spaces() { + let result = export("dashes", "png"); + assert_eq!(file_names(&result), vec!["p-1_0000_Blue-Half.png".to_string(), "p-1_0001_Background.png".to_string()]); +} + +#[test] +fn other_formats_keep_spaces() { + for format in ["psd", "jpg", "tif"] { + let result = export("keep", format); + assert_eq!(file_names(&result), vec![format!("p 1_0000_Blue Half.{format}"), format!("p 1_0001_Background.{format}")], "{format}"); + } +} + +#[test] +fn skipped_layers_keep_the_original_name() { + for format in ["png", "psd"] { + let result = export("skipped", format); + let skipped = result["skipped"].as_array().unwrap(); + assert_eq!(skipped.len(), 1, "{format}"); + assert_eq!(skipped[0]["name"], json!("Hid den"), "{format}"); + assert_eq!(skipped[0]["reason"], json!("hidden by visibleOnly"), "{format}"); + } +} From 7ef0d7ed08e31ce2665df04285299b387831801a Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 22:28:32 +0100 Subject: [PATCH 055/385] Add Anchor Point: right-click opens the path menu with the point's entry on top (#12710) The Add Anchor Point tool now opens the Pen's path menu on a canvas right-click, headed by Add Anchor Point on a segment or Delete Anchor Point on an anchor (none on empty canvas). A right-click on an anchor selects it. With anchors selected, the Fill, Stroke and transform rows read Fill/Stroke Subpath... (one subpath), Subpaths... (several) and Free Transform Points; with no path targeted the transform row reads Free Transform. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 68 ++++++- .../canvas_tool_menu/add_anchor_menu_tests.rs | 176 ++++++++++++++++++ 2 files changed, 241 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/canvas/canvas_tool_menu/add_anchor_menu_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index b7a9a99cdb..aea2814992 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -629,8 +629,11 @@ pub const PEN_MENU: &[Row] = &[ /// The label a row shows, untranslated. The Pen's transform row names what it acts on, as in /// Photoshop (#12913): the points of the path being drawn, or nothing when the document has no /// path at all. A path that exists but isn't active, and the Path Selection and Direct Selection -/// menus, keep the table's label. +/// menus, keep the table's label. The Add Anchor Point menu names the selected anchors (#12710). pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'static str, command: &str) -> &'static str { + if menu.tool == Tool::AddAnchorPoint { + return add_anchor_row_label(app, menu, label, command); + } if command != "path.transform" || menu.tool != Tool::Pen { return label; } @@ -645,6 +648,32 @@ pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'sta if any_path { label } else { "Free Transform" } } +/// The Add Anchor Point menu's Fill, Stroke and transform rows, as measured (#12710): with anchors +/// of the targeted path selected they act on those, **Fill Subpath…** / **Stroke Subpath…** for one +/// subpath, **Fill Subpaths…** / **Stroke Subpaths…** for several, and **Free Transform Points**. +/// With no path targeted the transform row reads **Free Transform**. +fn add_anchor_row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'static str, command: &str) -> &'static str { + if !menu.has_path { + return if command == "path.transform" { "Free Transform" } else { label }; + } + let ds = &app.ui.direct_selection; + if ds.anchors.is_empty() || !crate::direct_select::still_valid(app, ds) { + return label; + } + let mut subpaths: Vec = ds.anchors.iter().map(|[s, _]| *s).collect(); + subpaths.sort_unstable(); + subpaths.dedup(); + let several = subpaths.len() > 1; + match command { + "path.fill" if several => "Fill Subpaths…", + "path.fill" => "Fill Subpath…", + "path.stroke" if several => "Stroke Subpaths…", + "path.stroke" => "Stroke Subpath…", + "path.transform" => "Free Transform Points", + _ => label, + } +} + /// The Color Sampler menu's Delete row: removes the sampler the menu opened on. pub const SAMPLER_DELETE: &str = "view.colorSamplers.delete"; @@ -774,9 +803,30 @@ pub fn path_menu(tool: Tool) -> bool { } /// The anchor tools whose path menu also heads with the entry for the point under the right-click -/// (#12771, #12744). Add Anchor Point (#12710) joins here. +/// (#12771, #12744, #12710). fn point_menu(tool: Tool) -> bool { - matches!(tool, Tool::DeleteAnchorPoint | Tool::ConvertPoint) + matches!(tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint) +} + +/// The Add Anchor Point tool's right-click on an anchor selects it, as measured (#12710); an anchor +/// already among the selected ones keeps the selection. Elsewhere, and on a path the anchor tools +/// ignore, nothing changes. +fn select_anchor_at(app: &mut PhotocraftApp, doc: [f64; 2]) { + let Some((target, _, Hit::Anchor(k))) = crate::direct_select::hit_active(app, doc) else { return }; + if target == PathRef::Pen || crate::anchor_tools::ignores(app, &target) { + return; + } + let owner = crate::direct_select::Owner::current(app); + let ds = &app.ui.direct_selection; + if ds.target.as_ref() != Some(&target) || !crate::direct_select::still_valid(app, ds) { + app.ui.direct_selection = crate::direct_select::DirectSelection { target: Some(target), ..Default::default() }; + } + let ds = &mut app.ui.direct_selection; + ds.owner = owner; + ds.segment = None; + if !ds.anchors.contains(&k) { + ds.anchors = vec![k]; + } } /// The anchor or segment of the targeted path under document point `doc`, as the anchor tools hit @@ -1315,6 +1365,12 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; let point = if point_menu(tool) && has_path { doc.filter(|d| d.iter().all(|v| v.is_finite())).and_then(|d| point_at(app, d)) } else { None }; + if tool == Tool::AddAnchorPoint + && point.as_ref().is_some_and(|(c, ..)| c == POINT_DELETE) + && let Some(d) = doc + { + select_anchor_at(app, d); + } let inside_selection = tool == Tool::ContentAwareMove && doc.is_some_and(|d| selected_at(app, d)); let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); @@ -1784,6 +1840,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { let text = match row_label(app, &menu, label, command) { // Spelled out so `cargo xtask i18n-coverage` lists the new label. "Free Transform Points" => tl!("Free Transform Points"), + "Fill Subpath…" => tl!("Fill Subpath…"), + "Fill Subpaths…" => tl!("Fill Subpaths…"), + "Stroke Subpath…" => tl!("Stroke Subpath…"), + "Stroke Subpaths…" => tl!("Stroke Subpaths…"), key => tl!(key), }; let item = egui::Button::selectable(mode_checked(app, &menu, command), text).min_size(egui::vec2(200.0, 20.0)); @@ -1837,6 +1897,8 @@ mod make_selection_dialog_tests; #[cfg(test)] mod type_layer_menu_tests; +#[cfg(test)] +mod add_anchor_menu_tests; #[cfg(test)] mod delete_anchor_menu_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/add_anchor_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/add_anchor_menu_tests.rs new file mode 100644 index 0000000000..d5f4688cc9 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/add_anchor_menu_tests.rs @@ -0,0 +1,176 @@ +//! #12710: with the Add Anchor Point tool a right-click on the canvas opens the Pen's path menu +//! with the entry for the point under the pointer on top, as for Delete Anchor Point (#12771). +//! A right-click on an anchor selects it, and with anchors selected the Fill, Stroke and transform +//! rows name what they act on: Fill / Stroke Subpath… (one subpath), Subpaths… (several), Free +//! Transform Points. The shared steps live in `delete_anchor_menu_tests`. + +use egui::Modifiers; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use super::delete_anchor_menu_tests::{assert_top_entry, empty_canvas, right_clicked, saved, setup, steps}; +use super::tests::{harness, right_click, screen_of}; +use super::{PEN_MENU, rows}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const TOOL: Tool = Tool::AddAnchorPoint; + +/// The Add Anchor Point tool with Ctrl held (its temporary Direct Selection) clicks `anchors`: the +/// first with Ctrl, the rest with Ctrl+Shift. +fn with_selected(anchors: &[[f64; 2]]) -> PhotocraftApp { + let mut app = setup(TOOL); + for (i, [x, y]) in anchors.iter().copied().enumerate() { + let mods = if i == 0 { Modifiers::COMMAND } else { Modifiers::COMMAND | Modifiers::SHIFT }; + tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(&mut app, ToolEvent::Up { x, y }, mods); + } + assert_eq!(app.ui.direct_selection.anchors.len(), anchors.len(), "the anchors are selected"); + app +} + +fn right_click_at(app: PhotocraftApp, at: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut h = harness(app); + let p = screen_of(h.state(), at); + right_click(&mut h, p, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu opened at {at:?}"); + h +} + +/// The Fill, Stroke and transform rows of the open menu read `labels`, and none of the others. +fn assert_rows(h: &Harness<'static, PhotocraftApp>, labels: [&str; 3]) { + const ALL: [&str; 11] = [ + "Fill Path…", + "Fill Subpath…", + "Fill Subpaths…", + "Stroke Path…", + "Stroke Subpath…", + "Stroke Subpaths…", + "Free Transform Path", + "Free Transform Points", + "Free Transform", + "Fill Subpath(s)…", + "Stroke Subpath(s)…", + ]; + for label in ALL { + assert_eq!(h.query_by_label(label).is_some(), labels.contains(&label), "{label}: expected only {labels:?}"); + } +} + +/// Right-click the square's right edge at (300,400): Add Anchor Point heads the menu, then the +/// Pen's rows in their order; choosing it puts an anchor there, one step named Add Anchor Point. +#[test] +fn right_click_on_a_segment_offers_add_anchor_point_and_it_inserts_there() { + let mut h = right_clicked(TOOL, [300.0, 400.0]); + assert_top_entry(&h, TOOL, "Add Anchor Point"); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| rows(m) == PEN_MENU), "then PEN_MENU's rows"); + let before = steps(h.state()); + h.get_by_label("Add Anchor Point").click(); + h.run_steps(2); + let path = saved(h.state()); + assert_eq!(path.subpaths[0].knots.len(), 5); + assert!(path.subpaths[0].closed); + let added = &path.subpaths[0].knots[2].anchor; + assert!((added.x - 300.0).abs() < 1.0 && (added.y - 400.0).abs() < 3.0, "the anchor lands at (300,400): {added:?}"); + assert_eq!(steps(h.state()), before + 1); + assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); +} + +/// Right-click the corner (100,300): Delete Anchor Point heads the menu and the corner is selected; +/// choosing it removes the corner, the square stays closed, one step named Delete Anchor Point. +#[test] +fn right_click_on_an_anchor_selects_it_and_offers_delete_anchor_point() { + let mut h = right_clicked(TOOL, [100.0, 300.0]); + assert_top_entry(&h, TOOL, "Delete Anchor Point"); + assert_eq!(h.state().ui.direct_selection.anchors, vec![[0, 0]], "the right-clicked anchor is selected"); + let before = steps(h.state()); + h.get_by_label("Delete Anchor Point").click(); + h.run_steps(2); + let path = saved(h.state()); + assert!(path.subpaths[0].closed, "the square stays closed"); + assert_eq!(path.subpaths[0].knots.len(), 3); + assert!(path.subpaths[0].knots.iter().all(|k| (k.anchor.x, k.anchor.y) != (100.0, 300.0)), "(100,300) is gone"); + assert_eq!(steps(h.state()), before + 1); + assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); +} + +#[test] +fn right_click_on_empty_canvas_opens_the_path_menu_without_a_top_entry() { + empty_canvas(TOOL); +} + +/// Opening the menu on an anchor only selects it: no history step and no path change. +#[test] +fn right_click_on_an_anchor_changes_no_path() { + let app = setup(TOOL); + let (path, n) = (saved(&app), steps(&app)); + let h = right_click_at(app, [100.0, 300.0]); + assert_eq!(steps(h.state()), n); + assert_eq!(saved(h.state()), path); +} + +/// Nothing selected, path targeted: the table's labels. +#[test] +fn with_no_anchor_selected_the_rows_name_the_path() { + let h = right_clicked(TOOL, [500.0, 100.0]); + assert_rows(&h, ["Fill Path…", "Stroke Path…", "Free Transform Path"]); +} + +/// Anchors of one subpath selected: the singular labels and Free Transform Points. +#[test] +fn with_anchors_of_one_subpath_selected_the_rows_name_the_subpath() { + let h = right_click_at(with_selected(&[[100.0, 300.0], [300.0, 300.0]]), [500.0, 100.0]); + assert_rows(&h, ["Fill Subpath…", "Stroke Subpath…", "Free Transform Points"]); +} + +/// Anchors in two subpaths selected: the plural labels. +#[test] +fn with_anchors_of_two_subpaths_selected_the_rows_name_the_subpaths() { + let h = right_click_at(with_selected(&[[100.0, 300.0], [400.0, 300.0]]), [500.0, 100.0]); + assert_rows(&h, ["Fill Subpaths…", "Stroke Subpaths…", "Free Transform Points"]); +} + +/// The anchor a right-click selects counts too: the menu on (100,300) reads Subpath… +#[test] +fn the_right_clicked_anchor_counts_as_selected() { + let h = right_clicked(TOOL, [100.0, 300.0]); + assert_rows(&h, ["Fill Subpath…", "Stroke Subpath…", "Free Transform Points"]); +} + +/// A right-click on an anchor already among several selected ones keeps them all. +#[test] +fn right_click_on_a_selected_anchor_keeps_the_selection() { + let h = right_click_at(with_selected(&[[100.0, 300.0], [400.0, 300.0]]), [400.0, 300.0]); + assert_eq!(h.state().ui.direct_selection.anchors, vec![[0, 0], [1, 0]]); + assert_rows(&h, ["Fill Subpaths…", "Stroke Subpaths…", "Free Transform Points"]); +} + +/// No path targeted: Fill Path…, Stroke Path… and Free Transform, and no top entry. +#[test] +fn with_no_path_targeted_the_transform_row_reads_free_transform() { + let mut app = setup(TOOL); + app.ui.selected_path = None; + let h = right_click_at(app, [300.0, 400.0]); + assert!(h.query_by_label("Add Anchor Point").is_none() && h.query_by_label("Delete Anchor Point").is_none(), "no top entry"); + assert_rows(&h, ["Fill Path…", "Stroke Path…", "Free Transform"]); +} + +/// The labels belong to this tool: Delete Anchor Point's menu keeps the table's, also on an anchor. +#[test] +fn other_anchor_tools_keep_the_path_labels() { + for tool in [Tool::DeleteAnchorPoint, Tool::ConvertPoint] { + let h = right_clicked(tool, [100.0, 300.0]); + assert_rows(&h, ["Fill Path…", "Stroke Path…", "Free Transform Path"]); + } +} + +/// A selection the control channel set on another document revision does not rename the rows. +#[test] +fn a_stale_selection_does_not_rename_the_rows() { + let mut app = with_selected(&[[100.0, 300.0]]); + app.run("path.addAnchor", json!({"name": "Path 1", "subpath": 1, "knot": 0, "t": 0.5})).unwrap(); + let h = right_click_at(app, [500.0, 100.0]); + assert_rows(&h, ["Fill Path…", "Stroke Path…", "Free Transform Path"]); +} From d60b6bd66d4c71d999098f96b691f2fdcf00f6b3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 22:35:58 +0100 Subject: [PATCH 056/385] Add Anchor Point menu: say the subpath rows still act on the whole path (#12710) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index aea2814992..46fa2756d7 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -648,10 +648,12 @@ pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'sta if any_path { label } else { "Free Transform" } } -/// The Add Anchor Point menu's Fill, Stroke and transform rows, as measured (#12710): with anchors -/// of the targeted path selected they act on those, **Fill Subpath…** / **Stroke Subpath…** for one +/// The Add Anchor Point menu's Fill, Stroke and transform rows, labelled as measured (#12710): with +/// anchors of the targeted path selected they read **Fill Subpath…** / **Stroke Subpath…** for one /// subpath, **Fill Subpaths…** / **Stroke Subpaths…** for several, and **Free Transform Points**. -/// With no path targeted the transform row reads **Free Transform**. +/// With no path targeted the transform row reads **Free Transform**. Only the labels follow the +/// selection: `path.fill`, `path.stroke` and `path.transform` take no subpath or anchor selection +/// yet, so the rows still act on the whole path. fn add_anchor_row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'static str, command: &str) -> &'static str { if !menu.has_path { return if command == "path.transform" { "Free Transform" } else { label }; From 922006b1e0d93f591e425780e4a432e36ecaf6fa Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 22:39:49 +0100 Subject: [PATCH 057/385] Add Anchor Point: Escape deselects anchors, then the targeted path (#12728) The first Escape with the Add Anchor Point tool clears the anchors selected on the saved path targeted in the Paths panel and keeps the path targeted; the second deselects the path, so its outline goes and clicks add nothing. Reuses the Delete Anchor Point step (#12773). Escape adds no History step. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/input/shortcuts.rs | 19 ++-- crates/ui-egui/src/tools/anchor_tools.rs | 3 + .../anchor_tools/add_anchor_escape_tests.rs | 104 ++++++++++++++++++ 3 files changed, 117 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/tools/anchor_tools/add_anchor_escape_tests.rs diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 0628aa94f8..b3c6c93083 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -910,8 +910,8 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // and the toolbar tool and "…" flyouts. A canvas drag in progress (a marquee being drawn) keeps it too. let esc_taken = app.drag.is_some() // A Direct Selection drag (a Cmd-drag on an anchor) never reaches `app.drag`: Esc must not - // leave full screen or deselect pixels while its release is still to come (#13072). - || (app.ui.tool == Tool::DeleteAnchorPoint && app.ui.direct_selection.drag.is_some()) + // leave full screen or deselect pixels while its release is still to come (#13072, #12728). + || (matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) && app.ui.direct_selection.drag.is_some()) || app.ui.palette_open || app.ui.canvas_tool_menu.is_some() || app.ui.layer_menu.is_some() @@ -951,14 +951,15 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } - // Delete Anchor Point (#12773): Esc first hides the anchors of the saved path targeted in the - // Paths panel, then deselects that path, so clicks edit nothing. The first Esc leaves the path - // targeted whether or not an anchor was selected (#13072), and clears only anchors selected on - // that path, never another path's. Not while its name is typed in the panel: egui has already - // dropped the field's focus, and the panel cancels on Esc. A Direct Selection drag keeps Esc - // away through `esc_taken` above, so its release still moves the anchors (#13072). + // Add (#12728) and Delete Anchor Point (#12773): Esc first hides the anchors of the saved path + // targeted in the Paths panel, then deselects that path, so clicks edit nothing. The first Esc + // leaves the path targeted whether or not an anchor was selected (#13072), and clears only + // anchors selected on that path, never another path's. Not while its name is typed in the + // panel: egui has already dropped the field's focus, and the panel cancels on Esc. A Direct + // Selection drag keeps Esc away through `esc_taken` above, so its release still moves the + // anchors (#13072). if !esc_taken - && app.ui.tool == Tool::DeleteAnchorPoint + && matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) && !crate::vector_ui::path_renaming(app, ctx) && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) { diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index f36814934c..9cf0a5fed9 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -424,6 +424,9 @@ mod tests; #[cfg(test)] mod add_anchor_delete_key_tests; +#[cfg(test)] +mod add_anchor_escape_tests; + #[cfg(test)] mod delete_anchor_delete_key_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_escape_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_escape_tests.rs new file mode 100644 index 0000000000..4d1f9d6dc0 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_escape_tests.rs @@ -0,0 +1,104 @@ +//! #12728: with Add Anchor Point, Esc first clears anchors selected on the saved path targeted in +//! the Paths panel, then deselects that path, so its outline goes and a click on a segment adds +//! nothing. Esc never adds a History step. + +use egui::{Key, Modifiers}; +use serde_json::json; + +use super::add_anchor_delete_key_tests::{app, ctrl_click, path1, steps}; +use super::tests::click; +use crate::PhotocraftApp; +use crate::direct_select::{Drag, PathRef, active_paths, candidates}; + +fn escape(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + let key = egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + ctx.begin_pass(egui::RawInput { events: vec![key], ..Default::default() }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +#[test] +fn the_first_escape_clears_the_selected_anchor_and_keeps_path_1() { + let mut app = app(); + // ⌘ is Direct Selection while held: it selects the anchor at (300, 300). + ctrl_click(&mut app, [300.0, 300.0]); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Saved(0)), vec![[0, 1]])); + let n = steps(&app); + escape(&mut app); + assert!(app.ui.direct_selection.anchors.is_empty(), "the first Esc clears the anchor"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "Path 1 stays selected in the Paths panel"); + assert!(!active_paths(&app).is_empty(), "its outline stays"); + assert_eq!(steps(&app), n, "Esc adds no History step"); +} + +#[test] +fn the_second_escape_deselects_path_1_and_a_click_on_a_segment_then_adds_nothing() { + let mut app = app(); + ctrl_click(&mut app, [300.0, 300.0]); + let n = steps(&app); + escape(&mut app); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "the second Esc deselects Path 1 in the Paths panel"); + assert!(candidates(&app).is_empty(), "its outline is hidden"); + assert_eq!(steps(&app), n, "Esc adds no History step"); + let before = path1(&app); + // The square's top edge runs from (100, 300) to (300, 300). + click(&mut app, [200.0, 300.0], Modifiers::NONE); + assert_eq!(path1(&app), before, "the click adds no anchor"); + assert_eq!(steps(&app), n, "and no History step"); +} + +#[test] +fn an_anchor_just_added_is_cleared_first_then_the_path_is_deselected() { + let mut app = app(); + let n = steps(&app); + click(&mut app, [200.0, 300.0], Modifiers::NONE); + assert_eq!(path1(&app).subpaths[0].knots.len(), 5, "the click on the top edge adds an anchor"); + assert_eq!(steps(&app), n + 1); + escape(&mut app); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the first Esc keeps Path 1 targeted"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "the second Esc deselects it"); + assert_eq!(steps(&app), n + 1, "neither Esc adds a History step"); +} + +#[test] +fn an_escape_during_a_direct_selection_drag_keeps_the_anchors_and_the_path() { + let mut app = app(); + app.run("select.all", json!({})).unwrap(); + ctrl_click(&mut app, [300.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + app.ui.direct_selection.drag = Some(Drag::Marquee { start: [200.0, 200.0], end: [400.0, 400.0], add: false }); + escape(&mut app); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "the drag's release still moves them"); + assert!(app.ui.direct_selection.drag.is_some(), "Esc does not end the drag"); + assert!(app.session.active().unwrap().doc.selection.is_some(), "nor deselects the pixels"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "nor deactivates the path"); +} + +#[test] +fn escape_still_leaves_full_screen_and_deselects_pixels_first() { + let mut app = app(); + app.ui.view.screen_mode = "fullScreen".into(); + escape(&mut app); + assert_eq!(app.ui.view.screen_mode, "standard"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "leaving full screen keeps Path 1 selected"); + app.run("select.all", json!({})).unwrap(); + escape(&mut app); + assert!(app.session.active().unwrap().doc.selection.is_none(), "Esc deselects the pixels"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "and keeps Path 1 selected"); +} + +#[test] +fn with_no_path_targeted_escape_still_leaves_full_screen_and_deselects_pixels() { + let mut app = app(); + app.ui.selected_path = None; + app.ui.view.screen_mode = "fullScreen".into(); + escape(&mut app); + assert_eq!(app.ui.view.screen_mode, "standard"); + app.run("select.all", json!({})).unwrap(); + escape(&mut app); + assert!(app.session.active().unwrap().doc.selection.is_none()); +} From bca20afc2032f103b23d0367437a6fef5bde327e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 18:56:36 -0500 Subject: [PATCH 058/385] Package: a layer named after a renamed link takes the new name (#14079) When Package gives a linked file's copy a new name because of a clash, a layer of the packaged copy linked to that copy whose name starts with the link file's old base name now gets the copy's new base name in its place (`logo b` -> `logo_1 b` when `logo.png` became `logo_1.png`). Layers whose link kept its name, and layers whose name does not start with the old base name, keep their names. The open document is never renamed. The rename derives both base names from the old and the new file names, so it follows whatever clash name the copy gets. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/print_cmds.rs | 20 ++++- .../print_cmds/package_layer_rename_tests.rs | 83 +++++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/print_cmds/package_layer_rename_tests.rs diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index d0f1fd9cd9..45f2899aa1 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -1445,7 +1445,7 @@ fn package(s: &mut Session, p: &Value) -> Result { let dir = std::path::absolute(dir).map_or_else(|_| dir.to_string(), |d| d.to_string_lossy().into_owned()); let dir = crate::file_cmds::forward_slashes(dir); let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = (*d.doc).clone(); + let mut doc = (*d.doc).clone(); let document = d.path.clone(); let name = stem(&d.path.clone().unwrap_or_else(|| doc.name.clone())); // The native format keeps external links; our PSD writer has no `lnkE` (external linked @@ -1460,6 +1460,8 @@ fn package(s: &mut Session, p: &Value) -> Result { // Copy every linked file once; relink the copy of the document to the copies. let mut copied: Vec<(String, String)> = Vec::new(); let mut relinks: Vec<(photocraft_doc::LayerId, String)> = Vec::new(); + // (layer, the link's old base name, the base name its copy got), for copies renamed by a clash. + let mut renames: Vec<(photocraft_doc::LayerId, String, String)> = Vec::new(); let mut missing = Vec::new(); for (_, _, l) in doc.walk() { let LayerContent::Smart(so) = &l.content else { continue }; @@ -1510,8 +1512,20 @@ fn package(s: &mut Session, p: &Value) -> Result { } } }; + if file_name(path) != file_name(&target) { + renames.push((l.id, stem(path), stem(&target))); + } relinks.push((l.id, target)); } + // A layer named after its link's old file name takes the copy's new name (the packaged copy + // only; the open document keeps its names). + for (id, old, new) in &renames { + if let Some(layer) = doc.layer_mut(*id) + && let Some(rest) = layer.name.strip_prefix(old.as_str()) + { + layer.name = format!("{new}{rest}"); + } + } let mut t = Session::new(); t.add_document(doc, None); for (id, path) in &relinks { @@ -1704,3 +1718,7 @@ mod tests; #[cfg(test)] #[path = "print_cmds/paths_export_path_blocks_tests.rs"] mod paths_export_path_blocks_tests; + +#[cfg(test)] +#[path = "print_cmds/package_layer_rename_tests.rs"] +mod package_layer_rename_tests; diff --git a/crates/engine/src/cmd/print_cmds/package_layer_rename_tests.rs b/crates/engine/src/cmd/print_cmds/package_layer_rename_tests.rs new file mode 100644 index 0000000000..b4a1cad7f0 --- /dev/null +++ b/crates/engine/src/cmd/print_cmds/package_layer_rename_tests.rs @@ -0,0 +1,83 @@ +//! Package: a layer named after a link whose copy got a new name takes the new base name, in +//! the packaged document only (#14079). + +use super::*; + +/// (layer name, linked file's file name) of every linked layer, top to bottom. +fn linked_layers(doc: &photocraft_doc::Document) -> Vec<(String, String)> { + doc.walk() + .iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Smart(so) => match &so.source { + SmartSource::Linked { path } => Some((l.name.clone(), file_name(path))), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn base(file: &str) -> String { + file.rsplit_once('.').map_or(file, |(b, _)| b).to_string() +} + +/// Two `logo.png` files (folders `a` and `b`), layers `logo a`, `logo a again`, `logo b` and +/// `other` (a second placement of `b/logo.png` whose name does not start with `logo`). +fn package_the_document(tag: &str) -> (String, Session, serde_json::Value) { + let dir = { + let d = std::env::temp_dir().join(format!("photocraft-pkg-rename-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().replace('\\', "/") + }; + let mut s = Session::new(); + s.execute("file.new", json!({"width": 120, "height": 90, "name": "Print Me.psd", "background": "#3366cc"})).unwrap(); + let path_of = |sub: &str, colour: &str| { + std::fs::create_dir_all(format!("{dir}/{sub}")).unwrap(); + let link = format!("{dir}/{sub}/logo.png"); + let mut src = Session::new(); + src.execute("file.new", json!({"width": 4, "height": 4, "background": colour})).unwrap(); + crate::file_cmds::save_doc(&src.active().unwrap().doc, &link, None).unwrap(); + link + }; + let a = path_of("a", "#ff0000"); + let b = path_of("b", "#00ff00"); + for (link, name) in [(&a, "logo a"), (&a, "logo a again"), (&b, "logo b"), (&b, "other")] { + s.execute("file.placeLinked", json!({"path": link})).unwrap(); + s.execute("layer.renameLayer", json!({"name": name})).unwrap(); + } + let r = s.execute("file.package", json!({"dir": format!("{dir}/pkg")})).unwrap(); + (dir, s, r) +} + +#[test] +fn a_layer_named_after_a_renamed_link_takes_the_new_base_name() { + let (dir, s, r) = package_the_document("rename"); + let docp = r["document"].as_str().unwrap(); + let back = photocraft_io::import("Print Me.pcraft", &std::fs::read(docp).unwrap()).unwrap().document; + let packaged = linked_layers(&back); + let open = linked_layers(&s.active().unwrap().doc); + assert_eq!(packaged.len(), 4, "{packaged:?}"); + let by_name = |list: &[(String, String)], name: &str| list.iter().find(|(n, _)| n.as_str() == name).cloned(); + // Whichever copy was renamed, it is the one the clash gave a new file name. + let renamed: Vec<&(String, String)> = packaged.iter().filter(|(_, f)| base(f) != "logo").collect(); + assert!(!renamed.is_empty(), "one link's copy got a new name: {packaged:?}"); + let new_file = &renamed[0].1; + let new_base = base(new_file); + assert_ne!(new_base, "logo"); + // The renamed link is `b/logo.png`: its layers are `logo b` and `other`. + assert_eq!(by_name(&packaged, &format!("{new_base} b")).map(|(_, f)| f), Some(new_file.clone()), "{packaged:?}"); + assert!(by_name(&packaged, "logo b").is_none(), "{packaged:?}"); + // A layer named otherwise, linked to the renamed copy, keeps its name. + assert_eq!(by_name(&packaged, "other").map(|(_, f)| f), Some(new_file.clone()), "{packaged:?}"); + // Layers whose link kept its name keep theirs. + for name in ["logo a", "logo a again"] { + assert_eq!(by_name(&packaged, name).map(|(_, f)| f), Some("logo.png".to_string()), "{name}: {packaged:?}"); + } + // The open document is unchanged. + let names: Vec<&str> = open.iter().map(|(n, _)| n.as_str()).collect(); + for want in ["logo a", "logo a again", "logo b", "other"] { + assert!(names.contains(&want), "{want}: {open:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} From aedac66d9514b38681cfa71b676d0d830b20866e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:35:26 +0100 Subject: [PATCH 059/385] WIP: Art History Brush: Area 0-500 px, field alerts and tooltips (#12630) From 6b7325c0b36f87b28391f142a6d2e0fb307155f7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:56:31 +0100 Subject: [PATCH 060/385] Art History Brush: Pressure for Opacity, Angle and Pressure for Size on the bar (#12629) Pressure for Opacity follows Opacity; Angle (the Background Eraser's field) and Pressure for Size follow Tolerance, with the reference tooltips. They edit the tool's own brush through tools.setBrush, so Reset Tool clears them and the History Brush and Brush keep theirs. Co-Authored-By: Claude Opus 5.5 --- .../panels/art_history_bar_controls_tests.rs | 118 ++++++++++++++++++ crates/ui-egui/src/panels/options_bar.rs | 9 ++ crates/ui-egui/src/tools/eraser_ui.rs | 2 +- crates/ui-egui/src/tools/retouch_ui.rs | 14 +++ 4 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/panels/art_history_bar_controls_tests.rs diff --git a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs new file mode 100644 index 0000000000..cb2c7018d8 --- /dev/null +++ b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs @@ -0,0 +1,118 @@ +//! #12629: the Art History Brush's options bar has a Pressure for Opacity toggle right after +//! Opacity, and an Angle field and a Pressure for Size toggle after Tolerance, with the reference +//! application's tooltips, off / 0° by default and after Reset Tool. They edit the tool's own +//! brush, not the History Brush's or the Brush's, and the bar has no Flow and no Airbrush. + +use egui::accesskit::Role; +use egui::{Modifiers, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::eraser_range_alert_tests::bar; +use crate::PhotocraftApp; +use crate::state::Tool; + +const PRESSURE_OPACITY: &str = "Always use pressure for opacity"; +const PRESSURE_SIZE: &str = "Always use pressure for size"; + +fn rect(h: &Harness<'static, PhotocraftApp>, label: &str) -> Rect { + h.get_by_label(label).rect() +} + +/// The field captioned `label` ("Opacity", "Tolerance"), by its caption's name. +fn field<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> Option> { + let label = format!("{label}:"); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label.as_str())) +} + +fn angle_field<'a>(h: &'a Harness<'static, PhotocraftApp>) -> Option> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().description().as_deref() == Some("Set the brush angle")) +} + +fn type_angle(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + angle_field(h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); +} + +/// The live brush's Pressure for Opacity, angle and Pressure for Size. +fn controls(app: &PhotocraftApp) -> (bool, f32, bool) { + let b = &app.session.tools.brush; + (b.pressure_opacity, b.angle, b.pressure_size) +} + +fn switch(h: &mut Harness<'static, PhotocraftApp>, tool: Tool) { + h.state_mut().ui.tool = tool; + h.run_steps(3); +} + +#[test] +fn pressure_for_opacity_follows_opacity_and_angle_and_pressure_for_size_follow_tolerance() { + let h = bar(Tool::ArtHistoryBrush); + let opacity = field(&h, "Opacity").expect("the Opacity field").rect(); + let pressure_opacity = rect(&h, PRESSURE_OPACITY); + let style = h.query_all_by_role(Role::ComboBox).next().expect("the Style dropdown").rect(); + assert!(opacity.right() <= pressure_opacity.left() && pressure_opacity.right() <= style.left(), "Opacity, Pressure for Opacity, Style"); + let angle = angle_field(&h).expect("the Angle field").rect(); + // The Tolerance field takes its caption's name. + let tolerance = rect(&h, "Tolerance"); + let pressure_size = rect(&h, PRESSURE_SIZE); + assert!(tolerance.right() <= angle.left() && angle.right() <= pressure_size.left(), "Tolerance, Angle, Pressure for Size"); +} + +#[test] +fn the_controls_carry_the_reference_tooltips() { + let h = bar(Tool::ArtHistoryBrush); + let tip = |label: &str| h.get_by_label(label).accesskit_node().description().map(|d| d.to_string()); + assert_eq!(tip(PRESSURE_OPACITY).as_deref(), Some("Always use Pressure for Opacity. When off, Brush Preset controls pressure")); + assert_eq!(tip(PRESSURE_SIZE).as_deref(), Some("Always use Pressure for Size. When off, Brush Preset controls pressure")); + assert!(angle_field(&h).is_some(), "the Angle field says \"Set the brush angle\""); +} + +#[test] +fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { + let mut h = bar(Tool::ArtHistoryBrush); + assert_eq!(controls(h.state()), (false, 0.0, false)); + assert!(angle_field(&h).and_then(|n| n.accesskit_node().numeric_value()) == Some(0.0), "the field shows 0°"); + h.get_by_label(PRESSURE_OPACITY).click(); + h.run_steps(2); + h.get_by_label(PRESSURE_SIZE).click(); + h.run_steps(2); + type_angle(&mut h, "45"); + assert_eq!(controls(h.state()), (true, 45.0, true)); + crate::burn_default_tip_tests::invoke(h.state_mut(), "tool.reset", json!({})); + h.run_steps(3); + assert_eq!(controls(h.state()), (false, 0.0, false)); +} + +#[test] +fn they_edit_the_art_history_brush_only() { + let mut h = bar(Tool::Brush); + // Each tool keeps its own brush from its first use on. + switch(&mut h, Tool::HistoryBrush); + switch(&mut h, Tool::ArtHistoryBrush); + h.get_by_label(PRESSURE_OPACITY).click(); + h.run_steps(2); + h.get_by_label(PRESSURE_SIZE).click(); + h.run_steps(2); + type_angle(&mut h, "-30"); + assert_eq!(controls(h.state()), (true, -30.0, true)); + for other in [Tool::HistoryBrush, Tool::Brush] { + switch(&mut h, other); + assert_eq!(controls(h.state()), (false, 0.0, false), "{other:?} keeps its own brush"); + } + switch(&mut h, Tool::ArtHistoryBrush); + assert_eq!(controls(h.state()), (true, -30.0, true), "the Art History Brush keeps its settings"); +} + +#[test] +fn the_bar_has_no_flow_and_no_airbrush() { + let h = bar(Tool::ArtHistoryBrush); + assert!(field(&h, "Flow").is_none(), "no Flow field"); + assert!(h.query_by_label("Enable airbrush-style build-up effects").is_none(), "no Airbrush toggle"); +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 005bf4793e..d387c4660c 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -177,6 +177,11 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { 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); + // Right after Opacity, as measured (#12629). + let pressure = pressure_button(ui, brush.pressure_opacity, tl!("Always use pressure for opacity"), true); + if pressure.on_hover_text(tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure")).clicked() { + brush.pressure_opacity = !brush.pressure_opacity; + } } crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); widgets::vline(ui, 22.0); @@ -1070,3 +1075,7 @@ mod smudge_strength_alert_tests; #[cfg(test)] #[path = "../pattern_stamp_opacity_flow_tests.rs"] mod pattern_stamp_opacity_flow_tests; + +#[cfg(test)] +#[path = "art_history_bar_controls_tests.rs"] +mod art_history_bar_controls_tests; diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 3a88440a52..769dcaddb6 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -152,7 +152,7 @@ pub(crate) const ANGLE_RANGE_MESSAGE: &str = "An integer between -180 ° and 180 /// The Background Eraser's Angle: an angle icon and a whole-degree field on the brush tip's /// angle, −180…180, default 0. Returns true when a typed value was out of range and was clamped /// (400 → 180): the caller shows [`ANGLE_RANGE_MESSAGE`] once the entry is committed. -fn angle_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) -> bool { +pub(crate) fn angle_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) -> bool { let t = Tokens::get(ui.ctx()); let tip = tl!("Set the brush angle"); ui.add(icons::image("rotate-cw", 15.0, t.text_dim)).on_hover_text(tip); diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 944c9a28b9..02b0d7df28 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1144,6 +1144,20 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::value_field(ui, &mut o.art_history_area, 0.0..=100.0, "", 50.0); opt(ui, tl!("Tolerance")); crate::widgets::value_field(ui, &mut o.art_history_tolerance, 0.0..=100.0, "", 50.0); + // Angle and Pressure for Size end the bar (#12629): they edit the tool's own brush, + // through `tools.setBrush`, with the Background Eraser's Angle field. + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + if crate::eraser_ui::angle_field(ui, &mut brush) { + let message = tl!(crate::eraser_ui::ANGLE_RANGE_MESSAGE).to_string(); + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + let name = tl!("Always use pressure for size"); + let pressure = crate::icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false); + if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { + brush.pressure_size = !brush.pressure_size; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); crate::widgets::vline(ui, 22.0); opt(ui, tl!("Stylized dabs from a history state")); } From 4eb0b6ea23f4ae8934f3632691e466a15f0028a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:59:26 +0100 Subject: [PATCH 061/385] 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 d24803345897453df4c0b5d8364665d0f4daf7f2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 02:08:31 +0100 Subject: [PATCH 062/385] Art History Brush: move Angle and Pressure for Size into a helper (#12629) Keeps retouch_ui::options_bar under clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/retouch_ui.rs | 32 +++++++++++++++----------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 02b0d7df28..fe19ce03e8 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -893,6 +893,23 @@ fn clone_sample_dropdown(ui: &mut egui::Ui, stored: &mut String, indexed: bool) } } +/// The Art History Brush's Angle and Pressure for Size, which end its bar (#12629). They edit +/// the tool's own brush through `tools.setBrush`, with the Background Eraser's Angle field. +fn art_history_angle_pressure(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + if crate::eraser_ui::angle_field(ui, &mut brush) { + let message = tl!(crate::eraser_ui::ANGLE_RANGE_MESSAGE).to_string(); + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + let name = tl!("Always use pressure for size"); + let pressure = crate::icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false); + if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { + brush.pressure_size = !brush.pressure_size; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); +} + /// Options bar for the retouching and smart-selection tools. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye) @@ -1144,20 +1161,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::value_field(ui, &mut o.art_history_area, 0.0..=100.0, "", 50.0); opt(ui, tl!("Tolerance")); crate::widgets::value_field(ui, &mut o.art_history_tolerance, 0.0..=100.0, "", 50.0); - // Angle and Pressure for Size end the bar (#12629): they edit the tool's own brush, - // through `tools.setBrush`, with the Background Eraser's Angle field. - let before = app.session.tools.brush.clone(); - let mut brush = before.clone(); - if crate::eraser_ui::angle_field(ui, &mut brush) { - let message = tl!(crate::eraser_ui::ANGLE_RANGE_MESSAGE).to_string(); - app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); - } - let name = tl!("Always use pressure for size"); - let pressure = crate::icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false); - if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { - brush.pressure_size = !brush.pressure_size; - } - crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); + art_history_angle_pressure(app, ui); crate::widgets::vline(ui, 22.0); opt(ui, tl!("Stylized dabs from a history state")); } From a55396638cf9169c3b68e2151f0c1a1050753045 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 02:23:18 +0100 Subject: [PATCH 063/385] 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 064/385] 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 065/385] 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 066/385] 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 067/385] 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 068/385] 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 9a9f2b78409558c16689ab582c5417ce0b737498 Mon Sep 17 00:00:00 2001 From: HankGrimm <87528983+HankGrimm@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:06:13 +0800 Subject: [PATCH 069/385] docs: point the Affinity format-notes links at craft-libs crates/affinity moved to craft-libs (8c7544ed); the README it linked to no longer exists in this repository. --- book/src/formats/affinity.md | 2 +- docs/file-format-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/book/src/formats/affinity.md b/book/src/formats/affinity.md index f77a5f0f32..7a45efc8f9 100644 --- a/book/src/formats/affinity.md +++ b/book/src/formats/affinity.md @@ -31,6 +31,6 @@ opens the small PNG preview Affinity stores in the file instead, as a single pix stacks, batch processing or other imports that can't show the warning. Export PSD or PNG from Affinity in that case. -See [the crate's notes](https://github.com/storytold/photocraft/blob/main/crates/affinity/README.md) +See [the crate's notes](https://github.com/storytold/craft-libs/blob/main/crates/affinity/README.md) for the full list of what is imported, how the reader was written and validated, and its safety limits. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5c4b436b96..a5776470f1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -99,7 +99,7 @@ D5100 colour profile. Counts and the G14 estimate are unchanged. ### Affinity import notes (moved from `roadmap.md`) 2026-10-08: Affinity `.af`, `.afdesign`, `.afphoto` and `.afpub` documents (container versions -8–12) open **natively** ([format notes](../crates/affinity/README.md)): pages and artboards, layers +8–12) open **natively** ([format notes](https://github.com/storytold/craft-libs/blob/main/crates/affinity/README.md)): pages and artboards, layers and groups, curves and geometric shapes with fills, gradients and strokes, text as type layers, placed images as smart objects, pixel layers and masks, as an 8-bit RGB document without a source save path. Measured against the thumbnail Affinity embeds in each file, 21 pinned public documents From 926738b5eb4af9f0a0681a966a93a880fb502f46 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 05:08:37 +0100 Subject: [PATCH 070/385] 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 071/385] 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 057bc457c0a5e92ddf9f0ca476c3c4136b4c6c86 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 13 Nov 2026 18:55:19 +0530 Subject: [PATCH 072/385] Custom Shape: Alt at the press picks the foreground and Fill colour (#13467) With no shape layer active and the tool in Shape mode, Alt held at the press samples the colour under the pointer into the foreground and the tool's Fill instead of drawing. Alt pressed only after the drag started still draws from the centre; with a shape layer active Alt at the press does not sample. Pixels and Path mode keep their behaviour. --- crates/ui-egui/src/canvas/cursors.rs | 34 +++-- .../custom_shape_alt_eyedropper_tests.rs | 127 ++++++++++++++++++ 2 files changed, 149 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index fd44445a2a..b081bdfa3d 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -294,16 +294,16 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: if !app.alt_sampling { return false; } - // The Triangle tool's ⇧⌥ at the press samples as ⌥ does, and the release point's colour is the - // one it keeps (#13364). - let triangle = app.active_tool() == Tool::Triangle; + // The Triangle and Custom Shape tools' ⇧⌥ at the press samples as ⌥ does, and the release + // point's colour is the one they keep (#13364, #13467). + let shape_tool = shape_samples_fill(app.active_tool()); match ev { // ⇧⌥-click adds a colour sampler at the clicked pixel instead, as the Color Sampler tool // places one: no foreground change, nothing painted (#11890). A refused point (the // document's limit) reports in the status bar as that tool's does; off the canvas, as that // tool, it places none and says nothing. A press on an existing point wasn't measured, so // it samples the foreground as before. - ToolEvent::Down { x, y, .. } if mods.shift && !triangle && !on_sampler(app, x, y) => { + ToolEvent::Down { x, y, .. } if mods.shift && !shape_tool && !on_sampler(app, x, y) => { let size = app.session.active().map(|d| d.doc.size); let inside = size.is_some_and(|s| (0.0..f64::from(s.width)).contains(&x) && (0.0..f64::from(s.height)).contains(&y)); if inside && let Err(e) = app.run("view.colorSamplers.add", json!({"x": x, "y": y})) { @@ -315,12 +315,12 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: } } // While ⇧⌥ stay held after that press, moves sample nothing. - ToolEvent::Move { .. } if mods.shift && !triangle => {} - ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } if triangle => sample_shape_fill(app, x, y), + ToolEvent::Move { .. } if mods.shift && !shape_tool => {} + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } if shape_tool => sample_shape_fill(app, x, y), // Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do. ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE), ToolEvent::Up { x, y } => { - if triangle { + if shape_tool { sample_shape_fill(app, x, y); } app.alt_sampling = false; @@ -329,21 +329,27 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: true } -/// The Triangle tool samples with ⌥ held at the press at (x, y) only in Shape mode and with no -/// shape layer active (#13364): with one, ⌥ subtracts from it. Path or Pixels mode and a press +/// The Triangle and Custom Shape tools sample with ⌥ held at the press at (x, y) only in Shape +/// mode and with no shape layer active (#13364, #13467): with one, ⌥ subtracts from it. Path or Pixels mode and a press /// with nothing to sample (off the image, over transparency) weren't measured and keep drawing /// from the centre. Control+⌥ stays the brush-resize drag, as in [`alt_samples`]. fn shape_alt_samples(app: &mut PhotocraftApp, mods: egui::Modifiers, x: f64, y: f64) -> bool { mods.alt && !mods.ctrl - && app.active_tool() == Tool::Triangle + && shape_samples_fill(app.active_tool()) && app.ui.tool_options.shape_mode == "shape" && crate::vector_ui::active_shape_path(app).is_none() && eyedropper_color(app, x, y).is_some() } -/// The Triangle tool's ⌥ sample: the colour at (x, y) becomes the foreground and the tool's Fill, a -/// solid fill, which follows the foreground (#13364). Where nothing is sampled, both stay. +/// Does this tool's ⌥ sample also set its Fill? The Triangle (#13364) and Custom Shape (#13467) +/// tools. +fn shape_samples_fill(tool: Tool) -> bool { + matches!(tool, Tool::Triangle | Tool::CustomShape) +} + +/// The Triangle or Custom Shape tool's ⌥ sample: the colour at (x, y) becomes the foreground and +/// the tool's Fill, a solid fill, which follows the foreground. Where nothing is sampled, both stay. fn sample_shape_fill(app: &mut PhotocraftApp, x: f64, y: f64) { if sampled_eyedropper(app, x, y, egui::Modifiers::NONE) { app.ui.tool_options.shape_fill = true; @@ -362,6 +368,10 @@ fn on_sampler(app: &PhotocraftApp, x: f64, y: f64) -> bool { #[path = "triangle_alt_eyedropper_tests.rs"] mod triangle_alt_eyedropper_tests; +#[cfg(test)] +#[path = "../tools/vector_ui/custom_shape_alt_eyedropper_tests.rs"] +mod custom_shape_alt_eyedropper_tests; + #[cfg(test)] #[path = "../brush_shift_alt_sampler_tests.rs"] mod brush_shift_alt_sampler_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs b/crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs new file mode 100644 index 0000000000..aff6ddfeef --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/custom_shape_alt_eyedropper_tests.rs @@ -0,0 +1,127 @@ +//! #13467: with the Custom Shape tool, Alt held at the press (no shape layer active) picks the +//! colour under the pointer as the foreground and the tool's Fill instead of drawing. Alt pressed +//! only after the drag started still draws from the centre, and with a shape layer active Alt at +//! the press does not sample. + +use egui::Modifiers; +use serde_json::json; + +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +/// 800 × 600, white Background, a red (220,30,30) pixel layer at 100,100 to 300,250 (active), +/// black foreground, the Custom Shape tool in Shape mode. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + app.ui.tool = Tool::CustomShape; + app.sync_views(); + app +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn foreground(app: &PhotocraftApp) -> [u8; 3] { + let c = app.session.tools.foreground; + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], press: Modifiers, rest: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, press); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, rest); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, rest); +} + +/// The tool's Fill colour: a solid fill follows the foreground (`vector_ui::shapes::tool_paint`). +fn tool_fill(app: &PhotocraftApp) -> [u8; 3] { + let o = &app.ui.tool_options; + assert!(o.shape_fill && o.shape_fill_gradient.is_none(), "a solid Fill"); + foreground(app) +} + +#[test] +fn alt_click_on_the_red_layer_picks_it_as_foreground_and_fill() { + let mut app = app(); + // A gradient or no Fill becomes the sampled solid colour. + app.ui.tool_options.shape_fill = false; + app.ui.tool_options.shape_fill_gradient = Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); + let (before, count) = (steps(&app), layers(&app)); + drag(&mut app, [200.0, 175.0], [200.0, 175.0], Modifiers::ALT, Modifiers::ALT); + assert_eq!(foreground(&app), [220, 30, 30], "#DC1E1E"); + assert_eq!(tool_fill(&app), [220, 30, 30], "Fill 220,30,30"); + assert_eq!(layers(&app), count, "no new layer"); + assert_eq!(steps(&app), before, "no History state"); +} + +#[test] +fn alt_drag_ending_on_white_picks_white() { + let mut app = app(); + let (before, count) = (steps(&app), layers(&app)); + drag(&mut app, [400.0, 300.0], [500.0, 350.0], Modifiers::ALT, Modifiers::ALT); + assert_eq!(foreground(&app), [255, 255, 255]); + assert_eq!(tool_fill(&app), [255, 255, 255], "Fill white"); + assert_eq!(layers(&app), count, "no new layer"); + assert_eq!(steps(&app), before, "no History state"); +} + +#[test] +fn the_release_point_colour_is_the_one_kept() { + let mut app = app(); + // The last move is on the red layer, the release on the white Background. + tool_event(&mut app, ToolEvent::Down { x: 200.0, y: 175.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 250.0, y: 200.0, pressure: 1.0 }, Modifiers::ALT); + assert_eq!(foreground(&app), [220, 30, 30], "red while over the layer"); + tool_event(&mut app, ToolEvent::Up { x: 500.0, y: 350.0 }, Modifiers::ALT); + assert_eq!(foreground(&app), [255, 255, 255], "white where released"); + assert_eq!(tool_fill(&app), [255, 255, 255], "Fill white"); +} + +#[test] +fn alt_pressed_after_the_drag_started_draws_from_the_centre() { + let mut app = app(); + let count = layers(&app); + drag(&mut app, [400.0, 300.0], [500.0, 350.0], Modifiers::NONE, Modifiers::ALT); + assert_eq!(foreground(&app), [0, 0, 0], "nothing sampled"); + assert_eq!(layers(&app), count + 1, "a shape layer"); + let st = app.session.active().unwrap(); + let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + // In the 300,250 to 500,350 box round the press, centred on it (a corner drag centres on 450,325). + let (x0, y0, x1, y1) = shape.path.control_bounds().unwrap(); + assert!(x0 >= 299.5 && y0 >= 249.5 && x1 <= 500.5 && y1 <= 350.5, "{x0},{y0} to {x1},{y1}"); + assert!(((x0 + x1) / 2.0 - 400.0).abs() < 1.0 && ((y0 + y1) / 2.0 - 300.0).abs() < 1.0, "drawn from the centre: {x0},{y0} to {x1},{y1}"); +} + +#[test] +fn a_shape_layer_active_does_not_sample() { + let mut app = app(); + app.run("shape.create", json!({"rect": [500, 400, 100, 100], "fill": "#3270c0", "stroke": null})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0)); + tool_event(&mut app, ToolEvent::Down { x: 200.0, y: 175.0, pressure: 1.0 }, Modifiers::ALT); + assert!(!app.alt_sampling, "Alt at the press is not the Eyedropper"); + assert_eq!(foreground(&app), [0, 0, 0]); +} + +#[test] +fn path_and_pixels_mode_and_ctrl_alt_do_not_sample() { + let mut app = app(); + for mode in ["path", "pixels"] { + app.ui.tool_options.shape_mode = mode.into(); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0), "{mode} mode was not measured"); + } + app.ui.tool_options.shape_mode = "shape".into(); + assert!(shape_alt_samples(&mut app, Modifiers::ALT, 200.0, 175.0)); + assert!(!shape_alt_samples(&mut app, Modifiers { alt: true, ctrl: true, ..Modifiers::NONE }, 200.0, 175.0), "Ctrl+Alt is the brush resize"); + assert!(!shape_alt_samples(&mut app, Modifiers::NONE, 200.0, 175.0)); +} From 21672d4a300715f9f17a1db43e7980de35d36c65 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 06:26:42 +0100 Subject: [PATCH 073/385] 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 8ce5afe1a8a82437d1fd204dec21ec4e94a3ecd4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 09:45:06 +0100 Subject: [PATCH 074/385] Artboards to PDF: Export Selected Artboards checkbox (#13647) The dialog gets the checkbox after the path field. It is ticked when an artboard is the active layer and greyed and unticked otherwise, set from the layer selection on every open. Ticked, Run passes the selected artboards' ids, so only those boards become pages; unticked, every board is exported as before. Co-Authored-By: Claude Opus 5.5 --- .../src/artboards_to_pdf_selected_tests.rs | 218 ++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 44 +++- 2 files changed, 261 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/artboards_to_pdf_selected_tests.rs diff --git a/crates/ui-egui/src/artboards_to_pdf_selected_tests.rs b/crates/ui-egui/src/artboards_to_pdf_selected_tests.rs new file mode 100644 index 0000000000..4511b7d192 --- /dev/null +++ b/crates/ui-egui/src/artboards_to_pdf_selected_tests.rs @@ -0,0 +1,218 @@ +//! #13647: File › Export › Artboards to PDF has the Export Selected Artboards checkbox. It is +//! enabled and ticked when an artboard is the active layer, greyed and unticked otherwise, and set +//! from the selection at every open. Ticked, only the selected boards become pages; unticked, +//! every board does, as before. +//! +//! The document is the spec's: 800 x 400, transparent, with, bottom to top, `Red Board` +//! 0,0-200,150 (white, pixel layer `Red`), `Blue Board` 120,30-320,230 (white, pixel layer +//! `Blue`) and `Empty Board` 600,0-700,100 (white, no layers). At 72 ppi a page's MediaBox is the +//! board's size in pixels, so it tells the pages apart. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +const ARTBOARDS_TO_PDF: &str = "file.export.artboardsToPdf"; +const CHECKBOX: &str = "Export Selected Artboards"; +const RED: &str = "/MediaBox [0 0 200.000 150.000]"; +const BLUE: &str = "/MediaBox [0 0 200.000 200.000]"; +const EMPTY: &str = "/MediaBox [0 0 100.000 100.000]"; + +struct Boards { + red: u64, + blue: u64, + red_layer: u64, +} + +/// Adds a white artboard `name` at `rect` ([x, y, w, h]), optionally with a pixel layer filled +/// with `color` over `fill`; returns the board's and the layer's ids. +fn board(app: &mut PhotocraftApp, name: &str, rect: [i32; 4], layer: Option<(&str, [i32; 4], &str)>) -> (u64, Option) { + let id = app.run("layer.new.artboard", json!({"rect": rect, "name": name, "background": "white"})).unwrap()["layer"].as_u64().unwrap(); + let inner = layer.map(|(layer, [x, y, width, height], color)| { + app.run("layer.select", json!({"layer": id})).unwrap(); + let l = app.run("layer.new.layer", json!({"name": layer})).unwrap()["layer"].as_u64().unwrap(); + app.run("select.rect", json!({"x": x, "y": y, "width": width, "height": height, "antiAlias": false})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + l + }); + (id, inner) +} + +fn harness() -> (Harness<'static, PhotocraftApp>, Boards) { + 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": 800, "height": 400, "background": "transparent", "name": "abpdf-test"})).unwrap(); + let (red, red_layer) = board(app, "Red Board", [0, 0, 200, 150], Some(("Red", [20, 20, 100, 80], "#DC1E1E"))); + let (blue, _) = board(app, "Blue Board", [120, 30, 200, 200], Some(("Blue", [130, 40, 100, 100], "#1E1EDC"))); + let (empty, _) = board(app, "Empty Board", [600, 0, 100, 100], None); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.artboards().iter().map(|b| b.0.0).collect::>(), [red, blue, empty], "the boards, bottom to top"); + let red_layer = red_layer.unwrap(); + assert_eq!(doc.artboard_of(LayerId(red_layer)), Some(LayerId(red))); + app.sync_views(); + (h, Boards { red, blue, red_layer }) +} + +/// Makes `layers` the selection; the last one added is the active layer. +fn select(h: &mut Harness<'_, PhotocraftApp>, layers: &[u64]) { + for (i, layer) in layers.iter().enumerate() { + let mode = if i == 0 { "replace" } else { "add" }; + h.state_mut().run("layer.select", json!({"layer": layer, "mode": mode})).unwrap(); + } + h.state_mut().sync_views(); +} + +/// Opens Artboards to PDF from the menu, writing to `path`. +fn open(h: &mut Harness<'_, PhotocraftApp>, path: &std::path::Path) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS_TO_PDF, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("path".into(), json!(path.to_string_lossy())); + h.run_steps(4); + dialog +} + +fn params(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(dialog).unwrap().fields) +} + +/// The checkbox's (enabled, ticked) state, as the accessibility tree reports it. +fn checkbox(h: &Harness<'_, PhotocraftApp>) -> (bool, bool) { + let node = h.get_by_role_and_label(Role::CheckBox, CHECKBOX); + let node = node.accesskit_node(); + (!node.is_disabled(), node.toggled() == Some(Toggled::True)) +} + +fn click(h: &mut Harness<'_, PhotocraftApp>) { + h.get_by_role_and_label(Role::CheckBox, CHECKBOX).click(); + h.run_steps(2); +} + +/// Run: exports, and returns the MediaBoxes of the PDF's pages in file order. +fn run(h: &mut Harness<'_, PhotocraftApp>, dialog: u64, path: &std::path::Path) -> Vec<&'static str> { + let before = h.state().session.active().map(|st| (st.revision, st.history.entries())); + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + assert_eq!(h.state().session.active().map(|st| (st.revision, st.history.entries())), before, "the document and its History are unchanged"); + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); + std::fs::remove_file(path).unwrap(); + let mut pages: Vec<(usize, &'static str)> = [RED, BLUE, EMPTY].into_iter().flat_map(|b| text.match_indices(b).map(move |(i, _)| (i, b))).collect(); + pages.sort_unstable(); + assert_eq!(r["pages"], json!(pages.len()), "{r}"); + assert_eq!(text.matches("/Type /Page ").count(), pages.len()); + pages.into_iter().map(|(_, b)| b).collect() +} + +fn sorted(mut pages: Vec<&'static str>) -> Vec<&'static str> { + pages.sort_unstable(); + pages +} + +#[test] +fn with_red_board_active_the_ticked_checkbox_exports_only_red_board() { + let (mut h, b) = harness(); + let dir = tempfile::tempdir().unwrap(); + let pdf = dir.path().join("out.pdf"); + select(&mut h, &[b.red]); + let dialog = open(&mut h, &pdf); + assert_eq!(checkbox(&h), (true, true), "an artboard is active: enabled and ticked"); + assert_eq!(params(&mut h, dialog)["artboards"], json!([b.red]), "Run sends Red Board's id"); + assert_eq!(run(&mut h, dialog, &pdf), [RED]); +} + +#[test] +fn two_selected_boards_both_become_pages() { + let (mut h, b) = harness(); + let dir = tempfile::tempdir().unwrap(); + let pdf = dir.path().join("out.pdf"); + select(&mut h, &[b.blue, b.red]); + let dialog = open(&mut h, &pdf); + assert_eq!(checkbox(&h), (true, true)); + let mut sent: Vec = params(&mut h, dialog)["artboards"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + sent.sort_unstable(); + assert_eq!(sent, [b.red, b.blue], "Run sends both boards' ids"); + assert_eq!(sorted(run(&mut h, dialog, &pdf)), sorted(vec![RED, BLUE])); +} + +#[test] +fn unticked_exports_every_board() { + let (mut h, b) = harness(); + let dir = tempfile::tempdir().unwrap(); + let pdf = dir.path().join("out.pdf"); + select(&mut h, &[b.red]); + let dialog = open(&mut h, &pdf); + click(&mut h); + assert_eq!(checkbox(&h), (true, false), "the click unticks it"); + assert!(params(&mut h, dialog)["artboards"].is_null(), "unticked, no boards are named"); + assert_eq!(sorted(run(&mut h, dialog, &pdf)), sorted(vec![RED, BLUE, EMPTY]), "every board, the empty one included"); + // Ticked again, the selected board is sent again. + let dialog = open(&mut h, &pdf); + click(&mut h); + click(&mut h); + assert_eq!((checkbox(&h), params(&mut h, dialog)["artboards"].clone()), ((true, true), json!([b.red]))); + crate::dialogs::cancel(h.state_mut(), dialog).unwrap(); +} + +#[test] +fn without_an_active_artboard_the_checkbox_is_greyed_and_every_board_is_exported() { + let (mut h, b) = harness(); + let dir = tempfile::tempdir().unwrap(); + let pdf = dir.path().join("out.pdf"); + // A layer inside a board active, alone and with Blue Board also selected, and no layer at all. + for active in [vec![b.red_layer], vec![b.blue, b.red_layer], vec![]] { + if active.is_empty() { + h.state_mut().session.active_mut().unwrap().active_layer = None; + h.state_mut().sync_views(); + } else { + select(&mut h, &active); + let st = h.state().session.active().unwrap(); + assert_eq!((st.active_layer, st.selected_layers().len()), (Some(LayerId(b.red_layer)), active.len()), "{active:?}"); + } + let dialog = open(&mut h, &pdf); + assert_eq!(checkbox(&h), (false, false), "{active:?}: greyed and unticked"); + click(&mut h); + assert_eq!(checkbox(&h), (false, false), "{active:?}: a click on the greyed checkbox does nothing"); + assert!(params(&mut h, dialog)["artboards"].is_null(), "{active:?}"); + assert_eq!(run(&mut h, dialog, &pdf).len(), 3, "{active:?}"); + } +} + +#[test] +fn the_checkbox_follows_the_selection_at_every_open() { + let (mut h, b) = harness(); + let dir = tempfile::tempdir().unwrap(); + let pdf = dir.path().join("out.pdf"); + select(&mut h, &[b.red]); + let dialog = open(&mut h, &pdf); + click(&mut h); + assert_eq!(run(&mut h, dialog, &pdf).len(), 3, "an unticked run exports every board"); + // Not remembered: the next open is ticked again, now for Blue Board. + select(&mut h, &[b.blue]); + let dialog = open(&mut h, &pdf); + assert_eq!(checkbox(&h), (true, true), "ticked again after an unticked run"); + assert_eq!(run(&mut h, dialog, &pdf), [BLUE]); + // And greyed once no artboard is active. + select(&mut h, &[b.red_layer]); + let dialog = open(&mut h, &pdf); + assert_eq!(checkbox(&h), (false, false)); + crate::dialogs::cancel(h.state_mut(), dialog).unwrap(); +} + +#[test] +fn the_checkbox_sits_between_the_path_and_the_quality() { + let (mut h, b) = harness(); + select(&mut h, &[b.red]); + let dialog = open(&mut h, std::path::Path::new("out.pdf")); + let fields = h.state_mut().ui.dialog_mut(dialog).unwrap().fields.clone(); + assert_eq!(crate::view_cmds::form_keys(&fields), ["path", "artboards", "quality"]); + let path = h.query_all_by_label("Path").next().unwrap().rect(); + let check = h.get_by_role_and_label(Role::CheckBox, CHECKBOX).rect(); + let quality = h.query_all_by_label("Quality").next().unwrap().rect(); + assert!(path.bottom() <= check.top() && check.bottom() <= quality.top(), "Path {path:?}, the checkbox {check:?}, Quality {quality:?}"); + crate::dialogs::cancel(h.state_mut(), dialog).unwrap(); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..7410fac9e0 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -191,6 +191,12 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { ui.end_row(); continue; } + if k == "artboards" && f.contains_key(SELECTED_ARTBOARDS) { + ui.label(""); + selected_artboards_field(ui, f); + ui.end_row(); + continue; + } let new = match &v { Value::Array(_) | Value::Object(_) | Value::Null => continue, Value::Bool(b) => { @@ -279,6 +285,31 @@ const JPEG_CUSTOM: &str = "__jpegCustom"; const JPEG_QUALITY: &str = "__jpegQuality"; /// The shell keys Alt+Reset restores along with a form's params. const RESET_SHELL_KEYS: [&str; 3] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY]; +/// Artboards to PDF's Export Selected Artboards (#13647): the artboards selected when the dialog +/// opened, sent as `artboards` while the checkbox is ticked. Shell state, never a command +/// parameter, and set from the selection at every open, so nothing is remembered. +const SELECTED_ARTBOARDS: &str = "__selectedArtboards"; + +/// The Export Selected Artboards checkbox: greyed and unticked when the dialog opened without an +/// artboard active. Ticked, `artboards` holds the selected boards; unticked it is null, and the +/// command exports every board. +fn selected_artboards_field(ui: &mut egui::Ui, f: &mut Map) { + let selected = f.get(SELECTED_ARTBOARDS).and_then(Value::as_array).filter(|ids| !ids.is_empty()).cloned(); + let mut ticked = selected.is_some() && f.get("artboards").is_some_and(Value::is_array); + ui.add_enabled_ui(selected.is_some(), |ui| crate::widgets::checkbox(ui, &mut ticked, tl!("Export Selected Artboards"))); + f.insert("artboards".into(), selected.filter(|_| ticked).map_or(Value::Null, Value::Array)); +} + +/// The boards Export Selected Artboards exports: the selected top-level artboards while an +/// artboard is the active layer, else none (the checkbox is greyed and every board is exported). +fn selected_artboards(app: &PhotocraftApp) -> Vec { + let Some(st) = app.session.active() else { return Vec::new() }; + let is_board = |id: &photocraft_doc::LayerId| st.doc.layers.iter().any(|l| l.id == *id && l.artboard().is_some()); + if !st.active_layer.as_ref().is_some_and(is_board) { + return Vec::new(); + } + st.selected_layers().into_iter().filter(is_board).map(|id| id.0).collect() +} /// A Custom checkbox and the 0..12 Quality field it enables (Batch, the exports to files). Off, /// the command gets no quality and keeps its own defaults; `usable` false greys out both. @@ -514,7 +545,14 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + // Export Selected Artboards, ticked when an artboard is active, set at every open. + let selected = selected_artboards(app); + let ticked = if selected.is_empty() { Value::Null } else { json!(selected) }; + dialog( + app, + json!({"path": format!("{dir}/{stem}.pdf"), "artboards": ticked, SELECTED_ARTBOARDS: selected, "quality": 10, "__order": ["path", "artboards", "quality"]}), + json!({}), + ) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] @@ -765,3 +803,7 @@ fn export_contents(app: &mut PhotocraftApp) -> Result { Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()})) }) } + +#[cfg(test)] +#[path = "../../artboards_to_pdf_selected_tests.rs"] +mod artboards_to_pdf_selected_tests; From f72dc60713bbcc77a1318017df41de51284fefd6 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 11:55:05 +0100 Subject: [PATCH 075/385] fix(engine): the Channel Mixer command mixes with whole percentages --- crates/engine/src/adjust_params.rs | 6 +++++- crates/engine/src/adjust_params/tests.rs | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 1dc244d6f8..9ace6e22d8 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -449,8 +449,12 @@ fn merge(mut a: Value, b: Value) -> Value { a } +/// One Channel Mixer output row: every coefficient and the constant is a whole percentage. +/// Scripted values round to the nearest whole percent before clamping, as the reference +/// application measures (0.4 to 0, 0.5 to 1, 50.6 to 51, 300 to 200, #14414); halves round away +/// from zero, which is what the dialog's own slider pass already does (`f32::round`). fn mixer_row(v: &[f32]) -> [f32; 4] { - std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).clamp(-200.0, 200.0) / 100.0) + std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).round().clamp(-200.0, 200.0) / 100.0) } fn hue_saturation(r: &Reader<'_>, base: Option<&Adjustment>) -> Result { diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs index 859757eae2..52b4d16529 100644 --- a/crates/engine/src/adjust_params/tests.rs +++ b/crates/engine/src/adjust_params/tests.rs @@ -706,3 +706,21 @@ fn gradient_map_source_params() { assert!(from_params("gradientMap", &json!({"source": bad}), None, ColorMode::Rgb).is_err(), "{bad}"); } } + +/// #14414: the reference application mixes with whole percentages. Scripted values round to the +/// nearest whole percent before clamping; the dialog already sends whole percents. +#[test] +fn channel_mixer_percentages_are_whole_numbers() { + let a = from_params( + "channelMixer", + &json!({"red": [0.4, 0.5, 50.6, -0.5], "green": [33.3, 33.3, 33.3, 0.0], "blue": [-300.0, 300.0, 0.0, 0.0]}), + None, + ColorMode::Rgb, + ) + .unwrap(); + let Adjustment::ChannelMixer { matrix, .. } = a else { panic!("wrong kind") }; + assert_eq!(matrix[0], [0.0, 0.01, 0.51, -0.01], "0.4 to 0, 0.5 to 1, 50.6 to 51, halves away from zero"); + assert_eq!(matrix[1], [0.33, 0.33, 0.33, 0.0], "33.3 stores as 33"); + assert_eq!(matrix[2], [-2.0, 2.0, 0.0, 0.0], "clamps stay -200 and 200"); + assert_eq!(to_params(&a)["red"], json!([0.0, 1.0, 51.0, -1.0]), "the stored step reads back whole"); +} From d6019ea85501324d2a8b7cacb6d80f2d69c96b18 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 11:55:10 +0100 Subject: [PATCH 076/385] fix(engine): Color Balance action steps round tones and default Preserve Luminosity off --- crates/engine/src/adjust_params.rs | 2 +- crates/engine/src/adjust_params/tests.rs | 10 +++++++ crates/engine/src/cmd/atn_cmds/adjustments.rs | 2 ++ crates/engine/src/cmd/atn_cmds/events.rs | 29 ++++++++++++++++++- crates/engine/src/cmd/atn_cmds/tests.rs | 13 +++++++++ 5 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 1dc244d6f8..7e3def4e22 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -146,7 +146,7 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color }; for (i, key) in ["shadows", "midtones", "highlights"].iter().enumerate() { if let Some(v) = r.numbers(key, 3)? { - tones[i] = [v[0], v[1], v[2]].map(|x| x.clamp(-100.0, 100.0)); + tones[i] = [v[0], v[1], v[2]].map(|x| x.round().clamp(-100.0, 100.0)); } } Adjustment::ColorBalance { diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs index 859757eae2..0d8f5af141 100644 --- a/crates/engine/src/adjust_params/tests.rs +++ b/crates/engine/src/adjust_params/tests.rs @@ -706,3 +706,13 @@ fn gradient_map_source_params() { assert!(from_params("gradientMap", &json!({"source": bad}), None, ColorMode::Rgb).is_err(), "{bad}"); } } + +/// #14417: tone values are whole percentages; scripted fractions round like the dialog's own +/// slider pass (away from zero on halves, which no measured case pins to). +#[test] +fn color_balance_tones_round_to_whole_numbers() { + let a = from_params("colorBalance", &json!({"midtones": [12.7, -0.4, 100.4], "highlights": [-100.4, 0.0, 0.0]}), None, ColorMode::Rgb).unwrap(); + let Adjustment::ColorBalance { midtones, highlights, .. } = a else { panic!("wrong kind") }; + assert_eq!(midtones, [13.0, 0.0, 100.0], "12.7 to 13, -0.4 to 0, 100.4 rounds into the clamp"); + assert_eq!(highlights, [-100.0, 0.0, 0.0], "-100.4 to -100"); +} diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 383b0b6267..21bebcb5c8 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -225,6 +225,8 @@ fn color_balance_from(d: &Descriptor) -> Option { out.insert(param.into(), v); } } + // Absent PrsL stays absent here on purpose: a layer edit merges and must not force the key, + // and the event path fills the measured default itself (#14417, see events.rs). if let Some(b) = get_bool(d, "PrsL") { out.insert("preserveLuminosity".into(), b.into()); } diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 97292737a4..08f1583357 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -708,7 +708,34 @@ pub(super) const EVENTS: &[Event] = &[ adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), adjustment_event!("Invr", "Invr", "invert", "Invert"), - adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), + // Color Balance: an Image > Adjustments apply step whose descriptor has no PrsL plays with + // Preserve Luminosity OFF (measured, #14417) - the reference's on default belongs to the + // dialog and to fresh adjustments. The shared from() keeps the key absent because a layer + // edit is a merge, so only this event path fills it. + Event { + code: "ClrB", + name: "colorBalance", + label: "Color Balance", + ids: &["image.adjustments.colorBalance"], + from: |d| match adjustment_by_class("ClrB") { + Some(a) => match adjustment_steps(a, "image.adjustments.", Some(d)) { + Mapped::Steps(steps) => Mapped::Steps( + steps + .into_iter() + .map(|(id, mut p)| { + if p.get("preserveLuminosity").is_none() { + p["preserveLuminosity"] = serde_json::Value::Bool(false); + } + (id, p) + }) + .collect(), + ), + other => other, + }, + None => Mapped::Unsupported { harmless: false }, + }, + to: |_, p| adjustment_by_class("ClrB").and_then(|a| (a.to)(p)), + }, // Written as the string event the reference application runs, with the `vibrance` class it // records; the old `Vbrn` code still loads through LEGACY_CODES. adjustment_event!("", "vibrance", "vibrance", "Vibrance"), diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index cbbb23f6cc..709decf6ee 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -7012,3 +7012,16 @@ fn adjustment_layer_name_must_round_trip() { } } } + +/// #14417: an Image > Adjustments apply step without PrsL plays with Preserve Luminosity off; +/// an explicit PrsL is honoured. (A layer edit's missing PrsL stays a merge, which the reset +/// test pins on the setd path.) +#[test] +fn color_balance_event_defaults_preserve_luminosity_off() { + let e = event_for(&item("ClrB", "Color Balance", None).event).expect("ClrB is mapped"); + let row = D::List(vec![long(10.0), long(0.0), long(0.0)]); + let Mapped::Steps(steps) = (e.from)(&desc("ClrB").with("MdtL", row.clone())) else { panic!("ClrB maps to a step") }; + assert_eq!(steps[0].1, json!({"midtones": [10.0, 0.0, 0.0], "preserveLuminosity": false}), "no PrsL plays off"); + let Mapped::Steps(on) = (e.from)(&desc("ClrB").with("MdtL", row).with("PrsL", D::Boolean(true))) else { panic!("ClrB maps to a step") }; + assert_eq!(on[0].1["preserveLuminosity"], json!(true), "an explicit PrsL is honoured"); +} From a6da8bc4b20cccaa256958afc6b0aa7f475ac599 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 13:39:38 +0100 Subject: [PATCH 077/385] Variables: own Apply Data Set dialog with a list of sets (#14495) Image > Apply Data Set... opens a small dialog: the document's data sets in a list (document order, first selected on every open) with Apply and Cancel beside it. Apply, Enter and a double-click apply the selected set once and close; Cancel, Escape and the close box change nothing. The dialog never writes the variables or data sets. The Variables dialog's apply mode is removed; its Data Sets page keeps its own Apply. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 13 +- crates/ui-egui/src/panels.rs | 1 + .../ui-egui/src/panels/apply_data_set_ui.rs | 99 ++++++ crates/ui-egui/src/panels/variables_ui.rs | 47 +-- .../ui-egui/tests/it/apply_data_set_dialog.rs | 325 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/variables_data_sets.rs | 189 ++-------- 7 files changed, 479 insertions(+), 196 deletions(-) create mode 100644 crates/ui-egui/src/panels/apply_data_set_ui.rs create mode 100644 crates/ui-egui/tests/it/apply_data_set_dialog.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba..85069a10b1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -335,15 +335,16 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::stack_dialog::owns(fields) => crate::stack_dialog::body(app, ui, fields, d.id), _ if crate::tool_reset::owns(fields) => crate::tool_reset::body(ui), _ if crate::crop_presets::owns(fields) => crate::crop_presets::body(app, ui, fields), - _ => return command_body_more(app, ui, d, fields, id), + _ => return command_body_more(app, ui, d, fields, id, interactive), } outcome } /// The rest of the command dialogs: files, colour, export, sizing, filters and forms. -fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id) -> Option { +fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { let mut outcome: Option = None; match d.kind { + _ if crate::panels::apply_data_set_ui::owns(fields) => outcome = crate::panels::apply_data_set_ui::body(app, ui, fields, interactive), _ if crate::variables_ui::owns(fields) => crate::variables_ui::body(app, ui, fields), _ if merge_channels_ui::owns(fields) => merge_channels_ui::body(ui, fields), _ if crate::file_ui::owns(fields) => crate::file_ui::body(app, ui, fields, d.id), @@ -739,7 +740,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) { browse_field(app, d.id, &fields, &key); } - if d.kind == DialogKind::LayerStyle || crate::guide_layout_ui::owns(&fields) || crate::brush_preset_dialog::owns(&fields) { + if d.kind == DialogKind::LayerStyle + || crate::guide_layout_ui::owns(&fields) + || crate::brush_preset_dialog::owns(&fields) + || crate::panels::apply_data_set_ui::owns(&fields) + { // These dialogs own their right-side actions and validate Enter themselves. } else if crate::color_picker_ui::owns(&fields) { if interactive && outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { @@ -932,6 +937,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::stack_dialog::owns, crate::tool_reset::owns, crate::crop_presets::owns, + crate::panels::apply_data_set_ui::owns, crate::variables_ui::owns, crate::file_ui::owns, crate::new_guide_ui::owns, @@ -1161,6 +1167,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result /// The rest of the command dialogs: files, colour, preferences and export, then any other command. fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result { match d.kind { + _ if crate::panels::apply_data_set_ui::owns(&d.fields) => crate::panels::apply_data_set_ui::confirm(app, &d.fields), _ if merge_channels_ui::owns(&d.fields) => merge_channels_ui::confirm(app, &d.fields), _ if crate::analysis_ui::owns_delete_note(&d.fields) => crate::analysis_ui::confirm_delete_note(app, &d.fields), _ if crate::analysis_ui::owns_clear_notes(&d.fields) => crate::analysis_ui::confirm_clear_notes(app, &d.fields), diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index b8eb48bd4f..407b51c52c 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -14,6 +14,7 @@ use crate::{PhotocraftApp, icons, widgets}; pub mod actions; pub mod adjust_ui; pub mod apply_color; +pub mod apply_data_set_ui; pub(crate) mod blend_preview; pub(super) mod brand; mod brush_controls; diff --git a/crates/ui-egui/src/panels/apply_data_set_ui.rs b/crates/ui-egui/src/panels/apply_data_set_ui.rs new file mode 100644 index 0000000000..b37a3cb3cd --- /dev/null +++ b/crates/ui-egui/src/panels/apply_data_set_ui.rs @@ -0,0 +1,99 @@ +//! Image › Apply Data Set… (#14495): a small dialog with the document's data sets in a list and +//! Apply / Cancel beside it, as in the reference application. It only applies a set +//! (`image.applyDataSet`); the variables and data sets are edited in Image › Variables. +//! +//! The selected row is the dialog's `index` field, so the control channel picks a set with +//! `ui.dialog.set` and applies it with `ui.dialog.confirm`. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::DialogKind; +use crate::theme::Tokens; + +const MARK: &str = "__applyDataSet"; +const LIST: egui::Vec2 = egui::vec2(300.0, 240.0); +const ROW: f32 = 20.0; + +/// This dialog owns a field set when it carries its marker. +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Open the dialog with the first set selected, as on every open in the reference application. +pub fn open(app: &mut PhotocraftApp) -> u64 { + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!("image.applyDataSet")); + f.insert("__label".into(), json!("Apply Data Set")); + f.insert("index".into(), json!(0)); + app.ui.open_dialog(DialogKind::Command, f) +} + +/// The document's data set names, in document order. +fn names(app: &PhotocraftApp) -> Vec { + app.session.active().map(|st| st.doc.variables.data_sets.iter().map(|s| s.name.clone()).collect()).unwrap_or_default() +} + +/// The list on the left, Apply and Cancel on the right. Returns `Some(true)` when a set is to be +/// applied (Apply, Enter, a double-click on a row) and `Some(false)` for Cancel. +pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { + let t = Tokens::get(ui.ctx()); + let sets = names(app); + let selected = f.get("index").and_then(Value::as_u64); + let mut outcome = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.label(tl!("Data Set:")); + let (frame, _) = ui.allocate_exact_size(LIST, egui::Sense::hover()); + ui.painter().rect_filled(frame, t.radius_sm, t.field); + ui.painter().rect_stroke(frame, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + let mut list = ui.new_child(egui::UiBuilder::new().max_rect(frame.shrink(1.0))); + egui::ScrollArea::vertical().id_salt("apply-data-set-list").auto_shrink([false, false]).show(&mut list, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + for (i, name) in sets.iter().enumerate() { + let on = selected == Some(i as u64); + let (rect, r) = ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW), egui::Sense::click()); + r.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, on, name)); + if on { + ui.painter().rect_filled(rect, 0.0, t.row_selected); + } else if r.hovered() { + ui.painter().rect_filled(rect, 0.0, t.hover); + } + let text = ui.painter().layout_no_wrap(name.clone(), egui::FontId::proportional(12.0), t.text); + let text_rect = rect.shrink2(egui::vec2(6.0, 0.0)); + ui.painter().with_clip_rect(text_rect).galley(egui::pos2(text_rect.left(), rect.center().y - text.size().y / 2.0), text, t.text); + // Any click selects only this row (Shift and Ctrl too); right-click shows no menu. + if r.clicked() || r.secondary_clicked() || r.double_clicked() { + f.insert("index".into(), json!(i)); + } + if r.double_clicked() { + outcome = Some(true); + } + } + }); + }); + ui.add_space(12.0); + ui.vertical(|ui| { + ui.add_space(ui.text_style_height(&egui::TextStyle::Body) + ui.spacing().item_spacing.y); + if crate::widgets::primary_button(ui, tl!("Apply"), 84.0).clicked() { + outcome = Some(true); + } + ui.add_space(4.0); + if crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked() { + outcome = Some(false); + } + }); + }); + if outcome.is_none() && interactive && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + outcome = Some(true); + } + outcome +} + +/// Apply, Enter or a double-click: apply the selected set once. The variables and data sets +/// themselves are never written here. +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + let index = f.get("index").and_then(Value::as_u64).ok_or_else(|| tl!("Select a data set to apply.").to_string())?; + app.run("image.applyDataSet", json!({"index": index})) +} diff --git a/crates/ui-egui/src/panels/variables_ui.rs b/crates/ui-egui/src/panels/variables_ui.rs index 3839a6e8cc..5fb32413b9 100644 --- a/crates/ui-egui/src/panels/variables_ui.rs +++ b/crates/ui-egui/src/panels/variables_ui.rs @@ -1,7 +1,7 @@ -//! Front end for Image › Variables (Define… / Data Sets…) and Apply Data Set — Photoshop's -//! data-driven graphics dialog. All editing drives the headless engine commands -//! (`image.variables.define`, `image.variables.dataSets`, `image.applyDataSet`), so the control -//! channel can drive this with `ui.dialog.set` / `confirm` exactly like a human. +//! Front end for Image › Variables (Define… / Data Sets…), the data-driven graphics dialog. +//! Image › Apply Data Set… has its own small dialog (`apply_data_set_ui`). All editing drives the +//! headless engine commands (`image.variables.define`, `image.variables.dataSets`, +//! `image.applyDataSet`), so the control channel can drive this with `ui.dialog.set` / `confirm` exactly like a human. //! //! The dialog keeps its working state as JSON in the `__variables` field, shaped like the engine //! command params, so `confirm` passes it straight through. @@ -48,17 +48,8 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option { - // No data set named: open the dialog on the Data Sets page to pick one. - let mut f = Map::new(); - f.insert("__command".into(), json!(id)); - let state = app.session.active().map(|st| crate::variables_ui::to_state(&st.doc.variables)).unwrap_or_else(|| json!({"defs": [], "dataSets": []})); - f.insert("__variablesOrig".into(), state.clone()); - f.insert("__variables".into(), state); - f.insert("__page".into(), json!("dataSets")); - f.insert("__label".into(), json!("Variables")); - Some(Ok(json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)}))) - } + // No data set named: the Apply Data Set dialog picks one from the list. + "image.applyDataSet" if !has_params => Some(Ok(json!({"dialog": crate::panels::apply_data_set_ui::open(app)}))), _ => None, } } @@ -152,16 +143,8 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map) -> Result { let empty = json!([]); let state = fields.get("__variables").unwrap_or(&Value::Null); let defs = state.get("defs").unwrap_or(&empty); let sets = state.get("dataSets").unwrap_or(&empty); - let selected = if fields.get("__command").and_then(Value::as_str) == Some("image.applyDataSet") && !fields.contains_key("__apply") { - sets.as_array().filter(|rows| !rows.is_empty()).map(|rows| data_set_index(fields, rows.len())) - } else { - None - }; - // An unchanged OK after Apply closes without another application or history entry. - if let Some(index) = selected - && let Some(st) = app.session.active() - && fields.get("__appliedAt") == Some(&json!([st.doc.id.0, st.revision])) - && st.doc.variables.active == Some(index) - && state == &to_state(&st.doc.variables) - { - return Ok(json!({"defined": true})); - } app.run("image.variables.define", json!({"defs": defs}))?; app.run("image.variables.dataSets", json!({"dataSets": sets}))?; let request = match fields.get("__apply") { Some(Value::String(name)) => Some(json!({"name": name})), Some(value) => value.as_u64().map(|index| json!({"index": index})), - None => selected.map(|index| json!({"index": index})), + None => None, }; match request { Some(params) => app.run("image.applyDataSet", params), diff --git a/crates/ui-egui/tests/it/apply_data_set_dialog.rs b/crates/ui-egui/tests/it/apply_data_set_dialog.rs new file mode 100644 index 0000000000..e6a77fcd1b --- /dev/null +++ b/crates/ui-egui/tests/it/apply_data_set_dialog.rs @@ -0,0 +1,325 @@ +//! #14495: Image › Apply Data Set… opens its own small dialog, as in the reference application: a +//! "Data Set:" list of the document's sets in document order with the first one selected on every +//! open, Apply (default) and Cancel beside it. Apply, Enter and a double-click apply the selected +//! set once and close; Cancel, Escape and the close box change nothing. The dialog never writes the +//! variables or data sets, and Image › Variables › Data Sets… keeps its own page. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, Outcome, handle}; +use serde_json::{Value, json}; + +const SETS: [&str; 3] = ["Zed", "Data Set 2", "Data Set 3"]; + +/// A document with a visibility and a pixel replacement variable on one layer, and three sets +/// (not in name order) that only set the visibility: Zed hides it, Data Set 2 shows it, Data Set 3 +/// hides it. No set has an image for the pixel variable. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap().0; + app.run( + "image.variables.define", + json!({"defs": [ + {"name": "badge", "layer": layer, "type": "visibility"}, + {"name": "photo", "layer": layer, "type": "pixelReplacement", "method": "fit"}, + ]}), + ) + .unwrap(); + let sets: Vec = SETS + .iter() + .zip([false, true, false]) + .map(|(name, on)| json!({"name": name, "values": [{"variable": "badge", "kind": "visibility", "value": on}]})) + .collect(); + app.run("image.variables.dataSets", json!({"dataSets": sets})).unwrap(); + app +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + photocraft_ui_egui::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, photocraft_ui_egui::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h +} + +/// Image › Apply Data Set… as the menu runs it, then a few frames. +fn open(h: &mut Harness<'static, PhotocraftApp>) { + let ctx = h.ctx.clone(); + photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.applyDataSet", json!({})).unwrap(); + h.run_steps(3); +} + +fn opened() -> Harness<'static, PhotocraftApp> { + let mut h = harness(app()); + open(&mut h); + h +} + +fn index(h: &Harness<'static, PhotocraftApp>) -> Value { + h.state().ui.dialogs.last().unwrap().fields["index"].clone() +} + +fn visible(h: &Harness<'static, PhotocraftApp>) -> bool { + let st = h.state().session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().visible +} + +/// History states added since the test document was made (making its layer is one). +fn history(h: &Harness<'static, PhotocraftApp>) -> usize { + let base = app().session.active().unwrap().history.past_len(); + h.state().session.active().unwrap().history.past_len() - base +} + +fn variables(h: &Harness<'static, PhotocraftApp>) -> photocraft_doc::Variables { + h.state().session.active().unwrap().doc.variables.clone() +} + +#[test] +fn menu_opens_the_apply_data_set_dialog_not_the_variables_editor() { + let h = opened(); + assert_eq!(h.state().ui.dialogs.len(), 1); + let d = h.state().ui.dialogs.last().unwrap(); + assert_eq!(photocraft_ui_egui::dialogs::title(d), "Apply Data Set"); + assert_eq!(d.fields["__command"], "image.applyDataSet"); + assert!(!d.fields.contains_key("__variables"), "the dialog carries no editable variables"); + h.get_by_label("Data Set:"); + h.get_by_label("Apply"); + h.get_by_label("Cancel"); + for absent in ["OK", "Define", "Data Sets", "New", "Delete", "Name:", "▶"] { + assert!(h.query_by_label(absent).is_none(), "{absent}"); + } +} + +#[test] +fn variables_data_sets_page_keeps_its_own_dialog() { + let mut h = harness(app()); + let ctx = h.ctx.clone(); + photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.variables.dataSets", json!({})).unwrap(); + h.run_steps(3); + let d = h.state().ui.dialogs.last().unwrap(); + assert!(d.fields.contains_key("__variables")); + assert_eq!(photocraft_ui_egui::dialogs::title(d), "Variables"); + h.get_by_label("OK"); + h.get_by_label("Define"); + assert!(h.query_by_label("Data Set:").is_none()); +} + +#[test] +fn list_shows_every_set_in_document_order_with_the_first_selected() { + let h = opened(); + let tops: Vec = SETS.iter().map(|name| h.get_by_label(name).rect().top()).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "document order, not sorted: {tops:?}"); + assert_eq!(index(&h), 0); + let selected: Vec = SETS.iter().map(|name| h.get_by_label(name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)).collect(); + assert_eq!(selected, [true, false, false]); +} + +#[test] +fn first_set_is_selected_on_every_open_also_after_another_was_applied() { + let mut h = opened(); + h.get_by_label("Data Set 3").click(); + h.run_steps(2); + assert_eq!(index(&h), 2); + h.get_by_label("Apply").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(variables(&h).active, Some(2)); + open(&mut h); + assert_eq!(index(&h), 0); +} + +#[test] +fn clicks_select_one_row_and_a_click_below_the_rows_keeps_it() { + let mut h = opened(); + h.get_by_label("Data Set 2").click(); + h.run_steps(2); + assert_eq!(index(&h), 1); + for modifiers in [egui::Modifiers::SHIFT, egui::Modifiers::COMMAND] { + h.get_by_label("Data Set 3").click_modifiers(modifiers); + h.run_steps(2); + assert_eq!(index(&h), 2, "{modifiers:?} selects only the clicked row"); + h.get_by_label("Zed").click_modifiers(modifiers); + h.run_steps(2); + assert_eq!(index(&h), 0, "{modifiers:?}"); + } + h.get_by_label("Data Set 2").click_secondary(); + h.run_steps(2); + assert_eq!(index(&h), 1, "right-click selects"); + assert_eq!(h.state().ui.dialogs.len(), 1, "and shows no menu"); + // The empty area under the last row. + let below = h.get_by_label("Data Set 3").rect().center() + egui::vec2(0.0, 60.0); + h.event(egui::Event::PointerMoved(below)); + h.event(egui::Event::PointerButton { pos: below, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: below, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + assert_eq!(index(&h), 1); + assert!(visible(&h), "selecting applies nothing"); + assert_eq!(history(&h), 0); +} + +/// Apply, Enter and a double-click each apply the selected set once and close the dialog. +#[test] +fn apply_enter_and_double_click_apply_the_selected_set_once() { + for way in ["button", "enter", "double-click"] { + let mut h = opened(); + let before = variables(&h); + match way { + "button" | "enter" => { + h.get_by_label("Data Set 3").click(); + h.run_steps(2); + if way == "button" { + h.get_by_label("Apply").click(); + } else { + h.key_press(egui::Key::Enter); + } + } + _ => { + // Two clicks in a row on a row that isn't selected yet, pressed and released + // in separate frames as a mouse does. + let at = h.get_by_label("Data Set 3").rect().center(); + h.hover_at(at); + h.run_steps(40); + for _ in 0..2 { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } + } + } + } + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{way}: closes"); + assert!(h.state().ui.status.is_empty(), "{way}: {}", h.state().ui.status); + assert!(!visible(&h), "{way}: Data Set 3 hides the layer"); + assert_eq!(history(&h), 1, "{way}: one history state"); + let after = variables(&h); + assert_eq!(after.active, Some(2), "{way}"); + assert_eq!((after.defs, after.data_sets), (before.defs, before.data_sets), "{way}: the variables and data sets stay as they were"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(visible(&h), "{way}: one undo restores the layer"); + } +} + +/// The first set applies with nothing clicked: Zed hides the layer. +#[test] +fn apply_right_after_open_applies_the_first_set() { + let mut h = opened(); + h.get_by_label("Apply").click(); + h.run_steps(3); + assert!(!visible(&h)); + assert_eq!(variables(&h).active, Some(0)); +} + +#[test] +fn cancel_escape_and_the_close_box_change_nothing() { + for way in ["cancel", "escape", "close"] { + if way == "close" && cfg!(target_os = "macos") { + continue; // No close box on macOS. + } + let mut h = opened(); + let before = variables(&h); + let revision = h.state().session.active().unwrap().revision; + h.get_by_label("Data Set 3").click(); + h.run_steps(2); + match way { + "cancel" => h.get_by_label("Cancel").click(), + "escape" => h.key_press(egui::Key::Escape), + _ => h.get_by_label("Close").click(), + } + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{way}"); + assert!(visible(&h), "{way}"); + assert_eq!(history(&h), 0, "{way}"); + assert_eq!(variables(&h), before, "{way}"); + assert_eq!(h.state().session.active().unwrap().revision, revision, "{way}"); + } +} + +#[test] +fn holding_alt_keeps_cancel() { + let mut h = opened(); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(2); + assert!(h.query_by_label("Reset").is_none()); + h.get_by_label("Cancel"); +} + +fn control(h: &mut Harness<'static, PhotocraftApp>, method: &str, params: Value) -> Value { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + let reply = match handle(h.state_mut(), &ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + }; + h.run_steps(2); + reply +} + +#[test] +fn control_channel_lists_sets_and_applies_the_selected_one() { + let mut h = opened(); + let inspected = control(&mut h, "ui.inspect", json!({})); + let dialogs = inspected["result"]["dialogs"].as_array().unwrap(); + let d = dialogs.iter().find(|d| d["fields"]["__command"] == "image.applyDataSet").expect("listed in ui.inspect"); + assert_eq!(d["fields"]["index"], 0); + let id = d["id"].clone(); + + let set = control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "index", "value": 1})); + assert_eq!(set["ok"], true, "{set}"); + assert_eq!(index(&h), 1); + let confirmed = control(&mut h, "ui.dialog.confirm", json!({"dialog": id})); + assert_eq!(confirmed["ok"], true, "{confirmed}"); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(variables(&h).active, Some(1)); + assert_eq!(history(&h), 1); + + open(&mut h); + let id = h.state().ui.dialogs.last().unwrap().id; + let cancelled = control(&mut h, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(history(&h), 1); +} + +/// `ui.dialog.set` can store anything in `index`: a bad one is an error, never a panic or a +/// different set. +#[test] +fn bad_index_from_the_control_channel_is_an_error() { + for bad in [json!(99), json!(-1), json!("Zed"), json!(1.5), Value::Null, json!(u64::MAX)] { + let mut h = opened(); + let id = h.state().ui.dialogs.last().unwrap().id; + control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "index", "value": bad})); + h.run_steps(2); + let confirmed = control(&mut h, "ui.dialog.confirm", json!({"dialog": id})); + assert_ne!(confirmed["ok"], true, "{bad}: {confirmed}"); + assert!(visible(&h), "{bad}"); + assert_eq!(history(&h), 0, "{bad}"); + } +} + +/// A document without data sets (the menu item is disabled then, but the control channel can open +/// it on any document) shows an empty list, and Apply only reports why. +#[test] +fn no_data_sets_shows_an_empty_list_and_apply_reports_it() { + let mut a = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + a.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut h = harness(a); + let id = photocraft_ui_egui::panels::apply_data_set_ui::open(h.state_mut()); + h.run_steps(3); + assert_eq!(h.state().ui.dialogs.last().unwrap().id, id); + h.get_by_label("Apply").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert!(!h.state().ui.status.is_empty(), "the failure is reported"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8004bf5b73..8dcbd48d78 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,6 +4,7 @@ mod actions_duplicate; mod actions_panel_menu; mod actions_record_again; mod adjust_preview_gpu; +mod apply_data_set_dialog; mod arbitrary_rotation_preview; mod background_eraser_reset_tip; mod batch_export_options; diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index aef5630199..39d0d4f224 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -82,20 +82,11 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, Harness<'static, Photocraf (dir, harness(app)) } -fn save_draft_and_open_apply_menu(h: &mut Harness<'static, PhotocraftApp>) { - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - let ctx = h.ctx.clone(); - photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.applyDataSet", json!({})).unwrap(); - h.run_steps(3); -} - fn read_pixel(h: &mut Harness<'static, PhotocraftApp>) -> serde_json::Value { h.state_mut().run("document.pixel", json!({"x": 4, "y": 4})).unwrap() } -/// CSV chosen through the import menu supplies the row that Apply renders and OK preserves. +/// CSV chosen through the import menu supplies the row that Apply Data Set applies. #[test] fn imported_csv_replaces_pixels_through_the_apply_dialog() { use photocraft_ui_egui::file_dialog::{FileDialogAnswer, FileDialogRequest}; @@ -131,41 +122,12 @@ fn imported_csv_replaces_pixels_through_the_apply_dialog() { h.get_by_label("Apply").click(); h.run_steps(3); assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0])); - assert_eq!(h.state().ui.dialogs.len(), 1); - let revision = h.state().session.active().unwrap().revision; - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - assert_eq!(h.state().session.active().unwrap().revision, revision); + assert!(h.state().ui.dialogs.is_empty(), "Apply Data Set closes on Apply"); h.state_mut().run("edit.undo", json!({})).unwrap(); assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); } } -#[test] -fn apply_menu_ok_requires_a_row_but_not_variable_definitions() { - for (rows, explicit, expected) in [(json!([]), false, None), (json!([{"name": "Empty", "values": []}]), false, Some(0)), (json!([]), true, None)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - app.run("image.variables.dataSets", json!({"dataSets": rows})).unwrap(); - photocraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "image.applyDataSet", json!({})).unwrap(); - if explicit { - app.ui.dialogs.last_mut().unwrap().fields.insert("__apply".into(), json!(0)); - } - let mut h = harness(app); - h.state_mut().ui.status.clear(); - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - assert_eq!(h.state().session.active().unwrap().doc.variables.active, expected); - if explicit { - assert!(h.state().ui.status.contains("no data sets in document")); - } else { - assert!(h.state().ui.status.is_empty(), "{}", h.state().ui.status); - } - } -} - /// Apply updates the canvas immediately; OK must not apply the same request again. #[test] fn apply_replaces_pixels_before_ok_and_keeps_the_dialog_open() { @@ -189,99 +151,23 @@ fn apply_replaces_pixels_before_ok_and_keeps_the_dialog_open() { assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); } -/// Duplicate labels must not change which row Apply or OK sends to the engine. +/// Duplicate labels must not change which row the Data Sets page's Apply sends to the engine. #[test] -fn duplicate_names_apply_the_selected_row_for_apply_and_ok() { - for button in ["Apply", "OK"] { - let (_dir, mut h) = pixel_replacement_harness(); - let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; - let selected = fields["__variables"]["dataSets"][0].clone(); - fields["__variables"]["dataSets"] = json!([{"name": "Blue", "values": []}, selected]); - save_draft_and_open_apply_menu(&mut h); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]), "editing data sets only saves them"); - h.get_by_label("▶").click(); - h.run_steps(2); - let fields = &h.state().ui.dialogs.last().unwrap().fields; - assert_eq!(fields["__cur"], 1); - assert!(!fields.contains_key("__apply")); - h.get_by_label(button).click(); - h.run_steps(3); - assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]), "{button}"); - assert_eq!(h.state().session.active().unwrap().doc.variables.active, Some(1), "{button}"); - } -} - -#[test] -fn apply_menu_apply_then_ok_keeps_one_history_entry() { +fn duplicate_names_apply_the_selected_row() { let (_dir, mut h) = pixel_replacement_harness(); - save_draft_and_open_apply_menu(&mut h); + let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; + let selected = fields["__variables"]["dataSets"][0].clone(); + fields["__variables"]["dataSets"] = json!([{"name": "Blue", "values": []}, selected]); + h.run_steps(2); + h.get_by_label("▶").click(); + h.run_steps(2); + let fields = &h.state().ui.dialogs.last().unwrap().fields; + assert_eq!(fields["__cur"], 1); + assert!(!fields.contains_key("__apply")); h.get_by_label("Apply").click(); h.run_steps(3); assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0])); - let revision = h.state().session.active().unwrap().revision; - h.get_by_label("OK").click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().revision, revision); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); -} - -#[test] -fn apply_menu_ok_honors_changes_after_apply() { - for change in ["row", "value", "document"] { - let (dir, mut h) = pixel_replacement_harness(); - let red = json!(dir.path().join("red.png")); - if change == "row" { - let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; - let mut row = fields["__variables"]["dataSets"][0].clone(); - row["values"][0]["value"] = red.clone(); - fields["__variables"]["dataSets"].as_array_mut().unwrap().push(row); - } - save_draft_and_open_apply_menu(&mut h); - h.get_by_label("Apply").click(); - h.run_steps(3); - if change == "row" { - h.get_by_label("▶").click(); - } else if change == "value" { - h.state_mut().ui.dialogs.last_mut().unwrap().fields["__variables"]["dataSets"][0]["values"][0]["value"] = red; - } else { - h.state_mut().run("image.adjustments.invert", json!({})).unwrap(); - } - h.run_steps(3); - let before = if change == "document" { json!([1.0, 1.0, 0.0, 1.0]) } else { json!([0.0, 0.0, 1.0, 1.0]) }; - assert_eq!(read_pixel(&mut h), before, "{change}: only document edits change pixels before OK"); - h.get_by_label("OK").click(); - h.run_steps(3); - let after = if change == "document" { json!([0.0, 0.0, 1.0, 1.0]) } else { json!([1.0, 0.0, 0.0, 1.0]) }; - assert_eq!(read_pixel(&mut h), after, "{change}"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(read_pixel(&mut h), before); - } -} - -#[test] -fn apply_menu_cancel_does_not_apply_the_selected_row() { - let (_dir, mut h) = pixel_replacement_harness(); - save_draft_and_open_apply_menu(&mut h); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); -} - -#[test] -fn apply_menu_ok_after_deleting_the_last_row_only_saves() { - let (_dir, mut h) = pixel_replacement_harness(); - save_draft_and_open_apply_menu(&mut h); - h.get_by_label("Delete").click(); - h.run_steps(2); - h.state_mut().ui.status.clear(); - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - assert!(h.state().ui.status.is_empty(), "{}", h.state().ui.status); - assert!(h.state().session.active().unwrap().doc.variables.data_sets.is_empty()); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); + assert_eq!(h.state().session.active().unwrap().doc.variables.active, Some(1)); } #[test] @@ -317,33 +203,28 @@ fn variables_editor_ok_only_saves_configuration() { /// A failed request reports once; correcting it can be applied and kept when Cancel closes. #[test] fn failed_apply_can_be_corrected_without_retries_or_cancel_rollback() { - for apply_mode in [false, true] { - let (dir, mut h) = pixel_replacement_harness(); - if apply_mode { - save_draft_and_open_apply_menu(&mut h); - } - let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; - fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("missing.png")); - h.get_by_label("Apply").click(); - h.run_steps(3); - assert!(h.state().ui.status.contains("missing.png"), "{}", h.state().ui.status); - assert!(!h.state().ui.dialogs.last().unwrap().fields.contains_key("__apply")); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); - h.state_mut().ui.status.clear(); - h.run_steps(3); - assert!(h.state().ui.status.is_empty(), "a failed Apply must not retry each frame"); + let (dir, mut h) = pixel_replacement_harness(); + let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; + fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("missing.png")); + h.get_by_label("Apply").click(); + h.run_steps(3); + assert!(h.state().ui.status.contains("missing.png"), "{}", h.state().ui.status); + assert!(!h.state().ui.dialogs.last().unwrap().fields.contains_key("__apply")); + assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); + h.state_mut().ui.status.clear(); + h.run_steps(3); + assert!(h.state().ui.status.is_empty(), "a failed Apply must not retry each frame"); - let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; - fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("blue.png")); - h.get_by_label("Apply").click(); - h.run_steps(3); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0])); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); - } + let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields; + fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("blue.png")); + h.get_by_label("Apply").click(); + h.run_steps(3); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0])); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); } /// `ui.dialog.set` can store any JSON in `__variables`; the editors write into its entries. From 1066751578d35474c60860a77e0769796f5df8fe Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 14:03:08 +0100 Subject: [PATCH 078/385] Variables: Preview checkbox in the Apply Data Set dialog (#14496) Preview shows the selected data set in the document without a history state; unticking it, Cancel, Escape and the close box put the document back. Apply reverts the preview first, so it leaves the same document and one history state. The box is kept for the next open after Apply, off after Cancel. A set that can't be applied shows nothing of itself. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/variables_cmds.rs | 15 + crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/panels/apply_data_set_ui.rs | 110 +++++- .../tests/it/apply_data_set_preview.rs | 334 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 8 files changed, 464 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/tests/it/apply_data_set_preview.rs diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index d109959bdd..537e00254a 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -283,6 +283,21 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { Ok(json!({"applied": set.name, "index": idx})) } +/// The document as `image.applyDataSet {"index": index}` would leave it, built without touching the +/// session: the Apply Data Set dialog's Preview (#14496). It reads replacement images as the +/// command does (the same path gate, relative to the document) and fails as a whole, so a set +/// that can't be applied never gives a partly applied preview. +pub fn data_set_preview(s: &Session, index: usize) -> Result { + let (set, _) = resolve_set(s, &json!({"index": index}), "image.applyDataSet")?; + authorize_pixel_paths(s, &set)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let _authorization = crate::jobs::render_authorization_scope(s.authorize); + let _document = crate::doc_path::scope(st.path.as_deref().map(std::path::Path::new)); + let mut doc = (*st.doc).clone(); + apply_to_doc(&mut doc, &st.doc.variables, &set)?; + Ok(doc) +} + /// 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; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef4eae9be2..ee6e38c33e 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_preview, 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..9cd3feec66 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -75,6 +75,7 @@ impl PhotocraftApp { reorder_preview_hit: false, patch_preview: None, cam_preview: None, + data_set_preview: Default::default(), magnetic: Default::default(), secondary_erase: false, held_erase: false, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 85069a10b1..24b833c51f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1219,6 +1219,7 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; dont_show_again::closed(app, &closed); crate::guide_edit::cancel(app, id); + crate::panels::apply_data_set_ui::cancel(app, &closed.fields); // A Color Picker puts back what its live preview showed in its target. crate::color_picker_ui::live_preview::end(app, id); // A field Color Picker of this dialog has no target left: it closes with the dialog. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..e6cf8d6c5e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -422,6 +422,8 @@ pub struct PhotocraftApp { pub(crate) patch_preview: Option, /// Content-Aware Move drag or box shown with its result (`cam_preview`). pub(crate) cam_preview: Option, + /// Image › Apply Data Set…'s Preview: the set shown in the document (`apply_data_set_ui`). + pub(crate) data_set_preview: panels::apply_data_set_ui::PreviewState, /// The pixels a Magnetic Lasso border follows (`magnetic_lasso_ui`). pub(crate) magnetic: magnetic_lasso_ui::Runtime, /// The next tool `Down` is a right-button drag that erases (see `paint_mouse`). diff --git a/crates/ui-egui/src/panels/apply_data_set_ui.rs b/crates/ui-egui/src/panels/apply_data_set_ui.rs index b37a3cb3cd..3a0f8d4518 100644 --- a/crates/ui-egui/src/panels/apply_data_set_ui.rs +++ b/crates/ui-egui/src/panels/apply_data_set_ui.rs @@ -4,7 +4,17 @@ //! //! The selected row is the dialog's `index` field, so the control channel picks a set with //! `ui.dialog.set` and applies it with `ui.dialog.confirm`. +//! +//! Preview (#14496, the `preview` field) shows the selected set in the document: the canvas and +//! the Layers panel show the document as Apply would leave it, but no history state is made and +//! a clean document stays clean. Unticking it, Cancel, Escape and the close box put the document +//! back as it was. Apply puts it back first and then runs the command, so it leaves the same +//! document and the one history state Apply without Preview does. The box keeps its state for +//! the next open after Apply, and is off again after Cancel. +use std::sync::Arc; + +use photocraft_doc::{DocId, Document}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -15,6 +25,27 @@ const MARK: &str = "__applyDataSet"; const LIST: egui::Vec2 = egui::vec2(300.0, 240.0); const ROW: f32 = 20.0; +/// The set Preview shows and the document as it was before. +pub(crate) struct Preview { + doc: DocId, + index: usize, + original: Arc, + /// The revision showing the preview left. Anything that moved it since changed the previewed + /// document itself, so putting `original` back would undo that change: the preview is dropped. + revision: u64, + was_clean: bool, +} + +/// Preview's state for the session (not saved, as the checkbox is per session). +#[derive(Default)] +pub(crate) struct PreviewState { + shown: Option, + /// The preview that could not be built (document, revision, set), so it isn't retried each frame. + failed: Option<(DocId, u64, usize)>, + /// The checkbox on the next open: what Apply left, off after Cancel. + remembered: bool, +} + /// This dialog owns a field set when it carries its marker. pub fn owns(fields: &Map) -> bool { fields.contains_key(MARK) @@ -27,6 +58,7 @@ pub fn open(app: &mut PhotocraftApp) -> u64 { f.insert("__command".into(), json!("image.applyDataSet")); f.insert("__label".into(), json!("Apply Data Set")); f.insert("index".into(), json!(0)); + f.insert("preview".into(), json!(app.data_set_preview.remembered)); app.ui.open_dialog(DialogKind::Command, f) } @@ -37,7 +69,7 @@ fn names(app: &PhotocraftApp) -> Vec { /// The list on the left, Apply and Cancel on the right. Returns `Some(true)` when a set is to be /// applied (Apply, Enter, a double-click on a row) and `Some(false)` for Cancel. -pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { let t = Tokens::get(ui.ctx()); let sets = names(app); let selected = f.get("index").and_then(Value::as_u64); @@ -83,17 +115,93 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, if crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked() { outcome = Some(false); } + ui.add_space(8.0); + let mut preview = f.get("preview").and_then(Value::as_bool).unwrap_or(false); + if crate::widgets::checkbox(ui, &mut preview, tl!("Preview")).on_hover_text(tl!("Preview the selected data set")).changed() { + f.insert("preview".into(), json!(preview)); + } }); }); if outcome.is_none() && interactive && ui.input(|i| i.key_pressed(egui::Key::Enter)) { outcome = Some(true); } + // Alt+P toggles Preview, its mnemonic in the reference application. + if interactive && ui.input_mut(|i| i.consume_key(egui::Modifiers::ALT, egui::Key::P)) { + let on = f.get("preview").and_then(Value::as_bool).unwrap_or(false); + f.insert("preview".into(), json!(!on)); + } + if outcome.is_none() { + let wanted = f.get("preview").and_then(Value::as_bool).unwrap_or(false).then(|| f.get("index").and_then(Value::as_u64)).flatten(); + sync(app, wanted.and_then(|i| usize::try_from(i).ok())); + } outcome } +/// Show set `wanted` in the active document, or nothing. A set that can't be applied (a missing +/// or unreadable replacement file, an index past the list) shows nothing rather than part of it. +fn sync(app: &mut PhotocraftApp, wanted: Option) { + let current = app.session.active().map(|st| (st.doc.id, st.revision)); + if let Some(p) = &app.data_set_preview.shown + && current != Some((p.doc, p.revision)) + { + app.data_set_preview.shown = None; + } + if app.data_set_preview.shown.as_ref().map(|p| p.index) == wanted { + return; + } + revert(app); + let Some(index) = wanted else { return }; + let Some(st) = app.session.active() else { return }; + let key = (st.doc.id, st.revision, index); + if app.data_set_preview.failed == Some(key) { + return; + } + let Ok(previewed) = photocraft_engine::data_set_preview(&app.session, index) else { + app.data_set_preview.failed = Some(key); + return; + }; + let Some(st) = app.session.active_mut() else { return }; + let was_clean = !st.is_dirty(); + let original = std::mem::replace(&mut st.doc, Arc::new(previewed)); + shown(st, was_clean); + app.data_set_preview.shown = Some(Preview { doc: original.id, index, original, revision: st.revision, was_clean }); +} + +/// A new revision for a document swapped in by Preview: everything is redrawn, a clean document +/// stays clean. +fn shown(st: &mut photocraft_engine::DocState, was_clean: bool) { + st.revision += 1; + if was_clean { + st.saved_revision = st.revision; + } + st.last_damage = None; +} + +/// Put the document back as it was before Preview showed a set. +fn revert(app: &mut PhotocraftApp) { + let Some(p) = app.data_set_preview.shown.take() else { return }; + if let Some(st) = app.session.active_mut() + && st.doc.id == p.doc + && st.revision == p.revision + { + st.doc = p.original; + shown(st, p.was_clean); + } +} + +/// Cancel, Escape and the close box: the preview goes, and the next open starts with it off. +pub fn cancel(app: &mut PhotocraftApp, f: &Map) { + if owns(f) { + revert(app); + app.data_set_preview.remembered = false; + } +} + /// Apply, Enter or a double-click: apply the selected set once. The variables and data sets /// themselves are never written here. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + revert(app); + app.data_set_preview.remembered = f.get("preview").and_then(Value::as_bool).unwrap_or(false); let index = f.get("index").and_then(Value::as_u64).ok_or_else(|| tl!("Select a data set to apply.").to_string())?; app.run("image.applyDataSet", json!({"index": index})) } diff --git a/crates/ui-egui/tests/it/apply_data_set_preview.rs b/crates/ui-egui/tests/it/apply_data_set_preview.rs new file mode 100644 index 0000000000..0ed4f2cba0 --- /dev/null +++ b/crates/ui-egui/tests/it/apply_data_set_preview.rs @@ -0,0 +1,334 @@ +//! #14496: the Apply Data Set dialog's Preview checkbox, as in the reference application. Off on +//! the first open, tooltip "Preview the selected data set", Alt+P toggles it. On, the selected set +//! is shown in the document (canvas and Layers panel read it) without a history state, and +//! selecting another row switches the preview; off again, the document is as before the dialog. +//! Cancel, Escape and the close box revert it; Apply with Preview on leaves the same document and +//! the one history state Apply without it does. The box keeps its state for the next open after +//! Apply, not after Cancel. A set that can't be applied (its replacement file is missing) shows +//! nothing of itself. + +use std::sync::Arc; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, TextLayer}; +use photocraft_geom::Rect; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, Outcome, handle}; +use serde_json::{Value, json}; + +struct Layers { + photo: LayerId, + badge: LayerId, + title: LayerId, +} + +/// An 8x8 blue PNG for the Pixel Replacement variable. +fn blue_png() -> String { + let dir = std::env::temp_dir().join(format!("pc-apply-data-set-preview-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("blue.png"); + let mut src = photocraft_engine::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(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +/// The test document of the spec, small: a grey pixel layer `Photo`, a red `Badge` and a text layer +/// `Title` ("Old"), with a visibility, a text and a pixel variable. Sets in document order: +/// Zed (Badge hidden, "Alpha", Photo blue), Data Set 2 (Badge shown, "Beta", no image) and +/// Data Set 3 (Badge hidden, "Gamma", an image file that doesn't exist). +fn app() -> (PhotocraftApp, Layers) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + let (photo, badge, title) = app + .session + .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(40, 0, 60, 20), &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.push(photo); + doc.layers.push(badge); + doc.layers.push(title); + Ok(ids) + }) + .unwrap(); + app.run( + "image.variables.define", + json!({"defs": [ + {"name": "badge", "layer": badge.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + {"name": "picture", "layer": photo.0, "type": "pixelReplacement", "method": "conform"}, + ]}), + ) + .unwrap(); + let missing = std::env::temp_dir().join(format!("pc-apply-data-set-preview-{}-missing", std::process::id())).join("gone.png"); + app.run( + "image.variables.dataSets", + json!({"dataSets": [ + {"name": "Zed", "values": [ + {"variable": "badge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Alpha"}, + {"variable": "picture", "kind": "pixels", "value": blue_png()}, + ]}, + {"name": "Data Set 2", "values": [ + {"variable": "badge", "kind": "visibility", "value": true}, + {"variable": "headline", "kind": "text", "value": "Beta"}, + ]}, + {"name": "Data Set 3", "values": [ + {"variable": "badge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "Gamma"}, + {"variable": "picture", "kind": "pixels", "value": missing.to_string_lossy()}, + ]}, + ]}), + ) + .unwrap(); + // As opened from disk: nothing to save yet, so a preview that marks it modified shows. + let st = app.session.active_mut().unwrap(); + st.saved_revision = st.revision; + (app, Layers { photo, badge, title }) +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + photocraft_ui_egui::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, photocraft_ui_egui::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h +} + +/// Image › Apply Data Set… as the menu runs it, then a few frames. +fn open(h: &mut Harness<'static, PhotocraftApp>) { + let ctx = h.ctx.clone(); + photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.applyDataSet", json!({})).unwrap(); + h.run_steps(3); +} + +/// The dialog open on the test document, and the document as it was before. +fn opened() -> (Harness<'static, PhotocraftApp>, Layers, Arc) { + let (app, layers) = app(); + let mut h = harness(app); + let before = doc(&h); + open(&mut h); + (h, layers, before) +} + +fn doc(h: &Harness<'static, PhotocraftApp>) -> Arc { + h.state().session.active().unwrap().doc.clone() +} + +fn preview_field(h: &Harness<'static, PhotocraftApp>) -> Value { + h.state().ui.dialogs.last().unwrap().fields["preview"].clone() +} + +fn history(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn dirty(h: &Harness<'static, PhotocraftApp>) -> bool { + h.state().session.active().unwrap().is_dirty() +} + +fn text(d: &Document, id: LayerId) -> String { + match &d.layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + _ => panic!("not a text layer"), + } +} + +/// Blue at the middle of `Photo`: the replacement image is in. +fn photo_blue(d: &Document, id: LayerId) -> bool { + let s = d.layer(id).unwrap().surface().unwrap(); + let px = photocraft_raster::to_rgba(&s.format(), &s.pixel(32, 24)); + px[2] > 0.9 && px[0] < 0.1 +} + +/// What the Layers panel and the canvas show of the three variables. +fn shown(h: &Harness<'static, PhotocraftApp>, l: &Layers) -> (bool, String, bool) { + let d = doc(h); + (d.layer(l.badge).unwrap().visible, text(&d, l.title), photo_blue(&d, l.photo)) +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, label: &str) { + h.get_by_label(label).click(); + h.run_steps(3); +} + +#[test] +fn preview_is_off_on_the_first_open_with_its_tooltip_and_alt_p_toggles_it() { + let (mut h, _l, before) = opened(); + assert_eq!(preview_field(&h), false); + h.get_by_label("Preview").hover(); + h.run_steps(30); + h.get_by_label("Preview the selected data set"); + + h.event(egui::Event::Key { key: egui::Key::P, physical_key: Some(egui::Key::P), pressed: true, repeat: false, modifiers: egui::Modifiers::ALT }); + h.run_steps(3); + assert_eq!(preview_field(&h), true, "Alt+P ticks it"); + assert_ne!(*doc(&h), *before, "and the first set is shown"); + h.event(egui::Event::Key { key: egui::Key::P, physical_key: Some(egui::Key::P), pressed: true, repeat: false, modifiers: egui::Modifiers::ALT }); + h.run_steps(3); + assert_eq!(preview_field(&h), false, "Alt+P unticks it"); + assert_eq!(*doc(&h), *before); + assert_eq!(h.state().ui.dialogs.len(), 1, "the dialog stays open"); +} + +#[test] +fn preview_shows_the_selected_set_and_follows_the_selection_without_history() { + let (mut h, l, before) = opened(); + let past = history(&h); + // Preview off: selecting a row changes nothing. + click(&mut h, "Data Set 2"); + assert_eq!(*doc(&h), *before); + + click(&mut h, "Preview"); + assert_eq!(preview_field(&h), true); + assert_eq!(shown(&h, &l), (true, "Beta".into(), false), "Data Set 2 at once"); + click(&mut h, "Zed"); + assert_eq!(shown(&h, &l), (false, "Alpha".into(), true), "the preview switches to Zed"); + assert_eq!(history(&h), past, "previewing adds no history state"); + assert!(!dirty(&h), "nor marks the document modified"); + assert!(h.state().session.active().unwrap().doc.variables.active.is_none(), "the set isn't marked applied"); + + click(&mut h, "Preview"); + assert_eq!(*doc(&h), *before, "unticked: the document as before the dialog"); + assert_eq!(history(&h), past); + assert!(!dirty(&h)); + click(&mut h, "Data Set 2"); + assert_eq!(*doc(&h), *before, "off again: selecting changes nothing"); +} + +#[test] +fn cancel_escape_and_the_close_box_revert_the_preview_without_history() { + for way in ["cancel", "escape", "close"] { + if way == "close" && cfg!(target_os = "macos") { + continue; // No close box on macOS. + } + let (mut h, l, before) = opened(); + let past = history(&h); + click(&mut h, "Preview"); + click(&mut h, "Data Set 2"); + assert_eq!(shown(&h, &l).1, "Beta", "{way}"); + match way { + "cancel" => h.get_by_label("Cancel").click(), + "escape" => h.key_press(egui::Key::Escape), + _ => h.get_by_label("Close").click(), + } + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{way}"); + assert_eq!(*doc(&h), *before, "{way}"); + assert_eq!(history(&h), past, "{way}"); + assert!(!dirty(&h), "{way}"); + } +} + +#[test] +fn apply_with_preview_gives_the_same_document_and_one_history_state() { + let (mut h, l, before) = opened(); + let past = history(&h); + click(&mut h, "Data Set 2"); + click(&mut h, "Apply"); + let plain = doc(&h); + assert_eq!(history(&h), past + 1); + + assert!(h.state_mut().session.undo()); + assert_eq!(*doc(&h), *before); + open(&mut h); + click(&mut h, "Preview"); + click(&mut h, "Data Set 2"); + assert_eq!(shown(&h, &l).1, "Beta"); + click(&mut h, "Apply"); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(*doc(&h), *plain, "the same document as Apply without Preview"); + assert_eq!(history(&h), past + 1, "one history state"); + assert!(h.state_mut().session.undo()); + assert_eq!(*doc(&h), *before, "one Undo reverts the whole apply"); +} + +#[test] +fn preview_is_kept_for_the_next_open_after_apply_not_after_cancel() { + let (mut h, l, _) = opened(); + click(&mut h, "Preview"); + click(&mut h, "Apply"); + open(&mut h); + assert_eq!(preview_field(&h), true, "on stays on after Apply"); + // The first set is selected again and shown at once (Zed: already applied, so check Data Set 2). + click(&mut h, "Data Set 2"); + assert_eq!(shown(&h, &l).1, "Beta"); + + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert_eq!(shown(&h, &l).1, "Alpha", "Cancel put back the applied Zed"); + open(&mut h); + assert_eq!(preview_field(&h), false, "off after Cancel"); + click(&mut h, "Apply"); + open(&mut h); + assert_eq!(preview_field(&h), false, "off stays off after Apply"); +} + +#[test] +fn a_set_whose_replacement_file_is_missing_shows_nothing_of_itself() { + let (mut h, l, before) = opened(); + let past = history(&h); + click(&mut h, "Preview"); + assert_eq!(shown(&h, &l), (false, "Alpha".into(), true)); + click(&mut h, "Data Set 3"); + assert_eq!(*doc(&h), *before, "no partial preview: neither Badge nor the text of Data Set 3"); + assert_eq!(history(&h), past); + h.run_steps(5); + assert_eq!(*doc(&h), *before, "and it isn't retried into something else"); + click(&mut h, "Data Set 2"); + assert_eq!(shown(&h, &l), (true, "Beta".into(), false), "another set still previews"); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert_eq!(*doc(&h), *before); +} + +fn control(h: &mut Harness<'static, PhotocraftApp>, method: &str, params: Value) -> Value { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + let reply = match handle(h.state_mut(), &ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + }; + h.run_steps(3); + reply +} + +#[test] +fn control_channel_reads_and_sets_preview() { + let (mut h, l, before) = opened(); + let inspected = control(&mut h, "ui.inspect", json!({})); + let d = inspected["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["fields"]["__command"] == "image.applyDataSet").cloned().unwrap(); + assert_eq!(d["fields"]["preview"], false); + let id = d["id"].clone(); + let set = control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "preview", "value": true})); + assert_eq!(set["ok"], true, "{set}"); + assert_eq!(shown(&h, &l), (false, "Alpha".into(), true)); + control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "index", "value": 1})); + assert_eq!(shown(&h, &l).1, "Beta"); + // Anything else in `preview` is off, never a panic. + for odd in [json!("yes"), json!(1), Value::Null] { + control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "preview", "value": odd})); + assert_eq!(*doc(&h), *before, "{odd}"); + } + control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "preview", "value": true})); + control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "index", "value": 99})); + assert_eq!(*doc(&h), *before, "an index past the list shows nothing"); + let cancelled = control(&mut h, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + assert_eq!(*doc(&h), *before); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8dcbd48d78..466d2e8cab 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -5,6 +5,7 @@ mod actions_panel_menu; mod actions_record_again; mod adjust_preview_gpu; mod apply_data_set_dialog; +mod apply_data_set_preview; mod arbitrary_rotation_preview; mod background_eraser_reset_tip; mod batch_export_options; From bdfcd183a413581a7af7575657b63df84235abe0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 14:12:43 +0100 Subject: [PATCH 079/385] Apply Data Set: visible selection in every theme, checked set index Themes without a row colour mark the selected row with their soft accent. The index is checked against the document's sets before it goes to the engine, so a value past usize on wasm32 cannot wrap to a valid row. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/apply_data_set_ui.rs | 18 ++++++++++++++++-- .../ui-egui/tests/it/apply_data_set_dialog.rs | 14 +++++++++++++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/apply_data_set_ui.rs b/crates/ui-egui/src/panels/apply_data_set_ui.rs index b37a3cb3cd..de3a1dc857 100644 --- a/crates/ui-egui/src/panels/apply_data_set_ui.rs +++ b/crates/ui-egui/src/panels/apply_data_set_ui.rs @@ -35,6 +35,12 @@ fn names(app: &PhotocraftApp) -> Vec { app.session.active().map(|st| st.doc.variables.data_sets.iter().map(|s| s.name.clone()).collect()).unwrap_or_default() } +/// The selected row's fill. Themes without a row colour (transparent `row_selected`) use their +/// soft accent, so the set Apply will use is always marked. +pub fn selected_fill(t: &Tokens) -> egui::Color32 { + if t.row_selected.a() == 0 { t.accent_soft } else { t.row_selected } +} + /// The list on the left, Apply and Cancel on the right. Returns `Some(true)` when a set is to be /// applied (Apply, Enter, a double-click on a row) and `Some(false)` for Cancel. pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { @@ -56,7 +62,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, let (rect, r) = ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW), egui::Sense::click()); r.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, on, name)); if on { - ui.painter().rect_filled(rect, 0.0, t.row_selected); + ui.painter().rect_filled(rect, 0.0, selected_fill(&t)); } else if r.hovered() { ui.painter().rect_filled(rect, 0.0, t.hover); } @@ -94,6 +100,14 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, /// Apply, Enter or a double-click: apply the selected set once. The variables and data sets /// themselves are never written here. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { - let index = f.get("index").and_then(Value::as_u64).ok_or_else(|| tl!("Select a data set to apply.").to_string())?; + // Checked against the document's sets here: an index past `usize` (wasm32) must not wrap + // around to a valid row on its way to the engine. + let count = names(app).len(); + let index = f + .get("index") + .and_then(Value::as_u64) + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < count) + .ok_or_else(|| tl!("Select a data set to apply.").to_string())?; app.run("image.applyDataSet", json!({"index": index})) } diff --git a/crates/ui-egui/tests/it/apply_data_set_dialog.rs b/crates/ui-egui/tests/it/apply_data_set_dialog.rs index e6a77fcd1b..16c78bc646 100644 --- a/crates/ui-egui/tests/it/apply_data_set_dialog.rs +++ b/crates/ui-egui/tests/it/apply_data_set_dialog.rs @@ -296,13 +296,14 @@ fn control_channel_lists_sets_and_applies_the_selected_one() { /// different set. #[test] fn bad_index_from_the_control_channel_is_an_error() { - for bad in [json!(99), json!(-1), json!("Zed"), json!(1.5), Value::Null, json!(u64::MAX)] { + for bad in [json!(99), json!(3), json!(-1), json!("Zed"), json!(1.5), Value::Null, json!(u64::MAX), json!(4_294_967_296_u64)] { let mut h = opened(); let id = h.state().ui.dialogs.last().unwrap().id; control(&mut h, "ui.dialog.set", json!({"dialog": id, "field": "index", "value": bad})); h.run_steps(2); let confirmed = control(&mut h, "ui.dialog.confirm", json!({"dialog": id})); assert_ne!(confirmed["ok"], true, "{bad}: {confirmed}"); + assert_eq!(variables(&h).active, None, "{bad}: no set was applied"); assert!(visible(&h), "{bad}"); assert_eq!(history(&h), 0, "{bad}"); } @@ -323,3 +324,14 @@ fn no_data_sets_shows_an_empty_list_and_apply_reports_it() { assert!(h.state().ui.dialogs.is_empty()); assert!(!h.state().ui.status.is_empty(), "the failure is reported"); } + +/// Every theme marks the selected row, also those without a row colour of their own. +#[test] +fn the_selected_row_is_visible_in_every_theme() { + for kind in photocraft_ui_egui::theme::ThemeKind::ALL { + let t = photocraft_ui_egui::theme::Tokens::for_kind(kind); + let fill = photocraft_ui_egui::panels::apply_data_set_ui::selected_fill(&t); + assert!(fill.a() > 0, "{kind:?}: the selected row has a fill"); + assert_ne!(fill, t.field, "{kind:?}: it differs from the list background"); + } +} From e6634fdbf62b15fc2b9153ee2aaaa3c0cdbd072e Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 14:38:14 +0100 Subject: [PATCH 080/385] fix(engine): arbitrary canvas rotation keeps and turns its guides --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/analysis_cmds.rs | 2 +- crates/engine/src/cmd/image_cmds.rs | 2 +- crates/engine/src/cmd/mode_cmds.rs | 36 +++- .../src/cmd/rotate_canvas_guides_tests.rs | 176 ++++++++++++++++++ 5 files changed, 212 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/rotate_canvas_guides_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 36a1081edd..cf9c5c23f5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -148,6 +148,8 @@ pub mod rasterize_style_cmds; pub mod redeye_cmds; pub mod render_cmds; pub mod retouch_cmds; +#[cfg(test)] +mod rotate_canvas_guides_tests; pub mod sample_cmds; #[cfg(test)] mod sample_zoom_box_tests; diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 451cdeaf67..5354c933e4 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -802,7 +802,7 @@ fn straighten(s: &mut Session, p: &Value) -> Result { if let Some(gate) = s.authorize { gate("image.rotation.arbitrary", &rotation)?; } - crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false)?; + crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false, false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 318b5dbad2..181eeab2bd 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1055,7 +1055,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar Ok(()) })?; } - crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false)?; + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false, false)?; // Color Sampler points follow the crop's origin shift too (the rotation moved them above). s.set_sampler_map(crop_target.sampler_map(target)); let extension = s.tools.background; diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index e5ad74c640..f0d18c24ee 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -63,12 +63,15 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { } pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { - rotate_arbitrary_with(s, p, true) + rotate_arbitrary_with(s, p, true, true) } /// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, -/// #11762). The Crop tool's straighten turn moves them with the image, as before. -pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool) -> Result { +/// unlike the turned Crop and Straighten, keeps the Color Sampler points — #11762). The Crop +/// tool's straighten turn moves them with the image, as before. `keep_guides` turns the guides +/// with the canvas (#14508, measured for Image Rotation > Arbitrary) instead of dropping them, +/// as the turned Crop and the Straighten still do (not measured there). +pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool, keep_guides: bool) -> Result { const CMD: &str = "image.rotation.arbitrary"; // At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers. let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0); @@ -138,6 +141,7 @@ pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: boo // What Free Transform leaves alone: unlinked vector masks, gradient angles, artboards… crate::canvas_geom::transform_layer_geometry(l, &a, false, dpi); } + let guides_before = doc.guides.clone(); if keep_counts { crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::transform_doc_marks(doc, &a)); } else { @@ -152,7 +156,31 @@ pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: boo // Type, shapes and smart objects re-render from their new geometry; type in a missing // font keeps its turned pixels. crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All); - doc.guides = Default::default(); + // #14508: the turn keeps its guides. A right angle goes through transform_doc_marks + // above, which swaps orientation and position exactly as the reference measures + // (90° clockwise: a vertical guide at x=100 becomes a horizontal one at y=100). Any + // other angle follows the measured rule: each guide's edge point (the vertical guide's + // point on the top edge, the horizontal one's on the left) turns about the old centre + // while the UNROUNDED turned bounding box sits flush at the new canvas's origin - on a + // 400x300 canvas turned 30° that lands x=100 at 236.60 and y=50 at 43.30, both within + // 0.15 px of the reference's 236.49 and 43.19 (the exact rule is not settled, so no + // further refinement is guessed). The content itself is centred in the ROUNDED canvas, + // so on a non-right angle the guides hug the unrounded geometry, up to a pixel off the + // painted edge - as measured. Guide COLOURS for a turned canvas were not measured and + // stay cleared as today; guides that end up off the new canvas follow the same rule + // continued, they are kept. The turned Crop and Straighten pass keep_guides=false: not + // measured there, so they drop guides exactly as they do today. + if !keep_guides { + doc.guides = Default::default(); + } else if sn.abs() > 1e-9 && cs.abs() > 1e-9 { + let (ow, oh) = (f64::from(old.width), f64::from(old.height)); + let gw = ow * cs.abs() + oh * sn.abs(); + let gh = ow * sn.abs() + oh * cs.abs(); + let txf = gw / 2.0 - (cs * cx - sn * cy); + let tyf = gh / 2.0 - (sn * cx + cs * cy); + doc.guides.vertical = guides_before.vertical.iter().map(|x| cs * *x + txf).collect(); + doc.guides.horizontal = guides_before.horizontal.iter().map(|y| cs * *y + tyf).collect(); + } Ok(new) })?; Ok(json!({"width": size.width, "height": size.height})) diff --git a/crates/engine/src/cmd/rotate_canvas_guides_tests.rs b/crates/engine/src/cmd/rotate_canvas_guides_tests.rs new file mode 100644 index 0000000000..a07120ddd1 --- /dev/null +++ b/crates/engine/src/cmd/rotate_canvas_guides_tests.rs @@ -0,0 +1,176 @@ +//! #14508: Image › Image Rotation › Arbitrary keeps the document's guides and turns them with the +//! image instead of dropping them. The reference application measures a 400×300 canvas turned 30° +//! clockwise: the vertical guide at x=100 lands at 236.49 and the horizontal guide at y=50 at +//! 43.19, each within 0.15 px. A quarter turn swaps the guides' orientation, agreeing with Image +//! Rotation › 90° Clockwise (#14469). The Crop tool's straighten turn shares the rotation and keeps +//! dropping guides: not measured, so today's behaviour. + +use serde_json::json; + +use crate::Session; + +/// The tolerance the measured guide positions came with. +const TOL: f64 = 0.15; + +/// A 400×300 document with a vertical guide at x=100 and a horizontal guide at y=50. +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.edit("guides", |d, _| { + d.guides.vertical = vec![100.0]; + d.guides.horizontal = vec![50.0]; + Ok(()) + }) + .unwrap(); + s +} + +/// The document's guides, as (vertical positions, horizontal positions). +fn guides(s: &Session) -> (Vec, Vec) { + let g = &s.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) +} + +/// A guide at `want` within the measuring tolerance. +fn near(got: f64, want: f64, what: &str) { + assert!((got - want).abs() <= TOL, "{what}: got {got}, want {want} ± {TOL}"); +} + +/// The same guide position (an exact map, up to float noise). +fn same(got: f64, want: f64, what: &str) { + assert!((got - want).abs() < 1e-6, "{what}: got {got}, want {want}"); +} + +#[test] +fn arbitrary_turn_keeps_both_measured_guide_positions() { + let mut s = doc(); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "cw"})).unwrap(); + let (v, h) = guides(&s); + assert_eq!((v.len(), h.len()), (1, 1), "a 30° turn keeps both guides, each in its own direction"); + near(v[0], 236.49, "the vertical guide at x=100 after 30° clockwise"); + near(h[0], 43.19, "the horizontal guide at y=50 after 30° clockwise"); +} + +#[test] +fn arbitrary_turn_puts_a_guide_at_its_turned_canvas_edge_point() { + // The guide follows the point it crossed the canvas edge, so the guide along the old left edge + // ends up at the turned image's top corner: (0, 0) → (150, 0) for a 30° clockwise turn. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.edit("guides", |d, _| { + d.guides.vertical = vec![0.0]; + d.guides.horizontal = vec![0.0]; + Ok(()) + }) + .unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "cw"})).unwrap(); + let (v, h) = guides(&s); + same(v[0], 150.0, "the guide along the left edge"); + same(h[0], 0.0, "the guide along the top edge"); +} + +#[test] +fn quarter_turn_swaps_the_guides_like_the_right_angle_command_does() { + let mut s = doc(); + s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); + let (v, h) = guides(&s); + assert_eq!((v.len(), h.len()), (1, 1), "a quarter turn swaps their orientation"); + // x=100 vertical becomes y=100 horizontal, and y=50 horizontal becomes x = 300 − 50 vertical. + near(h[0], 100.0, "the vertical guide at x=100 after 90° clockwise"); + near(v[0], 250.0, "the horizontal guide at y=50 after 90° clockwise"); + // Image Rotation › 90° Clockwise on the same document lands on the same guides (#14469). + let mut s2 = doc(); + s2.execute("image.imageRotation.90cw", json!({})).unwrap(); + let (v2, h2) = guides(&s2); + assert_eq!((v2.len(), h2.len()), (v.len(), h.len()), "90° clockwise"); + for (a, b) in v.iter().zip(&v2) { + same(*a, *b, "arbitrary 90° vs imageRotation.90cw, vertical"); + } + for (a, b) in h.iter().zip(&h2) { + same(*a, *b, "arbitrary 90° vs imageRotation.90cw, horizontal"); + } +} + +#[test] +fn right_angle_turns_keep_the_number_of_guides() { + for angle in [90.0, 180.0, 270.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.edit("guides", |d, _| { + d.guides.vertical = vec![100.0, 250.0]; + d.guides.horizontal = vec![50.0]; + Ok(()) + }) + .unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": "cw"})).unwrap(); + let (v, h) = guides(&s); + // A half turn keeps both guides in their own direction; a quarter turn swaps them. + let want = if angle == 180.0 { (2, 1) } else { (1, 2) }; + assert_eq!((v.len(), h.len()), want, "{angle}° clockwise keeps every guide"); + } +} + +#[test] +fn undo_restores_the_guides_before_the_turn() { + let mut s = doc(); + let before = guides(&s); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "cw"})).unwrap(); + assert_ne!(guides(&s), before, "the turn moved them"); + s.undo(); + assert_eq!(guides(&s), before, "undo puts the guides back exactly"); +} + +#[test] +fn a_guide_outside_the_canvas_is_turned_rather_than_dropped() { + // Nothing is clamped to the canvas: every point of the image's own edges lands inside the + // turned canvas, and a guide that was already outside it (a mark left outside by Canvas Size, + // cf. #11762) turns with the image and stays outside instead of going away. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.edit("guides", |d, _| { + d.guides.vertical = vec![500.0]; + d.guides.horizontal = vec![-20.0]; + Ok(()) + }) + .unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "cw"})).unwrap(); + let (v, h) = guides(&s); + assert_eq!((v.len(), h.len()), (1, 1), "no guide is dropped for sitting outside the canvas"); + let size = s.active().unwrap().doc.size; + assert!(v[0] > f64::from(size.width), "the vertical guide should stay outside the {} px width: {v:?}", size.width); + assert!(h[0] < 0.0, "the horizontal guide should stay outside the {} px height: {h:?}", size.height); +} + +#[test] +fn the_turn_drops_guide_colours_as_it_does_today() { + // Guide colours for a turn are not measured, so they keep today's behaviour: the guide's + // position stays, its own colour goes with the cleared colours. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 100, "color": "#ff00ff"})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "cw"})).unwrap(); + let d = s.active().unwrap().doc.clone(); + assert_eq!(d.guides.vertical.len(), 1, "the guide itself stays"); + assert!(d.guides.colors.is_empty(), "its colour goes, as it does today"); +} + +#[test] +fn crop_with_an_angle_still_drops_the_guides() { + // The Crop tool's straighten turn runs the same rotation with `keep_counts` off; its guides are + // not measured, so they keep going away. + let mut s = doc(); + s.execute("image.crop", json!({"x": 50, "y": 40, "width": 300, "height": 200, "angle": 30})).unwrap(); + let (v, h) = guides(&s); + assert!(v.is_empty() && h.is_empty(), "the turned crop still drops the guides: vertical {v:?}, horizontal {h:?}"); +} + +#[test] +fn ruler_straighten_still_drops_the_guides() { + // Straighten Layer is off for the Background (#12033), so a layer is added first. + let mut s = doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + let (v, h) = guides(&s); + assert!(v.is_empty() && h.is_empty(), "straighten still drops the guides: vertical {v:?}, horizontal {h:?}"); +} From 720e5b20ad60034942e7003d541a5f3432cfb0fa Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 14:41:25 +0100 Subject: [PATCH 081/385] Apply Data Set Preview: commands and autosave never see the preview Every command run first gives the document back (the dialog shows the set again on the next frame), so a Save or any edit works on the real document. Autosave skips a document while it is previewed. A preview is restored by document id when another document became active. Each test fixture writes its own replacement image. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/session/documents.rs | 5 + crates/ui-egui/src/app/commands.rs | 3 + .../ui-egui/src/panels/apply_data_set_ui.rs | 27 ++++-- crates/ui-egui/src/prefs/prefs_ui/save.rs | 2 + .../tests/it/apply_data_set_preview.rs | 92 ++++++++++++++++++- 5 files changed, 116 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index fc3b1708aa..35b61f43a8 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -36,6 +36,11 @@ impl Session { self.active.and_then(|i| self.docs.get_mut(i)) } + /// The open document with this id, active or not. + pub fn document_mut(&mut self, id: photocraft_doc::DocId) -> Option<&mut DocState> { + self.docs.iter_mut().find(|d| d.doc.id == id) + } + /// Monotonic active-document generation. It changes when a different document becomes /// active, including a switch away and back between two observations; equal values therefore /// mean the document was not switched in between. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1aa81115d4..dad4a0ce62 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -50,6 +50,9 @@ impl PhotocraftApp { } fn run_command_at_depth(&mut self, id: &str, params: Value) -> Result { + // Commands never see Apply Data Set's Preview: it is not the document (a Save would write + // it). The dialog shows it again on the next frame. + crate::panels::apply_data_set_ui::end_preview(self); if !vector_ui::cancel_stale(self) { return Err(self.ui.status.clone()); } diff --git a/crates/ui-egui/src/panels/apply_data_set_ui.rs b/crates/ui-egui/src/panels/apply_data_set_ui.rs index d166daae73..f32d821452 100644 --- a/crates/ui-egui/src/panels/apply_data_set_ui.rs +++ b/crates/ui-egui/src/panels/apply_data_set_ui.rs @@ -146,15 +146,11 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - let current = app.session.active().map(|st| (st.doc.id, st.revision)); - if let Some(p) = &app.data_set_preview.shown - && current != Some((p.doc, p.revision)) - { - app.data_set_preview.shown = None; - } - if app.data_set_preview.shown.as_ref().map(|p| p.index) == wanted { + let active = app.session.active().map(|st| st.doc.id); + if app.data_set_preview.shown.as_ref().is_some_and(|p| Some(p.doc) == active && Some(p.index) == wanted) { return; } + // Also when another document became active: the previewed one gets its own document back. revert(app); let Some(index) = wanted else { return }; let Some(st) = app.session.active() else { return }; @@ -183,11 +179,11 @@ fn shown(st: &mut photocraft_engine::DocState, was_clean: bool) { st.last_damage = None; } -/// Put the document back as it was before Preview showed a set. +/// Put the document back as it was before Preview showed a set, whether it is active or not. A +/// document changed since keeps that change (and with it the preview). fn revert(app: &mut PhotocraftApp) { let Some(p) = app.data_set_preview.shown.take() else { return }; - if let Some(st) = app.session.active_mut() - && st.doc.id == p.doc + if let Some(st) = app.session.document_mut(p.doc) && st.revision == p.revision { st.doc = p.original; @@ -195,6 +191,17 @@ fn revert(app: &mut PhotocraftApp) { } } +/// Before any command runs: the document goes back to itself, so the command neither works on +/// nor saves the preview. The dialog, still open with Preview on, shows the set again. +pub(crate) fn end_preview(app: &mut PhotocraftApp) { + revert(app); +} + +/// Whether Preview is showing a set in document `doc` (autosave waits for it to end). +pub(crate) fn previewing(app: &PhotocraftApp, doc: DocId) -> bool { + app.data_set_preview.shown.as_ref().is_some_and(|p| p.doc == doc) +} + /// Cancel, Escape and the close box: the preview goes, and the next open starts with it off. pub fn cancel(app: &mut PhotocraftApp, f: &Map) { if owns(f) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/save.rs b/crates/ui-egui/src/prefs/prefs_ui/save.rs index d960159160..3d04c484e6 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/save.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/save.rs @@ -289,6 +289,8 @@ fn autosave(app: &mut PhotocraftApp) { .documents() .iter() .filter(|d| d.is_dirty() && app.prefs_rt.autosaved.get(&d.doc.id) != Some(&d.revision) && !app.prefs_rt.autosave_pending.contains_key(&d.doc.id)) + // Apply Data Set's Preview is not the document: it waits until the preview ends. + .filter(|d| !crate::panels::apply_data_set_ui::previewing(app, d.doc.id)) .map(|d| (d.doc.clone(), d.revision, d.path.clone())) .collect(); for (doc, rev, path) in jobs { diff --git a/crates/ui-egui/tests/it/apply_data_set_preview.rs b/crates/ui-egui/tests/it/apply_data_set_preview.rs index 0ed4f2cba0..2e77633646 100644 --- a/crates/ui-egui/tests/it/apply_data_set_preview.rs +++ b/crates/ui-egui/tests/it/apply_data_set_preview.rs @@ -23,9 +23,12 @@ struct Layers { title: LayerId, } -/// An 8x8 blue PNG for the Pixel Replacement variable. +/// An 8x8 blue PNG for the Pixel Replacement variable, in a folder of its own for each fixture: +/// tests run in parallel, and rewriting a shared file could hand another test a half-written one. fn blue_png() -> String { - let dir = std::env::temp_dir().join(format!("pc-apply-data-set-preview-{}", std::process::id())); + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("pc-apply-data-set-preview-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("blue.png"); let mut src = photocraft_engine::Session::new(); @@ -40,7 +43,11 @@ fn blue_png() -> String { /// Zed (Badge hidden, "Alpha", Photo blue), Data Set 2 (Badge shown, "Beta", no image) and /// Data Set 3 (Badge hidden, "Gamma", an image file that doesn't exist). fn app() -> (PhotocraftApp, Layers) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + app_with(photocraft_ui_egui::Services::default()) +} + +fn app_with(services: photocraft_ui_egui::Services) -> (PhotocraftApp, Layers) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); app.run("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); let (photo, badge, title) = app .session @@ -332,3 +339,82 @@ fn control_channel_reads_and_sets_preview() { assert_eq!(cancelled["ok"], true, "{cancelled}"); assert_eq!(*doc(&h), *before); } + +/// A command run while the dialog is open (a script or an action step calls `run` directly) works on +/// the document itself, +/// never on the preview: its history state starts from the real document, and Cancel leaves the +/// command's change without any of the set. +#[test] +fn a_command_run_while_previewing_works_on_the_document_itself() { + let (mut h, l, before) = opened(); + let past = history(&h); + click(&mut h, "Preview"); + assert_eq!(shown(&h, &l).1, "Alpha"); + h.state_mut().run("layer.new.layer", json!({"name": "Extra"})).unwrap(); + h.run_steps(3); + assert_eq!(history(&h), past + 1); + assert_eq!(shown(&h, &l), (false, "Alpha".into(), true), "the dialog shows the set again"); + h.get_by_label("Cancel").click(); + h.run_steps(3); + let d = doc(&h); + assert!(d.walk().iter().any(|(_, _, layer)| layer.name == "Extra"), "the command's layer stays"); + assert_eq!((d.layer(l.badge).unwrap().visible, text(&d, l.title), photo_blue(&d, l.photo)), (true, "Old".into(), false), "nothing of Zed"); + assert!(h.state_mut().session.undo()); + assert_eq!(*doc(&h), *before, "the command's state undoes to the document before the dialog"); +} + +/// Another document made active while a set is previewed (not through a command): the previewed +/// document gets its own content back, without being made active. +#[test] +fn another_active_document_gives_the_previewed_one_its_document_back() { + let (mut a, l) = app(); + a.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + assert!(a.session.set_active(0)); + let mut h = harness(a); + let before = doc(&h); + open(&mut h); + click(&mut h, "Preview"); + assert_eq!(shown(&h, &l).1, "Alpha"); + assert!(h.state_mut().session.set_active(1)); + h.run_steps(3); + assert_eq!(h.state().session.active_index(), Some(1), "the other document stays active"); + let first = h.state().session.documents()[0].doc.clone(); + assert_eq!(*first, *before, "the previewed document is itself again"); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert_eq!(*h.state().session.documents()[0].doc, *before); +} + +/// Autosave never writes the preview: it waits while a set is shown and saves the real document +/// once the preview ends. +#[test] +fn autosave_waits_while_previewing() { + type Saved = std::sync::Arc>>>; + let saved: Saved = Default::default(); + let log = saved.clone(); + let services = photocraft_ui_egui::Services { + autosave: Some(Box::new(move |d: &Arc, _rev: u64, _path: Option<&str>| { + log.lock().unwrap().push(d.clone()); + Ok(()) + })), + ..Default::default() + }; + let (mut a, l) = app_with(services); + // Unsaved work, so autosave has something to write. + a.run("layer.new.layer", json!({"name": "Work"})).unwrap(); + let mut h = harness(a); + let before = doc(&h); + open(&mut h); + click(&mut h, "Preview"); + assert_eq!(shown(&h, &l).1, "Alpha"); + let ctx = h.ctx.clone(); + photocraft_ui_egui::prefs_ui::autosave_now(h.state_mut()); + photocraft_ui_egui::prefs_ui::tick(h.state_mut(), &ctx); + assert!(saved.lock().unwrap().is_empty(), "nothing saved while the preview shows"); + click(&mut h, "Preview"); + photocraft_ui_egui::prefs_ui::autosave_now(h.state_mut()); + photocraft_ui_egui::prefs_ui::tick(h.state_mut(), &ctx); + let saved = saved.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(*saved[0], *before, "the document itself"); +} From 321c308f90be1766f8500c151119ebdec1aaf548 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 14:47:26 +0100 Subject: [PATCH 082/385] 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 f36652453f3b058abe5d7862b306d0e815e24a20 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 14:59:55 +0100 Subject: [PATCH 083/385] fix(engine): Image Rotation Arbitrary refuses Bitmap documents --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/mode_cmds.rs | 20 +- .../src/cmd/rotate_canvas_bitmap_tests.rs | 203 ++++++++++++++++++ 3 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/rotate_canvas_bitmap_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 36a1081edd..2b3118e2b6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -148,6 +148,8 @@ pub mod rasterize_style_cmds; pub mod redeye_cmds; pub mod render_cmds; pub mod retouch_cmds; +#[cfg(test)] +mod rotate_canvas_bitmap_tests; pub mod sample_cmds; #[cfg(test)] mod sample_zoom_box_tests; diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index e5ad74c640..5d057666b0 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -42,15 +42,25 @@ fn str_or<'a>(p: &'a Value, key: &str, default: &'a str) -> &'a str { type Enabled = std::result::Result<(), String>; -fn has_doc(s: &Session) -> Enabled { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - fn mode_is(s: &Session, modes: &[ColorMode], what: &str) -> Enabled { let d = s.active().ok_or("no document open")?; if modes.contains(&d.doc.mode) { Ok(()) } else { Err(format!("{what} (the document is {:?})", d.doc.mode)) } } +/// #14509, measured: in a Bitmap document only Arbitrary is greyed in the Image Rotation +/// submenu - 180, the two 90 turns and both flips stay available - and a scripted call answers +/// this sentence with the document unchanged. The Crop tool's straighten shares +/// [`rotate_arbitrary_with`] but was not measured in Bitmap, so only this spec's gate names it. +const BITMAP_ROTATE_REFUSAL: &str = "Could not complete the command because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn rotate_arbitrary_enabled(s: &Session) -> Enabled { + let d = s.active().ok_or("no document open")?; + if d.doc.mode == ColorMode::Bitmap { + return Err(BITMAP_ROTATE_REFUSAL.into()); + } + Ok(()) +} + // ---------- Image Rotation › Arbitrary ---------- /// Canvas size after rotating `size` by `deg` (the canvas grows to fit, as in Photoshop). @@ -772,7 +782,7 @@ pub fn specs() -> Vec { "Arbitrary…", ["Image", "Image Rotation"], r##"{"angle":-359.99..359.99=0,"direction":"cw|ccw"="cw","interpolation":"bicubic|bilinear|nearest"="bicubic"}"##, - has_doc, + rotate_arbitrary_enabled, rotate_arbitrary ), spec!( diff --git a/crates/engine/src/cmd/rotate_canvas_bitmap_tests.rs b/crates/engine/src/cmd/rotate_canvas_bitmap_tests.rs new file mode 100644 index 0000000000..16ce8fb5c5 --- /dev/null +++ b/crates/engine/src/cmd/rotate_canvas_bitmap_tests.rs @@ -0,0 +1,203 @@ +//! #14509: Image › Image Rotation › Arbitrary in a Bitmap document. +//! +//! Measured in the reference application: in a Bitmap document only Arbitrary… is greyed in the +//! Image Rotation submenu, and running the turn from a script answers "Could not complete the +//! command because it does not work with Bitmap images (convert image to Grayscale mode to edit)." +//! with the document unchanged. The five other Image Rotation items — 180°, 90° Clockwise, 90° +//! Counter Clockwise and the two Flip Canvas items — stay available there, and every other colour +//! mode keeps what it has today. +//! +//! The Crop tool's straighten turn shares `rotate_arbitrary_with` with this command and is *not +//! measured* in Bitmap mode, so it keeps today's behaviour; the last test pins that the new check +//! does not reach it. + +use std::sync::Arc; + +use super::mode_cmds::rotated_size; +use super::*; + +const ARBITRARY: &str = "image.rotation.arbitrary"; + +/// The reference's words, measured (#14509), spelled out here rather than read from the command so +/// the test fails if what the app answers with ever drifts from what was measured. The engine wraps +/// a greyed command's reason in `EngineError::Disabled`, so a scripted call reads this sentence +/// after the usual `command "…" is not available right now: ` prefix. +const REFUSAL: &str = "Could not complete the command because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The five Image Rotation items the reference leaves available in a Bitmap document (#14509), each +/// with where the black 8 x 8 block at the top-left corner of a 32 x 24 canvas lands after it, and +/// the canvas it leaves (the two 90° turns swap the sides). +type TurnCase = (&'static str, (i32, i32), (u32, u32)); + +const TURNS: [TurnCase; 5] = [ + ("image.imageRotation.180", (29, 21), (32, 24)), + ("image.imageRotation.90cw", (21, 2), (24, 32)), + ("image.imageRotation.90ccw", (2, 29), (24, 32)), + ("image.imageRotation.flipCanvasHorizontal", (29, 2), (32, 24)), + ("image.imageRotation.flipCanvasVertical", (2, 21), (32, 24)), +]; + +/// A `w x h` document in `mode` at 8 bits, with a white Background. +fn doc_in(mode: &str, w: u32, h: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "mode": mode, "background": "white"})).unwrap(); + s +} + +/// A Bitmap document as Image › Mode › Bitmap leaves one: flattened and 1-bit (stored expanded as +/// Gray 8-bit) and, once [`mark`] has run, a white field with a black block at the top-left. +fn bitmap(w: u32, h: u32) -> Session { + let mut s = doc_in("grayscale", w, h); + s.execute("image.mode.bitmap", json!({"method": "threshold"})).unwrap(); + assert_eq!(doc_of(&s).mode, ColorMode::Bitmap, "the conversion made it a Bitmap document"); + mark(&mut s); + s +} + +/// The black 8 x 8 block at the canvas's top-left corner that makes a turn or a flip visible. +fn mark(s: &mut Session) { + s.edit("setup", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + // The layer's own channel count, so the same block works in Bitmap, Grayscale and RGB. + let black = vec![0.0; surf.channels()]; + surf.fill_rect(Rect::new(0, 0, 8, 8), &black); + Ok(()) + }) + .unwrap(); +} + +fn doc_of(s: &Session) -> Arc { + s.active().unwrap().doc.clone() +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn size_of(s: &Session) -> (u32, u32) { + let d = doc_of(s); + (d.size.width, d.size.height) +} + +/// The Background's level at `(x, y)`: 0.0 black, 1.0 white. +fn level(s: &Session, x: i32, y: i32) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().sample_channel(x, y, 0) +} + +/// Everything a refused turn must leave exactly as it was: the document itself, the canvas, the +/// History depth and the two corners of the mark. +type Snapshot = (Arc, (u32, u32), usize, [f32; 2]); + +fn snapshot(s: &Session) -> Snapshot { + (doc_of(s), size_of(s), steps(s), [level(s, 2, 2), level(s, 30, 23)]) +} + +#[test] +fn arbitrary_is_greyed_out_in_a_bitmap_document() { + let s = bitmap(32, 24); + assert!(!s.is_enabled(ARBITRARY), "Image › Image Rotation › Arbitrary is greyed out in a Bitmap document"); + assert_eq!(s.disabled_reason(ARBITRARY).as_deref(), Some(REFUSAL), "with the reason the reference gives"); + // Every param shape is off, including a null angle that would have changed nothing anyway. + for p in [json!({}), json!({"angle": 30}), json!({"angle": 90, "direction": "ccw"})] { + assert!(!s.is_enabled_with(ARBITRARY, &p), "{p}: still greyed"); + } + // With no document at all it stays off for the reason it already had. + assert_eq!(Session::new().disabled_reason(ARBITRARY).as_deref(), Some("no document open"), "no document open, as before"); +} + +#[test] +fn a_scripted_arbitrary_turn_in_a_bitmap_document_answers_the_reference_error_and_changes_nothing() { + let mut s = bitmap(32, 24); + let history = steps(&s); + for p in [json!({"angle": 30}), json!({"angle": 90, "direction": "ccw"}), json!({"angle": 45, "interpolation": "nearest"}), json!({})] { + let (doc, size, step_count, marks) = snapshot(&s); + let e = s.execute(ARBITRARY, p.clone()).unwrap_err(); + assert!(matches!(&e, EngineError::Disabled(id, why) if id == ARBITRARY && why == REFUSAL), "{p}: refused as a greyed command, got {e}"); + assert_eq!( + e.to_string(), + format!("command `{ARBITRARY}` is not available right now: {REFUSAL}"), + "{p}: the measured sentence is what the caller reads" + ); + // Nothing at all happened: not a History step, not a pixel, not a corner of the canvas. + let (after, size_after, steps_after, marks_after) = snapshot(&s); + assert!(Arc::ptr_eq(&doc, &after), "{p}: the document is untouched"); + assert_eq!(size_after, size, "{p}: the canvas keeps its size"); + assert_eq!(size_after, (32, 24), "{p}: still the 32 x 24 canvas it was"); + assert_eq!(steps_after, step_count, "{p}: no History step"); + assert_eq!(marks_after, marks, "{p}: the mark stays put"); + assert_eq!([level(&s, 2, 2), level(&s, 30, 23)], [0.0, 1.0], "{p}: black at the top-left, white at the bottom-right"); + } + // The refusal took nothing away either: the document is still Bitmap and its History still holds + // the steps made before the call. + assert_eq!(doc_of(&s).mode, ColorMode::Bitmap, "still a Bitmap document"); + assert_eq!(steps(&s), history, "the whole run added no History step"); + assert!(s.undo(), "the steps made before the refusal are still there to undo"); +} + +#[test] +fn the_other_image_rotation_items_stay_available_in_a_bitmap_document() { + for (id, (bx, by), size) in TURNS { + let mut s = bitmap(32, 24); + assert!(s.is_enabled(id), "{id} stays available in a Bitmap document"); + let history = steps(&s); + s.execute(id, json!({})).unwrap_or_else(|e| panic!("{id} turns in a Bitmap document, got {e}")); + assert_eq!(size_of(&s), size, "{id}: the canvas it leaves"); + assert_eq!([level(&s, bx, by), level(&s, 2, 2)], [0.0, 1.0], "{id}: the mark turned to ({bx}, {by})"); + assert_eq!(steps(&s), history + 1, "{id}: one History step"); + assert!(s.undo(), "{id}: and it undoes"); + assert_eq!([level(&s, 2, 2), level(&s, 30, 23)], [0.0, 1.0], "{id}: back to the mark at the top-left"); + } +} + +#[test] +fn arbitrary_stays_available_and_turns_in_rgb_and_grayscale() { + for (mode, want) in [("grayscale", ColorMode::Grayscale), ("rgb", ColorMode::Rgb)] { + let mut s = doc_in(mode, 32, 24); + mark(&mut s); + assert!(s.is_enabled(ARBITRARY), "{mode}: still available"); + let r = s.execute(ARBITRARY, json!({"angle": 30})).unwrap_or_else(|e| panic!("{mode}: turns as today, got {e}")); + let d = doc_of(&s); + assert_eq!(d.size, rotated_size(Size::new(32, 24), 30.0), "{mode}: the canvas grows to fit, as today"); + assert_eq!( + (r["width"].as_u64(), r["height"].as_u64()), + (Some(u64::from(d.size.width)), Some(u64::from(d.size.height))), + "{mode}: the result reports the new canvas" + ); + assert!(d.size.width > 32 && d.size.height > 24, "{mode}: the turned canvas"); + assert_eq!(d.mode, want, "{mode}: and the mode is untouched"); + } +} + +#[test] +fn only_a_bitmap_document_greys_the_arbitrary_turn_out() { + // The other modes, the other expanded-pixel ones included, answer as they do today. + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel, ColorMode::Duotone] { + let d = Document::with_background("modes", Size::new(32, 24), mode, SampleType::U8, Color::WHITE); + let mut s = Session::new(); + s.add_document(d, None); + assert!(s.is_enabled(ARBITRARY), "{mode:?}: not measured, so it stays available"); + } + let mut s = bitmap(32, 24); + assert!(!s.is_enabled(ARBITRARY), "Bitmap: the one measured refusal"); + // Grayscale, the mode the reason points at, answers with the turn. + s.execute("image.mode.grayscale", json!({})).unwrap_or_else(|e| panic!("Image › Mode › Grayscale, got {e}")); + assert!(s.is_enabled(ARBITRARY), "Grayscale again: available again"); + s.execute(ARBITRARY, json!({"angle": 30})).unwrap(); + assert_eq!(doc_of(&s).size, rotated_size(Size::new(32, 24), 30.0), "and it turns"); +} + +#[test] +fn the_crop_straighten_turn_still_turns_a_bitmap_document() { + // Not measured in the reference, so it keeps today's behaviour: `image.crop` with an `angle` + // turns through the same `rotate_arbitrary_with` the menu item runs, and stays ungated. + let mut s = bitmap(32, 24); + assert!(s.is_enabled("image.crop"), "Crop stays available in a Bitmap document"); + let history = steps(&s); + let r = s + .execute("image.crop", json!({"x": 4, "y": 4, "width": 24, "height": 16, "angle": 10})) + .unwrap_or_else(|e| panic!("the Crop straighten turn keeps today's behaviour, got {e}")); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(24), Some(16)), "{r}"); + assert_eq!(size_of(&s), (24, 16), "turned and cropped, as today"); + assert_eq!(steps(&s), history + 1, "one History step"); +} From af15d2769973a1200f851df7405c323589f2ff31 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 16:14:38 +0100 Subject: [PATCH 084/385] 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 085/385] 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 7504d4eabccb7800a470ff059dbc4d476c3799d5 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 17:49:14 +0100 Subject: [PATCH 086/385] fix(engine): Image Rotation Arbitrary follows the Image Interpolation preference The rotation dialog seeded its Interpolation field from the params-doc default and `rotate_arbitrary_with` fell back to bicubic, so Preferences > General > Image Interpolation (`general.image_interpolation`) never reached `image.rotation.arbitrary`. The command entry point now fills the `interpolation` param from the preference when the param is absent, the dialog seeds its field from the preference on open, and `rotate_arbitrary_with` keeps the bicubic default so the Crop tool's rotated crop and Straighten keep today's behaviour exactly. The param stays for scripts and actions (#7630). New tests in `crates/engine/src/cmd/rotate_canvas_interpolation_pref_tests.rs` cover Nearest/Bilinear/Bicubic preferences with and without an explicit param, the not-measured preference variants and the unchanged Crop/Straighten paths. Fixes #14465. Part of #14461 (EPIC-ROTATE-CANVAS). --- crates/engine/src/cmd/mode_cmds.rs | 19 ++- .../rotate_canvas_interpolation_pref_tests.rs | 143 ++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 11 ++ 3 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/rotate_canvas_interpolation_pref_tests.rs diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index e5ad74c640..b14bff5e1a 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -63,7 +63,18 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { } pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { - rotate_arbitrary_with(s, p, true) + // #14465: with no `interpolation` param the resampling comes from Preferences › + // General › Image Interpolation; the preference's own names feed `Interp::parse`, so + // Nearest Neighbor and Bilinear act as the `nearest`/`bilinear` params do and the + // *not measured* variants (Bicubic Automatic/Sharper/Smoother, Preserve Details) + // resample as Bicubic, as today. The param stays for scripts and actions (#7630). + // The direct callers keep the old default through `rotate_arbitrary_with`: the Crop + // tool's rotated crop and Straighten pass no param and still rotate Bicubic. + let mut p = p.as_object().cloned().unwrap_or_default(); + if p.get("interpolation").and_then(Value::as_str).is_none() { + p.insert("interpolation".into(), json!(s.prefs().general.image_interpolation.name())); + } + rotate_arbitrary_with(s, &Value::Object(p), true) } /// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, @@ -771,7 +782,7 @@ pub fn specs() -> Vec { "image.rotation.arbitrary", "Arbitrary…", ["Image", "Image Rotation"], - r##"{"angle":-359.99..359.99=0,"direction":"cw|ccw"="cw","interpolation":"bicubic|bilinear|nearest"="bicubic"}"##, + r##"{"angle":-359.99..359.99=0,"direction":"cw|ccw"="cw","interpolation":"bicubic|bilinear|nearest" (absent: Preferences › General › Image Interpolation; its not-measured variants resample as bicubic)}"##, has_doc, rotate_arbitrary ), @@ -830,3 +841,7 @@ pub fn display_document(doc: &Document) -> Option { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "rotate_canvas_interpolation_pref_tests.rs"] +mod rotate_canvas_interpolation_pref_tests; diff --git a/crates/engine/src/cmd/rotate_canvas_interpolation_pref_tests.rs b/crates/engine/src/cmd/rotate_canvas_interpolation_pref_tests.rs new file mode 100644 index 0000000000..6c2ce6c10f --- /dev/null +++ b/crates/engine/src/cmd/rotate_canvas_interpolation_pref_tests.rs @@ -0,0 +1,143 @@ +//! #14465: Image › Image Rotation › Arbitrary resamples with Preferences › General › Image +//! Interpolation when the `interpolation` param is absent; an explicit param still wins +//! (scripts and actions, #7630). Measured with the issue's document: a 400×300 RGB 8-bit +//! white Background with a green square (x 174..274, y 100..260) rotated 30° cw. The +//! square's left edge crosses row y=230 at x≈218.5, inside the scanned window 205..235, +//! and nothing else does: with `nearest` that row is pure white and pure green (the hard +//! edge the reference application shows for Nearest Neighbor), bilinear and bicubic put +//! soft pixels there. The exact soft values are not asserted (not part of the item). + +use super::*; +use crate::prefs::Interpolation; + +fn green_edge_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": 8, "mode": "rgb", "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 174, "y": 100, "width": 100, "height": 160, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// Row pixels as 8-bit triples, x0..x1 at y (the rotated Background is layers[0]). +fn row(s: &Session, y: i32, x0: i32, x1: i32) -> Vec<[u8; 3]> { + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + (x0..x1) + .map(|x| { + let c = surf.rgba(x, y); + [c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8) + }) + .collect() +} + +/// Every Background pixel, row-major, as 8-bit triples. +fn snapshot(s: &Session) -> Vec<[u8; 3]> { + let d = &s.active().unwrap().doc; + let surf = d.layers[0].surface().unwrap(); + (0..d.size.height as i32) + .flat_map(|y| { + (0..d.size.width as i32).map(move |x| { + let c = surf.rgba(x, y); + [c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8) + }) + }) + .collect() +} + +fn is_white(p: &[u8; 3]) -> bool { + p[0] >= 250 && p[1] >= 250 && p[2] >= 250 +} + +fn is_green(p: &[u8; 3]) -> bool { + p[0] <= 5 && p[1] >= 250 && p[2] <= 5 +} + +/// Pixels neither white nor green: soft (resampled) edge pixels. +fn soft(r: &[[u8; 3]]) -> usize { + r.iter().filter(|p| !is_white(p) && !is_green(p)).count() +} + +/// Rotate 30° with the preference set to `pref` and no `interpolation` param; the edge row. +fn rotate_with_pref(pref: Interpolation) -> Vec<[u8; 3]> { + let mut s = green_edge_doc(); + s.edit_prefs(|p| p.general.image_interpolation = pref); + s.execute("image.rotation.arbitrary", json!({"angle": 30})).unwrap(); + row(&s, 230, 205, 236) +} + +/// Rotate 30° with an explicit param on default preferences; the edge row. +fn rotate_with_param(tag: &str) -> Vec<[u8; 3]> { + let mut s = green_edge_doc(); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "interpolation": tag})).unwrap(); + row(&s, 230, 205, 236) +} + +#[test] +fn absent_param_uses_the_nearest_neighbor_preference() { + let r = rotate_with_pref(Interpolation::Nearest); + assert!(r.iter().any(is_white) && r.iter().any(is_green), "the edge must cross the scanned row: {r:?}"); + assert_eq!(soft(&r), 0, "Nearest Neighbor gives hard edges"); + assert_eq!(r, rotate_with_param("nearest"), "the preference acts as the `nearest` param does"); +} + +#[test] +fn absent_param_uses_the_bilinear_preference() { + let r = rotate_with_pref(Interpolation::Bilinear); + assert!(soft(&r) > 0, "Bilinear gives soft edges"); + assert_eq!(r, rotate_with_param("bilinear"), "the preference acts as the `bilinear` param does"); + assert_ne!(r, rotate_with_param("bicubic"), "the preference is not ignored"); +} + +#[test] +fn absent_param_with_a_bicubic_preference_stays_bicubic() { + for pref in [Interpolation::Bicubic, Interpolation::BicubicAutomatic] { + let r = rotate_with_pref(pref); + assert!(soft(&r) > 0, "{pref:?} gives soft edges"); + assert_eq!(r, rotate_with_param("bicubic"), "{pref:?}"); + } +} + +#[test] +fn explicit_interpolation_param_beats_the_preference() { + let mut s = green_edge_doc(); + s.edit_prefs(|p| p.general.image_interpolation = Interpolation::Nearest); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "interpolation": "bicubic"})).unwrap(); + assert!(soft(&row(&s, 230, 205, 236)) > 0, "scripts and actions keep their param"); + + let mut s = green_edge_doc(); + s.edit_prefs(|p| p.general.image_interpolation = Interpolation::Bicubic); + s.execute("image.rotation.arbitrary", json!({"angle": 30, "interpolation": "nearest"})).unwrap(); + assert_eq!(soft(&row(&s, 230, 205, 236)), 0, "a `nearest` param still gives hard edges"); +} + +#[test] +fn not_measured_preferences_keep_todays_bicubic_result() { + for pref in [Interpolation::BicubicSmoother, Interpolation::BicubicSharper, Interpolation::PreserveDetails] { + assert_eq!(rotate_with_pref(pref), rotate_with_param("bicubic"), "{pref:?}"); + } +} + +#[test] +fn rotated_crop_and_straighten_ignore_the_interpolation_preference() { + // #14465 measured Image Rotation › Arbitrary only: the Crop tool's rotated crop and + // Straighten call the rotation with today's Bicubic and must not pick up the + // preference (their cases are the epic's *not measured*, today's behaviour). + for setup in ["crop", "straighten"] { + let mut a = green_edge_doc(); + let mut b = green_edge_doc(); + b.edit_prefs(|p| p.general.image_interpolation = Interpolation::Nearest); + for s in [&mut a, &mut b] { + if setup == "crop" { + s.execute("image.crop", json!({"x": 50, "y": 40, "width": 300, "height": 200, "angle": 30})).unwrap(); + } else { + s.execute("image.analysis.rulerTool", json!({"start": [100.0, 250.0], "end": [300.0, 150.0]})).unwrap(); + // Straighten Layer is greyed out for the Background (#12033); `crop: true` is + // the branch that turns the canvas through `rotate_arbitrary_with`. + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + } + } + assert_eq!(snapshot(&a), snapshot(&b), "{setup} keeps today's behaviour with the preference set"); + assert!(soft(&snapshot(&a)) > 0, "{setup} keeps the soft (bicubic) edge it has today"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 2f02574690..cb2cd39ac8 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -441,6 +441,17 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map "nearest", + Interpolation::Bilinear => "bilinear", + _ => "bicubic", + }; + fields.insert("interpolation".into(), json!(interp)); } if command == "type.warpText" { warp_defaults(app, fields); From e5ce74d868644dd175eb6934ff3c43b13f5554b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 17:42:42 +0100 Subject: [PATCH 087/385] 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 5c042b9945ef03000b66ab46fe0fbaacf59bf726 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 18:14:27 +0100 Subject: [PATCH 088/385] Apply Image: Darker Color and Lighter Color blending (#14478) image.applyImage accepts darkerColor and lighterColor. On an RGB layer the whole pixel comes from the target or the source, whichever has the lower (higher) luminosity; on one plane (an alpha channel, a layer mask, a grayscale layer, or only some colour channels targeted) they act as Darken / Lighten. A CMYK or Lab composite target and Calculations keep refusing them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/channel_cmds.rs | 2 + .../apply_image_darker_lighter_tests.rs | 142 ++++++++++++++++++ crates/engine/src/cmd/channel_cmds/calc.rs | 33 +++- crates/engine/src/cmd/channel_cmds/refs.rs | 25 ++- 4 files changed, 191 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/cmd/channel_cmds/apply_image_darker_lighter_tests.rs diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..a76036df16 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_darker_lighter_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/channel_cmds/apply_image_darker_lighter_tests.rs b/crates/engine/src/cmd/channel_cmds/apply_image_darker_lighter_tests.rs new file mode 100644 index 0000000000..26b60a2041 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/apply_image_darker_lighter_tests.rs @@ -0,0 +1,142 @@ +//! Apply Image with Darker Color and Lighter Color (#14478): the whole pixel comes from whichever of +//! target and source has the lower (higher) luminosity; one plane takes Darken (Lighten). +use super::*; + +const W: u32 = 400; +const H: u32 = 300; + +fn halves(s: &mut Session, left: &str, right: &str) { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"color": left})).unwrap(); + s.execute("select.rect", json!({"x": W / 2, "y": 0, "width": W / 2, "height": H, "mode": "replace"})).unwrap(); + s.execute("edit.fill", json!({"color": right})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); +} + +/// The measured test documents: "target" (0) RGB 200/100/50 | 50/150/250 and "source" (1) +/// 128/128/128 | 255/255/255, with "target" active. +fn session(mode: &str, depth: u32) -> Session { + let mut s = Session::new(); + for (left, right) in [("#c86432", "#3296fa"), ("#808080", "#ffffff")] { + s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "depth": depth})).unwrap(); + halves(&mut s, left, right); + } + s.set_active(0); + 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 assert_rgb(s: &Session, x: i32, want: [u8; 3], what: &str) { + let p = px(s, x, 50); + let ok = p[..3].iter().zip(want).all(|(v, w)| (v - f32::from(w) / 255.0).abs() < 0.003); + assert!(ok, "{what} at ({x},50): {p:?}, want {want:?}"); +} + +fn apply(s: &mut Session, blending: &str) -> Result { + s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": blending})) +} + +#[test] +fn darker_and_lighter_color_take_the_whole_pixel_by_luminosity() { + for depth in [8, 16, 32] { + let mut s = session("rgb", depth); + apply(&mut s, "darkerColor").unwrap(); + assert_rgb(&s, 50, [200, 100, 50], &format!("Darker Color, {depth} bit")); + assert_rgb(&s, 300, [50, 150, 250], &format!("Darker Color, {depth} bit")); + s.undo(); + apply(&mut s, "lighterColor").unwrap(); + assert_rgb(&s, 50, [128, 128, 128], &format!("Lighter Color, {depth} bit")); + assert_rgb(&s, 300, [255, 255, 255], &format!("Lighter Color, {depth} bit")); + } +} + +#[test] +fn the_labels_parse_too() { + let mut s = session("rgb", 8); + apply(&mut s, "Darker Color").unwrap(); + assert_rgb(&s, 50, [200, 100, 50], "Darker Color"); + s.undo(); + apply(&mut s, "lighter_color").unwrap(); + assert_rgb(&s, 50, [128, 128, 128], "Lighter Color"); +} + +#[test] +fn a_single_colour_channel_takes_darken_and_lighten() { + let mut s = session("rgb", 8); + s.execute("channel.target", json!({"channel": "red"})).unwrap(); + // Red 200 vs 128: Darken gives 128 (Darker Color on the whole pixel would keep 200). + apply(&mut s, "darkerColor").unwrap(); + assert_rgb(&s, 50, [128, 100, 50], "Darker Color onto Red"); + assert_rgb(&s, 300, [50, 150, 250], "Darker Color onto Red"); + s.undo(); + s.execute("channel.target", json!({"channel": "blue"})).unwrap(); + apply(&mut s, "lighterColor").unwrap(); + assert_rgb(&s, 50, [200, 100, 128], "Lighter Color onto Blue"); + assert_rgb(&s, 300, [50, 150, 255], "Lighter Color onto Blue"); +} + +#[test] +fn an_alpha_channel_and_a_layer_mask_take_darken_and_lighten() { + let mut s = session("rgb", 8); + let a = s.execute("channel.new", json!({"fill": "white"})).unwrap()["channel"].as_u64().unwrap() as usize; + // Into an alpha channel: white onto the source's gray (Darken) is the gray. + s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "darkerColor", "target": {"channel": a}})).unwrap(); + let alpha = |s: &Session, x| s.active().unwrap().doc.channels[a].surface.sample_channel(x, 50, 0); + assert!((alpha(&s, 50) - 128.0 / 255.0).abs() < 0.003 && (alpha(&s, 300) - 1.0).abs() < 0.003); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": "mask"})).unwrap(); + // Into a black layer mask: Lighten takes the source's gray and white. + s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "lighterColor"})).unwrap(); + let d = s.active().unwrap(); + let m = &d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; + assert!((m.sample_channel(50, 50, 0) - 128.0 / 255.0).abs() < 0.003, "{}", m.sample_channel(50, 50, 0)); + assert!((m.sample_channel(300, 50, 0) - 1.0).abs() < 0.003); +} + +#[test] +fn a_grayscale_layer_takes_darken_and_lighten() { + let mut s = Session::new(); + for color in ["#c8c8c8", "#808080"] { + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "grayscale"})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + } + s.set_active(0); + apply(&mut s, "darkerColor").unwrap(); + assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.003, "{:?}", px(&s, 5, 5)); + s.undo(); + apply(&mut s, "lighterColor").unwrap(); + assert!((px(&s, 5, 5)[0] - 200.0 / 255.0).abs() < 0.003, "{:?}", px(&s, 5, 5)); +} + +#[test] +fn other_modes_and_refusals_are_unchanged() { + let mut s = session("rgb", 8); + // Darken still mixes the channels: min per channel. + apply(&mut s, "darken").unwrap(); + assert_rgb(&s, 50, [128, 100, 50], "Darken"); + s.undo(); + for bad in ["hue", "luminosity", "dissolve", "darkerColour", ""] { + assert!(apply(&mut s, bad).is_err(), "{bad} is refused"); + } + assert_rgb(&s, 50, [200, 100, 50], "nothing changed"); + // Calculations keeps refusing them. + for blending in ["darkerColor", "lighterColor"] { + let e = s.execute("image.calculations", json!({"source1": {}, "source2": {}, "blending": blending})).unwrap_err(); + assert!(e.to_string().contains("unsupported blending"), "{e}"); + } + assert!(s.active().unwrap().doc.channels.is_empty()); +} + +#[test] +fn a_cmyk_composite_target_is_refused_and_left_alone() { + let mut s = session("cmyk", 8); + let before = px(&s, 50, 50); + assert!(apply(&mut s, "darkerColor").is_err()); + assert_eq!(px(&s, 50, 50), before); +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 9c1d0ea6b8..d116cc810b 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -3,6 +3,7 @@ use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, r 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}; +use photocraft_color::blend::blend_rgb; // --------------------------------------------------------------------------------------------- // Apply Image / Calculations @@ -20,6 +21,8 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { let src = source(s, &src_spec, cmd, src_mode == ColorMode::Cmyk && (is_channel_target(p) || target_of(p) == Target::Mask))?; let mask = mask_plane(s, p, cmd)?; let layer = s.active().and_then(|d| d.active_layer); + // With only some colour channels targeted each one is a plane of its own. + let color_targets = crate::color_channels::target(s, p)?; s.edit("Apply Image", |doc, _| { let area = doc.bounds(); let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); @@ -63,6 +66,11 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { } let n = sf.channels(); let colors = sf.mode.color_channels(); + // Darker Color / Lighter Color compare RGB luminosity; one plane takes Darken / Lighten. + let whole = blending.whole_pixel().filter(|_| colors > 1 && color_targets.is_none_or(|t| t.len() >= colors)); + if whole.is_some() && sf.mode != ColorMode::Rgb { + return Err(EngineError::Other(format!("Darker Color and Lighter Color need an RGB or one-channel target, not {:?}", sf.mode))); + } 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 }; @@ -77,15 +85,22 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { // pixels (where it is transparent the source shows as is), and the alpha grows by // source-over, so applying to an empty layer copies the source in any mode. let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; + // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back + // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. + // A CMYK composite onto another mode darkens each tone by its Black, so Black + // alone stays black. + 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_of = |c: usize| if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] }; + // The whole pixel comes from the side Darker / Lighter Color picks; channels never mix. + let picked = whole.and_then(|m| { + let base = [px.first()?, px.get(1)?, px.get(2)?].map(|&b| tone(sf.mode, b)); + Some(blend_rgb(m, base, [top_of(0), top_of(1), top_of(2)])) + }); for (c, b) in px[..colors].iter_mut().enumerate() { - // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back - // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. - // A CMYK composite onto another mode darkens each tone by its Black, so Black - // alone stays black. - 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 top = top_of(c); let base = tone(sf.mode, *b); - let blended = top + (blending.apply(base, top) - top) * base_a; + let mixed = picked.and_then(|p| p.get(c).copied()).unwrap_or_else(|| blending.apply(base, top)); + let blended = top + (mixed - top) * base_a; *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); } if sf.alpha { @@ -102,6 +117,10 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { let cmd = "image.calculations"; let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?; + // Not offered by Calculations yet (a separate item); Apply Image only. + if blending.whole_pixel().is_some() { + return Err(bad(cmd, format!("unsupported blending `{}`", p.get("blending").and_then(Value::as_str).unwrap_or_default().to_ascii_lowercase()))); + } let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; let s1 = source(s, &source_spec(p, "source1", "source1").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); let s2 = source(s, &source_spec(p, "source2", "source2").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index 39a56e1928..af96497915 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -297,8 +297,8 @@ pub(super) fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result Ok(Blending::Add { scale, offset }), "subtract" => Ok(Blending::Subtract { scale, offset }), other => match crate::commands::blend_from_str(other) { - Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)), + Some(m) + if (m.is_separable() || matches!(m, BlendMode::DarkerColor | BlendMode::LighterColor)) + && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => + { + Ok(Blending::Mode(m)) + } _ => Err(format!("unsupported blending `{other}`")), }, } } - /// Blend `top` (the source) onto `base` (the target). + /// Darker Color or Lighter Color: they take the whole pixel from whichever side has the lower + /// or higher luminosity, so a colour target blends them per pixel, not with [`Self::apply`]. + pub fn whole_pixel(self) -> Option { + match self { + Blending::Mode(m @ (BlendMode::DarkerColor | BlendMode::LighterColor)) => Some(m), + _ => None, + } + } + + /// Blend `top` (the source) onto `base` (the target). On one plane Darker Color and Lighter + /// Color are Darken and Lighten. pub fn apply(self, base: f32, top: f32) -> f32 { match self { + Blending::Mode(BlendMode::DarkerColor) => blend_channel(BlendMode::Darken, base, top), + Blending::Mode(BlendMode::LighterColor) => blend_channel(BlendMode::Lighten, base, top), Blending::Mode(m) => blend_channel(m, base, top), Blending::Add { scale, offset } => (base + top) / scale + offset, Blending::Subtract { scale, offset } => (base - top) / scale + offset, From 938b4e067a21ea71c274a90aa0265c4ea82bc599 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:34:41 +0100 Subject: [PATCH 089/385] docs: point PSD API guide to craft-libs --- book/src/formats/psd-psb.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/formats/psd-psb.md b/book/src/formats/psd-psb.md index c82fc8a135..db5171e4b0 100644 --- a/book/src/formats/psd-psb.md +++ b/book/src/formats/psd-psb.md @@ -2,7 +2,7 @@ `craft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily. -The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [`crates/psd/README.md`](https://github.com/storytold/photocraft/blob/main/crates/psd/README.md). +The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [craft-psd README](https://github.com/storytold/craft-libs/blob/main/crates/psd/README.md). ## Implemented parser protections From 177db3650a22fde6f03fbae19170cba33fa86aee Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:36:00 +1100 Subject: [PATCH 090/385] Name the Artboard from Layers history step "New Artboard From Layers" (#14578) Adds a test at 8/16/32 bit that exactly one step with that name is added and a single undo restores the layer tree. --- crates/engine/src/cmd/artboard_cmds.rs | 5 ++- .../from_layers_history_name_tests.rs | 44 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..e786286e4e 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -408,7 +408,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps // their bounds on that axis (#9087). let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; - let (gid, rect, shift) = s.edit("Artboard from Layers", |doc, active| { + let (gid, rect, shift) = s.edit("New Artboard From Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { return Err(EngineError::Other("select layers that are not in an artboard".into())); @@ -848,5 +848,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/from_layers_history_name_tests.rs"] +mod from_layers_history_name_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs new file mode 100644 index 0000000000..34dbe6d306 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs @@ -0,0 +1,44 @@ +//! Artboard from Layers adds one history step named "New Artboard From Layers" (#14578). + +use super::*; +use photocraft_geom::Rect; + +/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + s +} + +fn steps(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + +fn tree(s: &Session) -> Vec<(String, bool)> { + s.active().unwrap().doc.walk().iter().map(|(_, _, l)| (l.name.clone(), l.children().is_some())).collect() +} + +#[test] +fn artboard_from_layers_adds_one_new_artboard_from_layers_step() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let before_steps = steps(&s); + let before_tree = tree(&s); + s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap(); + let after = steps(&s); + assert_eq!(after.len(), before_steps.len() + 1, "exactly one step at {depth} bit: {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("New Artboard From Layers"), "{depth} bit"); + s.undo(); + assert_eq!(tree(&s), before_tree, "one undo restores the layer tree at {depth} bit"); + assert!(s.active().unwrap().doc.artboards().is_empty()); + } +} From 362c994adf7c96eab1bbcd4b5e35d662778277c9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:41:11 +0100 Subject: [PATCH 091/385] docs: repair raster codec README link --- book/src/formats/raster-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index 5e8d870de1..7aa81ca5c5 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -58,4 +58,4 @@ Format adapters pass compatible allocation limits into PNG, TIFF, WebP, and `ima `Limits::none()` exists for callers with a deliberate reason to relax policy. It remains bounded by representable memory sizes, but it removes the default resource policy and should not be used for untrusted input. -Animated containers and multi-page TIFFs are represented as a single decoded frame or page by the current codec API; opening one adds an import warning such as "only the first of 3 frames was imported". A JPEG cut off inside its image data opens with a warning that its data ends early (an error when it holds no image data at all). Refer to [`crates/codecs/README.md`](https://github.com/storytold/photocraft/blob/main/crates/codecs/README.md) and source capability declarations for current behavior. +Animated containers and multi-page TIFFs are represented as a single decoded frame or page by the current codec API; opening one adds an import warning such as "only the first of 3 frames was imported". A JPEG cut off inside its image data opens with a warning that its data ends early (an error when it holds no image data at all). Refer to [the `craft-image-codecs` README](https://github.com/storytold/craft-libs/blob/main/crates/image-codecs/README.md) and source capability declarations for current behavior. From 7acd50ca9dabd88a39a0a3a305b90855c60bd0b5 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 19:04:21 +0100 Subject: [PATCH 092/385] 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 605cc9f70ffbfa6c67a95fe898191a3fcb32aa2f Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 19:23:33 +0100 Subject: [PATCH 093/385] fix(ui-egui): the Curves graph grabs a point up to 15 screen px away A press 13 or 15 px from an existing point missed the shared widget's single 9 px HIT_RADIUS, so the Curves graph added a second point right next to the one the click meant: insert() only folds clicks within MIN_GAP = 2 levels onto an existing point. The grab radius is now per host. The Curves editor passes the new CURVES_HIT_RADIUS = 16.0 px, inside the measured window (select at 15 px, still add at 30 px), while the hosts the reference application was not measured in - the raw development dialog and the layer-style contour - go on using interact() and today's 9 px exactly. Refs #14443 --- .../src/dialogs/adjust_editors/curves.rs | 2 +- crates/ui-egui/src/widgets.rs | 4 + crates/ui-egui/src/widgets/point_curve.rs | 29 ++++- .../widgets/point_curve_hit_radius_tests.rs | 112 ++++++++++++++++++ 4 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs diff --git a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs index c57c285f61..20ecd6cce1 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs @@ -396,7 +396,7 @@ pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { } ui.data_mut(|d| d.insert_temp(stroke_id, (active, last))); } else { - let interaction = crate::point_curve::interact(ui, &resp, graph, &mut pts, &mut st.gesture); + let interaction = crate::point_curve::interact_with_hit_radius(ui, &resp, graph, &mut pts, &mut st.gesture, crate::point_curve::CURVES_HIT_RADIUS); changed = interaction.changed; e.commit |= interaction.commit; } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5e22305dce..0b7d982c49 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -88,3 +88,7 @@ mod color_button_tests; #[cfg(test)] #[path = "widgets/numeric_input_tests.rs"] mod numeric_input_tests; + +#[cfg(test)] +#[path = "widgets/point_curve_hit_radius_tests.rs"] +mod point_curve_hit_radius_tests; diff --git a/crates/ui-egui/src/widgets/point_curve.rs b/crates/ui-egui/src/widgets/point_curve.rs index e3928e8fa3..f3a73e0ae2 100644 --- a/crates/ui-egui/src/widgets/point_curve.rs +++ b/crates/ui-egui/src/widgets/point_curve.rs @@ -9,7 +9,13 @@ pub struct Interaction { pub commit: bool, } +/// Grab radius of the hosts the reference application was not measured in, so it stays as it is. const HIT_RADIUS: f32 = 9.0; +/// Screen pixels a click in the **Curves graph** may sit from an existing point and still select it. +/// The reference application selects a point clicked 8, 13 and 15 px away at 1 px per input level +/// and still adds a point 30 px away, so this has to sit in that window; 16.0 is the smallest clean +/// screen distance above the measured 15, and it is one pixel per level for 16 input levels. +pub const CURVES_HIT_RADIUS: f32 = 16.0; /// Interior points disappear outside this margin and return on re-entry during the same drag. const DRAG_OFF: f32 = 12.0; @@ -75,7 +81,26 @@ pub fn move_to(pts: &mut [[f32; 2]], i: usize, v: [f32; 2]) -> bool { /// Capture a point at button-down, preserve its grab offset, and keep it through release. /// `commit` ends a gesture; hosts decide how that becomes document history. +/// +/// Uses today's 9 px grab radius, which the hosts the reference application was not measured in +/// keep; the Curves graph asks for its own through [`interact_with_hit_radius`]. pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2]>, state: &mut PointCurveState) -> Interaction { + interact_with_hit_radius(ui, resp, graph, pts, state, HIT_RADIUS) +} + +/// [`interact`], with the host's grab radius in screen pixels: the Curves graph passes +/// [`CURVES_HIT_RADIUS`]; a host the reference application was not measured in passes the 9 px +/// default. +pub fn interact_with_hit_radius( + ui: &mut Ui, + resp: &Response, + graph: Rect, + pts: &mut Vec<[f32; 2]>, + state: &mut PointCurveState, + hit_radius: f32, +) -> Interaction { + // Hosts pass a constant; a hostile value must not leave every point ungrabbable. + let hit_radius = if hit_radius.is_finite() { hit_radius.max(0.0) } else { HIT_RADIUS }; if !graph.is_finite() || graph.width() <= 0.0 || graph.height() <= 0.0 { *state = PointCurveState::default(); return Interaction::default(); @@ -91,7 +116,7 @@ pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2 if resp.secondary_clicked() && let Some(pos) = resp.interact_pointer_pos() { - if let Some(i) = hit(pts, to_scr, pos, HIT_RADIUS) + if let Some(i) = hit(pts, to_scr, pos, hit_radius) && delete(pts, i) { e.changed = true; @@ -109,7 +134,7 @@ pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2 if press && let Some(pos) = press_pos { resp.request_focus(); let delete_pressed = ui.input(|i| i.modifiers.command); - match hit(pts, to_scr, pos, HIT_RADIUS) { + match hit(pts, to_scr, pos, hit_radius) { Some(i) if delete_pressed => { if delete(pts, i) { e.changed = true; diff --git a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs new file mode 100644 index 0000000000..f947437195 --- /dev/null +++ b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs @@ -0,0 +1,112 @@ +//! #14443: in the Curves graph a click up to 15 screen px from an existing point selects that +//! point instead of adding a second one next to it, while a click clearly away still adds. +//! The other hosts of the shared widget were not measured in the reference application, so they +//! keep today's 9 px radius. + +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Sense, vec2}; +use egui_kittest::Harness; + +use crate::state::PointCurveState; +use crate::widgets::point_curve::{self, CURVES_HIT_RADIUS}; + +/// One screen pixel per input level, the scale the issue measures at: the graph is exactly 255 px +/// on a side, so a screen distance in px and an input distance in levels are the same number. +const SIDE: f32 = 255.0; +/// The radius of the hosts that stay as they are today. +const TODAY: f32 = 9.0; + +#[derive(Clone, Debug)] +struct Host { + pts: Vec<[f32; 2]>, + gesture: PointCurveState, + graph: Rect, + radius: f32, +} + +/// A bare point-curve graph of `radius` grab pixels: identity curve, one point at level 128. +fn graph(radius: f32) -> Harness<'static, Host> { + let mut h = Harness::builder().with_size(vec2(600.0, 600.0)).build_ui_state( + |ui, host: &mut Host| { + let (rect, resp) = ui.allocate_exact_size(vec2(SIDE, SIDE), Sense::click_and_drag()); + host.graph = rect; + point_curve::interact_with_hit_radius(ui, &resp, rect, &mut host.pts, &mut host.gesture, host.radius); + }, + Host { pts: vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], gesture: PointCurveState::default(), graph: Rect::NOTHING, radius }, + ); + h.run_steps(2); // The first frame lays the graph out. + h +} + +/// Screen position of the input/output level pair `level` (1 px per level). +fn at(host: &Host, level: [f32; 2]) -> Pos2 { + Pos2::new(host.graph.left() + level[0], host.graph.bottom() - level[1]) +} + +/// Press and release at `pos`, a frame each: one click. +fn click(h: &mut Harness<'static, Host>, pos: Pos2) { + h.event(Event::PointerMoved(pos)); + h.run_steps(1); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// A click `d` px right of the middle point. +fn click_right_of_point(h: &mut Harness<'static, Host>, d: f32) { + let pos = at(h.state(), [128.0 + d, 128.0]); + click(h, pos); +} + +/// The measured case: at 1 px per level a click 8, 13 or 15 px from a point selects it and adds +/// nothing. The point does not move either: the press keeps the grab offset through the release. +#[test] +fn curves_selects_a_point_clicked_up_to_fifteen_pixels_away() { + for d in [8.0, 13.0, 15.0] { + let mut h = graph(CURVES_HIT_RADIUS); + click_right_of_point(&mut h, d); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], "a click {d} px away adds a point next to the existing one"); + assert_eq!(host.gesture.selected, Some(1), "a click {d} px away does not select the existing point"); + } +} + +/// The same 15 px measured diagonally (9 right, 12 up): the radius is a screen disc. +#[test] +fn curves_selects_the_point_across_a_diagonal_click() { + let mut h = graph(CURVES_HIT_RADIUS); + let pos = at(h.state(), [137.0, 140.0]); + click(&mut h, pos); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], "the 15 px diagonal click adds a point"); + assert_eq!(host.gesture.selected, Some(1), "the 15 px diagonal click does not select the point"); +} + +/// A click clearly away from every point still adds a point there and selects it. +#[test] +fn curves_still_adds_a_point_clicked_thirty_pixels_away() { + let mut h = graph(CURVES_HIT_RADIUS); + click_right_of_point(&mut h, 30.0); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [158.0, 128.0], [255.0, 255.0]], "the 30 px click adds no new point"); + assert_eq!(host.gesture.selected, Some(2), "the added point is the selected one"); +} + +/// The radius has to reach the measured 15 px select and stay clear of the 30 px add. +#[test] +fn the_curves_hit_radius_sits_inside_the_measured_window() { + assert!((15.0..30.0).contains(&CURVES_HIT_RADIUS), "the Curves grab radius is {CURVES_HIT_RADIUS} px, outside the measured 15..30 px window"); +} + +/// Not measured in the reference application, so the other hosts keep today's radius exactly: a +/// click 8 or 9 px away grabs the point, one 10 px away still adds a second point. +#[test] +fn the_unmeasured_hosts_keep_todays_nine_pixel_radius() { + for (d, added) in [(8.0, false), (9.0, false), (10.0, true)] { + let mut h = graph(TODAY); + click_right_of_point(&mut h, d); + let host = h.state(); + assert_eq!(host.pts.len(), if added { 4 } else { 3 }, "a click {d} px away through the default radius changes the point count"); + assert_eq!(host.gesture.selected, Some(if added { 2 } else { 1 }), "a click {d} px away selects the wrong point"); + } +} From 9375a5f459188a3b24eb7ac5fbc9ee2e19106ea9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:03:03 +0100 Subject: [PATCH 094/385] docs: pin codec README to the locked dependency revision --- book/src/formats/raster-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index 7aa81ca5c5..02dc57b962 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -58,4 +58,4 @@ Format adapters pass compatible allocation limits into PNG, TIFF, WebP, and `ima `Limits::none()` exists for callers with a deliberate reason to relax policy. It remains bounded by representable memory sizes, but it removes the default resource policy and should not be used for untrusted input. -Animated containers and multi-page TIFFs are represented as a single decoded frame or page by the current codec API; opening one adds an import warning such as "only the first of 3 frames was imported". A JPEG cut off inside its image data opens with a warning that its data ends early (an error when it holds no image data at all). Refer to [the `craft-image-codecs` README](https://github.com/storytold/craft-libs/blob/main/crates/image-codecs/README.md) and source capability declarations for current behavior. +Animated containers and multi-page TIFFs are represented as a single decoded frame or page by the current codec API; opening one adds an import warning such as "only the first of 3 frames was imported". A JPEG cut off inside its image data opens with a warning that its data ends early (an error when it holds no image data at all). Refer to [the `craft-image-codecs` README](https://github.com/storytold/craft-libs/blob/e2dc681a3ad8a47038da2f11ddd2c5e1c0454991/crates/image-codecs/README.md) and source capability declarations for current behavior. From f97c6478d812ed713c0a8cd778e1da61e531b0fb Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:03:28 +0100 Subject: [PATCH 095/385] docs: pin PSD README to the locked dependency revision --- book/src/formats/psd-psb.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/formats/psd-psb.md b/book/src/formats/psd-psb.md index db5171e4b0..14e9bb4516 100644 --- a/book/src/formats/psd-psb.md +++ b/book/src/formats/psd-psb.md @@ -2,7 +2,7 @@ `craft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily. -The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [craft-psd README](https://github.com/storytold/craft-libs/blob/main/crates/psd/README.md). +The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [craft-psd README](https://github.com/storytold/craft-libs/blob/e2dc681a3ad8a47038da2f11ddd2c5e1c0454991/crates/psd/README.md). ## Implemented parser protections From 2fc63aee8f287a79264dba3437387c5f51dfd578 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:45:23 +0000 Subject: [PATCH 096/385] Keep existing Image Processor folder outputs --- crates/engine/src/cmd/file_cmds/batch_run.rs | 86 ++++++++++--- .../image_processor_unique_names_tests.rs | 113 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/processing.rs | 9 +- 3 files changed, 191 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 5085b47f21..288a0b07f6 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -140,27 +140,36 @@ pub(crate) fn process_files( f: &dyn Fn(&mut Session) -> Result<()>, ) -> Value { let inputs: Vec = inputs.iter().map(|path| BatchInput { path: path.clone(), rel_dir: String::new() }).collect(); - process_tree(s, &inputs, output, format, save, suffix, &|scratch, _| f(scratch).map(|()| false)) + process_tree(s, &inputs, output, format, save, TreeNaming::Suffix(suffix), &|scratch, _| f(scratch).map(|()| false)) +} + +pub(super) enum TreeNaming<'a> { + Suffix(&'a str), + Unique, } /// [`process_files`] for inputs from subfolders: each result goes to its input's relative folder /// under `output` (created as needed), so `a/x.png` and `b/x.png` don't collide. `f` gets the /// output path and returns `true` when it wrote the result there itself (Batch writes what a /// recorded save marked); otherwise the active document is saved after it. -pub(crate) fn process_tree( +pub(super) fn process_tree( s: &Session, inputs: &[BatchInput], output: &str, format: &str, save: SaveOpts, - suffix: &str, + naming: TreeNaming<'_>, f: &dyn Fn(&mut Session, &str) -> Result, ) -> Value { + let (suffix, unique) = match naming { + TreeNaming::Suffix(suffix) => (suffix, false), + TreeNaming::Unique => ("", true), + }; let outputs = inputs.iter().map(|BatchInput { path, rel_dir }| { let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; (path.as_str(), join(&join(output, rel_dir), &format!("{}{suffix}.{ext}", stem(path)))) }); - process_outputs(s, outputs, save, f) + process_outputs(s, outputs, save, unique, f) } /// The extension a batch output takes with Format "Same": the input's own, except for formats @@ -240,6 +249,7 @@ fn process_outputs<'a>( s: &Session, outputs: impl IntoIterator, save: SaveOpts, + unique: bool, f: &dyn Fn(&mut Session, &str) -> Result, ) -> Value { // The scratch sessions have default preferences; a raw opens at the user's Raw Defaults. @@ -256,9 +266,11 @@ fn process_outputs<'a>( f(scratch, out).map_err(FileFailure::from) }; for (path, out) in outputs { - let r = process_one(raw_ppi, path, &out, save, ProcessOptions { format: None, written: Some(&written), ctx: None, input: None }, &run); + let options = ProcessOptions { format: None, written: (!unique).then_some(&written), ctx: None, input: None, unique }; + let r = process_one(raw_ppi, path, &out, save, options, &run); match r { - Ok(()) => { + Ok(Some(out)) => files.push(out), + Ok(None) => { written.record(&out, path); files.push(out); } @@ -311,9 +323,9 @@ pub(super) fn process_document_copies( let notices = std::cell::RefCell::new(Vec::new()); let input = InputPolicy { prepare: &prepare, notices: ¬ices }; let run = |scratch: &mut Session, out: &str| f(scratch, out).map_err(FileFailure::from); - let options = ProcessOptions { format: Some(&ext), written: Some(&written), ctx: None, input: Some(&input) }; + let options = ProcessOptions { format: Some(&ext), written: Some(&written), ctx: None, input: Some(&input), unique: false }; match process_one(s.prefs().raw_defaults.resolution, &path, &out, save, options, &run) { - Ok(()) => { + Ok(_) => { written.record(&out, &path); files.push(out); } @@ -333,6 +345,7 @@ struct ProcessOptions<'a> { written: Option<&'a OutputClaims>, ctx: Option<&'a crate::jobs::JobCtx>, input: Option<&'a InputPolicy<'a>>, + unique: bool, } /// Open and process one scratch input, collecting opening diagnostics even on failure. @@ -344,12 +357,12 @@ fn process_one( save: SaveOpts, options: ProcessOptions<'_>, f: &dyn Fn(&mut Session, &str) -> std::result::Result, -) -> std::result::Result<(), FileFailure> { +) -> std::result::Result, FileFailure> { if let Some(written) = options.written { written.check(out).map_err(EngineError::Other)?; } let mut scratch = Session::new(); - let result = (|| -> std::result::Result<(), FileFailure> { + let result = (|| -> std::result::Result, FileFailure> { if let Some(input) = options.input { (input.prepare)(&mut scratch, path)?; } else { @@ -364,7 +377,7 @@ fn process_one( if saved_by_action { // The action's saved snapshot is already written: a cancel or Esc arriving now stops the // inputs after this one, not this result. - return Ok(()); + return Ok(None); } if let Some(ctx) = options.ctx { ctx.check()?; @@ -373,6 +386,12 @@ fn process_one( } } let d = scratch.active().ok_or(EngineError::NoDocument)?; + if options.unique { + let (bytes, mut warnings) = encode(&d.doc, out, save)?; + let actual = save_unique_output(out, &bytes, &mut warnings)?; + record_export_warnings(&mut scratch, &actual, warnings); + return Ok(Some(actual)); + } let warnings = if let Some(format) = options.format { let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; if let Some(ctx) = options.ctx { save_batch_doc(&d.doc, out, &ext, save, ctx)? } else { save_doc_as(&d.doc, out, &ext, save)? } @@ -380,7 +399,7 @@ fn process_one( save_doc(&d.doc, out, save)? }; record_export_warnings(&mut scratch, out, warnings); - Ok(()) + Ok(None) })(); if let Some(input) = options.input { input.notices.borrow_mut().extend(scratch.batch_open_notices.take().unwrap_or_default()); @@ -390,6 +409,45 @@ fn process_one( /// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore /// leaves the current destination untouched; the worker owns the write once the checkpoint passes. +/// Claim a destination atomically so another process creating it during export cannot lose its file. +#[cfg(not(target_arch = "wasm32"))] +fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Result { + use std::{fs, io::ErrorKind, path::Path}; + + let path = Path::new(out); + let dir = path.parent().filter(|dir| !dir.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(dir).map_err(|error| EngineError::Other(format!("{}: {error}", dir.display())))?; + let name = file_name(out); + let prefix = out.strip_suffix(&name).unwrap_or_default(); + let (stem, extension) = name.rsplit_once('.').unwrap_or((&name, "")); + for suffix in 0..=100_000 { + let candidate = if suffix == 0 { out.to_owned() } else { format!("{prefix}{stem}_{suffix}.{extension}") }; + let path = Path::new(&candidate); + // Avoid staging encoded bytes when the name is already visibly occupied, including + // directories and dangling symlinks. The publication still checks the name atomically. + match fs::symlink_metadata(path) { + Ok(_) => continue, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), + } + match photocraft_format::write_noreplace(path, bytes) { + Ok(()) => return Ok(candidate), + Err(error) if error.published => { + warnings.push(error.to_string()); + return Ok(candidate); + } + Err(error) if error.error.kind() == ErrorKind::AlreadyExists => {} + Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), + } + } + Err(EngineError::Other(format!("{out}: no free output name through suffix _100000"))) +} + +#[cfg(target_arch = "wasm32")] +fn save_unique_output(out: &str, _bytes: &[u8], _warnings: &mut Vec) -> Result { + Err(EngineError::Other(format!("cannot write {out}: no file system on the web"))) +} + fn save_batch_doc(doc: &Document, out: &str, format: &str, save: SaveOpts, ctx: &crate::jobs::JobCtx) -> Result> { let (bytes, warnings) = encode(doc, format, save)?; ctx.batch_before_write()?; @@ -548,7 +606,7 @@ fn process_batch_outputs_with( path, out, save, - ProcessOptions { format: Some(format), written: check_duplicates.then_some(&written), ctx: Some(ctx), input }, + ProcessOptions { format: Some(format), written: check_duplicates.then_some(&written), ctx: Some(ctx), input, unique: false }, f, ); if result.is_ok() { @@ -595,7 +653,7 @@ fn process_batch_outputs_with( ctx.publish_batch_preview(path, None); done = index + 1; match result { - Ok(()) => { + Ok(_) => { files.push(out.clone()); } Err(error) => { diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs new file mode 100644 index 0000000000..296426eb8b --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -0,0 +1,113 @@ +use std::{fs, path::Path, sync::Barrier, thread}; + +use serde_json::json; + +use crate::Session; + +const COMMAND: &str = "file.scripts.imageProcessor"; +const PIXELS: &[u8] = b"P6\n2 1\n255\n\xff\0\0\0\xff\0"; + +#[test] +fn selects_the_first_free_suffix_and_reports_every_written_format() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("a.b.ppm"); + fs::write(&source, PIXELS).unwrap(); + let output = root.path().join("out"); + fs::create_dir(&output).unwrap(); + for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { + fs::write(output.join(name), name.as_bytes()).unwrap(); + } + let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"jpeg":{},"psd":{},"tiff":{}})).unwrap(); + let expected = ["a.b_2.jpg", "a.b.psd", "a.b_1.tif"]; + assert_eq!(result, json!({"files":expected.map(|name| output.join(name)), "errors":[]})); + let next = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"jpg"})).unwrap(); + assert_eq!(next, json!({"files":[output.join("a.b_4.jpg")], "errors":[]})); + for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { + assert_eq!(fs::read(output.join(name)).unwrap(), name.as_bytes()); + } + assert_eq!(fs::read(&source).unwrap(), PIXELS); + for name in expected { + let file = output.join(name); + let result = photocraft_io::import(name, &fs::read(file).unwrap()).unwrap(); + assert_eq!((result.document.size.width, result.document.size.height), (2, 1)); + } +} + +#[test] +fn same_stem_inputs_get_separate_results_without_changing_shared_processing() { + let source = tempfile::tempdir().unwrap(); + let output = source.path().join("output"); + let a = source.path().join("a/same.ppm"); + let b = source.path().join("b/same.ppm"); + for path in [&a, &b] { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, PIXELS).unwrap(); + } + let mut session = Session::new(); + let result = session.execute(COMMAND, json!({"input":[a,b],"output":output,"format":"png"})).unwrap(); + assert_eq!(result, json!({"files":[output.join("same.png"),output.join("same_1.png")],"errors":[]})); + + let result = session.execute(COMMAND, json!({"input":source.path(),"output":output,"format":"png","includeSubfolders":true})).unwrap(); + assert_eq!(result, json!({"files":[output.join("a/same.png"),output.join("b/same.png")],"errors":[]})); + + let legacy = source.path().join("legacy"); + let inputs = [a.to_string_lossy().into_owned(), b.to_string_lossy().into_owned()]; + let result = super::super::batch_run::process_files(&session, &inputs, &legacy.to_string_lossy(), "png", Default::default(), "", &|_| Ok(())); + assert_eq!(result["files"], json!([legacy.join("same.png")])); + let errors = result["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1); + assert!(errors[0]["error"].as_str().unwrap().contains("same output name")); +} + +#[test] +fn concurrent_folder_runs_cannot_replace_each_others_results() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("same.ppm"); + let output = root.path().join("out"); + fs::write(&source, PIXELS).unwrap(); + let params = json!({"input": [source], "output": output, "format": "png"}); + let gate = Barrier::new(4); + let results = thread::scope(|scope| { + let workers: Vec<_> = (0..4) + .map(|_| { + scope.spawn(|| { + let mut session = Session::new(); + gate.wait(); + session.execute(COMMAND, params.clone()) + }) + }) + .collect(); + workers.into_iter().map(|worker| worker.join()).collect::>() + }); + let mut written = Vec::new(); + for result in results { + let result = result.unwrap().unwrap(); + assert_eq!(result["errors"], json!([])); + written.push(result["files"][0].as_str().unwrap().to_owned()); + } + written.sort(); + let expected = ["same.png", "same_1.png", "same_2.png", "same_3.png"].map(|file| output.join(file)); + assert_eq!(written.iter().map(Path::new).collect::>(), expected.iter().map(|path| path.as_path()).collect::>()); + assert_eq!(fs::read_dir(&output).unwrap().count(), 4); + for path in &expected { + assert!(photocraft_io::import(&path.to_string_lossy(), &fs::read(path).unwrap()).is_ok()); + } +} + +#[test] +fn directory_and_dangling_symlink_names_stay_occupied() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("example.ppm"); + fs::write(&source, PIXELS).unwrap(); + let output = root.path().join("out"); + fs::create_dir_all(output.join("example.png")).unwrap(); + let counter = if cfg!(unix) { 2 } else { 1 }; + #[cfg(unix)] + std::os::unix::fs::symlink(output.join("missing.png"), output.join("example_1.png")).unwrap(); + let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"png"})).unwrap(); + assert_eq!(result, json!({"files":[output.join(format!("example_{counter}.png"))],"errors":[]})); + assert!(output.join("example.png").is_dir()); + #[cfg(unix)] + assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); + assert!(!output.join("missing.png").exists()); +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5e0d6b2ddb..de1da87809 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -1,4 +1,4 @@ -use super::batch_run::{BatchInput, batch_inputs_tree, process_document_copies, process_tree}; +use super::batch_run::{BatchInput, TreeNaming, batch_inputs_tree, process_document_copies, process_tree}; use super::open::import_opened; use super::paths::{file_name, list_images, read_file, stem, untitled_name}; use super::save::SaveOpts; @@ -13,6 +13,9 @@ mod image_processor_formats_tests; #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "image_processor_tests.rs"] mod image_processor_tests; +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "image_processor_unique_names_tests.rs"] +mod image_processor_unique_names_tests; #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "load_stack_name_tests.rs"] @@ -132,7 +135,7 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { }; let r = if source == "folder" { let inputs = batch_inputs_tree(p, cmd, &output)?; - process_tree(s, &inputs, &output, format, save, "", &process) + process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process) } else { let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() }; if documents.is_empty() { @@ -246,7 +249,7 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - Ok(false) }; let mut result = match &inputs { - ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, "", &process), + ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, TreeNaming::Unique, &process), ProcessorInputs::Documents(documents) => process_document_copies(s, documents, output, format.extension, format.save, &process), }; if let Some(Value::Array(written)) = result.get_mut("files").map(Value::take) { From 147ae5c04c1b3c792fb61f74e241da9690f9d9b6 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:46:01 +0000 Subject: [PATCH 097/385] Compare Image Processor paths using native path semantics --- .../image_processor_unique_names_tests.rs | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 296426eb8b..25d0a15f27 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -1,12 +1,21 @@ -use std::{fs, path::Path, sync::Barrier, thread}; +use std::{ + fs, + path::{Path, PathBuf}, + sync::Barrier, + thread, +}; -use serde_json::json; +use serde_json::{Value, json}; use crate::Session; const COMMAND: &str = "file.scripts.imageProcessor"; const PIXELS: &[u8] = b"P6\n2 1\n255\n\xff\0\0\0\xff\0"; +fn files(result: &Value) -> Result, serde_json::Error> { + serde_json::from_value(result["files"].clone()) +} + #[test] fn selects_the_first_free_suffix_and_reports_every_written_format() { let root = tempfile::tempdir().unwrap(); @@ -19,9 +28,11 @@ fn selects_the_first_free_suffix_and_reports_every_written_format() { } let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"jpeg":{},"psd":{},"tiff":{}})).unwrap(); let expected = ["a.b_2.jpg", "a.b.psd", "a.b_1.tif"]; - assert_eq!(result, json!({"files":expected.map(|name| output.join(name)), "errors":[]})); + assert_eq!(files(&result).unwrap(), expected.map(|name| output.join(name))); + assert_eq!(result["errors"], json!([])); let next = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"jpg"})).unwrap(); - assert_eq!(next, json!({"files":[output.join("a.b_4.jpg")], "errors":[]})); + assert_eq!(files(&next).unwrap(), [output.join("a.b_4.jpg")]); + assert_eq!(next["errors"], json!([])); for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { assert_eq!(fs::read(output.join(name)).unwrap(), name.as_bytes()); } @@ -45,15 +56,17 @@ fn same_stem_inputs_get_separate_results_without_changing_shared_processing() { } let mut session = Session::new(); let result = session.execute(COMMAND, json!({"input":[a,b],"output":output,"format":"png"})).unwrap(); - assert_eq!(result, json!({"files":[output.join("same.png"),output.join("same_1.png")],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join("same.png"), output.join("same_1.png")]); + assert_eq!(result["errors"], json!([])); let result = session.execute(COMMAND, json!({"input":source.path(),"output":output,"format":"png","includeSubfolders":true})).unwrap(); - assert_eq!(result, json!({"files":[output.join("a/same.png"),output.join("b/same.png")],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join("a/same.png"), output.join("b/same.png")]); + assert_eq!(result["errors"], json!([])); let legacy = source.path().join("legacy"); let inputs = [a.to_string_lossy().into_owned(), b.to_string_lossy().into_owned()]; let result = super::super::batch_run::process_files(&session, &inputs, &legacy.to_string_lossy(), "png", Default::default(), "", &|_| Ok(())); - assert_eq!(result["files"], json!([legacy.join("same.png")])); + assert_eq!(files(&result).unwrap(), [legacy.join("same.png")]); let errors = result["errors"].as_array().unwrap(); assert_eq!(errors.len(), 1); assert!(errors[0]["error"].as_str().unwrap().contains("same output name")); @@ -105,7 +118,8 @@ fn directory_and_dangling_symlink_names_stay_occupied() { #[cfg(unix)] std::os::unix::fs::symlink(output.join("missing.png"), output.join("example_1.png")).unwrap(); let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"png"})).unwrap(); - assert_eq!(result, json!({"files":[output.join(format!("example_{counter}.png"))],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join(format!("example_{counter}.png"))]); + assert_eq!(result["errors"], json!([])); assert!(output.join("example.png").is_dir()); #[cfg(unix)] assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); From 8138cccaa307153043ec1209fa9f06bf083a24d8 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:47:11 +0000 Subject: [PATCH 098/385] Report completed publications and cover failed inputs --- crates/engine/src/cmd/file_cmds/batch_run.rs | 37 +++++++++++-------- .../image_processor_unique_names_tests.rs | 33 +++++++++++++++++ 2 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 288a0b07f6..c19e6f9c1f 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -269,7 +269,12 @@ fn process_outputs<'a>( let options = ProcessOptions { format: None, written: (!unique).then_some(&written), ctx: None, input: None, unique }; let r = process_one(raw_ppi, path, &out, save, options, &run); match r { - Ok(Some(out)) => files.push(out), + Ok(Some(PublishedOutput { path: out, warning })) => { + if let Some(warning) = warning { + errors.push(json!({"file": path, "output": out, "error": warning})); + } + files.push(out); + } Ok(None) => { written.record(&out, path); files.push(out); @@ -357,12 +362,12 @@ fn process_one( save: SaveOpts, options: ProcessOptions<'_>, f: &dyn Fn(&mut Session, &str) -> std::result::Result, -) -> std::result::Result, FileFailure> { +) -> std::result::Result, FileFailure> { if let Some(written) = options.written { written.check(out).map_err(EngineError::Other)?; } let mut scratch = Session::new(); - let result = (|| -> std::result::Result, FileFailure> { + let result = (|| -> std::result::Result, FileFailure> { if let Some(input) = options.input { (input.prepare)(&mut scratch, path)?; } else { @@ -387,9 +392,9 @@ fn process_one( } let d = scratch.active().ok_or(EngineError::NoDocument)?; if options.unique { - let (bytes, mut warnings) = encode(&d.doc, out, save)?; - let actual = save_unique_output(out, &bytes, &mut warnings)?; - record_export_warnings(&mut scratch, &actual, warnings); + let (bytes, warnings) = encode(&d.doc, out, save)?; + let actual = save_unique_output(out, &bytes)?; + record_export_warnings(&mut scratch, &actual.path, warnings); return Ok(Some(actual)); } let warnings = if let Some(format) = options.format { @@ -407,11 +412,14 @@ fn process_one( result } -/// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore -/// leaves the current destination untouched; the worker owns the write once the checkpoint passes. +struct PublishedOutput { + path: String, + warning: Option, +} + /// Claim a destination atomically so another process creating it during export cannot lose its file. #[cfg(not(target_arch = "wasm32"))] -fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Result { +fn save_unique_output(out: &str, bytes: &[u8]) -> Result { use std::{fs, io::ErrorKind, path::Path}; let path = Path::new(out); @@ -431,11 +439,8 @@ fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Re Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), } match photocraft_format::write_noreplace(path, bytes) { - Ok(()) => return Ok(candidate), - Err(error) if error.published => { - warnings.push(error.to_string()); - return Ok(candidate); - } + Ok(()) => return Ok(PublishedOutput { path: candidate, warning: None }), + Err(error) if error.published => return Ok(PublishedOutput { path: candidate, warning: Some(error.to_string()) }), Err(error) if error.error.kind() == ErrorKind::AlreadyExists => {} Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), } @@ -444,10 +449,12 @@ fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Re } #[cfg(target_arch = "wasm32")] -fn save_unique_output(out: &str, _bytes: &[u8], _warnings: &mut Vec) -> Result { +fn save_unique_output(out: &str, _bytes: &[u8]) -> Result { Err(EngineError::Other(format!("cannot write {out}: no file system on the web"))) } +/// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore +/// leaves the current destination untouched; the worker owns the write once the checkpoint passes. fn save_batch_doc(doc: &Document, out: &str, format: &str, save: SaveOpts, ctx: &crate::jobs::JobCtx) -> Result> { let (bytes, warnings) = encode(doc, format, save)?; ctx.batch_before_write()?; diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 25d0a15f27..7f37fa827a 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -125,3 +125,36 @@ fn directory_and_dangling_symlink_names_stay_occupied() { assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); assert!(!output.join("missing.png").exists()); } + +#[test] +fn failed_input_does_not_claim_an_output_name() { + let root = tempfile::tempdir().unwrap(); + let corrupt = root.path().join("broken/same.ppm"); + let valid = root.path().join("good/same.ppm"); + fs::create_dir_all(corrupt.parent().unwrap()).unwrap(); + fs::create_dir_all(valid.parent().unwrap()).unwrap(); + fs::write(&corrupt, b"not an image").unwrap(); + fs::write(&valid, PIXELS).unwrap(); + let output = root.path().join("out"); + let result = Session::new().execute(COMMAND, json!({"input":[corrupt,valid],"output":output,"format":"png"})).unwrap(); + assert_eq!(files(&result).unwrap(), [output.join("same.png")]); + let errors = result["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0]["file"], json!(corrupt)); + assert_eq!(fs::read_dir(&output).unwrap().count(), 1); +} + +#[test] +fn current_and_open_document_sources_keep_their_output_naming() { + let root = tempfile::tempdir().unwrap(); + let mut session = Session::new(); + session.execute("file.new", json!({"name":"Current", "width":2, "height":2})).unwrap(); + for source in ["current", "open"] { + let out = root.path().join("Current.png"); + fs::write(&out, b"old output").unwrap(); + let result = session.execute(COMMAND, json!({"source":source,"output":root.path(),"format":"png"})).unwrap(); + assert_eq!(files(&result).unwrap(), [out.clone()]); + assert_eq!(result["errors"], json!([])); + assert!(photocraft_io::import("Current.png", &fs::read(out).unwrap()).is_ok()); + } +} From 207d6882e50df03c0098f086f3b3fb8e76e28c67 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:53:39 +0000 Subject: [PATCH 099/385] Avoid cloning the expected output path --- .../src/cmd/file_cmds/image_processor_unique_names_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 7f37fa827a..9d9576a476 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -153,7 +153,7 @@ fn current_and_open_document_sources_keep_their_output_naming() { let out = root.path().join("Current.png"); fs::write(&out, b"old output").unwrap(); let result = session.execute(COMMAND, json!({"source":source,"output":root.path(),"format":"png"})).unwrap(); - assert_eq!(files(&result).unwrap(), [out.clone()]); + assert_eq!(files(&result).unwrap().as_slice(), std::slice::from_ref(&out)); assert_eq!(result["errors"], json!([])); assert!(photocraft_io::import("Current.png", &fs::read(out).unwrap()).is_ok()); } From fd11847db35212639ab933fd5df679b1809e3c9d Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 20:01:43 +0000 Subject: [PATCH 100/385] Keep the shared collision regression scoped to unchanged commands --- crates/engine/src/cmd/file_cmds/tests.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index f5fd3abe65..09f4ca1f06 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3382,8 +3382,7 @@ fn batch_naming_serial_keeps_same_named_inputs_and_their_pixels() { } } -/// Batch follows Photoshop's later-file-wins behavior. Image Processor and lens correction -/// keep their existing collision error so their outputs are never silently replaced. +/// Batch follows Photoshop's later-file-wins behavior. Lens correction reports collisions. #[test] fn batch_reports_inputs_that_share_an_output_name() { let dir = tmp("collide"); @@ -3397,7 +3396,6 @@ fn batch_reports_inputs_that_share_an_output_name() { png(&input, "b.tif", 8, 8, "#00ff00"); for (cmd, extra) in [ ("file.automate.batch", json!({"steps": [], "format": "jpg"})), - ("file.scripts.imageProcessor", json!({})), ("file.automate.lensCorrection", json!({"format": "jpg"})), ] { let out = join(&dir, cmd); From 25ea9a96ca20266fe2e68b655e52d8714f1931d4 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 20:11:01 +0000 Subject: [PATCH 101/385] Format the updated Batch collision regression --- crates/engine/src/cmd/file_cmds/tests.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 09f4ca1f06..51bde7b41a 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3394,10 +3394,7 @@ fn batch_reports_inputs_that_share_an_output_name() { save_doc(doc(&s), &join(&input, "a.jpg"), None).unwrap(); png(&input, "B.png", 8, 8, "#00ff00"); png(&input, "b.tif", 8, 8, "#00ff00"); - for (cmd, extra) in [ - ("file.automate.batch", json!({"steps": [], "format": "jpg"})), - ("file.automate.lensCorrection", json!({"format": "jpg"})), - ] { + for (cmd, extra) in [("file.automate.batch", json!({"steps": [], "format": "jpg"})), ("file.automate.lensCorrection", json!({"format": "jpg"}))] { let out = join(&dir, cmd); let mut p = extra; p["input"] = json!(input); From c3038610f840dfb7882ac0d02aeb7551840dd51f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 14 Nov 2026 21:31:15 +0100 Subject: [PATCH 102/385] fix(io): poll the interrupt on the indexed GIF export route The indexed Color route renders and encodes on its own path, ahead of the ordinary one, and never looked at the export interrupt. A cancel that landed while it worked was noticed only after the whole GIF was rendered and encoded. The route now checks the interrupt before the render, per rendered band and before the encoder (#11861 review). --- crates/io/src/flat.rs | 9 +++++++-- crates/io/tests/it/modes.rs | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index f953032ead..95c71cc48d 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -1738,7 +1738,7 @@ pub fn export_flat_with_renderer( ctl: &photocraft_raster::Interrupt, mut renderer: Option<&mut dyn BandRenderer>, ) -> Result { - if let Some(mut r) = export_mode_specific(doc, format, opts)? { + if let Some(mut r) = export_mode_specific(doc, format, opts, ctl)? { // Palette PNG/BMP/GIF and Duotone exports render on their own paths before the renderer // branch: say so, or `--gpu` would silently do nothing for them. if let Some(renderer) = &mut renderer { @@ -2360,7 +2360,7 @@ fn gif_dropped_metadata(doc: &Document, opts: &ExportOptions) -> Vec { /// Indexed Color → PNG-8, an 8-bit BMP or a GIF with the document's colour table; Duotone → the /// inks rendered as RGB. -fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> Result, IoError> { +fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result, IoError> { match doc.mode { ColorMode::Indexed if matches!(format, Format::Png | Format::Bmp | Format::Gif) => { let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) }; @@ -2370,8 +2370,12 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> let (opaque_indices, colors): (Vec, Vec<_>) = table.colors.iter().copied().enumerate().filter(|(i, _)| Some(*i) != transparent_index).map(|(i, c)| (i as u8, c)).unzip(); let opaque = photocraft_doc::ColorTable { colors, transparent: None }; + // This route renders and encodes on its own, so it polls `ctl` itself: before the + // render, per band and before the encoder (#11861 review). + ctl.check().map_err(|_| IoError::Cancelled)?; let mut idx = try_buffer(doc.size.area() as usize, 1)?; photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; for p in &band.px { let i = match table.transparent { Some(t) if p[3] < 0.5 => t, @@ -2383,6 +2387,7 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> } Ok(()) })?; + ctl.check().map_err(|_| IoError::Cancelled)?; if format == Format::Bmp { let bytes = codecs::encode_bmp_indexed(doc.size.width, doc.size.height, &idx, &table.colors)?; let mut warnings = vec![format!("written as an 8-bit palette BMP ({} colours)", table.colors.len())]; diff --git a/crates/io/tests/it/modes.rs b/crates/io/tests/it/modes.rs index 07e23a5aed..63c1a487d8 100644 --- a/crates/io/tests/it/modes.rs +++ b/crates/io/tests/it/modes.rs @@ -317,6 +317,29 @@ fn indexed_gif_pads_the_palette_through_a_transparent_index_beyond_it() { assert_eq!(back.color_table.as_ref().unwrap().transparent, Some(5)); } +#[test] +fn indexed_gif_export_polls_the_interrupt_while_it_renders() { + // #11861 review: the indexed GIF route renders and encodes on its own path. `export_with` + // refuses an already-cancelled export up front and again at the end, so a cancel that lands + // while the route works used to be noticed only after the whole GIF was rendered and encoded. + // The route now polls between its stages: the interrupt is asked before the render, per + // rendered band and before the encoder, on top of `export_with`'s own two checks. + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0]], transparent: None }); + let polls = std::sync::atomic::AtomicU32::new(0); + let counting = || { + polls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + false + }; + let ok = photocraft_io::export_with(&d, "x.gif", &Default::default(), &photocraft_raster::Interrupt::cancel_only(&counting)); + assert!(ok.is_ok(), "{:?}", ok.map(|r| r.bytes.len())); + let n = polls.load(std::sync::atomic::Ordering::Relaxed); + assert!(n >= 5, "export_with polls twice; the route adds a poll before render, per band and before encode: {n}"); + // Cancelled from the start: the export stops with `Cancelled`. + let yes = || true; + let r = photocraft_io::export_with(&d, "x.gif", &Default::default(), &photocraft_raster::Interrupt::cancel_only(&yes)); + assert!(matches!(r, Err(photocraft_io::IoError::Cancelled)), "{:?}", r.map(|r| r.bytes.len())); +} #[test] fn indexed_gif_keeps_the_transparent_index() { let mut d = Document::with_background("m", Size::new(2, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(1.0, 0.0, 0.0, 1.0)); From 9128a7c34f8395bc98d6d83825538ca421cb89b2 Mon Sep 17 00:00:00 2001 From: Lcoding15 <125505497+Lcoding15@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:00:13 +0100 Subject: [PATCH 103/385] fix(color): Convert to Profile is greyed and refused for Bitmap documents (#14263) --- crates/engine/src/cmd/color_cmds.rs | 19 ++++++++- .../convert_profile_bitmap_tests.rs | 42 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/color_cmds/convert_profile_bitmap_tests.rs diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index 3f4cfa0083..14193e8e2f 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -1005,6 +1005,16 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } +/// Edit > Convert to Profile: a document open, and not in Bitmap mode, where the reference +/// application greys it (#14263). +fn convert_profile_enabled(s: &Session) -> std::result::Result<(), String> { + let doc = &s.active().ok_or("no document open")?.doc; + if doc.mode == ColorMode::Bitmap { + return Err("Convert to Profile is not available for Bitmap documents".into()); + } + Ok(()) +} + fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) } @@ -1111,6 +1121,10 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result { .and_then(Value::as_str) .ok_or_else(|| EngineError::BadParams { cmd: "edit.convertToProfile".into(), msg: "missing `profile`".into() })?; let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + // Also for a caller that runs it without the enabled check (#14263). + if doc.mode == ColorMode::Bitmap { + return Err(EngineError::Other("Convert to Profile is not available for Bitmap documents".into())); + } let dst = s.color.resolve(spec, Some(doc), None)?; let intent = intent_or(p, s.color.settings.intent())?; let bpc = bool_param(p, "bpc", s.color.settings.bpc); @@ -1344,7 +1358,7 @@ pub fn specs() -> Vec { "Convert to Profile…", ["Edit"], r##"{"profile":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020|gray-gamma-2.2|sgray|lab-d50|coated-cmyk|working" (or a path to an .icc file),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"dither":bool=false (deterministic color quantization for 8-bit profile changes),"flatten":bool=false (flatten in the source profile before conversion),"rasterizePlaced":bool=false (freeze displayed Smart Object pixels; flatten takes precedence)}"##, - has_doc, + convert_profile_enabled, convert_to_profile, true ), @@ -1927,3 +1941,6 @@ mod settings_tests { assert!(s.execute("color.profileMismatch", json!({"action": "explode"})).is_err()); } } + +#[cfg(test)] +mod convert_profile_bitmap_tests; diff --git a/crates/engine/src/cmd/color_cmds/convert_profile_bitmap_tests.rs b/crates/engine/src/cmd/color_cmds/convert_profile_bitmap_tests.rs new file mode 100644 index 0000000000..0aa50d9fe1 --- /dev/null +++ b/crates/engine/src/cmd/color_cmds/convert_profile_bitmap_tests.rs @@ -0,0 +1,42 @@ +//! #14263: Edit > Convert to Profile is greyed for a Bitmap document, and running it anyway is +//! refused with the mode named, leaving the document and its history as they were. The other +//! modes keep it. + +use super::*; + +fn bitmap() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Bitmap); + s +} + +#[test] +fn convert_to_profile_is_greyed_and_refused_for_bitmap() { + let mut s = bitmap(); + assert!(!s.is_enabled("edit.convertToProfile")); + assert!(s.disabled_reason("edit.convertToProfile").is_some_and(|why| why.contains("Bitmap"))); + let (doc, past) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len()); + let err = s.execute("edit.convertToProfile", json!({"profile": "sgray"})).unwrap_err().to_string(); + assert!(err.contains("Bitmap"), "{err}"); + assert_eq!(s.active().unwrap().doc, doc, "unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), past, "no history state"); + // The command itself refuses too, for a caller that skips the enabled check. + let err = convert_to_profile(&mut s, &json!({"profile": "sgray"})).unwrap_err().to_string(); + assert!(err.contains("Bitmap"), "{err}"); +} + +#[test] +fn convert_to_profile_stays_enabled_for_the_other_modes() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("grayscale", 16), ("lab", 8), ("indexedColor", 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "white"})).unwrap(); + if mode != "rgb" { + s.execute(&format!("image.mode.{mode}"), json!({})).unwrap(); + } + assert!(s.is_enabled("edit.convertToProfile"), "{mode} {depth}-bit"); + } + assert!(!Session::new().is_enabled("edit.convertToProfile"), "no document"); +} From 549ba8c4f2f80d0b77176bdc70f2bcff0fe9495a Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 21:12:23 +0000 Subject: [PATCH 104/385] Find and Replace Text: search layers in the reference order (#14661) --- crates/engine/src/cmd/edit_menu_cmds.rs | 8 +- .../src/cmd/edit_menu_cmds/find_replace.rs | 94 ++++++---- .../find_replace_order_tests.rs | 162 ++++++++++++++++++ 3 files changed, 226 insertions(+), 38 deletions(-) create mode 100644 crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index b021ce0cc5..d93f5ed56c 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -59,8 +59,10 @@ pub struct EditState { pub fade: Option, /// Custom shape library (the vector tools read it). pub custom_shapes: Vec, - /// Find and Replace Text position: (layer, byte offset after the current match). + /// Find and Replace Text position: (layer, start byte, end byte of the current match). pub find_cursor: Option<(LayerId, usize, usize)>, + /// First layer visited in the current Find Next round (so wrapping stops before it). + pub find_start: Option, } /// Commands whose result Edit › Fade can blend back against the previous state. @@ -453,3 +455,7 @@ mod tests; #[cfg(test)] #[path = "edit_menu_cmds/fade_visibility_tests.rs"] mod fade_visibility_tests; + +#[cfg(test)] +#[path = "edit_menu_cmds/find_replace_order_tests.rs"] +mod find_replace_order_tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs index 4b9e3ace73..257a510bfc 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs @@ -37,19 +37,27 @@ pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usi out } -fn type_layers(doc: &Document, forward: bool) -> Vec { - // Layers panel order: top first. - let mut ids: Vec = - doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect(); - if !forward { - ids.reverse(); +fn type_layers(doc: &Document) -> Vec { + // Layers panel order: bottom to top (upward), with group contents in stack position. + doc.walk().into_iter().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect() +} + +/// Index in `layers` to start a new round from `active` (going upward in `doc.walk()`). +fn start_index(doc: &Document, layers: &[LayerId], active: Option) -> usize { + let Some(aid) = active else { return 0 }; + if let Some(pos) = layers.iter().position(|id| *id == aid) { + return pos; } - ids + let walk = doc.walk(); + let Some(active_walk) = walk.iter().position(|(_, _, l)| l.id == aid) else { + return 0; + }; + walk.iter().skip(active_walk + 1).find_map(|(_, _, l)| layers.iter().position(|id| *id == l.id)).unwrap_or(0) } pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; - if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } + if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } } pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { @@ -60,7 +68,8 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true)); let action = str_or(p, "action", "changeAll").to_string(); let st = s.active().ok_or(EngineError::NoDocument)?; - let mut layers = type_layers(&st.doc, forward); + let active_layer = st.active_layer; + let mut layers = type_layers(&st.doc); if !all_layers { let active = layer_param(s, p).ok(); layers.retain(|id| Some(*id) == active); @@ -93,6 +102,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { Ok(()) })?; s.edit_state.find_cursor = None; + s.edit_state.find_start = None; Ok(json!({"count": count, "layers": plan.len()})) } "find" | "change" | "changeFind" => { @@ -122,40 +132,50 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}})); } } - // Find the next match after the cursor (wrapping through the layers). + // Find the next match after the cursor (upward, wrapping once, stopping before the start layer). let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let cursor = s.edit_state.find_cursor; - let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0); - for k in 0..=layers.len() { - // `allLayers: false` with a non-type layer active leaves no layers to search (#703). - let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break }; - let Some(text) = text_of(&doc, id) else { continue }; - let ms = find_matches(&text, &find, case, whole); - let hit = match (k, cursor) { - (0, Some((cid, a, b))) if cid == id => { - if forward { - ms.into_iter().find(|m| m.0 >= b) - } else { - ms.into_iter().rev().find(|m| m.1 <= a) - } - } - _ => { - if forward { - ms.into_iter().next() - } else { - ms.into_iter().next_back() - } - } + if !layers.is_empty() { + let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or_else(|| start_index(&doc, &layers, active_layer)); + let origin = match cursor { + Some(_) => s.edit_state.find_start.filter(|o| layers.contains(o)).unwrap_or(layers[start]), + None => layers[start], }; - if let Some((a, b)) = hit { - s.edit_state.find_cursor = Some((id, a, b)); - let _ = s.select_layer(id); - return Ok( - json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), - ); + for k in 0..layers.len() { + let id = layers[(start + k) % layers.len()]; + if k > 0 && id == origin { + break; + } + let Some(text) = text_of(&doc, id) else { continue }; + let ms = find_matches(&text, &find, case, whole); + let hit = match (k, cursor) { + (0, Some((cid, a, b))) if cid == id => { + if forward { + ms.into_iter().find(|m| m.0 >= b) + } else { + ms.into_iter().rev().find(|m| m.1 <= a) + } + } + _ => { + if forward { + ms.into_iter().next() + } else { + ms.into_iter().next_back() + } + } + }; + if let Some((a, b)) = hit { + s.edit_state.find_cursor = Some((id, a, b)); + s.edit_state.find_start = Some(origin); + let _ = s.select_layer(id); + return Ok( + json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), + ); + } } } s.edit_state.find_cursor = None; + s.edit_state.find_start = None; Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))})) } other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs new file mode 100644 index 0000000000..b5dee10238 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs @@ -0,0 +1,162 @@ +use super::*; + +fn make_order_doc() -> (Session, [LayerId; 6], LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 500, "depth": 8, "background": "white"})).unwrap(); + let id_of = |v: Value| LayerId(v["layer"].as_u64().unwrap()); + + let t1 = id_of(s.execute("type.create", json!({"text": "cat Cat CAT cats", "x": 10, "y": 40, "size": 12})).unwrap()); + let t2 = id_of(s.execute("type.create", json!({"text": "the cat sat", "x": 10, "y": 80, "size": 12})).unwrap()); + let t5 = id_of(s.execute("type.create", json!({"box": [10, 100, 200, 80], "text": "concatenate cat", "size": 12})).unwrap()); + let t6 = id_of(s.execute("type.create", json!({"text": "café cafe", "x": 10, "y": 200, "size": 12})).unwrap()); + let t7 = id_of(s.execute("type.create", json!({"text": "dog", "x": 10, "y": 240, "size": 12})).unwrap()); + + // Group G1 holding T8, then an empty pixel layer on top. + let t8 = id_of(s.execute("type.create", json!({"text": "grouped cat", "x": 10, "y": 280, "size": 12})).unwrap()); + s.execute("layer.new.groupFromLayers", json!({"name": "G1", "layers": [t8.0]})).unwrap(); + let top_pixel = id_of(s.execute("layer.new.layer", json!({"name": "empty"})).unwrap()); + + // Verify bottom-to-top walk order of type layers is T1, T2, T5, T6, T7, T8. + let walked_type_ids: Vec = + s.active().unwrap().doc.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Text(_)).then_some(l.id)).collect(); + assert_eq!(walked_type_ids, vec![t1, t2, t5, t6, t7, t8]); + + (s, [t1, t2, t5, t6, t7, t8], top_pixel) +} + +fn find_next(s: &mut Session, forward: bool, all_layers: bool) -> Option<(LayerId, usize, usize, String)> { + let r = s + .execute( + "edit.findAndReplaceText", + json!({ + "find": "cat", + "action": "find", + "forward": forward, + "allLayers": all_layers, + "caseSensitive": false, + "wholeWord": false, + }), + ) + .unwrap(); + let f = r.get("found")?; + if f.is_null() { + return None; + } + let layer = LayerId(f["layer"].as_u64().unwrap()); + let start = f["start"].as_u64().unwrap() as usize; + let end = f["end"].as_u64().unwrap() as usize; + let text = f["text"].as_str().unwrap().to_string(); + assert_eq!(s.active().unwrap().active_layer, Some(layer)); + Some((layer, start, end, text)) +} + +fn collect_round(s: &mut Session, forward: bool, all_layers: bool) -> Vec<(LayerId, usize, usize, String)> { + let mut hits = Vec::new(); + while let Some(hit) = find_next(s, forward, all_layers) { + assert!(hits.len() < 32, "search did not terminate: {hits:?}"); + hits.push(hit); + } + hits +} + +#[test] +fn find_next_from_t1_forward_visits_upward_and_stops_at_end() { + let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t1.0})).unwrap(); + let history_before = s.active().unwrap().history.past_len(); + + let hits = collect_round(&mut s, true, true); + + assert_eq!( + hits, + vec![ + (t1, 0, 3, "cat".into()), + (t1, 4, 7, "Cat".into()), + (t1, 8, 11, "CAT".into()), + (t1, 12, 15, "cat".into()), + (t2, 4, 7, "cat".into()), + (t5, 3, 6, "cat".into()), + (t5, 12, 15, "cat".into()), + (t8, 8, 11, "cat".into()), + ] + ); + assert_eq!(s.active().unwrap().history.past_len(), history_before, "Find Next adds no history state"); + + // Next Find Next after the end starts a new round from the active layer (t8). + assert_eq!(find_next(&mut s, true, true), Some((t8, 8, 11, "cat".into()))); +} + +#[test] +fn find_next_from_t5_forward_wraps_and_stops_before_t5() { + let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t5.0})).unwrap(); + + let hits = collect_round(&mut s, true, true); + + assert_eq!( + hits, + vec![ + (t5, 3, 6, "cat".into()), + (t5, 12, 15, "cat".into()), + (t8, 8, 11, "cat".into()), + (t1, 0, 3, "cat".into()), + (t1, 4, 7, "Cat".into()), + (t1, 8, 11, "CAT".into()), + (t1, 12, 15, "cat".into()), + (t2, 4, 7, "cat".into()), + ] + ); +} + +#[test] +fn find_next_from_t5_backward_reverses_only_in_layer_matches() { + let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t5.0})).unwrap(); + + let hits = collect_round(&mut s, false, true); + + assert_eq!( + hits, + vec![ + (t5, 12, 15, "cat".into()), + (t5, 3, 6, "cat".into()), + (t8, 8, 11, "cat".into()), + (t1, 12, 15, "cat".into()), + (t1, 8, 11, "CAT".into()), + (t1, 4, 7, "Cat".into()), + (t1, 0, 3, "cat".into()), + (t2, 4, 7, "cat".into()), + ] + ); +} + +#[test] +fn find_next_from_t7_backward_goes_upward_to_t8_first() { + let (mut s, [_t1, _t2, _t5, _t6, t7, t8], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t7.0})).unwrap(); + + assert_eq!(find_next(&mut s, false, true), Some((t8, 8, 11, "cat".into()))); +} + +#[test] +fn find_next_single_layer_and_change_all_preserved() { + let (mut s, [_t1, _t2, t5, _t6, _t7, _t8], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t5.0})).unwrap(); + + let fwd = collect_round(&mut s, true, false); + assert_eq!(fwd, vec![(t5, 3, 6, "cat".into()), (t5, 12, 15, "cat".into())]); + + let bwd = collect_round(&mut s, false, false); + assert_eq!(bwd, vec![(t5, 12, 15, "cat".into()), (t5, 3, 6, "cat".into())]); + + let r = s.execute("edit.findAndReplaceText", json!({"find": "cat", "replace": "fox", "action": "changeAll"})).unwrap(); + assert_eq!((r["count"].as_u64(), r["layers"].as_u64()), (Some(8), Some(4))); +} + +#[test] +fn find_next_from_top_pixel_layer_wraps_to_bottom_type_layer() { + let (mut s, [t1, ..], top_pixel) = make_order_doc(); + s.execute("layer.select", json!({"layer": top_pixel.0})).unwrap(); + + assert_eq!(find_next(&mut s, true, true), Some((t1, 0, 3, "cat".into()))); +} From 8e027f6ec015ab289f42ec49bcd98b73662c6dd6 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 14 Nov 2026 23:38:04 +0100 Subject: [PATCH 105/385] fix(ui): Reset to Default keeps the shared light angle The Layer Style dialog's Reset to Default copied the effect's stored or factory defaults over the instance as they are. Those carry their own `angle` (120 for the factory), so on a Bevel & Emboss page with Use Global Light on and Angle 45 the field jumped to 120 while the dialog still applied the shared light 45 on OK: field and result disagreed, and the page no longer matched the other globally lit effects. Seed the dialog's shared light angle into a globally lit effect during the reset, the way fresh_params already does for a new instance: the Angle field stays at 45, OK keeps the document's Global Light at 45, and every other field still returns to its (Make-)Default. An effect with Use Global Light off keeps the angle its default carries. Fixes #14843 --- crates/ui-egui/src/dialogs/layer_style.rs | 27 +++++- .../layer_style/bevel_reset_angle_tests.rs | 87 +++++++++++++++++++ 2 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 65772e1573..4f3c4f252a 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -23,6 +23,8 @@ use crate::{PhotocraftApp, widgets}; #[cfg(test)] mod bevel_modes_tests; +#[cfg(test)] +mod bevel_reset_angle_tests; pub(crate) mod color_picker; mod contour; mod gradient_field; @@ -102,6 +104,25 @@ fn fresh_params(kind: &str, light: f32, user: Option<&Value>) -> Value { p } +/// The shared light angle the dialog works with: the one edited since it opened, else the +/// document's. +fn light_angle(f: &Map) -> f64 { + f.get("pendingGlobalLight").or_else(|| f.get("globalLight")).and_then(Value::as_f64).unwrap_or(120.0) +} + +/// The defaults Reset to Default lays over an instance, with the shared light angle seeded into a +/// globally lit effect: the stored default carries its own `angle` (120 for the factory), and an +/// effect lit by the global light shows and keeps the shared angle instead — the same rule +/// [`fresh_params`] follows for a new instance (#14843). +fn default_params(f: &Map, mut params: Value) -> Value { + if params.get("useGlobalLight").and_then(Value::as_bool) == Some(true) + && let Some(o) = params.as_object_mut() + { + o.insert("angle".into(), json!(light_angle(f))); + } + params +} + fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { const POS: &[(&str, &str)] = &[("outside", "Outside"), ("inside", "Inside"), ("center", "Center")]; const GSTYLE: &[(&str, &str)] = &[("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")]; @@ -1777,9 +1798,11 @@ fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, ui.add_enabled_ui(page_kind, |ui| { if crate::widgets::secondary_button(ui, tl!("Reset to Default"), 130.0).clicked() && let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": sel_kind})) - && let Some(e) = entry_mut(f, selected) { - e["params"] = v["params"].clone(); + let params = default_params(f, v.get("params").cloned().unwrap_or(Value::Null)); + if let Some(e) = entry_mut(f, selected) { + e["params"] = params; + } } if crate::widgets::secondary_button(ui, tl!("Make Default"), 110.0).clicked() && app.run("layer.layerStyle.makeDefault", json!({"kind": sel_kind, "params": disp})).is_ok() diff --git a/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs new file mode 100644 index 0000000000..06ca7d5a37 --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs @@ -0,0 +1,87 @@ +//! #14843: Reset to Default on the Bevel & Emboss page replaced the page with the factory +//! defaults as they are, and those carry `angle: 120`. With Use Global Light on and Angle 45, the +//! field jumped to 120 while the dialog still applied the shared light 45 on OK, so field and +//! result disagreed. The reset now seeds the shared light angle into a globally lit effect, the +//! way a new instance starts from it (`fresh_params`). +use egui::vec2; +use egui_kittest::kittest::Queryable; + +use super::*; + +fn app_with_doc() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app +} + +/// The dialog body as it draws the selected page, so the real Reset to Default button is clicked. +fn draw_page(ui: &mut egui::Ui, state: &mut (PhotocraftApp, Map)) { + // The harness draws once before setup_context installs the app fonts. + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("semibold".into()))) { + body(&mut state.0, ui, &mut state.1); + } +} + +/// Use Global Light on, Angle 45 typed: Reset to Default keeps 45 and returns every other field +/// to its default; the other globally lit effect keeps the shared angle, and OK leaves the +/// document's Global Light at 45. +#[test] +fn reset_to_default_keeps_the_typed_shared_angle() { + let mut app = app_with_doc(); + app.run("layer.layerStyle.bevelEmboss", json!({})).unwrap(); + app.run("layer.layerStyle.dropShadow", json!({})).unwrap(); + let fields = { + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap(); + let mut f = initial_fields(layer, Some("bevelEmboss"), state.doc.global_light.angle); + // What the Angle row does when 45 is typed, plus two edits the reset has to undo. + set_param(&mut f, "fx1", "angle", json!(45.0)); + set_param(&mut f, "fx1", "depth", json!(40.0)); + set_param(&mut f, "fx1", "size", json!(9.0)); + assert_eq!(f["pendingGlobalLight"], json!(45.0), "fx1 and fx2 share 45"); + f + }; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 1200.0)).build_ui_state(draw_page, (app, fields)); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + harness.get_by_role_and_label(egui::accesskit::Role::Button, "Reset to Default").click(); + harness.run_steps(3); + let bevel = &harness.state().1["effects"][0]["params"]; + assert_eq!(bevel["angle"], json!(45.0), "the Angle field stays at the shared light angle"); + assert_eq!(bevel["useGlobalLight"], json!(true), "Use Global Light stays on"); + assert_eq!(harness.state().1["effects"][1]["params"]["angle"], json!(45.0), "the drop shadow keeps the shared angle"); + for (key, want) in [("depth", json!(100)), ("size", json!(5)), ("soften", json!(0)), ("altitude", json!(30)), ("style", json!("inner"))] { + assert_eq!(bevel[key], want, "{key} went back to its default"); + } + let (app, pending) = harness.state_mut(); + confirm(app, pending).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 45.0, "OK sets the document's Global Light to 45"); +} + +/// The document's light already at 45 when the dialog opens, nothing typed: Reset to Default still +/// shows 45, and OK leaves the document at 45 instead of moving its Global Light to the factory 120. +#[test] +fn reset_to_default_does_not_move_the_documents_light() { + let mut app = app_with_doc(); + app.run("layer.layerStyle.bevelEmboss", json!({})).unwrap(); + app.run("layer.layerStyle.globalLight", json!({"angle": 45})).unwrap(); + let fields = { + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap(); + let f = initial_fields(layer, Some("bevelEmboss"), state.doc.global_light.angle); + assert_eq!(f["effects"][0]["params"]["angle"], json!(45.0), "the page shows the shared light 45"); + f + }; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 1200.0)).build_ui_state(draw_page, (app, fields)); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + harness.get_by_role_and_label(egui::accesskit::Role::Button, "Reset to Default").click(); + harness.run_steps(3); + let bevel = &harness.state().1["effects"][0]["params"]; + assert_eq!(bevel["angle"], json!(45.0), "the Angle field stays at the document's light angle"); + assert_eq!(bevel["size"], json!(5), "the other fields still go back to their defaults"); + let (app, pending) = harness.state_mut(); + confirm(app, pending).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 45.0, "OK keeps the document's Global Light at 45"); +} From fbdeaff8e6a12b5b8954a293a871d4cb21dc0443 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 00:10:19 +0100 Subject: [PATCH 106/385] fix(engine): Layer from Background takes the lowest free Layer N layer_from_background named the converted layer through the shared unlock_background, which always writes "Layer 0". A document whose layer above the Background is already named "Layer 0" therefore ended up with two layers of that name, through the menu entry, the Background row's double-click and its lock icon alike. Name the converted layer "Layer N" with the lowest N of 0 or more that no other top-level layer is named, as the reference application does: with one other layer named Top it is "Layer 0", a taken "Layer 0" gives "Layer 1", "Layer 1" gives "Layer 0", "Layer 5" gives "Layer 0", and "Layer 0" plus "Layer 1" give "Layer 2". Document::next_layer_name counts from 1, so the command needs its own 0-based helper, kept next to the command: the other callers of unlock_background and background_to_layer (an edit the Background cannot take, artboards, the crop) keep naming the layer "Layer 0" as today, and a test pins that. Only top-level names are compared, and compared exactly as written. Whether a name inside a group, or the same name in other capitals, blocks a number is not measured in #14821, so the search keeps the scope of the measured cases; asked on the issue. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/extra_cmds.rs | 24 +++++- .../cmd/layer_from_background_name_tests.rs | 84 +++++++++++++++++++ 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/layer_from_background_name_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 36a1081edd..91db3a03b9 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -112,6 +112,8 @@ pub mod history_source_cmds; pub mod image_cmds; pub mod layer_copy_cmds; pub mod layer_css_cmds; +#[cfg(test)] +mod layer_from_background_name_tests; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 505048f6ae..ceaa6bf894 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -493,16 +493,36 @@ fn layer_from_background(s: &mut Session, p: &Value) -> Result { // names the Background while another layer is selected. let select = p.get("select").and_then(Value::as_bool).unwrap_or(true); let id = s.edit("Layer From Background", |doc, active| { + let bg = doc.background().ok_or(EngineError::Other("the document has no Background layer".into()))?; + let (id, name) = (bg.id, lowest_free_layer_name(doc, bg.id)); + // The name is read before the layer is unlocked, from the other layers' names. let l = doc.background_mut().ok_or(EngineError::Other("the document has no Background layer".into()))?; unlock_background(l); + l.name = name; if select || active.is_none() { - *active = Some(l.id); + *active = Some(id); } - Ok(l.id) + Ok(id) })?; Ok(json!({"layer": id.0})) } +/// The name `layer_from_background` gives the converted Background: "Layer N" with the lowest N of +/// 0 or more that no other top-level layer is named (#14821). `Document::next_layer_name` counts +/// from 1, so this is the 0-based variant the issue measures; it lives next to the command because +/// the rule is the command's alone - the other callers of `unlock_background` / +/// `background_to_layer` (an edit the Background can't take, artboards, the crop) keep naming the +/// layer "Layer 0" as today. +/// +/// Only top-level names count, and they are compared exactly: whether a name inside a group, or a +/// name written with other capitals ("LAYER 1"), blocks a number is not measured in #14821 (asked +/// on the issue), so the search stays with the measured cases. +fn lowest_free_layer_name(doc: &Document, renamed: LayerId) -> String { + let taken: std::collections::HashSet<&str> = doc.layers.iter().filter(|l| l.id != renamed).map(|l| l.name.as_str()).collect(); + // At most `taken.len() + 1` names from 0 are needed, so the search always succeeds. + (0..=taken.len()).map(|n| format!("Layer {n}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| "Layer".to_string()) +} + pub(crate) fn unlock_background(l: &mut Layer) { l.name = "Layer 0".into(); l.locks.transparency = false; diff --git a/crates/engine/src/cmd/layer_from_background_name_tests.rs b/crates/engine/src/cmd/layer_from_background_name_tests.rs new file mode 100644 index 0000000000..84e4e35f9f --- /dev/null +++ b/crates/engine/src/cmd/layer_from_background_name_tests.rs @@ -0,0 +1,84 @@ +//! #14821: Layer > New > Layer from Background names the converted layer "Layer N", with the +//! lowest free N counting from 0. Today `unlock_background` (`extra_cmds.rs`) always writes +//! "Layer 0", so a document that already has a layer of that name ends up with two layers called +//! "Layer 0". +//! +//! The five cases below are the ones measured in the issue. `Document::next_layer_name` counts from +//! 1, so the command needs its own 0-based rule. +//! +//! Not measured in the issue: whether a name inside a group takes part in the search, and whether a +//! differently cased name ("LAYER 1") counts as taken. Both keep the reading the measured cases +//! support: top-level layer names only, compared exactly, as `next_layer_name` compares them. The +//! group case is asked about on the issue. + +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::Session; + +fn doc(s: &Session) -> &photocraft_doc::Document { + &s.active().unwrap().doc +} + +/// A document with the white Background `file.new` makes and top-level layers named `others` above +/// it, then Layer from Background: the name the converted Background ends with. +fn converted_name(others: &[&str]) -> String { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + for n in others { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.setProps", json!({"layer": id.0, "name": n})).unwrap(); + } + assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), others, "the other layers are named as the issue's test document"); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + doc(&s).layer(bg).unwrap().name.clone() +} + +#[test] +fn the_name_is_the_lowest_layer_n_that_no_other_layer_uses() { + let cases: Vec<(Vec<&str>, &str)> = vec![ + (vec!["Top"], "Layer 0"), + (vec!["Layer 0"], "Layer 1"), + (vec!["Layer 1"], "Layer 0"), + (vec!["Layer 5"], "Layer 0"), + (vec!["Layer 0", "Layer 1"], "Layer 2"), + ]; + for (others, want) in cases { + assert_eq!(converted_name(&others), want, "other layers: {others:?}"); + } +} + +#[test] +fn a_document_that_is_only_a_background_takes_layer_0() { + assert_eq!(converted_name(&[]), "Layer 0"); +} + +#[test] +fn undo_restores_the_background_with_its_old_name() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + s.execute("layer.new.layer", json!({"name": "Layer 0"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + assert_eq!(doc(&s).layer(bg).unwrap().name, "Layer 1", "the taken name is skipped"); + assert!(s.undo(), "one history step"); + let l = doc(&s).layer(bg).unwrap(); + assert!(doc(&s).is_background(bg) && l.name == "Background", "the Background is back, named as before"); +} + +#[test] +fn the_other_callers_of_unlock_background_still_name_it_layer_0() { + // #14821 changes only Layer from Background. An edit the Background cannot take converts it + // through `background_to_layer`, which names it "Layer 0" as today, even when that name is + // already taken. + for (key, value) in [("opacity", json!(0.5)), ("fill", json!(0.5)), ("blend", json!("Multiply"))] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + s.execute("layer.new.layer", json!({"name": "Layer 0"})).unwrap(); + s.execute("layer.setProps", json!({"layer": bg.0, key: value})).unwrap(); + let l = doc(&s).layer(bg).unwrap(); + assert!(!doc(&s).is_background(bg) && l.name == "Layer 0", "{key}: still named Layer 0 as today"); + } +} From ac625c518c54a988c8974aae6a324d4557cf8706 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 22:26:09 +0000 Subject: [PATCH 107/385] compose: preserve gradient colour lightness for Grayscale Gradient Map (#14698) --- crates/compose/src/adjust.rs | 8 +- crates/compose/src/adjust/channels.rs | 7 + .../adjust/gradient_map_grayscale_tests.rs | 124 ++++++++++++++++++ 3 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 crates/compose/src/adjust/gradient_map_grayscale_tests.rs diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 7b6e207d3e..fd6a957654 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -20,7 +20,7 @@ pub use channels::{ LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, ink_brightness_contrast_lut, ink_luma, ink_through, lab_channel_adjustment, lab_stored_op, stored_channel_adjustment, stored_channels, threshold_white, }; -use channels::{apply_lab, legacy_brightness_contrast, legacy_brightness_contrast_hdr}; +use channels::{apply_lab, gray_from_srgb_lightness, legacy_brightness_contrast, legacy_brightness_contrast_hdr}; use color::gradient; pub use color::{ BalanceCurve, VIBRANCE_BOOST, VIBRANCE_GREY, bayer4, black_white_gray, color_balance_channel, colorize_saturation, hdr_saturation_factor, hsl_to_rgb, @@ -248,6 +248,7 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept } Adjustment::GradientMap { stops, reverse, dither, .. } => { let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0); + let gray_lightness = mode == ColorMode::Grayscale && depth != Some(SampleType::F32); for (i, p) in buf.px.iter_mut().enumerate() { if p[3] <= 0.0 { continue; @@ -260,6 +261,9 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept t = 1.0 - t; } let mut o = gradient(stops, t); + if gray_lightness { + o = gray_from_srgb_lightness(o); + } if *dither { let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0; o = o.map(|v| (v + d).clamp(0.0, 1.0)); @@ -396,6 +400,8 @@ mod lookup_tests { } } +#[cfg(test)] +mod gradient_map_grayscale_tests; #[cfg(test)] mod tone_tests; diff --git a/crates/compose/src/adjust/channels.rs b/crates/compose/src/adjust/channels.rs index 54ff3b1cf8..87ed60eb03 100644 --- a/crates/compose/src/adjust/channels.rs +++ b/crates/compose/src/adjust/channels.rs @@ -183,6 +183,13 @@ pub(super) fn lab_denorm(n: [f32; 3]) -> [f32; 3] { /// Neutral a or b as Lab surfaces store it ((0 + 128) / 255). pub const LAB_NEUTRAL: f32 = 128.0 / 255.0; +/// Lightness-preserving neutral gray for an sRGB Gradient Map stop colour in an 8/16-bit +/// Grayscale document: keeps the colour's CIE L* instead of Rec. 601 luma. +pub(super) fn gray_from_srgb_lightness(c: [f32; 3]) -> [f32; 3] { + let l = srgb_to_lab(c)[0]; + [lab_to_srgb([l, 0.0, 0.0])[0]; 3] +} + /// An adjustment Photoshop evaluates on a Lab document's own channels, as an operation on one /// pixel's stored L, a, b (normalised as Lab surfaces store them: L / 100, (a + 128) / 255, /// (b + 128) / 255) in a document of `depth`: Invert and Posterize (each channel), Threshold diff --git a/crates/compose/src/adjust/gradient_map_grayscale_tests.rs b/crates/compose/src/adjust/gradient_map_grayscale_tests.rs new file mode 100644 index 0000000000..44338bd29d --- /dev/null +++ b/crates/compose/src/adjust/gradient_map_grayscale_tests.rs @@ -0,0 +1,124 @@ +use photocraft_color::convert::{linear_to_srgb, srgb_to_lab}; +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Size}; +use photocraft_raster::Surface; + +use super::{Transfer, apply_depth, apply_in}; +use crate::{Buffer, Rect, flatten_to_surface}; + +fn render_grayscale_strips(depth: SampleType, strips: &[u8], adj: Adjustment) -> Vec { + let w = strips.len() as u32; + let mut doc = Document::new("gray", Size::new(w, 1), ColorMode::Grayscale, depth); + let fmt = doc.pixel_format(); + let mut base = Layer::raster("strips", fmt); + let mut s = Surface::new(fmt); + for (x, &v) in strips.iter().enumerate() { + s.write_pixel(x as i32, 0, &[f32::from(v) / 255.0, 1.0]); + } + base.content = LayerContent::Raster(s); + doc.layers.push(base); + doc.layers.push(Layer::new("gm", LayerContent::Adjustment(adj))); + + let flat = flatten_to_surface(&doc, PixelFormat::new(ColorMode::Grayscale, depth, false), Some([1.0; 3])); + (0..w).map(|x| flat.pixel(x as i32, 0)[0]).collect() +} + +fn gray_lstar(g: f32) -> f32 { + srgb_to_lab([g, g, g])[0] +} + +fn linear_red_to_blue_stops() -> Vec<(f32, [f32; 3])> { + (0u8..=255) + .map(|i| { + let t = f32::from(i) / 255.0; + (t, [linear_to_srgb(1.0 - t), 0.0, linear_to_srgb(t)]) + }) + .collect() +} + +#[test] +fn grayscale_8_and_16_bit_red_to_blue_uses_gradient_lightness() { + let strips = [16u8, 48, 80, 112, 144, 176, 208, 240]; + let adj = Adjustment::GradientMap { stops: linear_red_to_blue_stops(), reverse: false, dither: false, source: None }; + + let g8 = render_grayscale_strips(SampleType::U8, &strips, adj.clone()); + let g16 = render_grayscale_strips(SampleType::U16, &strips, adj); + + let l_first = gray_lstar(g8[0]); + let l_last = gray_lstar(g8[strips.len() - 1]); + assert!((l_first - 53.0).abs() <= 1.0, "strip 16: gray {} (L* {l_first:.2}), expected L* 53 ± 1", g8[0] * 255.0); + assert!((l_last - 31.0).abs() <= 1.0, "strip 240: gray {} (L* {l_last:.2}), expected L* 31 ± 1", g8[strips.len() - 1] * 255.0); + + for (i, (&a, &b)) in g8.iter().zip(&g16).enumerate() { + assert!((a - b).abs() <= 1.0 / 255.0 + 1e-4, "strip {} differs between 8-bit ({a}) and 16-bit ({b})", strips[i]); + } + for w in g16.windows(2) { + assert!(w[0] > w[1], "lightness should fall from red to blue: {g16:?}"); + } +} + +#[test] +fn grayscale_black_to_white_maps_each_gray_to_itself() { + let strips = [0u8, 16, 48, 80, 112, 128, 144, 176, 208, 240, 255]; + let adj = Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false, dither: false, source: None }; + for depth in [SampleType::U8, SampleType::U16] { + let out = render_grayscale_strips(depth, &strips, adj.clone()); + for (&want, &got) in strips.iter().zip(&out) { + let got_255 = got * 255.0; + assert!((got_255 - f32::from(want)).abs() <= 1.0, "{depth:?}: gray {want} mapped to {got_255:.2}"); + } + } +} + +#[test] +fn grayscale_reverse_and_dither_work_with_lightness() { + let adj_rev = Adjustment::GradientMap { stops: linear_red_to_blue_stops(), reverse: true, dither: false, source: None }; + let out = render_grayscale_strips(SampleType::U8, &[16, 240], adj_rev); + assert!((gray_lstar(out[0]) - 31.0).abs() <= 1.0, "reversed strip 16 L* {}", gray_lstar(out[0])); + assert!((gray_lstar(out[1]) - 53.0).abs() <= 1.0, "reversed strip 240 L* {}", gray_lstar(out[1])); + + let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])]; + let mut plain = Buffer::filled(Rect::new(0, 0, 16, 1), [0.5, 0.5, 0.5, 1.0]); + let mut dithered = plain.clone(); + apply_in( + &Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false, source: None }, + &mut plain, + Transfer::Gamma(1.732), + Some(SampleType::U8), + ColorMode::Grayscale, + ); + apply_in( + &Adjustment::GradientMap { stops, reverse: false, dither: true, source: None }, + &mut dithered, + Transfer::Gamma(1.732), + Some(SampleType::U8), + ColorMode::Grayscale, + ); + assert!(plain.px.iter().zip(&dithered.px).all(|(a, b)| (a[0] - b[0]).abs() <= 0.5 / 255.0 + 1e-6)); + assert!(plain.px.iter().zip(&dithered.px).any(|(a, b)| a[0] != b[0])); +} + +#[test] +fn rgb_cmyk_lab_duotone_and_gray32_keep_todays_behavior() { + let adj = Adjustment::GradientMap { stops: vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])], reverse: false, dither: false, source: None }; + let px = [0.25, 0.5, 0.75, 1.0]; + + for (mode, depth) in [ + (ColorMode::Rgb, Some(SampleType::U8)), + (ColorMode::Cmyk, Some(SampleType::U8)), + (ColorMode::Duotone, Some(SampleType::U8)), + (ColorMode::Grayscale, Some(SampleType::F32)), + ] { + let mut got = Buffer::filled(Rect::new(0, 0, 1, 1), px); + let mut want = got.clone(); + apply_in(&adj, &mut got, Transfer::Srgb, depth, mode); + apply_depth(&adj, &mut want, Transfer::Srgb, depth); + assert_eq!(got.px, want.px, "{mode:?} {depth:?} should keep today's screen-colour path"); + } + + // Lab keeps its L-driven RGB gradient output. + let mut lab = Buffer::filled(Rect::new(0, 0, 1, 1), [Color::WHITE.c[0]; 4]); + apply_in(&adj, &mut lab, Transfer::Srgb, Some(SampleType::U8), ColorMode::Lab); + assert_eq!(lab.px[0][2], 1.0); + assert!(lab.px[0][0] < 0.01); +} From aff1af0d2339fc6b9ddbbb819c363aeb4497ae20 Mon Sep 17 00:00:00 2001 From: Lcoding15 <125505497+Lcoding15@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:42:01 +0000 Subject: [PATCH 108/385] fix(file): Image Processor takes a Bitmap document to RGB before its sRGB conversion (#14263) --- .../file_cmds/image_processor_formats_tests.rs | 17 +++++++++++++++++ crates/engine/src/cmd/file_cmds/processing.rs | 5 +++++ 2 files changed, 22 insertions(+) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs index 134acee8af..9753f91456 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs @@ -160,3 +160,20 @@ fn legacy_format_and_resize_parameters_still_work() { let png = reopen(&files[0]).unwrap(); assert_eq!((png.size.width, png.size.height), (20, 10)); } + +/// CodeRabbit on #14826: a Bitmap document still goes out as an sRGB JPEG. Convert to Profile +/// refuses Bitmap now, so the run takes it to RGB first, as the single-format run does. +#[test] +fn a_bitmap_document_is_written_as_an_srgb_jpeg() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + s.execute("file.new", json!({"name": "Line art", "width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Bitmap); + let result = s.execute(COMMAND, json!({"source": "current", "output": dir.path(), "jpeg": {"convertToSrgb": true}})).unwrap(); + assert_eq!(result["errors"], json!([]), "{result}"); + let files = paths(&result).unwrap(); + assert_eq!(files, [dir.path().join("Line art.jpg")]); + assert_eq!(reopen(&files[0]).unwrap().mode, ColorMode::Rgb); +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5e0d6b2ddb..384ce764af 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -241,6 +241,11 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - fit_image(scratch, fit)?; } if format.srgb { + // Convert to Profile refuses a Bitmap document (#14263): it goes to RGB first, as + // the single-format run does, and is then converted. + if scratch.active().is_some_and(|d| d.doc.mode == ColorMode::Bitmap) { + scratch.execute("image.mode.rgb", json!({}))?; + } scratch.execute("edit.convertToProfile", json!({"profile": "srgb", "flatten": true}))?; } Ok(false) From 7858b050012059b022e22514d7af764486f8ba0d Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 08:37:33 +0100 Subject: [PATCH 109/385] docs(engine): restore the keep_counts doc comment The guides change reworded the keep_counts sentence and named the Color Sampler points, which it does not touch (it is about count markers, #11762). Original wording back; the keep_guides sentence stays. --- crates/engine/src/cmd/mode_cmds.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index f0d18c24ee..b2663ae999 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -67,8 +67,7 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { } /// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, -/// unlike the turned Crop and Straighten, keeps the Color Sampler points — #11762). The Crop -/// tool's straighten turn moves them with the image, as before. `keep_guides` turns the guides +/// #11762). The Crop tool's straighten turn moves them with the image, as before. `keep_guides` turns the guides /// with the canvas (#14508, measured for Image Rotation > Arbitrary) instead of dropping them, /// as the turned Crop and the Straighten still do (not measured there). pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool, keep_guides: bool) -> Result { From bb845f084b7e524aa89cbb2c9790c7af44ad3a21 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 08:53:22 +0100 Subject: [PATCH 110/385] fix(ui-egui): keep the 9 px grab radius in the Properties Curves editor Issue #14443 lists layer Properties among the hosts that were not measured and that keep today's 9 px if the radius becomes per-host. The Curves editor runs in both the Image > Adjustments dialog and the Properties panel, and the wiring gave both the new 16 px radius. curves_grab_radius(in_dialog) now hands the measured radius to the dialog only (EditorCx::dialog); the panel keeps the old one. A test pins both values. --- crates/ui-egui/src/dialogs/adjust_editors/curves.rs | 3 ++- crates/ui-egui/src/widgets/point_curve.rs | 7 ++++++- .../ui-egui/src/widgets/point_curve_hit_radius_tests.rs | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs index 20ecd6cce1..4cafa2cd7c 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs @@ -396,7 +396,8 @@ pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { } ui.data_mut(|d| d.insert_temp(stroke_id, (active, last))); } else { - let interaction = crate::point_curve::interact_with_hit_radius(ui, &resp, graph, &mut pts, &mut st.gesture, crate::point_curve::CURVES_HIT_RADIUS); + let interaction = + crate::point_curve::interact_with_hit_radius(ui, &resp, graph, &mut pts, &mut st.gesture, crate::point_curve::curves_grab_radius(cx.dialog)); changed = interaction.changed; e.commit |= interaction.commit; } diff --git a/crates/ui-egui/src/widgets/point_curve.rs b/crates/ui-egui/src/widgets/point_curve.rs index f3a73e0ae2..cd58b44773 100644 --- a/crates/ui-egui/src/widgets/point_curve.rs +++ b/crates/ui-egui/src/widgets/point_curve.rs @@ -16,6 +16,11 @@ const HIT_RADIUS: f32 = 9.0; /// and still adds a point 30 px away, so this has to sit in that window; 16.0 is the smallest clean /// screen distance above the measured 15, and it is one pixel per level for 16 input levels. pub const CURVES_HIT_RADIUS: f32 = 16.0; +/// Grab radius of the Curves editor: the measured [`CURVES_HIT_RADIUS`] in the Image > Adjustments +/// dialog; the Properties panel hosts the same editor but was not measured, so it keeps today's. +pub fn curves_grab_radius(in_dialog: bool) -> f32 { + if in_dialog { CURVES_HIT_RADIUS } else { HIT_RADIUS } +} /// Interior points disappear outside this margin and return on re-entry during the same drag. const DRAG_OFF: f32 = 12.0; @@ -187,7 +192,7 @@ pub fn interact_with_hit_radius( } // Arrows edit this graph rather than navigating to another widget on the next frame. ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })); - // Keys while the graph has focus: Delete/Backspace removes, arrows nudge (Shift: ×10). + // Keys while the graph has focus: Delete/Backspace removes, arrows nudge (Shift: ×10). if resp.has_focus() { crate::shortcut_dispatch::claim_delete_keys(ui.ctx(), resp.id); } diff --git a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs index f947437195..e95e5c15f2 100644 --- a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs +++ b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs @@ -98,6 +98,14 @@ fn the_curves_hit_radius_sits_inside_the_measured_window() { assert!((15.0..30.0).contains(&CURVES_HIT_RADIUS), "the Curves grab radius is {CURVES_HIT_RADIUS} px, outside the measured 15..30 px window"); } +/// The issue lists layer Properties among the hosts that were not measured: the Curves editor +/// there keeps today's radius, only the dialog gets the measured one. +#[test] +fn the_properties_panel_keeps_todays_radius_and_the_dialog_gets_the_curves_radius() { + assert_eq!(point_curve::curves_grab_radius(true), CURVES_HIT_RADIUS); + assert_eq!(point_curve::curves_grab_radius(false), TODAY); +} + /// Not measured in the reference application, so the other hosts keep today's radius exactly: a /// click 8 or 9 px away grabs the point, one 10 px away still adds a second point. #[test] From cb7f9770f5e59f5611a45b982db76a71869ae0ab Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sat, 14 Nov 2026 11:51:40 +0100 Subject: [PATCH 111/385] Color Table: pixels past a shrunk table render black An index past the new table's end took the new table's nearest colour; it now renders 0,0,0, as in the reference application (#14342). Duplicate entries still map by nearest colour until the document keeps each pixel's index. --- crates/engine/src/cmd/mode_cmds.rs | 6 +- .../cmd/mode_cmds/color_table_index_tests.rs | 73 +++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index e5ad74c640..ab8a4adf87 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -488,7 +488,8 @@ fn color_table(s: &mut Session, p: &Value) -> Result { } else { c[3] }; - let nc = if i < table.colors.len() { table.rgb(i) } else { table.rgb(table.nearest([c[0], c[1], c[2]])) }; + // An index past a shrunk table has no colour: black, as in Photoshop (#14342). + let nc = table.rgb(i); let mut enc = [0.0f32; 8]; let m = photocraft_raster::from_rgba_into(&fmt, [nc[0], nc[1], nc[2], alpha], &mut enc); q.copy_from_slice(&enc[..m]); @@ -830,3 +831,6 @@ pub fn display_document(doc: &Document) -> Option { #[cfg(test)] mod tests; + +#[cfg(test)] +mod color_table_index_tests; diff --git a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs new file mode 100644 index 0000000000..91fda489b9 --- /dev/null +++ b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs @@ -0,0 +1,73 @@ +//! Image › Mode › Color Table: pixels past a shrunk table turn black, and a table without +//! duplicates recolours as before (#14342). + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The epic's test document, scaled down: four solid bars red, green, blue and yellow, converted +/// to Indexed Color with an Exact palette, no dither and no transparency. +fn bars() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 4, "background": "white"})).unwrap(); + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + data.extend(photocraft_raster::from_rgba(&fmt, [RED, GREEN, BLUE, YELLOW][x as usize / 2])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap(); + s +} + +fn table(s: &Session) -> ColorTable { + s.active().unwrap().doc.color_table.clone().unwrap() +} + +/// The colour of each bar (one pixel per bar, from the middle row). +fn bar_colours(s: &Session) -> [[f32; 4]; 4] { + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + [0, 2, 4, 6].map(|x| surf.rgba(x, 2)) +} + +fn index_of(t: &ColorTable, c: [f32; 4]) -> usize { + t.colors.iter().position(|e| e.map(|v| f32::from(v) / 255.0) == [c[0], c[1], c[2]]).unwrap() +} + +#[test] +fn pixels_past_a_shrunk_table_turn_black() { + let mut s = bars(); + let before = (table(&s), bar_colours(&s)); + let indices = [RED, GREEN, BLUE, YELLOW].map(|c| index_of(&before.0, c)); + assert_eq!(before.0.colors.len(), 4); + let new = [[0.0, 1.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]; + s.execute("image.mode.colorTable", json!({"colors": ["#00ffff", "#ff00ff", "#ffffff"]})).unwrap(); + let want = indices.map(|i| new.get(i).copied().unwrap_or([0.0, 0.0, 0.0, 1.0])); + assert_eq!(bar_colours(&s), want, "indices {indices:?}: the bar past the table is black, the others take their entry"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Color Table")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((table(&s), bar_colours(&s)), before); +} + +/// Regression check for "a table without duplicates recolours exactly as today": passes on main too. +#[test] +fn editing_one_entry_recolours_only_its_pixels() { + let mut s = bars(); + let before = bar_colours(&s); + let blue = index_of(&table(&s), BLUE); + s.execute("image.mode.colorTable", json!({"entries": {blue.to_string(): "#ff00ff"}})).unwrap(); + assert_eq!(bar_colours(&s), [RED, GREEN, [1.0, 0.0, 1.0, 1.0], YELLOW]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(bar_colours(&s), before); +} From e2cb5a0cf58b031491c0809471a887c582986af1 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sat, 14 Nov 2026 14:22:05 +0100 Subject: [PATCH 112/385] Color Table: keep each pixel's index where it is known Indexed Color documents store RGB pixels, so Color Table found each pixel's index again as the nearest entry, and entries of one colour lost their own pixels (#14342). The document now keeps each pixel's index (Document::color_indices) where it is known: recorded when a palette PNG is opened, by Image > Mode > Indexed Color and by Color Table itself. Color Table uses it while the layer still has exactly the recorded tiles; after any other change it maps by nearest colour as before. A known index past a shrunk table stays black until the table grows back over it. The native format saves the indices only while they hold for the layer as saved, and pairs them with the loaded layer on open. --- Cargo.lock | 2 + crates/doc/src/lib.rs | 15 +- crates/doc/src/mode.rs | 56 ++++- crates/engine/Cargo.toml | 4 + .../engine/src/cmd/layer_multi_cmds/damage.rs | 4 + crates/engine/src/cmd/mode_cmds.rs | 32 ++- .../cmd/mode_cmds/color_table_index_tests.rs | 210 +++++++++++++++++- crates/format/src/convert.rs | 29 ++- crates/format/src/manifest.rs | 11 + crates/io/Cargo.toml | 3 + crates/io/src/flat.rs | 56 ++++- crates/io/src/flat/png_stream_tests.rs | 3 + crates/io/tests/it/png_steps.rs | 3 + 13 files changed, 410 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c0e3142ebd..6f4e45dae3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5599,6 +5599,7 @@ dependencies = [ "photocraft-testkit", "photocraft-text", "photocraft-vector", + "png 0.18.1", "rayon", "same-file", "semver", @@ -5703,6 +5704,7 @@ dependencies = [ "photocraft-testkit", "photocraft-text", "photocraft-vector", + "png 0.18.1", "proptest", "serde_json", "thiserror 2.0.21", diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d7a87ff756..e2014cd9a1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -38,7 +38,7 @@ pub use effects::{ GradientStyle, Satin, Shadow, StrokeFx, StrokePosition, }; pub use frame::Frame; -pub use mode::{ColorTable, Duotone, DuotoneInk, StackMode}; +pub use mode::{ColorIndices, ColorTable, Duotone, DuotoneInk, StackMode}; pub use pattern::Pattern; pub use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType}; pub use photocraft_geom::{Affine, Rect, Size}; @@ -930,6 +930,10 @@ pub struct Document { pub patterns: Vec, /// Indexed Color palette (Image › Mode › Color Table). Set while `mode` is Indexed. pub color_table: Option, + /// Each pixel's Color Table index where it is known (recorded by opening a palette PNG, the + /// Indexed Color conversion and Color Table), so entries of one colour keep their own pixels + /// (#14342). + pub color_indices: Option, /// Duotone inks. Set while `mode` is Duotone. pub duotone: Option, /// Window › Layer Comps, top to bottom as listed in the panel. @@ -1018,6 +1022,7 @@ impl Document { quick_mask_unselected: false, patterns: Vec::new(), color_table: None, + color_indices: None, duotone: None, layer_comps: Vec::new(), last_applied_comp: None, @@ -1088,8 +1093,8 @@ impl Document { } /// Every pixel surface the document holds: layer pixels and caches, masks, smart filter - /// masks, video frames (including the originals), channels, the quick mask, patterns and - /// the selection. History snapshots and saves cover exactly these tiles. + /// masks, video frames (including the originals), channels, the quick mask, the Color Table + /// indices, patterns and the selection. History snapshots and saves cover exactly these tiles. pub fn for_each_surface(&self, mut visit: impl FnMut(&Surface)) { for (_, _, layer) in self.walk() { if let Some(surface) = layer.surface() { @@ -1115,6 +1120,10 @@ impl Document { for channel in self.channels.iter().chain(&self.quick_mask) { visit(&channel.surface); } + if let Some(c) = &self.color_indices { + visit(&c.pixels); + visit(&c.indices); + } for pattern in &self.patterns { visit(&pattern.surface); } diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs index a74f2ea2dc..3fecadd2b7 100644 --- a/crates/doc/src/mode.rs +++ b/crates/doc/src/mode.rs @@ -1,10 +1,16 @@ -//! Colour-mode side data: the Indexed Color table, Duotone inks, and smart-object stack modes. +//! Colour-mode side data: the Indexed Color table and pixel indices, Duotone inks, and smart-object stack modes. //! //! Indexed, Bitmap and Duotone documents keep their pixels expanded (RGB / Gray, see //! [`crate::Document::pixel_format`]); these structs carry what the mode adds on top. +use std::sync::Arc; + +use photocraft_color::PixelFormat; +use photocraft_geom::Rect; +use photocraft_raster::Surface; use serde::{Deserialize, Serialize}; +use crate::LayerId; use crate::adjust::CurvePoint; /// Image › Mode › Color Table: the palette of an Indexed Color document (at most 256 entries). @@ -36,6 +42,54 @@ impl ColorTable { } } +/// The Color Table index of each pixel of an Indexed Color layer, where it is known (#14342). +/// The layer's pixels are RGB, so two entries of one colour can't be told apart by colour. +/// +/// The indices hold while the layer still has the very tiles recorded with them, at the same +/// places. One tile can't prove where its pixels came from: a move shares tiles, and a solid tile +/// can stand in for another solid tile of the same colour. A move or a paint stroke changes the +/// tiles at the layer's edges or under the stroke, though, so after any change but Color Table's +/// the indices are unknown and Color Table falls back to the nearest entry. Recording costs no +/// pixel copy while the layer is unchanged. A save keeps the indices only while they hold, and an +/// open pairs them with the layer it loads: identical tiles load as one, so loaded pixels can't +/// prove they are unchanged. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorIndices { + /// The layer the indices are for. + pub layer: LayerId, + /// The layer's pixels when the indices were recorded. + pub pixels: Surface, + /// One gray 8-bit sample per pixel: its index. + pub indices: Surface, +} + +impl ColorIndices { + /// Records `indices`, one byte per pixel row by row over `r`, for `layer`, whose pixels are + /// `pixels`. `None` when they don't cover `r` or there's no memory for them. + pub fn new(layer: LayerId, pixels: &Surface, r: Rect, indices: &[u8]) -> Option { + let mut map = Surface::new(PixelFormat::GRAY8); + map.try_write_interleaved(r, indices).ok()?; + Some(ColorIndices { layer, pixels: pixels.clone(), indices: map }) + } + + /// Whether the indices hold for `layer`, whose pixels are now `pixels`: it is the recorded + /// layer and has the very tiles recorded, at the same places. A damaged file can name another + /// format for the indices: they don't hold then, rather than give wrong ones. + pub fn holds(&self, layer: LayerId, pixels: &Surface) -> bool { + layer == self.layer + && self.indices.format() == PixelFormat::GRAY8 + && pixels.format() == self.pixels.format() + && pixels.tile_count() == self.pixels.tile_count() + && pixels.tiles().zip(self.pixels.tiles()).all(|((a, x), (b, y))| a == b && Arc::ptr_eq(x, y)) + } + + /// The recorded indices over `r`, one byte per pixel row by row, while they + /// [hold](Self::holds). + pub fn known(&self, layer: LayerId, pixels: &Surface, r: Rect) -> Option> { + self.holds(layer, pixels).then(|| self.indices.to_interleaved(r)) + } +} + /// One Duotone ink: its display colour and the curve mapping gray density to ink density. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DuotoneInk { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 99bf586b28..c471b9b236 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -72,3 +72,7 @@ exr = { version = "1.73", default-features = false } # WebAssembly text -> binary for plug-in test modules (Apache-2.0 WITH LLVM-exception). wat = "1.228" # Synthetic multi-part EXR fixtures for the parts-commands tests. + +# Palette PNGs at 1, 2 and 4 bits and with an eXIf chunk for the Color Table index tests +# (the png 0.18 already in the tree). +png = "0.18" diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs index 2b77acd211..83ea69e2f0 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -241,6 +241,8 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool { // Compared by `patterns_pixels_equal`. patterns: _, color_table, + // Not composited: Color Table reads it, and recolours the layer pixels it changes. + color_indices: _, duotone, layer_comps: _, last_applied_comp: _, @@ -389,6 +391,8 @@ pub fn selection_only_change(a: &Document, b: &Document) -> bool { quick_mask_unselected, patterns: _, color_table: _, + // Changes only with the layer pixels or the colour table, compared there. + color_indices: _, duotone: _, layer_comps, last_applied_comp, diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ab8a4adf87..ced1844d13 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -12,7 +12,7 @@ use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShap use photocraft_algo::transform::{Homography, Interp}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::adjust::CurvePoint; -use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size}; +use photocraft_doc::{ColorIndices, ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -244,6 +244,7 @@ fn single_layer_surface(doc: &mut Document, active: &mut Option, mode: } doc.quick_mask = None; doc.color_table = None; + doc.color_indices = None; doc.duotone = None; } @@ -363,9 +364,12 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result { None }; let w = doc.size.width as usize; - quantize::quantize(&mut px, w, &pal, dither, amount, transparent); + let indices = quantize::quantize(&mut px, w, &pal, dither, amount, transparent); single_layer(doc, active, ColorMode::Indexed, &px, if transparent.is_some() { "Index" } else { "Background" }, transparent.is_none()); doc.color_table = Some(ColorTable { colors: pal.clone(), transparent: transparent.map(|t| t as u8) }); + // Each pixel's index is known here: keep it for Color Table (#14342). + let bounds = doc.bounds(); + doc.color_indices = doc.layers.first().and_then(|l| ColorIndices::new(l.id, l.surface()?, bounds, &indices)); Ok((pal.len(), transparent)) })?; Ok(json!({"colors": pal_len, "transparentIndex": transparent})) @@ -461,7 +465,15 @@ fn color_table(s: &mut Session, p: &Value) -> Result { let out = report(&table); s.edit("Color Table", |doc, _| { let old = cur.clone(); - for surf in doc.layers.iter_mut().filter_map(Layer::surface_mut) { + // A pixel keeps its index where it is known, so entries of one colour keep their own + // pixels; elsewhere it takes the nearest entry (#14342). The indices written here are + // known afterwards, for the recorded layer (Indexed documents have one). + let known = doc.color_indices.take(); + let has_pixels = |id: LayerId| doc.layers.iter().any(|l| l.id == id && l.surface().is_some()); + let record = known.as_ref().map(|k| k.layer).filter(|&id| has_pixels(id)).or_else(|| doc.layers.iter().find(|l| l.surface().is_some()).map(|l| l.id)); + for l in doc.layers.iter_mut() { + let id = l.id; + let Some(surf) = l.surface_mut() else { continue }; let r = surf.content_bounds(); if r.is_empty() { continue; @@ -469,7 +481,9 @@ fn color_table(s: &mut Session, p: &Value) -> Result { let fmt = surf.format(); let n = fmt.channels(); let mut data = surf.read_region(r); - for q in data.chunks_exact_mut(n) { + let indices = known.as_ref().and_then(|k| k.known(id, surf, r)).unwrap_or_default(); + let mut written = vec![0u8; if record == Some(id) { data.len() / n } else { 0 }]; + for (k, q) in data.chunks_exact_mut(n).enumerate() { let c = photocraft_raster::to_rgba(&fmt, q); let rgb = [c[0], c[1], c[2]]; let i = if c[3] <= 0.0 { @@ -479,8 +493,13 @@ fn color_table(s: &mut Session, p: &Value) -> Result { } i } else { - old.nearest(rgb) + // A known index past the table stays: its pixel shows black until the table + // grows back over it. + indices.get(k).map_or_else(|| old.nearest(rgb), |&i| usize::from(i)) }; + if let Some(w) = written.get_mut(k) { + *w = i as u8; + } let alpha = if table.transparent == Some(i as u8) { 0.0 } else if c[3] <= 0.0 { @@ -496,6 +515,9 @@ fn color_table(s: &mut Session, p: &Value) -> Result { } surf.write_region(r, &data); surf.prune(); + if record == Some(id) { + doc.color_indices = ColorIndices::new(id, surf, r, &written); + } } doc.color_table = Some(table.clone()); Ok(()) diff --git a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs index 91fda489b9..a1815d3aba 100644 --- a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs +++ b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs @@ -1,5 +1,5 @@ -//! Image › Mode › Color Table: pixels past a shrunk table turn black, and a table without -//! duplicates recolours as before (#14342). +//! Image › Mode › Color Table recolours each pixel by its index where it is known, so entries of +//! one colour keep their own pixels; pixels past a shrunk table turn black (#14342). use super::*; @@ -71,3 +71,209 @@ fn editing_one_entry_recolours_only_its_pixels() { s.execute("edit.undo", json!({})).unwrap(); assert_eq!(bar_colours(&s), before); } + +const WHITE: [f32; 4] = [1.0; 4]; + +/// The issue's palette PNG: a 6 × 2 image over the table red, white, white, two columns per +/// index, opened as a document. +fn red_white_white() -> Session { + let row = [0u8, 0, 1, 1, 2, 2]; + let indices: Vec = row.iter().chain(&row).copied().collect(); + let png = photocraft_codecs::encode_png_indexed(6, 2, &indices, &[[255, 0, 0], [255, 255, 255], [255, 255, 255]], None, None, None).unwrap(); + let opened = photocraft_io::import("red-white-white.png", &png).unwrap(); + let mut s = Session::new(); + s.add_document(opened.document, None); + s +} + +/// One pixel per column pair (index 0, 1 and 2 in the file). +fn pairs(s: &Session) -> [[f32; 4]; 3] { + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + [0, 2, 4].map(|x| surf.rgba(x, 1)) +} + +#[test] +fn an_entry_shared_with_another_keeps_its_own_pixels() { + let mut s = red_white_white(); + assert_eq!(table(&s).colors, vec![[255, 0, 0], [255, 255, 255], [255, 255, 255]]); + let before = (table(&s), pairs(&s)); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + assert_eq!(pairs(&s), [RED, WHITE, GREEN], "the index-2 pixels turn green, the index-1 pixels stay white"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((table(&s), pairs(&s)), before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(pairs(&s), [RED, WHITE, GREEN]); +} + +#[test] +fn indices_survive_one_colour_table_edit_after_another() { + let mut s = red_white_white(); + s.execute("image.mode.colorTable", json!({"entries": {"1": "#0000ff"}})).unwrap(); + assert_eq!(pairs(&s), [RED, BLUE, WHITE]); + s.execute("image.mode.colorTable", json!({"entries": {"1": "#ffffff", "2": "#ffff00"}})).unwrap(); + assert_eq!(pairs(&s), [RED, WHITE, YELLOW]); +} + +#[test] +fn indices_from_the_indexed_color_conversion_tell_equal_entries_apart() { + // Turn the green entry blue, then green again: the green bar's pixels kept their index + // while the table had two blue entries. + let mut s = bars(); + let (red, green, blue) = (index_of(&table(&s), RED), index_of(&table(&s), GREEN), index_of(&table(&s), BLUE)); + s.execute("image.mode.colorTable", json!({"entries": {green.to_string(): "#0000ff"}})).unwrap(); + assert_eq!(bar_colours(&s), [RED, BLUE, BLUE, YELLOW]); + s.execute("image.mode.colorTable", json!({"entries": {green.to_string(): "#00ff00"}})).unwrap(); + assert_eq!(bar_colours(&s), [RED, GREEN, BLUE, YELLOW]); + s.execute("image.mode.colorTable", json!({"entries": {red.to_string(): "#0000ff", blue.to_string(): "#ff00ff"}})).unwrap(); + assert_eq!(bar_colours(&s), [BLUE, GREEN, [1.0, 0.0, 1.0, 1.0], YELLOW]); +} + +#[test] +fn a_saved_document_keeps_its_indices() { + let s = red_white_white(); + let saved = photocraft_io::export(&s.active().unwrap().doc, "pcraft", &Default::default()).unwrap(); + let reopened = photocraft_io::import("red-white-white.pcraft", &saved.bytes).unwrap(); + assert!(reopened.document.color_indices.is_some()); + let mut s = Session::new(); + s.add_document(reopened.document, None); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + assert_eq!(pairs(&s), [RED, WHITE, GREEN]); +} + +#[test] +fn painted_pixels_fall_back_to_the_nearest_entry() { + // After a paint stroke the indices are unknown: as before, each pixel's colour picks the + // first matching entry. + let mut s = red_white_white(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let fmt = surf.format(); + surf.write_region(Rect::from_xywh(5, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, WHITE)); + Ok(()) + }) + .unwrap(); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + assert_eq!(pairs(&s), [RED, WHITE, WHITE]); +} + +#[test] +fn a_known_index_past_a_shrunk_table_stays_black_until_the_table_grows_back() { + let mut s = bars(); + let t = table(&s); + let yellow = index_of(&t, YELLOW); + assert_eq!(yellow, 3, "the test needs a bar at index 3"); + s.execute("image.mode.colorTable", json!({"colors": ["#00ffff", "#ff00ff", "#ffffff"]})).unwrap(); + assert_eq!(bar_colours(&s)[3], [0.0, 0.0, 0.0, 1.0]); + // Black is as near cyan as magenta: by colour it would take entry 0 and turn red here. + s.execute("image.mode.colorTable", json!({"entries": {"0": "#ff0000"}})).unwrap(); + assert_eq!(bar_colours(&s)[3], [0.0, 0.0, 0.0, 1.0]); + s.execute("image.mode.colorTable", json!({"colors": ["#ff0000", "#ff00ff", "#ffffff", "#00ff00"]})).unwrap(); + assert_eq!(bar_colours(&s)[3], GREEN, "index 3 takes the new entry 3"); +} + +#[test] +fn moved_pixels_fall_back_to_the_nearest_entry() { + // Solid tiles of one colour but different indices: index 0 red, then index 2 white, then + // index 1 white, 256 columns each. Canvas Size anchored right moves the pixels 100 columns + // left; a moved tile can share storage with the one recorded at its place, so the indices + // must not be trusted after a move. The pixels of index 1 must not turn green. + let indices: Vec = (0..256).flat_map(|_| (0..768).map(|x| [0u8, 2, 1][x / 256])).collect(); + let png = photocraft_codecs::encode_png_indexed(768, 256, &indices, &[[255, 0, 0], [255, 255, 255], [255, 255, 255]], None, None, None).unwrap(); + let mut s = Session::new(); + s.add_document(photocraft_io::import("solid.png", &png).unwrap().document, None); + s.execute("image.canvasSize", json!({"width": 668, "height": 256, "anchor": "right"})).unwrap(); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + for x in [412, 500, 667] { + assert_eq!(surf.rgba(x, 10), WHITE, "x {x} came from index 1"); + } +} + +/// A palette PNG of `indices` (row by row, `w` wide) at `depth` bits over `palette`, with an +/// optional eXIf block. +fn palette_png(w: u32, indices: &[u8], depth: png::BitDepth, palette: &[[u8; 3]], exif: Option<&[u8]>) -> Vec { + let bits = depth as usize; + let rows: Vec = indices + .chunks(w as usize) + .flat_map(|row| { + let mut packed = vec![0u8; (row.len() * bits).div_ceil(8)]; + for (x, &i) in row.iter().enumerate() { + packed[x * bits / 8] |= i << (8 - bits - x * bits % 8); + } + packed + }) + .collect(); + let mut out = Vec::new(); + let mut e = png::Encoder::new(&mut out, w, (indices.len() / w as usize) as u32); + e.set_color(png::ColorType::Indexed); + e.set_depth(depth); + e.set_palette(palette.concat()); + let mut wr = e.write_header().unwrap(); + if let Some(exif) = exif { + wr.write_chunk(png::chunk::eXIf, exif).unwrap(); + } + wr.write_image_data(&rows).unwrap(); + drop(wr); + out +} + +#[test] +fn palette_pngs_of_every_bit_depth_keep_their_indices() { + // Odd widths, so rows end in a partly used byte. + for (depth, w) in [(png::BitDepth::One, 11), (png::BitDepth::Two, 7), (png::BitDepth::Four, 5), (png::BitDepth::Eight, 3)] { + let max = (1u16 << depth as u8) - 1; + let row: Vec = (0..w).map(|x| (x as u16 % (max + 1)).min(max) as u8).collect(); + let indices: Vec = row.iter().chain(&row).copied().collect(); + let palette: Vec<[u8; 3]> = (0..=max).map(|_| [255, 255, 255]).collect(); + let png = palette_png(w, &indices, depth, &palette, None); + let doc = photocraft_io::import("p.png", &png).unwrap().document; + let layer = &doc.layers[0]; + let known = doc.color_indices.as_ref().unwrap().known(layer.id, layer.surface().unwrap(), doc.bounds()); + assert_eq!(known.as_deref(), Some(&indices[..]), "{depth:?}"); + } +} + +#[test] +fn a_transparent_entry_keeps_its_index() { + let png = photocraft_codecs::encode_png_indexed(3, 1, &[0, 1, 2], &[[0, 0, 0], [255, 255, 255], [255, 255, 255]], Some(0), None, None).unwrap(); + let mut s = Session::new(); + s.add_document(photocraft_io::import("t.png", &png).unwrap().document, None); + assert!(s.active().unwrap().doc.color_indices.is_some()); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + assert_eq!([0, 1, 2].map(|x| surf.rgba(x, 0)), [[0.0; 4], WHITE, GREEN]); +} + +#[test] +fn a_turned_palette_png_records_no_indices() { + // EXIF orientation 2 (mirrored): the file's indices aren't where its pixels open, and with + // two white entries the colours can't show it. + let exif = b"MM\x00\x2a\x00\x00\x00\x08\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00\x00\x00\x00\x00"; + let png = palette_png(4, &[0, 0, 1, 1], png::BitDepth::Eight, &[[255, 255, 255], [255, 255, 255]], Some(exif)); + let opened = photocraft_io::import("turned.png", &png).unwrap(); + assert_eq!(opened.document.color_table.as_ref().map(|t| t.colors.len()), Some(2), "opens as Indexed Color"); + assert!(opened.document.color_indices.is_none()); + // Control: the same file without the eXIf block keeps them. + let png = palette_png(4, &[0, 0, 1, 1], png::BitDepth::Eight, &[[255, 255, 255], [255, 255, 255]], None); + assert!(photocraft_io::import("upright.png", &png).unwrap().document.color_indices.is_some()); +} + +#[test] +fn a_flip_saved_and_reopened_leaves_the_indices_unknown() { + // White, red, white: mirror-symmetric colours, so the flipped tiles have the same bytes as + // the recorded ones, and a reopened file loads identical tiles as one. The save must not + // carry the indices from before the flip. + let row = [0u8, 0, 1, 1, 2, 2]; + let indices: Vec = row.iter().chain(&row).copied().collect(); + let png = photocraft_codecs::encode_png_indexed(6, 2, &indices, &[[255, 255, 255], [255, 0, 0], [255, 255, 255]], None, None, None).unwrap(); + let mut s = Session::new(); + s.add_document(photocraft_io::import("wrw.png", &png).unwrap().document, None); + s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap(); + let saved = photocraft_io::export(&s.active().unwrap().doc, "pcraft", &Default::default()).unwrap(); + let reopened = photocraft_io::import("wrw.pcraft", &saved.bytes).unwrap(); + assert!(reopened.document.color_indices.is_none()); + let mut s = Session::new(); + s.add_document(reopened.document, None); + s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap(); + assert_eq!(pairs(&s), [WHITE, RED, WHITE], "the right columns came from index 0"); +} diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index cc255ab818..ea933c7662 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -5,15 +5,15 @@ use std::sync::Arc; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::{ - AlphaChannel, CompAppearance, CompLayerState, DocId, Document, Effects, FillCache, Group, Layer, LayerComp, LayerContent, LayerId, LayerMask, Metadata, - NamedPath, Pattern, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer, + AlphaChannel, ColorIndices, CompAppearance, CompLayerState, DocId, Document, Effects, FillCache, Group, Layer, LayerComp, LayerContent, LayerId, LayerMask, + Metadata, NamedPath, Pattern, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer, }; use photocraft_geom::{TILE_SIZE, TileCoord}; use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel}; use crate::manifest::{ - ChannelM, CompAppearanceM, CompStateM, ContentM, DocM, EffectsM, FillCacheM, Hash, LayerCompM, LayerM, MaskM, MetadataM, NamedPathM, PatternM, - SmartSourceM, SurfaceM, TileRef, VectorPreviewM, + ChannelM, ColorIndicesM, CompAppearanceM, CompStateM, ContentM, DocM, EffectsM, FillCacheM, Hash, LayerCompM, LayerM, MaskM, MetadataM, NamedPathM, + PatternM, SmartSourceM, SurfaceM, TileRef, VectorPreviewM, }; use crate::{FormatError, Result}; @@ -278,6 +278,13 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> Result { .map(|p| PatternM { id: p.id.clone(), name: p.name.clone(), width: p.width, height: p.height, surface: surface_m(&p.surface, sink) }) .collect(), color_table: d.color_table.clone(), + // Only while they hold for the layer saved here (and the document is Indexed Color): on + // open, identical tiles load as one, so loaded pixels can't show a change made since. + color_indices: d + .color_indices + .as_ref() + .filter(|c| d.color_table.is_some() && d.layer(c.layer).and_then(Layer::surface).is_some_and(|p| c.holds(c.layer, p))) + .map(|c| ColorIndicesM { layer: c.layer.0, indices: surface_m(&c.indices, sink) }), duotone: d.duotone.clone(), variables: d.variables.clone(), timeline: d.timeline.clone(), @@ -690,7 +697,7 @@ impl Loader<'_> { } } let id = if self.preserve_ids { DocId(m.id) } else { DocId::fresh() }; - Ok(Document { + let mut doc = Document { id, name: m.name.clone(), size: m.size, @@ -712,6 +719,7 @@ impl Loader<'_> { quick_mask_unselected: m.quick_mask_unselected, patterns, color_table: m.color_table.clone(), + color_indices: None, duotone: m.duotone.clone(), variables, timeline: m.timeline.clone(), @@ -723,7 +731,16 @@ impl Loader<'_> { notes: m.notes.clone(), text_styles: m.text_styles.clone(), slices, - }) + }; + // Saved only while they held for the layer as saved, so they pair with its pixels as + // loaded. Optional side data: indices of a layer the file doesn't hold, or damaged ones, + // are dropped (Color Table then maps by nearest colour) rather than failing the open. + doc.color_indices = m.color_indices.as_ref().and_then(|c| { + let layer = *self.id_map.get(&c.layer)?; + let pixels = doc.layer(layer)?.surface()?.clone(); + Some(ColorIndices { layer, pixels, indices: self.surface(&c.indices).ok()? }) + }); + Ok(doc) } fn channel(&mut self, c: &ChannelM) -> Result { diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 7a7002f958..1c26289192 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -60,6 +60,9 @@ pub struct DocM { /// Indexed Color palette. #[serde(default)] pub color_table: Option, + /// Indexed Color pixel indices, where known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color_indices: Option, /// Duotone inks. #[serde(default)] pub duotone: Option, @@ -143,6 +146,14 @@ pub struct NamedPathM { pub psd_raw: Option, } +/// [`photocraft_doc::ColorIndices`]: the layer (by id) and its pixels' indices. Saved only while +/// they hold for the layer as saved, so the layer's own pixels are the recorded ones on open. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ColorIndicesM { + pub layer: u64, + pub indices: SurfaceM, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SurfaceM { pub format: PixelFormat, diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 7280fa576e..d969b0352a 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -53,6 +53,9 @@ serde_json = { workspace = true } blake3 = { version = "1.8", default-features = false, features = ["pure"] } # pdn.rs inflates Paint.NET's gzip pixel chunks. flate2 = { workspace = true } +# flat.rs reads a palette PNG's pixel indices (Color Table, #14342). The png 0.18 that +# craft-image-codecs already links; naming it adds no crate to the graph. +png = "0.18" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 53611d5007..58635ed81d 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CSample}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent}; +use photocraft_doc::{AlphaChannel, ColorIndices, Document, Layer, LayerContent}; use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_raster::{AllocationError, Interrupt, PruneCursor, RowWriteError, Surface}; @@ -258,6 +258,57 @@ impl FlatBuilder { } } +/// Each pixel's palette index in the palette PNG `bytes`, opened as `doc`, so Color Table can +/// tell entries of one colour apart (#14342). `None`, and Color Table falls back to the nearest +/// entry, when the document's one layer doesn't show each pixel's entry at the file's place for +/// it (an EXIF orientation turned the pixels, which colours alone can't show when entries repeat, +/// or a colour conversion changed them), or when the file is interlaced (not read here). One row at a time: +/// next to the layer, only the indices themselves (a byte per pixel) are held. +fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { + let table = doc.color_table.as_ref()?; + let [layer] = doc.layers.as_slice() else { return None }; + let surface = layer.surface()?; + let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); + decoder.set_transformations(png::Transformations::IDENTITY); + decoder.set_ignore_text_chunk(true); + let mut reader = decoder.read_info().ok()?; + let info = reader.info(); + let (w, h, bits) = (info.width, info.height, info.bit_depth as usize); + if info.color_type != png::ColorType::Indexed || info.interlaced || !matches!(bits, 1 | 2 | 4 | 8) || (w, h) != (doc.size.width, doc.size.height) { + return None; + } + let width = usize::try_from(w).ok()?; + let count = width.checked_mul(usize::try_from(h).ok()?)?; + let mut indices = Vec::new(); + indices.try_reserve_exact(count).ok()?; + let mut shown = vec![[0u8; 4]; width]; + let mut y = 0; + while let Some(row) = reader.next_row().ok()? { + if indices.len() >= count { + return None; + } + surface.read_rgba8_into(Rect::from_xywh(0, y, w, 1), &mut shown); + for (x, px) in shown.iter().enumerate() { + let bit = x * bits; + let byte = *row.data().get(bit / 8)?; + let i = (byte >> (8 - bits - bit % 8)) & (0xff >> (8 - bits)); + let entry = table.colors.get(usize::from(i))?; + let ok = if px[3] == 0 { table.transparent == Some(i) } else { px[..3] == entry[..] }; + if !ok { + return None; + } + indices.push(i); + } + y += 1; + } + // An eXIf after the pixels counts too. + reader.finish().ok()?; + if reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || indices.len() != count { + return None; + } + ColorIndices::new(layer.id, surface, doc.bounds(), &indices) +} + /// What every flat format does to the document of its pixels: the palette mode, the save /// settings, a Targa's alpha channel and the profile an untagged image needs. `img` is the /// decoded image, when the document was built from one (a streamed PNG has none). @@ -275,6 +326,9 @@ pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Opti { r.document.mode = ColorMode::Indexed; r.document.color_table = Some(photocraft_doc::ColorTable { colors, transparent }); + if format == Some(Format::Png) { + r.document.color_indices = png_color_indices(bytes, &r.document); + } } // The decoder's count of frames or pages left out (set above) stays alongside the encoding. let encoding = file_encoding_as(format, bytes); diff --git a/crates/io/src/flat/png_stream_tests.rs b/crates/io/src/flat/png_stream_tests.rs index 43068b8e89..333951095b 100644 --- a/crates/io/src/flat/png_stream_tests.rs +++ b/crates/io/src/flat/png_stream_tests.rs @@ -159,6 +159,9 @@ fn assert_same(a: &ImportResult, b: &ImportResult, what: &str) { let mut db = db.clone(); db.id = da.id; db.layers.iter_mut().zip(&da.layers).for_each(|(l, k)| l.id = k.id); + if let (Some(c), Some(k)) = (db.color_indices.as_mut(), &da.color_indices) { + c.layer = k.layer; + } assert!(da == &db, "{what}: documents differ"); } diff --git a/crates/io/tests/it/png_steps.rs b/crates/io/tests/it/png_steps.rs index 73960301c5..437c6e0f06 100644 --- a/crates/io/tests/it/png_steps.rs +++ b/crates/io/tests/it/png_steps.rs @@ -45,6 +45,9 @@ fn assert_same(a: &Document, b: &Document, what: &str) { for (x, y) in a.layers.iter_mut().zip(&mut b.layers) { y.id = x.id; } + if let (Some(x), Some(y)) = (&a.color_indices, b.color_indices.as_mut()) { + y.layer = x.layer; + } assert!(a == b, "{what}: the documents differ"); } From 26b154babb076e42f4257ffa822663cdb4a7e3df Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 15 Nov 2026 11:20:32 +0100 Subject: [PATCH 113/385] Magic Eraser: the colour-mode alert leaves a floating selection floating (#13169) #12097 refuses a Magic Eraser click in an Indexed Color or Bitmap document inside the command's run, after dispatch has dropped a floating piece. admit now gives the same alert too, so the issue's own case is refused before the drop. run keeps its check for callers that skip dispatch. --- crates/engine/src/cmd/float_cmds/tests.rs | 18 ++++++++++++++++++ crates/engine/src/session/execute.rs | 10 +++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/float_cmds/tests.rs b/crates/engine/src/cmd/float_cmds/tests.rs index 4883d79850..1a9ebe332d 100644 --- a/crates/engine/src/cmd/float_cmds/tests.rs +++ b/crates/engine/src/cmd/float_cmds/tests.rs @@ -607,3 +607,21 @@ fn a_command_refused_for_the_colour_mode_leaves_the_piece_floating() { assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(5, 5, 15, 15)); assert_eq!(st.history.past_len(), steps, "no History step"); } + +/// The issue's own case: the Magic Eraser in an Indexed Color document answers with its alert +/// (#12032) and leaves the moved piece floating. +#[test] +fn a_magic_eraser_click_refused_in_indexed_color_leaves_the_piece_floating() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap(); + let refused = s.execute("paint.magicEraser", json!({"x": 30, "y": 30})); + assert_eq!(refused.unwrap_err().to_string(), crate::eraser_cmds::MAGIC_ERASER_INDEXED_ERROR, "the tool's alert, unchanged"); + let st = s.active().unwrap(); + assert_eq!(floating(st).map(|f| f.offset), Some((5, 0)), "the piece still floats"); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(5, 5, 15, 15)); + assert_eq!(st.history.past_len(), steps, "no History step"); +} diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 751bd05746..2552a9ad98 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -95,7 +95,8 @@ impl Session { /// What `dispatch` checks once the params are valid, before a floating selection drops (so a /// refused command leaves it floating) and again after: the precondition (on a named layer - /// for commands that take one), a job running on the document, a hidden target. The run params (the Channels panel's target filled in) when it + /// for commands that take one), a job running on the document, a hidden target, the Magic + /// Eraser's colour-mode alert. The run params (the Channels panel's target filled in) when it /// may run. pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); @@ -112,6 +113,13 @@ impl Session { if let Some(why) = hidden_target::refusal(self, id, params) { return Err(EngineError::Other(why.into())); } + // The Magic Eraser's alert for an Indexed Color or Bitmap document (#12032), the same + // error its `run` gives: checked here too, so a floating selection stays floating (#13169). + if id == "paint.magicEraser" + && let Some(why) = self.active().and_then(|st| crate::eraser_cmds::magic_eraser_refusal(&st.doc)) + { + return Err(EngineError::Other(why.into())); + } Ok(run_params) } From 40e70cb4087db259148860b26a87007ab01b3fe3 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 11:49:18 +0100 Subject: [PATCH 114/385] docs(ui-egui): restore the x10 character and say the grab radius is in egui points --- crates/ui-egui/src/widgets/point_curve.rs | 4 ++-- crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/widgets/point_curve.rs b/crates/ui-egui/src/widgets/point_curve.rs index cd58b44773..508f07e4a9 100644 --- a/crates/ui-egui/src/widgets/point_curve.rs +++ b/crates/ui-egui/src/widgets/point_curve.rs @@ -93,7 +93,7 @@ pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2 interact_with_hit_radius(ui, resp, graph, pts, state, HIT_RADIUS) } -/// [`interact`], with the host's grab radius in screen pixels: the Curves graph passes +/// [`interact`], with the host's grab radius in egui points (screen pixels at scale 1.0): the Curves graph passes /// [`CURVES_HIT_RADIUS`]; a host the reference application was not measured in passes the 9 px /// default. pub fn interact_with_hit_radius( @@ -192,7 +192,7 @@ pub fn interact_with_hit_radius( } // Arrows edit this graph rather than navigating to another widget on the next frame. ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })); - // Keys while the graph has focus: Delete/Backspace removes, arrows nudge (Shift: ×10). + // Keys while the graph has focus: Delete/Backspace removes, arrows nudge (Shift: ×10). if resp.has_focus() { crate::shortcut_dispatch::claim_delete_keys(ui.ctx(), resp.id); } diff --git a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs index e95e5c15f2..b474025a9a 100644 --- a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs +++ b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs @@ -9,8 +9,9 @@ use egui_kittest::Harness; use crate::state::PointCurveState; use crate::widgets::point_curve::{self, CURVES_HIT_RADIUS}; -/// One screen pixel per input level, the scale the issue measures at: the graph is exactly 255 px -/// on a side, so a screen distance in px and an input distance in levels are the same number. +/// One egui point per input level (one screen pixel at scale 1.0, the scale the issue measures at): +/// the graph is exactly 255 points on a side, so a distance in points and an input distance in +/// levels are the same number. const SIDE: f32 = 255.0; /// The radius of the hosts that stay as they are today. const TODAY: f32 = 9.0; From e77f5f6bf6a92bf299a5edcbd4be28053862ce17 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 15 Nov 2026 11:52:29 +0100 Subject: [PATCH 115/385] Color Table: read a palette PNG again only for shared colours When every entry of the palette has its own colour, the pixel colours already name the entries, and Color Table's nearest entry finds them. The second pass over the file then adds nothing, and it is a pass that neither the stepped import (the web build) splits up nor a cancel stops, so it is skipped. The io test helpers map the indices' layer along with the layers instead of copying the expected one, so indices that name no layer still make the documents differ. --- .../src/cmd/mode_cmds/color_table_index_tests.rs | 13 +++++++++++++ crates/io/src/flat.rs | 9 +++++++++ crates/io/src/flat/png_stream_tests.rs | 8 +++++--- crates/io/tests/it/png_steps.rs | 8 +++++--- 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs index a1815d3aba..184d43cbb0 100644 --- a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs +++ b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs @@ -244,6 +244,19 @@ fn a_transparent_entry_keeps_its_index() { assert_eq!([0, 1, 2].map(|x| surf.rgba(x, 0)), [[0.0; 4], WHITE, GREEN]); } +#[test] +fn a_palette_png_without_shared_colours_is_not_read_again() { + // Every entry its own colour: the colours already name the entries, so the open skips the + // second pass over the file, and Color Table still recolours by entry. + let png = photocraft_codecs::encode_png_indexed(3, 1, &[0, 1, 2], &[[0, 0, 0], [255, 255, 255], [0, 0, 255]], Some(0), None, None).unwrap(); + let mut s = Session::new(); + s.add_document(photocraft_io::import("unique.png", &png).unwrap().document, None); + assert!(s.active().unwrap().doc.color_indices.is_none()); + s.execute("image.mode.colorTable", json!({"entries": {"1": "#00ff00"}})).unwrap(); + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + assert_eq!([0, 1, 2].map(|x| surf.rgba(x, 0)), [[0.0; 4], GREEN, BLUE]); +} + #[test] fn a_turned_palette_png_records_no_indices() { // EXIF orientation 2 (mirrored): the file's indices aren't where its pixels open, and with diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 58635ed81d..4ba4191b2d 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -266,6 +266,15 @@ impl FlatBuilder { /// next to the layer, only the indices themselves (a byte per pixel) are held. fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { let table = doc.color_table.as_ref()?; + // Only entries that share a colour need the file. When every entry has its own colour, each + // pixel's colour names its entry and Color Table's nearest entry finds it. Reading the file + // again is one pass over all its rows that neither a stepped import (the web build) splits + // up nor a cancel stops, so it is skipped when it can't add anything. + let mut colors = table.colors.clone(); + colors.sort_unstable(); + if !colors.windows(2).any(|w| w[0] == w[1]) { + return None; + } let [layer] = doc.layers.as_slice() else { return None }; let surface = layer.surface()?; let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); diff --git a/crates/io/src/flat/png_stream_tests.rs b/crates/io/src/flat/png_stream_tests.rs index 333951095b..66578791fa 100644 --- a/crates/io/src/flat/png_stream_tests.rs +++ b/crates/io/src/flat/png_stream_tests.rs @@ -158,10 +158,12 @@ fn assert_same(a: &ImportResult, b: &ImportResult, what: &str) { // Everything else, but for the ids every document and layer gets fresh. let mut db = db.clone(); db.id = da.id; - db.layers.iter_mut().zip(&da.layers).for_each(|(l, k)| l.id = k.id); - if let (Some(c), Some(k)) = (db.color_indices.as_mut(), &da.color_indices) { - c.layer = k.layer; + // The indices' layer maps along with the layers, so indices naming no layer still differ. + let indices_layer = db.color_indices.as_ref().and_then(|c| db.layers.iter().zip(&da.layers).find(|(l, _)| l.id == c.layer)).map(|(_, k)| k.id); + if let (Some(c), Some(id)) = (db.color_indices.as_mut(), indices_layer) { + c.layer = id; } + db.layers.iter_mut().zip(&da.layers).for_each(|(l, k)| l.id = k.id); assert!(da == &db, "{what}: documents differ"); } diff --git a/crates/io/tests/it/png_steps.rs b/crates/io/tests/it/png_steps.rs index 437c6e0f06..f62e3bc57a 100644 --- a/crates/io/tests/it/png_steps.rs +++ b/crates/io/tests/it/png_steps.rs @@ -42,12 +42,14 @@ fn assert_same(a: &Document, b: &Document, what: &str) { let (mut a, mut b) = (a.clone(), b.clone()); b.id = a.id; assert_eq!(a.layers.len(), b.layers.len(), "{what}"); + // The indices' layer maps along with the layers, so indices naming no layer still differ. + let indices_layer = b.color_indices.as_ref().and_then(|c| b.layers.iter().zip(&a.layers).find(|(y, _)| y.id == c.layer)).map(|(_, x)| x.id); + if let (Some(c), Some(id)) = (b.color_indices.as_mut(), indices_layer) { + c.layer = id; + } for (x, y) in a.layers.iter_mut().zip(&mut b.layers) { y.id = x.id; } - if let (Some(x), Some(y)) = (&a.color_indices, b.color_indices.as_mut()) { - y.layer = x.layer; - } assert!(a == b, "{what}: the documents differ"); } From 61410617a0c96afe0a713c5d31931d3bd38d37eb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 02:55:19 -0800 Subject: [PATCH 116/385] Support digit shortcuts for Color Replacement tolerance --- .../src/background_eraser_digit_keys_tests.rs | 2 +- .../src/color_replacement_digit_keys_tests.rs | 73 +++++++++++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 11 ++- crates/ui-egui/src/lib.rs | 3 + 4 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/color_replacement_digit_keys_tests.rs diff --git a/crates/ui-egui/src/background_eraser_digit_keys_tests.rs b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs index 9cddb5a7eb..ea6fa42e28 100644 --- a/crates/ui-egui/src/background_eraser_digit_keys_tests.rs +++ b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs @@ -98,7 +98,7 @@ fn other_tools_digits_are_unchanged() { assert!((layer(&a).0 - 0.3).abs() < 1e-6); assert_eq!(tolerance(&a), 50.0); // The tools whose number is a strength, exposure or tolerance of their own still ignore the digits. - for tool in [Tool::ColorReplacement, Tool::Dodge, Tool::Smudge, Tool::MagicEraser] { + for tool in [Tool::Dodge, Tool::Smudge, Tool::MagicEraser] { let mut a = app(tool); let before = (a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone()); press(&mut a, 3, false, 0.0); diff --git a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs new file mode 100644 index 0000000000..81ebb19fec --- /dev/null +++ b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs @@ -0,0 +1,73 @@ +//! #11927: Color Replacement digits set its Tolerance, while Shift/Alt remain no-ops. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +/// Send one key event through the digit handler. +fn alt_digit(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let modifiers = egui::Modifiers::ALT; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::opacity_keys::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn layer(app: &PhotocraftApp) -> (f32, f32) { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + (l.opacity, l.fill_opacity) +} + +#[test] +fn digits_set_color_replacement_tolerance_and_quick_pairs_are_exact() { + let mut a = app(Tool::ColorReplacement); + assert_eq!(a.ui.tool_options.cr_tolerance, 30.0); + press(&mut a, 5, false, 0.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 50.0); + press(&mut a, 0, false, 5000.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 100.0); + press(&mut a, 1, false, 10000.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 10.0); + press(&mut a, 4, false, 20000.0); + press(&mut a, 5, false, 20300.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 45.0); + let options = serde_json::to_value(&a.ui.tool_options).unwrap(); + assert_eq!(options["cr_tolerance"], json!(45.0)); +} + +#[test] +fn modifiers_and_double_zero_preserve_color_replacement_and_layer_state() { + let mut a = app(Tool::ColorReplacement); + let before_layer = layer(&a); + press(&mut a, 5, true, 0.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 30.0, "Shift+digit is unchanged"); + alt_digit(&mut a, egui::Key::Num5); + assert_eq!(a.ui.tool_options.cr_tolerance, 30.0, "Alt+digit is unchanged"); + press(&mut a, 0, false, 5000.0); + press(&mut a, 0, false, 5100.0); + assert_eq!(a.ui.tool_options.cr_tolerance, 100.0, "unmeasured 00 keeps the first zero's value"); + assert_eq!(layer(&a), before_layer); + let brush = a.session.tools.brush.clone(); + let opacity = a.ui.tool_options.fill_opacity; + let bg_tolerance = a.ui.tool_options.bg_tolerance; + a.ui.tool = Tool::ColorReplacement; + press(&mut a, 3, false, 9000.0); + assert_eq!(a.session.tools.brush, brush); + assert_eq!(a.ui.tool_options.fill_opacity, opacity); + assert_eq!(a.ui.tool_options.bg_tolerance, bg_tolerance); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 41c571f312..2034a50060 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -3,9 +3,9 @@ //! Eraser they set the brush's Opacity (⇧: Flow, swapped while airbrush build-up is on; the Pencil has no Flow, so its ⇧ //! digits set Opacity too, #11967); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the -//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose -//! number is a strength or exposure are left alone. -//! ⌥+digit sets the Smoothing of the tools that show it (Brush, Pencil, Eraser; #11892). +//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907); and with +//! Color Replacement its Tolerance (#11927). Tools whose number is a strength or exposure are left alone. +//! ⌥+digit sets Smoothing for tools that show it (Brush, Pencil, Eraser; #11892). use egui::{Event, Key}; use serde_json::json; @@ -30,6 +30,8 @@ enum Target { ToolOpacity, /// The Background Eraser's Tolerance option. BgTolerance, + /// Color Replacement's Tolerance option. + CrTolerance, /// The active layer's opacity (⇧: fill). Layer, None, @@ -41,6 +43,7 @@ fn target(tool: Tool) -> Target { Tool::Pencil => Target::Brush { flow: false }, Tool::Gradient | Tool::PaintBucket => Target::ToolOpacity, Tool::BackgroundEraser => Target::BgTolerance, + Tool::ColorReplacement => Target::CrTolerance, // Their options-bar number is a strength, exposure or tolerance, not this opacity. t if t.is_brushlike() || t == Tool::MagicEraser => Target::None, _ => Target::Layer, @@ -165,6 +168,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { (Target::ToolOpacity, false) => app.ui.tool_options.fill_opacity = percent, // The Tolerance field starts at 1%; `00` (0%) keeps today's value rather than guessing. (Target::BgTolerance, false) if percent >= 1.0 => app.ui.tool_options.bg_tolerance = percent, + // The field starts at 1%; an unmeasured 00 keeps the existing value. + (Target::CrTolerance, false) if percent >= 1.0 => app.ui.tool_options.cr_tolerance = percent, (Target::Layer, _) => { // The locked Background has no opacity or fill. let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..438f0df40c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1119,3 +1119,6 @@ mod red_eye_context_menu_tests; #[cfg(test)] mod clone_stamp_indexed_bar_tests; + +#[cfg(test)] +mod color_replacement_digit_keys_tests; From 34c650aaa1356393875ba59442acbedc65d0e310 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 02:55:19 -0800 Subject: [PATCH 117/385] Support digit shortcuts for Magic Eraser opacity --- .../src/background_eraser_digit_keys_tests.rs | 2 +- crates/ui-egui/src/input.rs | 3 + .../input/magic_eraser_digit_keys_tests.rs | 55 +++++++++++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 15 +++-- 4 files changed, 69 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs diff --git a/crates/ui-egui/src/background_eraser_digit_keys_tests.rs b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs index 9cddb5a7eb..a9e0d40bdf 100644 --- a/crates/ui-egui/src/background_eraser_digit_keys_tests.rs +++ b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs @@ -98,7 +98,7 @@ fn other_tools_digits_are_unchanged() { assert!((layer(&a).0 - 0.3).abs() < 1e-6); assert_eq!(tolerance(&a), 50.0); // The tools whose number is a strength, exposure or tolerance of their own still ignore the digits. - for tool in [Tool::ColorReplacement, Tool::Dodge, Tool::Smudge, Tool::MagicEraser] { + for tool in [Tool::ColorReplacement, Tool::Dodge, Tool::Smudge] { let mut a = app(tool); let before = (a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone()); press(&mut a, 3, false, 0.0); diff --git a/crates/ui-egui/src/input.rs b/crates/ui-egui/src/input.rs index b147c2182d..b021371d81 100644 --- a/crates/ui-egui/src/input.rs +++ b/crates/ui-egui/src/input.rs @@ -14,3 +14,6 @@ pub mod spring_tools; pub mod stylus; pub(super) mod tool_shortcuts; pub mod touch_twins; + +#[cfg(test)] +mod magic_eraser_digit_keys_tests; diff --git a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs new file mode 100644 index 0000000000..431428e436 --- /dev/null +++ b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs @@ -0,0 +1,55 @@ +//! #11999: Magic Eraser digits set its Opacity; Shift digits set the same field. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +fn layer(app: &PhotocraftApp) -> (f32, f32) { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + (l.opacity, l.fill_opacity) +} + +#[test] +fn digits_and_shift_digits_set_magic_eraser_opacity() { + let mut a = app(Tool::MagicEraser); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 100.0); + press(&mut a, 5, false, 0.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 50.0); + press(&mut a, 0, false, 5000.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 100.0); + press(&mut a, 3, false, 10000.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 30.0); + press(&mut a, 4, false, 20000.0); + press(&mut a, 5, false, 20300.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 45.0); + let options = serde_json::to_value(&a.ui.tool_options).unwrap(); + assert_eq!(options["magic_eraser_opacity"], json!(45.0)); + press(&mut a, 5, true, 30000.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 50.0); +} + +#[test] +fn magic_eraser_digits_leave_tolerance_layer_and_brush_alone() { + let mut a = app(Tool::MagicEraser); + let tolerance = a.ui.tool_options.tolerance; + let layer_before = layer(&a); + let brush = a.session.tools.brush.clone(); + press(&mut a, 5, false, 0.0); + assert_eq!(a.ui.tool_options.tolerance, tolerance); + assert_eq!(layer(&a), layer_before); + assert_eq!(a.session.tools.brush, brush); + press(&mut a, 0, false, 5000.0); + press(&mut a, 0, false, 5100.0); + assert_eq!(a.ui.tool_options.magic_eraser_opacity, 100.0, "unmeasured 00 keeps the first zero's value"); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 41c571f312..de88690dc9 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -3,9 +3,9 @@ //! Eraser they set the brush's Opacity (⇧: Flow, swapped while airbrush build-up is on; the Pencil has no Flow, so its ⇧ //! digits set Opacity too, #11967); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the -//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose -//! number is a strength or exposure are left alone. -//! ⌥+digit sets the Smoothing of the tools that show it (Brush, Pencil, Eraser; #11892). +//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907); and with +//! Magic Eraser its Opacity (#11999). Tools whose number is a strength or exposure are left alone. +//! ⌥+digit sets Smoothing for tools that show it (Brush, Pencil, Eraser; #11892). use egui::{Event, Key}; use serde_json::json; @@ -30,6 +30,8 @@ enum Target { ToolOpacity, /// The Background Eraser's Tolerance option. BgTolerance, + /// The Magic Eraser's Opacity option. + MagicEraserOpacity, /// The active layer's opacity (⇧: fill). Layer, None, @@ -41,8 +43,9 @@ fn target(tool: Tool) -> Target { Tool::Pencil => Target::Brush { flow: false }, Tool::Gradient | Tool::PaintBucket => Target::ToolOpacity, Tool::BackgroundEraser => Target::BgTolerance, - // Their options-bar number is a strength, exposure or tolerance, not this opacity. - t if t.is_brushlike() || t == Tool::MagicEraser => Target::None, + Tool::MagicEraser => Target::MagicEraserOpacity, + // Other brush-like tools whose number is a strength, exposure or tolerance keep no target. + t if t.is_brushlike() => Target::None, _ => Target::Layer, } } @@ -165,6 +168,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { (Target::ToolOpacity, false) => app.ui.tool_options.fill_opacity = percent, // The Tolerance field starts at 1%; `00` (0%) keeps today's value rather than guessing. (Target::BgTolerance, false) if percent >= 1.0 => app.ui.tool_options.bg_tolerance = percent, + // The field starts at 1%; an unmeasured 00 keeps its current value. + (Target::MagicEraserOpacity, _) if percent >= 1.0 => app.ui.tool_options.magic_eraser_opacity = percent, (Target::Layer, _) => { // The locked Background has no opacity or fill. let Some(st) = app.session.active() else { return }; From 56cce1d46310234715ac4d064f38e3f960948762 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 12:10:21 +0100 Subject: [PATCH 118/385] test(ui-egui): a saved Bevel default with Use Global Light off keeps its own angle after Reset to Default --- .../layer_style/bevel_reset_angle_tests.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs index 06ca7d5a37..02a898b4b8 100644 --- a/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs @@ -85,3 +85,33 @@ fn reset_to_default_does_not_move_the_documents_light() { confirm(app, pending).unwrap(); assert_eq!(app.session.active().unwrap().doc.global_light.angle, 45.0, "OK keeps the document's Global Light at 45"); } + +/// A saved default with Use Global Light off keeps its own angle through Reset to Default: the +/// shared light (45 here) is only seeded into a globally lit effect. +#[test] +fn reset_to_default_keeps_a_saved_defaults_own_angle_when_global_light_is_off() { + let mut app = app_with_doc(); + let mut saved = app.run("layer.layerStyle.defaultFor", json!({"kind": "bevelEmboss"})).unwrap()["params"].clone(); + saved["useGlobalLight"] = json!(false); + saved["angle"] = json!(77.0); + saved["size"] = json!(12); + app.run("layer.layerStyle.makeDefault", json!({"kind": "bevelEmboss", "params": saved})).unwrap(); + app.run("layer.layerStyle.bevelEmboss", json!({})).unwrap(); + app.run("layer.layerStyle.globalLight", json!({"angle": 45})).unwrap(); + let fields = { + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap(); + let mut f = initial_fields(layer, Some("bevelEmboss"), state.doc.global_light.angle); + set_param(&mut f, "fx1", "size", json!(30.0)); + f + }; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 1200.0)).build_ui_state(draw_page, (app, fields)); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + harness.get_by_role_and_label(egui::accesskit::Role::Button, "Reset to Default").click(); + harness.run_steps(3); + let bevel = &harness.state().1["effects"][0]["params"]; + assert_eq!(bevel["useGlobalLight"], json!(false), "the saved default's switch is off"); + assert_eq!(bevel["angle"], json!(77.0), "the saved default's own angle, not the shared light"); + assert_eq!(bevel["size"], json!(12), "the other fields are the saved default's too"); +} From 2a69ea368a99df7536fa897df32bbcab8675213f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 03:55:58 -0800 Subject: [PATCH 119/385] Keep consecutive digit entry within its originating tool --- .../src/color_replacement_digit_keys_tests.rs | 16 ++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 32 ++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs index 81ebb19fec..e5cd63dabf 100644 --- a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs +++ b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs @@ -71,3 +71,19 @@ fn modifiers_and_double_zero_preserve_color_replacement_and_layer_state() { assert_eq!(a.ui.tool_options.fill_opacity, opacity); assert_eq!(a.ui.tool_options.bg_tolerance, bg_tolerance); } +#[test] +fn digits_do_not_pair_across_tools() { + let mut brush_to_color = app(Tool::Brush); + press(&mut brush_to_color, 4, false, 0.0); + brush_to_color.ui.tool = Tool::ColorReplacement; + press(&mut brush_to_color, 5, false, 300.0); + assert_eq!(brush_to_color.session.tools.brush.opacity, 0.4); + assert_eq!(brush_to_color.ui.tool_options.cr_tolerance, 50.0); + + let mut color_to_brush = app(Tool::ColorReplacement); + press(&mut color_to_brush, 4, false, 0.0); + color_to_brush.ui.tool = Tool::Brush; + press(&mut color_to_brush, 5, false, 300.0); + assert_eq!(color_to_brush.ui.tool_options.cr_tolerance, 40.0); + assert_eq!(color_to_brush.session.tools.brush.opacity, 0.5); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 2034a50060..8727122495 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -16,8 +16,8 @@ use crate::state::Tool; /// A second digit within this long of the first makes a two-digit value. const TWO_DIGITS_MS: f64 = 800.0; -/// The first digit of a possible two-digit value: (digit, ⇧ held, when). -pub type Pending = Option<(u8, bool, f64)>; +/// The first digit of a possible two-digit value: (digit, ⇧ held, when, originating tool). +pub type Pending = Option<(u8, bool, f64, Tool)>; /// What a tool's number keys change. #[derive(Clone, Copy, Debug, PartialEq)] @@ -132,10 +132,11 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { /// One digit press at `now` (ms). pub fn press(app: &mut PhotocraftApp, d: u8, shift: bool, now: f64) { + let tool = app.ui.tool; let percent = match app.opacity_keys.take() { - Some((first, s, at)) if s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), + Some((first, s, at, started_with)) if started_with == tool && s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), _ => { - app.opacity_keys = Some((d, shift, now)); + app.opacity_keys = Some((d, shift, now, tool)); if d == 0 { 100.0 } else { f32::from(d) * 10.0 } } }; @@ -202,6 +203,29 @@ mod tests { (l.opacity, l.fill_opacity) } + #[test] + fn two_digits_do_not_pair_across_tools() { + // Brush and Eraser both target shared brush opacity, but a tool switch starts a new value. + let mut brush_then_eraser = app(Tool::Brush); + press(&mut brush_then_eraser, 4, false, 0.0); + brush_then_eraser.ui.tool = Tool::Eraser; + press(&mut brush_then_eraser, 5, false, 300.0); + assert_eq!(brush_then_eraser.session.tools.brush.opacity, 0.5); + + // Gradient and Paint Bucket share their opacity option but still have separate sequences. + let mut gradient_then_bucket = app(Tool::Gradient); + press(&mut gradient_then_bucket, 4, false, 0.0); + gradient_then_bucket.ui.tool = Tool::PaintBucket; + press(&mut gradient_then_bucket, 5, false, 300.0); + assert_eq!(gradient_then_bucket.ui.tool_options.fill_opacity, 50.0); + + // Same-tool pairs remain exact. + let mut same_tool = app(Tool::Brush); + press(&mut same_tool, 4, false, 0.0); + press(&mut same_tool, 5, false, 300.0); + assert_eq!(same_tool.session.tools.brush.opacity, 0.45); + } + #[test] fn digits_set_the_brush_opacity_and_shift_digits_its_flow() { let mut a = app(Tool::Brush); From 2f19768c42673ab562d412e44e53ebaa3c89e8fb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 03:55:58 -0800 Subject: [PATCH 120/385] Keep consecutive digit entry within its originating tool --- .../input/magic_eraser_digit_keys_tests.rs | 16 ++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 32 ++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs index 431428e436..9609c657a3 100644 --- a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs +++ b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs @@ -53,3 +53,19 @@ fn magic_eraser_digits_leave_tolerance_layer_and_brush_alone() { press(&mut a, 0, false, 5100.0); assert_eq!(a.ui.tool_options.magic_eraser_opacity, 100.0, "unmeasured 00 keeps the first zero's value"); } +#[test] +fn digits_do_not_pair_across_tools() { + let mut brush_to_magic = app(Tool::Brush); + press(&mut brush_to_magic, 4, false, 0.0); + brush_to_magic.ui.tool = Tool::MagicEraser; + press(&mut brush_to_magic, 5, false, 300.0); + assert_eq!(brush_to_magic.session.tools.brush.opacity, 0.4); + assert_eq!(brush_to_magic.ui.tool_options.magic_eraser_opacity, 50.0); + + let mut magic_to_brush = app(Tool::MagicEraser); + press(&mut magic_to_brush, 4, false, 0.0); + magic_to_brush.ui.tool = Tool::Brush; + press(&mut magic_to_brush, 5, false, 300.0); + assert_eq!(magic_to_brush.ui.tool_options.magic_eraser_opacity, 40.0); + assert_eq!(magic_to_brush.session.tools.brush.opacity, 0.5); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index de88690dc9..471ec00acd 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -16,8 +16,8 @@ use crate::state::Tool; /// A second digit within this long of the first makes a two-digit value. const TWO_DIGITS_MS: f64 = 800.0; -/// The first digit of a possible two-digit value: (digit, ⇧ held, when). -pub type Pending = Option<(u8, bool, f64)>; +/// The first digit of a possible two-digit value: (digit, ⇧ held, when, originating tool). +pub type Pending = Option<(u8, bool, f64, Tool)>; /// What a tool's number keys change. #[derive(Clone, Copy, Debug, PartialEq)] @@ -132,10 +132,11 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { /// One digit press at `now` (ms). pub fn press(app: &mut PhotocraftApp, d: u8, shift: bool, now: f64) { + let tool = app.ui.tool; let percent = match app.opacity_keys.take() { - Some((first, s, at)) if s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), + Some((first, s, at, started_with)) if started_with == tool && s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), _ => { - app.opacity_keys = Some((d, shift, now)); + app.opacity_keys = Some((d, shift, now, tool)); if d == 0 { 100.0 } else { f32::from(d) * 10.0 } } }; @@ -202,6 +203,29 @@ mod tests { (l.opacity, l.fill_opacity) } + #[test] + fn two_digits_do_not_pair_across_tools() { + // Brush and Eraser both target shared brush opacity, but a tool switch starts a new value. + let mut brush_then_eraser = app(Tool::Brush); + press(&mut brush_then_eraser, 4, false, 0.0); + brush_then_eraser.ui.tool = Tool::Eraser; + press(&mut brush_then_eraser, 5, false, 300.0); + assert_eq!(brush_then_eraser.session.tools.brush.opacity, 0.5); + + // Gradient and Paint Bucket share their opacity option but still have separate sequences. + let mut gradient_then_bucket = app(Tool::Gradient); + press(&mut gradient_then_bucket, 4, false, 0.0); + gradient_then_bucket.ui.tool = Tool::PaintBucket; + press(&mut gradient_then_bucket, 5, false, 300.0); + assert_eq!(gradient_then_bucket.ui.tool_options.fill_opacity, 50.0); + + // Same-tool pairs remain exact. + let mut same_tool = app(Tool::Brush); + press(&mut same_tool, 4, false, 0.0); + press(&mut same_tool, 5, false, 300.0); + assert_eq!(same_tool.session.tools.brush.opacity, 0.45); + } + #[test] fn digits_set_the_brush_opacity_and_shift_digits_its_flow() { let mut a = app(Tool::Brush); From 050e5adac94651b6994828cf7a1c0e92d7a322eb Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:49:58 +0100 Subject: [PATCH 121/385] Hue/Saturation: pick the range with seven swatches and show its centre (#14753) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Master (a hue wheel), Red, Yellow, Green, Cyan, Blue and Magenta replace the Range dropdown; the selected swatch is ringed. An edited range splits its disc into before and after with a dot under it, a right-aligned label above Hue gives the range's centre ("0° / 30°" after Reds Hue +30), and Colorize collapses the row into one disc in the colorize colour. --- .../dialogs/adjust_editors/hue_saturation.rs | 145 +++++++++++++-- .../hue_saturation_swatches_tests.rs | 168 ++++++++++++++++++ 2 files changed, 302 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs index 29393a4031..f91d6ff6a1 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs @@ -11,6 +11,12 @@ use super::{ pub(super) const RANGE_LABELS: [&str; 6] = ["Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"]; +/// The range picker's swatches in order (#14753): Master, then the six colour ranges. +pub(super) const SWATCH_LABELS: [&str; 7] = ["Master", "Red", "Yellow", "Green", "Cyan", "Blue", "Magenta"]; + +/// A range swatch's diameter, in points. +const SWATCH: f32 = 18.0; + /// The Saturation slider's track: grey to the hue at full saturation (UI-217-16). pub(super) fn saturation_track(hue_deg: f32) -> [Color32; 2] { [Color32::from_gray(128), hue_color(hue_deg)] @@ -96,19 +102,131 @@ pub(super) fn move_hue_range_zone(start: [f32; 4], zone: u8, delta: f32) -> [f32 /// The spectrum bar after the adjustment (what each hue becomes), sampled at `n` hues. fn adjusted_spectrum(v: &Value, n: usize) -> Vec { + let hues: Vec<[f32; 3]> = (0..n).map(|i| photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0])).collect(); + adjusted_colors(v, &hues) +} + +/// What the adjustment `v` makes of each colour in `rgb`. +fn adjusted_colors(v: &Value, rgb: &[[f32; 3]]) -> Vec { let adj = photocraft_engine::commands::adjustment_from_params("hueSaturation", v); - let rect = photocraft_geom::Rect::new(0, 0, n as i32, 1); - let px = (0..n) - .map(|i| { - let c = photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0]); - [c[0], c[1], c[2], 1.0] - }) - .collect(); + let rect = photocraft_geom::Rect::new(0, 0, rgb.len() as i32, 1); + let px = rgb.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect(); let mut buf = photocraft_compose::Buffer { rect, px }; photocraft_compose::adjust::apply(&adj, &mut buf); buf.px.iter().map(|p| color32([p[0], p[1], p[2]])).collect() } +/// The centre of a colour range: the middle of its fully-on span, in 0..360. +fn range_centre(bounds: [f32; 4]) -> f32 { + let b = HueRange::canonical_bounds(bounds); + ((b[1] + b[2]) / 2.0).rem_euclid(360.0) +} + +/// The label above the Hue field (#14753): the centre of colour range `range` (1 = Reds … +/// 6 = Magentas) and, once its Hue moves it, where it goes ("0° / 30°"); none for Master (0). +pub(super) fn range_centre_label(v: &Value, range: usize) -> Option { + let i = range.checked_sub(1)?; + let o = &v[*HUE_RANGES.get(i)?]; + let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds)).round(); + let h = num(o, "hue", 0.0).round(); + // `+ 0.0` turns a -0 into 0, so no "-0°". + let deg = |d: f32| format!("{:.0}°", d.rem_euclid(360.0) + 0.0); + Some(if h == 0.0 { deg(c) } else { format!("{} / {}", deg(c), deg(c + h)) }) +} + +/// What colour range `i` (0 = Reds … 5 = Magentas) shows on its swatch (#14753): the colour at its +/// centre and, once its own Hue, Saturation or Lightness is not zero, what they make of it. +pub(super) fn range_swatch(v: &Value, i: usize) -> (Color32, Option) { + let Some(key) = HUE_RANGES.get(i) else { return (Color32::TRANSPARENT, None) }; + let o = &v[*key]; + let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds)); + let before = photocraft_color::convert::hsb_to_rgb([c, 1.0, 1.0]); + let edited = ["hue", "saturation", "lightness"].iter().any(|k| num(o, k, 0.0) != 0.0); + let after = edited.then(|| { + // This range alone: Master and the other ranges don't change its swatch. + let mut only = json!({}); + only[*key] = o.clone(); + adjusted_colors(&only, &[before]).first().copied().unwrap_or(Color32::TRANSPARENT) + }); + (color32(before), after) +} + +/// The colorize colour, as Colorize makes a mid grey (#14753). +pub(super) fn colorize_color(v: &Value) -> Color32 { + adjusted_colors(v, &[[0.5; 3]]).first().copied().unwrap_or(Color32::TRANSPARENT) +} + +/// Half a disc of radius `r` at `c`: the left half or the right one. +fn half_disc(p: &egui::Painter, c: egui::Pos2, r: f32, left: bool, fill: Color32) { + let start = if left { std::f32::consts::FRAC_PI_2 } else { -std::f32::consts::FRAC_PI_2 }; + let pts = (0..=16).map(|k| start + std::f32::consts::PI * k as f32 / 16.0).map(|a| c + vec2(a.cos(), a.sin()) * r).collect(); + p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); +} + +/// A hue wheel of radius `r` at `c`, red at the top: the Master swatch. +fn hue_wheel(p: &egui::Painter, c: egui::Pos2, r: f32) { + let at = |deg: f32| { + let a = (deg - 90.0).to_radians(); + c + vec2(a.cos(), a.sin()) * r + }; + for k in 0..36 { + let (a, z) = (k as f32 * 10.0, (k + 1) as f32 * 10.0); + // Each wedge overlaps the next by a little, so no background shows through the seams. + p.add(egui::Shape::convex_polygon(vec![c, at(a - 0.5), at(z + 0.5)], hue_color(a + 5.0), Stroke::NONE)); + } +} + +/// The range picker (#14753): seven round swatches, Master (a hue wheel) then the six colour +/// ranges, the selected one ringed; a click selects that range. An edited range shows its colour +/// before and after, split down the middle, with a dot under it. Colorize collapses the row into +/// one disc in the colorize colour. +fn range_swatches(ui: &mut egui::Ui, v: &Value, range: &mut usize, colorize: bool) { + let t = Tokens::get(ui.ctx()); + let size = vec2(SWATCH, SWATCH + 6.0); + let r = SWATCH / 2.0 - 2.0; + let centre = |rect: Rect| pos2(rect.center().x, rect.top() + SWATCH / 2.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if colorize { + let (rect, resp) = ui.allocate_exact_size(size, Sense::hover()); + ui.painter().circle(centre(rect), r, colorize_color(v), Stroke::new(1.0, t.field_border)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Colorize"))); + return; + } + let swatches: Vec<(Rect, egui::Response)> = SWATCH_LABELS.iter().map(|_| ui.allocate_exact_size(size, Sense::click())).collect(); + if let Some(i) = swatches.iter().position(|(_, resp)| resp.clicked()) { + *range = i; + } + let p = ui.painter(); + for (i, ((rect, resp), label)) in swatches.into_iter().zip(SWATCH_LABELS).enumerate() { + let c = centre(rect); + if i == 0 { + hue_wheel(p, c, r); + } else { + match range_swatch(v, i - 1) { + (before, Some(after)) => { + half_disc(p, c, r, true, before); + half_disc(p, c, r, false, after); + p.circle_filled(pos2(c.x, rect.bottom() - 1.5), 1.5, t.text_dim); + } + (before, None) => { + p.circle_filled(c, r, before); + } + } + } + let selected = i == *range; + if selected { + p.circle_stroke(c, r + 1.0, Stroke::new(2.0, t.text)); + } else { + p.circle_stroke(c, r, Stroke::new(1.0, t.field_border)); + } + let label = tl!(label); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, selected, label)); + resp.on_hover_text(label); + } + }); +} + pub(super) fn spectrum_bar(p: &egui::Painter, r: Rect, colors: &[Color32]) { let n = colors.len().saturating_sub(1).max(1); for (i, w) in colors.windows(2).enumerate() { @@ -126,10 +244,7 @@ pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> if colorize { range = 0; } - ui.horizontal(|ui| { - let opts: Vec<(usize, &str)> = std::iter::once((0, tl!("Master"))).chain(RANGE_LABELS.iter().enumerate().map(|(i, l)| (i + 1, *l))).collect(); - ui.add_enabled_ui(!colorize, |ui| widgets::dropdown(ui, &format!("{range_id:?}"), tl!("Range"), &mut range, &opts, 120.0)); - }); + range_swatches(ui, v, &mut range, colorize); ui.data_mut(|d| d.insert_temp(range_id, range)); let mut e = Edit::default(); let hue_grad = widgets::hue_stops(); @@ -162,6 +277,10 @@ pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> if !v.get(key).is_some_and(Value::is_object) { v[key] = json!({}); } + if let Some(centre) = range_centre_label(v, range) { + // One row, right-aligned: a bare right-to-left layout would centre it in all the height left. + ui.horizontal(|ui| ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(RichText::new(centre).color(t.text_dim)))); + } let mut o = v[key].clone(); let mut sub = Edit::default(); let mut h = num(&o, "hue", 0.0); @@ -291,3 +410,7 @@ pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> } e } + +#[cfg(test)] +#[path = "hue_saturation_swatches_tests.rs"] +mod swatches_tests; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs new file mode 100644 index 0000000000..097ba037fa --- /dev/null +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs @@ -0,0 +1,168 @@ +//! #14753: Hue/Saturation picks its range with seven round swatches (Master, then Red, Yellow, +//! Green, Cyan, Blue, Magenta) instead of a dropdown; an edited range shows its colour before and +//! after with a dot under it, a label above the Hue field gives the range's centre, and Colorize +//! collapses the row into one disc in the colorize colour. + +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +use super::super::EditorCx; +use super::{SWATCH_LABELS, colorize_color, hue_saturation, range_centre_label, range_swatch}; + +fn cx(mem: egui::Id) -> EditorCx { + EditorCx { + mem, + hist: None, + gray: false, + swatches: [[0.0; 3], [1.0; 3]], + gradients: Vec::new(), + dialog: false, + dynamic_color_sliders: true, + isolated_curve: None, + } +} + +fn mem() -> egui::Id { + egui::Id::unique("hue-saturation-swatches-test") +} + +/// The Hue/Saturation editor over `v`, as the Properties panel hosts it. +fn harness(v: Value) -> Harness<'static, Value> { + let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state( + |ui, v: &mut Value| { + // The app's fonts load over a few frames; draw once they're in. + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + hue_saturation(ui, v, &cx(mem())); + } + }, + v, + ); + crate::PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn swatches(h: &Harness<'_, Value>) -> Vec<(String, bool)> { + h.query_all_by_role(Role::RadioButton) + .map(|n| { + let a = n.accesskit_node(); + (a.label().unwrap_or_default(), a.toggled() == Some(Toggled::True)) + }) + .collect() +} + +fn text_rect(h: &Harness<'_, Value>, text: &str) -> Option { + h.query_all_by_role(Role::Label) + .find(|n| { + let a = n.accesskit_node(); + a.value().as_deref() == Some(text) || a.label().as_deref() == Some(text) + }) + .map(|n| n.rect()) +} + +fn has_text(h: &Harness<'_, Value>, text: &str) -> bool { + text_rect(h, text).is_some() +} + +fn range(h: &Harness<'_, Value>) -> Option { + h.ctx.data(|d| d.get_temp(mem().with("hs-range"))) +} + +#[test] +fn seven_swatches_replace_the_dropdown_with_master_selected() { + let h = harness(json!({})); + let want: Vec<(String, bool)> = SWATCH_LABELS.iter().enumerate().map(|(i, l)| (l.to_string(), i == 0)).collect(); + assert_eq!(swatches(&h), want, "Master, Red, Yellow, Green, Cyan, Blue, Magenta; Master selected"); + assert!(h.query_all_by_role(Role::ComboBox).next().is_none(), "no range dropdown"); +} + +#[test] +fn a_click_selects_that_range_and_shows_its_centre() { + let mut h = harness(json!({})); + assert!(!has_text(&h, "0°") && !has_text(&h, "240°"), "no centre label for Master"); + h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(5), "Blues selected"); + assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Blue")), "only Blue is selected: {:?}", swatches(&h)); + // Right-aligned just above the Hue row (title, field and slider), which now edits Blues. + let label = text_rect(&h, "240°").expect("the Blues centre"); + let hue = h.query_all_by_role(Role::Slider).find(|n| n.accesskit_node().label().as_deref() == Some("Hue")).expect("the Hue slider").rect(); + assert!(label.bottom() <= hue.top() + 1.0 && hue.top() - label.bottom() < 48.0, "label {label:?} right above Hue {hue:?}"); + assert!(label.center().x > 160.0, "right-aligned: {label:?}"); + + h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(1)); + assert!(has_text(&h, "0°"), "the Reds centre"); + + h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(0)); + assert!(!has_text(&h, "0°"), "no centre label for Master"); +} + +#[test] +fn reds_after_a_hue_shift_label_both_centres() { + let mut h = harness(json!({"reds": {"hue": 30}})); + h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click(); + h.run_steps(3); + assert!(has_text(&h, "0° / 30°")); +} + +#[test] +fn colorize_collapses_the_row_into_one_disc() { + let h = harness(json!({"colorize": true, "hue": 120, "saturation": 25})); + assert!(swatches(&h).is_empty(), "no range swatches with Colorize on"); + assert_eq!(h.query_all_by_role_and_label(Role::Image, "Colorize").count(), 1, "one colorize disc"); +} + +#[test] +fn centre_labels() { + let v = json!({}); + assert_eq!(range_centre_label(&v, 0), None, "Master"); + assert_eq!(range_centre_label(&v, 1).as_deref(), Some("0°"), "Reds"); + assert_eq!(range_centre_label(&v, 2).as_deref(), Some("60°"), "Yellows"); + assert_eq!(range_centre_label(&v, 5).as_deref(), Some("240°"), "Blues"); + assert_eq!(range_centre_label(&v, 6).as_deref(), Some("300°"), "Magentas"); + assert_eq!(range_centre_label(&v, 7), None, "past the ranges: no label, no panic"); + assert_eq!(range_centre_label(&json!({"reds": {"hue": 30}}), 1).as_deref(), Some("0° / 30°")); + assert_eq!(range_centre_label(&json!({"reds": {"hue": -30}}), 1).as_deref(), Some("0° / 330°")); + // A moved range: its centre is the middle of its fully-on span. + assert_eq!(range_centre_label(&json!({"blues": {"range": [190, 220, 240, 270]}}), 5).as_deref(), Some("230°")); + // Saturation or Lightness alone moves no hue. + assert_eq!(range_centre_label(&json!({"blues": {"saturation": 50}}), 5).as_deref(), Some("240°")); +} + +#[test] +fn an_edited_range_shows_before_and_after() { + let close = |a: egui::Color32, b: [u8; 3]| [a.r(), a.g(), a.b()].iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 2); + let (before, after) = range_swatch(&json!({}), 0); + assert!(close(before, [255, 0, 0]), "Reds: red, {before:?}"); + assert_eq!(after, None, "an untouched range has no after half"); + + let (before, after) = range_swatch(&json!({"reds": {"hue": 30}}), 0); + assert!(close(before, [255, 0, 0])); + let after = after.expect("Hue +30 edits Reds"); + assert!(close(after, [255, 128, 0]), "red turned 30° towards yellow: {after:?}"); + + let (_, after) = range_swatch(&json!({"blues": {"lightness": -100}}), 4); + assert!(close(after.expect("Lightness edits Blues"), [0, 0, 0]), "Blues at Lightness -100 is black"); + + // Master and the other ranges leave a range's swatch alone. + assert_eq!(range_swatch(&json!({"hue": 90, "greens": {"saturation": -50}}), 0).1, None); + // Reset puts every range back to zero: the after halves go. + let reset = json!({"reds": {"hue": 0, "saturation": 0, "lightness": 0}}); + assert_eq!(range_swatch(&reset, 0).1, None); + assert_eq!(range_swatch(&json!({}), 6), (egui::Color32::TRANSPARENT, None), "past the ranges: no panic"); +} + +#[test] +fn the_colorize_disc_takes_the_colorize_colour() { + let c = colorize_color(&json!({"colorize": true, "hue": 120, "saturation": 100})); + assert!(c.g() > c.r() + 64 && c.g() > c.b() + 64, "green: {c:?}"); + let c = colorize_color(&json!({"colorize": true, "hue": 240, "saturation": 100})); + assert!(c.b() > c.r() + 64 && c.b() > c.g() + 64, "blue: {c:?}"); +} From c5cdf2f40956154f83e2a2b1e622e2a40c41db3e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:01 +0100 Subject: [PATCH 122/385] Color Table: an .act count of 0 loads as one white entry (#14374) Load... with an .act trailer count of 0 gave an empty table that OK could not apply ("a color table has 1 to 256 entries"). act_table now returns one white entry for it, as measured. Other counts, a count over 256 and a file without a trailer load as before; transparency handling for a count-0 file is unchanged. --- crates/engine/src/cmd/swatch_cmds.rs | 11 +++- .../cmd/swatch_cmds/act_zero_count_tests.rs | 58 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/swatch_cmds/act_zero_count_tests.rs diff --git a/crates/engine/src/cmd/swatch_cmds.rs b/crates/engine/src/cmd/swatch_cmds.rs index 1a65981567..3e5e42999e 100644 --- a/crates/engine/src/cmd/swatch_cmds.rs +++ b/crates/engine/src/cmd/swatch_cmds.rs @@ -476,10 +476,16 @@ fn kind_to_ase(k: SwatchKind) -> AseKind { pub const ACT_COLORS: usize = craft_psd::act::COLOR_COUNT; /// `.act` bytes as `#rrggbb` colors plus the transparent index, for the Color Table dialog. +/// A trailer count of 0 gives one white entry, as Photoshop loads it, never an empty table +/// that `image.mode.colorTable` would refuse. pub fn act_table(bytes: &[u8]) -> std::result::Result<(Vec, Option), String> { let f = craft_psd::act::parse(bytes).map_err(|e| e.to_string())?; let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); - Ok((f.used().iter().map(hex).collect(), f.transparent_index().map(|i| i as u64))) + let mut colors: Vec = f.used().iter().map(hex).collect(); + if colors.is_empty() { + colors.push(hex(&[255, 255, 255])); + } + Ok((colors, f.transparent_index().map(|i| i as u64))) } /// Encode colors as `.act` bytes (at most [`ACT_COLORS`]); the transparent index is kept. @@ -880,3 +886,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod act_zero_count_tests; diff --git a/crates/engine/src/cmd/swatch_cmds/act_zero_count_tests.rs b/crates/engine/src/cmd/swatch_cmds/act_zero_count_tests.rs new file mode 100644 index 0000000000..121113f3bd --- /dev/null +++ b/crates/engine/src/cmd/swatch_cmds/act_zero_count_tests.rs @@ -0,0 +1,58 @@ +//! Color Table › Load… with an `.act` trailer count of 0 (#14374): one white entry, as Photoshop +//! loads it, instead of an empty table that OK can't apply. +use super::*; + +/// The measured test file: 256 triplets with entry 0 = (10, 20, 30), the rest black, then the +/// trailer (`count`, transparent 0xFFFF) unless `count` is `None`. +fn act(count: Option) -> Vec { + let mut b = vec![0u8; ACT_COLORS * 3]; + b[..3].copy_from_slice(&[10, 20, 30]); + if let Some(n) = count { + b.extend_from_slice(&n.to_be_bytes()); + b.extend_from_slice(&0xFFFFu16.to_be_bytes()); + } + b +} + +#[test] +fn count_zero_loads_one_white_entry() { + let bytes = act(Some(0)); + assert_eq!(bytes.len(), 772); + let (colors, transparent) = act_table(&bytes).unwrap(); + assert_eq!(colors, vec!["#ffffff".to_string()], "one white entry, not the file's first colour"); + assert_eq!(transparent, None); + // Not measured: a count-0 file that also names a transparent index keeps today's handling + // (the index is outside the file's zero used colours, so there is no transparent entry). + let mut bytes = act(Some(0)); + bytes[770..772].copy_from_slice(&0u16.to_be_bytes()); + assert_eq!(act_table(&bytes).unwrap().1, None); +} + +#[test] +fn the_loaded_table_applies_and_saves_with_count_one() { + let (colors, transparent) = act_table(&act(Some(0))).unwrap(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "uniform", "colors": 8, "dither": "none", "forced": "none"})).unwrap(); + // What the dialog's OK sends after Load…. + s.execute("image.mode.colorTable", json!({"table": "custom", "colors": colors, "transparent": transparent})).unwrap(); + let table = s.active().unwrap().doc.color_table.clone().unwrap(); + assert_eq!(table.colors, vec![[255u8, 255, 255]]); + // Save… writes the table with count 1 in the trailer. + let saved = act_bytes(&table.colors, None).unwrap(); + assert_eq!(saved.len(), 772); + assert_eq!(&saved[..3], &[255, 255, 255]); + assert_eq!(&saved[768..770], &1u16.to_be_bytes()); +} + +#[test] +fn other_counts_and_a_missing_trailer_load_as_before() { + for (count, len) in [(Some(1), 1), (Some(40), 40), (Some(256), 256), (Some(300), 256), (None, 256)] { + let (colors, transparent) = act_table(&act(count)).unwrap(); + assert_eq!(colors.len(), len, "count {count:?}"); + assert_eq!(colors[0], "#0a141e", "count {count:?}"); + assert!(colors[1..].iter().all(|c| c == "#000000"), "count {count:?}"); + assert_eq!(transparent, None, "count {count:?}"); + } + assert!(act_table(&[0u8; 10]).is_err(), "junk bytes still fail"); +} From 26029f9fce62a138af3af5582ed3aa0fe861c369 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:52:03 +0100 Subject: [PATCH 123/385] Hue/Saturation: a focused range swatch shows its own focus ring (#14753) Tabbing to a swatch left no visible mark while the selection ring stayed on the selected range. A focused swatch now gets a thin accent ring outside the selection ring, so focus and selection read apart. --- .../dialogs/adjust_editors/hue_saturation.rs | 5 ++++ .../hue_saturation_swatches_tests.rs | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs index f91d6ff6a1..acbab6f0ee 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs @@ -220,6 +220,11 @@ fn range_swatches(ui: &mut egui::Ui, v: &Value, range: &mut usize, colorize: boo } else { p.circle_stroke(c, r, Stroke::new(1.0, t.field_border)); } + // Keyboard focus gets its own accent ring, clear of the selection ring, so tabbing to + // a swatch shows where Space or Enter will act without moving the selection. + if resp.has_focus() { + p.circle_stroke(c, r + 3.0, Stroke::new(1.0, t.accent)); + } let label = tl!(label); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, selected, label)); resp.on_hover_text(label); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs index 097ba037fa..123fb09e06 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs @@ -112,6 +112,35 @@ fn reds_after_a_hue_shift_label_both_centres() { assert!(has_text(&h, "0° / 30°")); } +/// Circles stroked in `color` whose centre lies inside `rect`. +fn rings_in(h: &Harness<'_, Value>, rect: egui::Rect, color: egui::Color32) -> usize { + h.output() + .shapes + .iter() + .filter(|s| matches!(&s.shape, egui::Shape::Circle(c) if c.stroke.color == color && c.stroke.width > 0.0 && rect.contains(c.center))) + .count() +} + +#[test] +fn a_focused_swatch_shows_focus_apart_from_the_selection() { + let mut h = harness(json!({})); + let accent = crate::theme::Tokens::get(&h.ctx).accent; + let blue = h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").rect(); + let master = h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").rect(); + assert_eq!(rings_in(&h, blue, accent), 0, "no focus ring before focus"); + + h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").focus(); + h.run_steps(3); + assert_eq!(range(&h), Some(0), "focus alone keeps Master selected"); + assert_eq!(rings_in(&h, blue, accent), 1, "the focused Blue swatch has a focus ring"); + assert_eq!(rings_in(&h, master, accent), 0, "the selected Master swatch has none"); + assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Master")), "selection unchanged: {:?}", swatches(&h)); + + h.key_press(egui::Key::Space); + h.run_steps(3); + assert_eq!(range(&h), Some(5), "Space selects the focused swatch"); +} + #[test] fn colorize_collapses_the_row_into_one_disc() { let h = harness(json!({"colorize": true, "hue": 120, "saturation": 25})); From 5f9ed96ed34d1c674b9eee7af040991371b48e03 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:32:06 +0100 Subject: [PATCH 124/385] Import Data Sets: only `true` makes a Visibility variable visible (#13933) An imported Visibility cell counted `1`, `yes`, `visible` and `on` as visible; the reference application treats only `true` (any case) as visible and every other word as invisible. --- crates/engine/src/cmd/variables_cmds.rs | 4 +- .../variables_cmds/import_visibility_tests.rs | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/variables_cmds/import_visibility_tests.rs diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index 5ca297b7bb..b1e16a840c 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -333,7 +333,7 @@ pub fn import_data_sets_text(s: &mut Session, text: &str, p: &Value) -> Result VarValue::Visibility(matches!(cell.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "visible" | "on")), + VarKind::Visibility => VarValue::Visibility(cell.trim().eq_ignore_ascii_case("true")), VarKind::PixelReplacement { .. } => VarValue::Pixels(cell.clone()), VarKind::TextReplacement => VarValue::Text(cell.clone()), }; @@ -570,6 +570,8 @@ pub fn specs() -> Vec { #[cfg(test)] mod import_history_tests; #[cfg(test)] +mod import_visibility_tests; +#[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/variables_cmds/import_visibility_tests.rs b/crates/engine/src/cmd/variables_cmds/import_visibility_tests.rs new file mode 100644 index 0000000000..403af150d2 --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/import_visibility_tests.rs @@ -0,0 +1,50 @@ +//! Which words in an imported Visibility cell mean visible (#13933): only `true`. + +use super::*; +use photocraft_doc::Layer; + +/// Import one data set per `cells` entry into a document with a Visibility variable `show`, and +/// return each set's stored visibility. +fn imported_visibility(cells: &[&str]) -> Vec { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let badge = s + .edit("setup", |doc, _| { + let layer = Layer::raster("badge", doc.pixel_format()); + let id = layer.id; + doc.layers.push(layer); + Ok(id) + }) + .unwrap(); + s.execute("image.variables.define", json!({"defs": [{"name": "show", "layer": badge.0, "type": "visibility"}]})).unwrap(); + let csv = format!("show\n{}\n", cells.join("\n")); + let r = import_data_sets_text(&mut s, &csv, &json!({})).unwrap(); + assert_eq!(r["imported"], cells.len()); + s.active() + .unwrap() + .doc + .variables + .data_sets + .iter() + .map(|set| match set.values.as_slice() { + [DataValue { value: VarValue::Visibility(v), .. }] => *v, + other => panic!("expected one visibility value, got {other:?}"), + }) + .collect() +} + +#[test] +fn only_true_means_visible() { + assert_eq!(imported_visibility(&["true"]), [true]); +} + +#[test] +fn other_words_mean_invisible() { + let cells = ["false", "FALSE", "yes", "1", "visible", "on"]; + assert_eq!(imported_visibility(&cells), [false; 6]); +} + +#[test] +fn other_capitalisations_of_true_stay_visible() { + assert_eq!(imported_visibility(&["TRUE", "True", " true "]), [true; 3]); +} From eba0b09fcb49fcc30ac1c5fffaa0e7d6dc5a75eb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 07:06:47 -0800 Subject: [PATCH 125/385] Reset Mixer Brush to its measured per-tool defaults --- crates/ui-egui/src/canvas/paint_mouse.rs | 15 +- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/mixer_reset_defaults.rs | 212 ++++++++++++++++++ 3 files changed, 227 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/it/mixer_reset_defaults.rs diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index cb10304723..461823461a 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -90,6 +90,8 @@ fn session_fields(current: &BrushSettings, brush: &BrushSettings) -> BrushSettin /// The Brush tool's tip after Reset Tool, as the reference measures it (#11810): size, hardness /// and spacing of a 13 px soft round at 25 % spacing. const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); +/// The Mixer Brush's tip after Reset Tool (#11945): a 35 px soft round at 25 % spacing. +const MIXER_BRUSH_TIP: (f32, f32, f32) = (35.0, 0.0, 0.25); /// The Eraser's tip after Reset Tool (#11936): a 13 px hard round at 25 % spacing, with no /// smoothing. const ERASER_TOOL_TIP: (f32, f32, f32) = (13.0, 1.0, 0.25); @@ -113,7 +115,8 @@ const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is -/// [`BRUSH_TOOL_TIP`], the Eraser's [`ERASER_TOOL_TIP`] with no smoothing, the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's +/// [`BRUSH_TOOL_TIP`], the Mixer Brush's [`MIXER_BRUSH_TIP`] and measured mixer settings, the +/// Eraser's [`ERASER_TOOL_TIP`] with no smoothing, 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 /// tool's [`SMUDGE_TOOL_TIP`] and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the @@ -122,6 +125,16 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; match tool { Tool::Brush => (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP, + Tool::MixerBrush => { + (brush.size, brush.hardness, brush.spacing) = MIXER_BRUSH_TIP; + brush.mixer.wet = 0.8; + brush.mixer.load = 0.75; + brush.mixer.mix = 0.9; + brush.mixer.flow = 1.0; + brush.mixer.load_after_stroke = true; + brush.mixer.clean_after_stroke = true; + brush.mixer.sample_all_layers = false; + } Tool::Eraser => { (brush.size, brush.hardness, brush.spacing) = ERASER_TOOL_TIP; brush.smoothing.amount = 0.0; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ea4a520871..349a2148f8 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -47,6 +47,7 @@ mod live_stroke_canvas; mod magnetic_lasso_right_click; mod marching_ants_pixels; mod marquee_autoscroll; +mod mixer_reset_defaults; mod paint_bucket_all_layers; mod pattern_preview_canvas; mod radial_blur_center; diff --git a/crates/ui-egui/tests/it/mixer_reset_defaults.rs b/crates/ui-egui/tests/it/mixer_reset_defaults.rs new file mode 100644 index 0000000000..c55f7f3ff3 --- /dev/null +++ b/crates/ui-egui/tests/it/mixer_reset_defaults.rs @@ -0,0 +1,212 @@ +//! #11945: Mixer Brush reset defaults belong to the UI tool, not command constructors. + +use egui::{Context, RawInput, Shape}; +use photocraft_color::BlendMode; +use photocraft_engine::{BrushSettings, Session}; +use photocraft_ui_egui::control::{ControlRequest, Outcome, handle}; +use photocraft_ui_egui::{PhotocraftApp, Tool}; +use serde_json::{Value, json}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.sync_views(); + app +} + +fn control(app: &mut PhotocraftApp, params: Value) { + let ctx = Context::default(); + let (req, _rx) = ControlRequest::new("ui.menu.invoke", params); + let Outcome::Done(reply) = handle(app, &ctx, &req) else { panic!("reset must finish synchronously") }; + assert_eq!(reply["ok"], true, "{reply}"); + app.sync_views(); +} + +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + photocraft_ui_egui::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +fn reset(app: &mut PhotocraftApp) { + control(app, json!({"id": "tool.reset"})); +} + +fn reset_all(app: &mut PhotocraftApp) { + control(app, json!({"id": "tool.resetAll", "params": {"confirmed": true}})); +} + +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); + (b.flip_x, b.flip_y, b.pressure_size) = (true, true, true); + b.opacity = 0.3; + b.mode = BlendMode::Multiply; + b.smoothing.amount = 0.6; + let m = &mut b.mixer; + (m.wet, m.load, m.mix, m.flow) = (0.1, 0.2, 0.3, 0.4); + (m.load_after_stroke, m.clean_after_stroke, m.sample_all_layers) = (false, false, true); +} + +fn assert_mixer_reset(app: &mut PhotocraftApp) { + assert_eq!(tip(app), [35.0, 0.0, 0.25, 0.0, 1.0]); + let b = &app.session.tools.brush; + assert_eq!((b.flip_x, b.flip_y, b.pressure_size), (false, false, false)); + assert_eq!((b.opacity, b.mode, b.smoothing.amount), (1.0, BlendMode::Normal, 0.1)); + let m = &b.mixer; + assert_eq!((m.wet, m.load, m.mix, m.flow), (0.8, 0.75, 0.9, 1.0)); + assert_eq!((m.load_after_stroke, m.clean_after_stroke, m.sample_all_layers), (true, true, false)); +} + +/// Check the actual painted chip label, scoped to its public response rectangle. +fn assert_chip(app: &mut PhotocraftApp, label: &str) { + fn has_text(shape: &Shape, rect: egui::Rect, label: &str) -> bool { + match shape { + Shape::Text(text) => text.galley.text() == label && rect.contains(text.pos), + Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, rect, label)), + _ => false, + } + } + let ctx = Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 300.0))); + let mut out = ctx.run_ui(RawInput { screen_rect, ..Default::default() }, |ui| photocraft_ui_egui::panels::options_bar(app, ui)); + let rect = ctx.read_response(photocraft_ui_egui::brush_picker::chip_id()).expect("brush chip response").rect; + assert!(out.shapes.iter().any(|shape| has_text(&shape.shape, rect, label)), "painted chip {label}"); + out.textures_delta.clear(); +} + +#[test] +fn reset_tool_gives_the_mixer_its_35_px_soft_tip_and_measured_options() { + let mut app = app(); + pick(&mut app, Tool::MixerBrush); + scramble(&mut app); + assert_chip(&mut app, "57"); + reset(&mut app); + assert_mixer_reset(&mut app); + assert_chip(&mut app, "35"); +} + +#[test] +fn reset_all_gives_the_mixer_its_defaults_active_or_picked_later() { + let mut active = app(); + pick(&mut active, Tool::MixerBrush); + scramble(&mut active); + reset_all(&mut active); + assert_mixer_reset(&mut active); + assert_chip(&mut active, "35"); + let mut inactive = app(); + pick(&mut inactive, Tool::MixerBrush); + scramble(&mut inactive); + pick(&mut inactive, Tool::Brush); + reset_all(&mut inactive); + pick(&mut inactive, Tool::MixerBrush); + assert_mixer_reset(&mut inactive); + assert_chip(&mut inactive, "35"); +} + +#[test] +fn mixer_reset_preserves_the_brush_and_eraser_own_resets() { + let mut app = app(); + pick(&mut app, Tool::MixerBrush); + reset(&mut app); + for (tool, expected) in [(Tool::Brush, [13.0, 0.0, 0.25, 0.0, 1.0]), (Tool::Eraser, [13.0, 1.0, 0.25, 0.0, 1.0])] { + pick(&mut app, tool); + scramble(&mut app); + reset(&mut app); + assert_eq!(tip(&mut app), expected, "{tool:?} Reset Tool"); + } + pick(&mut app, Tool::MixerBrush); + reset_all(&mut app); + for (tool, expected) in [(Tool::Brush, [13.0, 0.0, 0.25, 0.0, 1.0]), (Tool::Eraser, [13.0, 1.0, 0.25, 0.0, 1.0])] { + pick(&mut app, tool); + assert_eq!(tip(&mut app), expected, "{tool:?} Reset All"); + } +} + +#[test] +fn switching_back_keeps_the_mixers_edited_brush() { + let mut app = app(); + pick(&mut app, Tool::MixerBrush); + reset(&mut app); + scramble(&mut app); + let edited = app.session.tools.brush.clone(); + pick(&mut app, Tool::Brush); + let brush = app.session.tools.brush.clone(); + pick(&mut app, Tool::MixerBrush); + assert_eq!(app.session.tools.brush, edited); + pick(&mut app, Tool::Brush); + assert_eq!(app.session.tools.brush, brush); +} + +#[test] +fn mixer_reset_keeps_session_fields_and_clears_the_current_preset() { + let mut app = app(); + pick(&mut app, Tool::MixerBrush); + let b = &mut app.session.tools.brush; + b.color = [0.2, 0.4, 0.6, 1.0]; + b.background = [0.8, 0.6, 0.4, 1.0]; + b.erase = true; + b.seed = 1234; + let fields = (b.color, b.background, b.erase, b.seed); + app.session.tools.current_preset = Some("mixer-before-reset".into()); + reset(&mut app); + assert_mixer_reset(&mut app); + let b = &app.session.tools.brush; + assert_eq!((b.color, b.background, b.erase, b.seed), fields); + assert_eq!(app.session.tools.current_preset, None); +} + +#[test] +fn constructors_and_implicit_mixer_commands_keep_global_defaults() { + let defaults = BrushSettings::default(); + assert_eq!((defaults.size, defaults.hardness, defaults.spacing), (20.0, 1.0, 0.1)); + assert_eq!(defaults.smoothing.amount, 0.0); + let m = defaults.mixer; + assert_eq!((m.wet, m.load, m.mix, m.flow), (0.5, 0.5, 0.5, 1.0)); + assert_eq!((m.load_after_stroke, m.clean_after_stroke, m.sample_all_layers), (true, true, false)); + // A session starts at 10% smoothing (ToolState::default), unlike the raw brush constructor. + let session_defaults = BrushSettings { smoothing: photocraft_paint::Smoothing { amount: 0.1, ..Default::default() }, ..BrushSettings::default() }; + assert_eq!(Session::new().tools.brush, session_defaults); + let mut implicit = app(); + let mut explicit = app(); + for app in [&mut implicit, &mut explicit] { + assert_eq!(app.session.tools.brush, session_defaults); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#8090a0"})).unwrap(); + } + let before = { + let st = implicit.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(30, 24) + }; + implicit.run("paint.mixerBrush", json!({"points": [[20, 24], [40, 24]], "seed": 17})).unwrap(); + explicit.run("paint.mixerBrush", json!({"points": [[20, 24], [40, 24]], "seed": 17, "wet": 50, "load": 50, "mix": 50, "flow": 100})).unwrap(); + let a = implicit.session.active().unwrap(); + let b = explicit.session.active().unwrap(); + let a = a.doc.layer(a.active_layer.unwrap()).unwrap().surface().unwrap(); + let b = b.doc.layer(b.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_ne!(a.pixel(30, 24), before, "the default-settings control actually paints"); + for y in 0..48 { + for x in 0..64 { + assert_eq!(a.pixel(x, y), b.pixel(x, y), "implicit mixer defaults at {x},{y}"); + } + } + assert_eq!(implicit.session.tools.brush, session_defaults); +} + +#[test] +fn first_use_without_reset_keeps_existing_inheritance() { + // A compatibility control, not a claim that the reference's first use was measured. + let mut app = app(); + pick(&mut app, Tool::Blur); + scramble(&mut app); + let old = app.session.tools.brush.clone(); + pick(&mut app, Tool::MixerBrush); + let expected = BrushSettings { mode: BlendMode::Normal, smoothing: photocraft_paint::Smoothing { amount: 0.1, ..Default::default() }, ..old }; + assert_eq!(app.session.tools.brush, expected); +} From f0a0543abfb28b01bee562922ad341df58ccfe8e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 10:10:46 -0500 Subject: [PATCH 126/385] Batch: an input that takes no number neither overflows the serial nor blocks an in-place batch plan_counting asks counts before it works out an input's serial, so a refused input past 4294967295 is named with the last number for its error entry instead of failing the batch. Both source-overwrite checks (plan_counting's and validate_flat_outputs, through the new validate_written_outputs) skip the names of refused inputs, which are never written, while every input stays a source. From CodeRabbit's review. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- .../engine/src/cmd/file_cmds/batch_naming.rs | 21 ++++++---- crates/engine/src/cmd/file_cmds/batch_run.rs | 11 +++++- .../batch_serial_skip_failed_tests.rs | 38 +++++++++++++++++++ 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/batch_naming.rs b/crates/engine/src/cmd/file_cmds/batch_naming.rs index 8b29be8495..992c1fdf46 100644 --- a/crates/engine/src/cmd/file_cmds/batch_naming.rs +++ b/crates/engine/src/cmd/file_cmds/batch_naming.rs @@ -293,13 +293,18 @@ pub fn plan_counting(inputs: &[BatchInput], output: &str, format: &str, params: None }; let mut outputs = Vec::with_capacity(inputs.len()); + let mut counted = Vec::with_capacity(inputs.len()); let mut index = 0usize; for input in inputs { let BatchInput { path, rel_dir } = input; - let serial = if has_serial { - u32::try_from(index).ok().and_then(|index| start.checked_add(index)).ok_or_else(|| bad("startingSerial plus the input count exceeds 4294967295"))? - } else { - start + let counts_serial = counts(input); + let serial = match u32::try_from(index).ok().and_then(|index| start.checked_add(index)) { + _ if !has_serial => start, + Some(serial) => serial, + // An input that takes no number is named only for its error entry: past the last + // number, it keeps the last one rather than failing the batch. + None if !counts_serial => u32::MAX, + None => return Err(bad("startingSerial plus the input count exceeds 4294967295")), }; let ext = if format == "same" { super::same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; let name = if let (Some(components), Some(calendar)) = (structured, calendar) { @@ -322,17 +327,19 @@ pub fn plan_counting(inputs: &[BatchInput], output: &str, format: &str, params: // Preserve the recorded structured routing; ordinary native templates use main's flat output. let subfolder = if structured.is_some() && !flat { rel_dir.as_str() } else { "" }; outputs.push(join(&join(output, subfolder), &name)); - if counts(input) { + counted.push(counts_serial); + if counts_serial { index += 1; } } // Renaming within the source folder could replace a later input before it is read. Resolve // existing paths so aliases such as `source/./001.png` cannot bypass the check. The default - // (no template) path keeps its existing in-place behavior. + // (no template) path keeps its existing in-place behavior. An input that takes no number + // fails before it is opened, so nothing is written to its name. #[cfg(not(target_arch = "wasm32"))] { let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|i| std::fs::canonicalize(&i.path).ok()).collect(); - for output in &outputs { + for output in outputs.iter().zip(&counted).filter_map(|(output, counts)| counts.then_some(output)) { let identity = super::paths::destination_identity(std::path::Path::new(output)) .ok_or_else(|| bad(format!("naming output path cannot be resolved safely: {output}")))?; if sources.contains(&identity) { diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index b410afb9fa..0344b7585c 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -477,9 +477,16 @@ fn validate_error_log(policy: &BatchPolicy, inputs: impl IntoIterator Result<()> { + validate_written_outputs(outputs, &|_| true) +} + +/// [`validate_flat_outputs`] for the outputs at the indices `written` accepts: every input stays a +/// source, but an input that fails before it is opened writes nothing to its name. +#[cfg(not(target_arch = "wasm32"))] +fn validate_written_outputs(outputs: &[(String, String)], written: &dyn Fn(usize) -> bool) -> Result<()> { let sources: std::collections::HashMap<_, _> = outputs.iter().enumerate().filter_map(|(index, (input, _))| std::fs::canonicalize(input).ok().map(|identity| (identity, index))).collect(); - for (index, (_, output)) in outputs.iter().enumerate() { + for (index, (_, output)) in outputs.iter().enumerate().filter(|(index, _)| written(*index)) { let identity = super::paths::destination_identity(std::path::Path::new(output)) .ok_or_else(|| EngineError::BadParams { cmd: "file.automate.batch".into(), msg: format!("output path cannot be resolved safely: {output}") })?; if sources.get(&identity).is_some_and(|&source_index| source_index != index) { @@ -940,7 +947,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } }; #[cfg(not(target_arch = "wasm32"))] - validate_flat_outputs(&outputs)?; + validate_written_outputs(&outputs, &|index| inputs.get(index).is_none_or(counts))?; validate_error_log(&policy, outputs.iter().map(|(path, _)| path.clone()), outputs.iter().map(|(_, path)| path.clone()))?; let was_playing = nested; #[cfg(test)] diff --git a/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs index fd553a6090..b3a3fd4217 100644 --- a/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs +++ b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs @@ -65,3 +65,41 @@ fn serial_letters_follow_the_same_counter() { let names = run(&input, &output, true, json!([{"component":"letter"}, {"text":"_x"}])); assert_eq!(names, ["a_x", "b_x", "c_x", "d_x", "e_x"]); } + +/// A folder of `files` (PNGs where the name ends in `.png`, text otherwise) run with `naming`. +fn run_named(label: &str, files: &[&str], in_place: bool, start: u32, naming: &str) -> (Vec, usize) { + let dir = tmp(label); + let input = join(&dir, "in"); + std::fs::create_dir_all(&input).unwrap(); + for name in files { + if name.ends_with(".png") { + write_png(&join(&input, name)); + } else { + std::fs::write(join(&input, name), b"not an image").unwrap(); + } + } + let output = if in_place { input.clone() } else { join(&dir, "out") }; + let mut s = Session::new(); + let p = json!({ + "input": input, "output": output, "steps": [], "format": "same", "startingSerial": start, + "includeNonImages": true, "naming": naming + }); + let result = s.execute("file.automate.batch", p).unwrap(); + let files = result["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap()).to_string()).collect(); + (files, result["errors"].as_array().unwrap().len()) +} + +#[test] +fn a_refused_input_after_the_last_serial_number_does_not_fail_the_batch() { + let (files, errors) = run_named("last-serial", &["a.png", "z"], false, u32::MAX, "{name}_{serial}.png"); + assert_eq!((files.as_slice(), errors), (["a_4294967295.png".to_string()].as_slice(), 1)); +} + +#[test] +fn a_refused_input_named_like_a_source_does_not_stop_an_in_place_batch() { + // `z` takes no number, so its name is `z_003.png`, the next input's own name: nothing is + // written to it, so the batch still runs in place. + let (files, errors) = run_named("in-place", &["a.png", "b", "c.png", "z", "z_003.png"], true, 1, "{name}_{serial:3}.png"); + assert_eq!(files, ["a_001.png", "c_002.png", "z_003_003.png"]); + assert_eq!(errors, 2); +} From ae57082612e342246105647550bbfd456bf58566 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:29:55 +0100 Subject: [PATCH 127/385] test(ui): expect sampler menus to close on document switches Capture the stale menu before file.new, assert immediate dismissal, and preserve the cross-document Delete safety assertion. --- crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs index e950d770f3..2bb0e270b6 100644 --- a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs @@ -135,11 +135,12 @@ fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() // Another document with a sampler at the same index and spot: still not this menu's sampler. right_click(&mut app, &ctx, 180.0, 90.0); assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + let menu = app.ui.canvas_tool_menu.clone().expect("the menu is open before switching documents"); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + assert!(app.ui.canvas_tool_menu.is_none(), "switching documents closes the menu"); for (x, y) in [(20, 20), (180, 90)] { app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); } - let menu = app.ui.canvas_tool_menu.clone().expect("the menu is still open"); assert!(!crate::canvas_tool_menu::entry_enabled(&app, &menu, SAMPLER_DELETE), "another document's sampler"); } From 10fbe302ff36456dfea6a42a3002d835924c22cb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 10:42:38 -0500 Subject: [PATCH 128/385] Batch: the error log may take the name of an input that takes no number validate_error_log compared the log path with every planned output, including the names of refused inputs, which are never written. It now gets only the outputs of inputs that count, while every input stays protected. From CodeRabbit's review. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/engine/src/cmd/file_cmds/batch_run.rs | 4 ++- .../batch_serial_skip_failed_tests.rs | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 0344b7585c..de2858b593 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -948,7 +948,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { }; #[cfg(not(target_arch = "wasm32"))] validate_written_outputs(&outputs, &|index| inputs.get(index).is_none_or(counts))?; - validate_error_log(&policy, outputs.iter().map(|(path, _)| path.clone()), outputs.iter().map(|(_, path)| path.clone()))?; + // Every input is protected; a refused input's name is never written, so the log may take it. + let written = outputs.iter().zip(&inputs).filter(|(_, input)| counts(input)).map(|((_, path), _)| path.clone()); + validate_error_log(&policy, outputs.iter().map(|(path, _)| path.clone()), written)?; let was_playing = nested; #[cfg(test)] let history_observer = s.batch_history_observer; diff --git a/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs index b3a3fd4217..f428a85688 100644 --- a/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs +++ b/crates/engine/src/cmd/file_cmds/batch_serial_skip_failed_tests.rs @@ -103,3 +103,28 @@ fn a_refused_input_named_like_a_source_does_not_stop_an_in_place_batch() { assert_eq!(files, ["a_001.png", "c_002.png", "z_003_003.png"]); assert_eq!(errors, 2); } + +#[test] +fn the_error_log_may_take_a_refused_inputs_name() { + // `d.txt` takes no number, so its name `d_003.png` is never written and the log can use it. + let dir = tmp("log-name"); + let input = join(&dir, "in"); + std::fs::create_dir_all(&input).unwrap(); + for name in ["a.png", "c.png"] { + write_png(&join(&input, name)); + } + for name in ["b.txt", "d.txt"] { + std::fs::write(join(&input, name), b"not an image").unwrap(); + } + let output = join(&dir, "out"); + let log = join(&output, "d_003.png"); + let p = json!({ + "input": input, "output": output, "steps": [], "format": "same", "includeNonImages": true, + "naming": "{name}_{serial:3}.png", "errorLog": log + }); + let result = Session::new().execute("file.automate.batch", p).unwrap(); + let files: Vec = result["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap()).to_string()).collect(); + assert_eq!(files, ["a_001.png", "c_002.png"]); + assert_eq!(result["errors"].as_array().unwrap().len(), 2); + assert_eq!(result["errorLog"], json!(log)); +} From a85439bedb8ade0e0aafe1190d724bedade62208 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 16:45:03 +0100 Subject: [PATCH 129/385] fix(compose): scatter effect noise at the measured strength Inner Shadow noise only scaled the coverage (1 + (n - 0.5) * 2 * amount), so the speckle seldom removed shadow: 0 of 1620 band pixels at G 128 with Noise 50 on the issue document. Replace the law in paint.rs noise(): a pixel drops out with probability min(1, amount * (1 - v) * (0.22 + 0.024 / v)) and otherwise its coverage deepens by up to 1 + 2 * amount. Deterministic per document coordinate (same hash_noise), Noise 0 stays bit-identical, empty pixels are never touched (#7833, #7846, #6112). Tests: effects/inner_shadow_noise_tests.rs pins the measured windows for Noise 50 (400..580 px at G 128, at most 30 equal, min G 12 <= 15) and Noise 100 (550..720 px, min G 0), the untouched interior, determinism and a whole-map FNV hash pin for Noise 0. --- crates/compose/src/effects.rs | 2 + .../src/effects/inner_shadow_noise_tests.rs | 134 ++++++++++++++++++ crates/compose/src/effects/paint.rs | 18 ++- 3 files changed, 150 insertions(+), 4 deletions(-) create mode 100644 crates/compose/src/effects/inner_shadow_noise_tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index adf0b7a7b0..df69a3f1d0 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -245,5 +245,7 @@ impl FxMaps { } } +#[cfg(test)] +mod inner_shadow_noise_tests; #[cfg(test)] mod tests; diff --git a/crates/compose/src/effects/inner_shadow_noise_tests.rs b/crates/compose/src/effects/inner_shadow_noise_tests.rs new file mode 100644 index 0000000000..f0a4f11674 --- /dev/null +++ b/crates/compose/src/effects/inner_shadow_noise_tests.rs @@ -0,0 +1,134 @@ +//! #14936 - BUG-LAYER-STYLE-INNER-SHADOW-NOISE-TOO-WEAK. +//! +//! Measured on the issue's test document: 400 x 300 px, RGB 8 bit, white Background, an orange +//! (255, 128, 0) pixel layer covering x 100..299, y 75..224. Inner Shadow black, Normal, 100 %, +//! Use Global Light off, Distance 0, Choke 0, Contour Linear, Anti-aliased off. The issue counts +//! the G channel of the flattened top band y 75..83, x 110..289 (1620 px): G 128 is the layer's +//! own orange (no shadow), G 0 is full black shadow. Today `noise` only scales the coverage by +//! `1 + (n - 0.5) * 2 * amount`, so Noise 50 removes the shadow nowhere (0 px at G 128) while the +//! reference application shows 491 px without shadow there. + +use super::*; + +const DOC_W: usize = 400; +const DOC_H: usize = 300; + +/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224. +fn document_shape() -> Map { + let mut m = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + m.v[y * DOC_W + x] = 1.0; + } + } + m +} + +/// The issue's Inner Shadow settings: black, Normal, 100 %, global light off, Distance 0, +/// Choke 0, Size 10, Contour Linear, Anti-aliased off, Noise `noise`. +fn shadow(noise: f32) -> Shadow { + Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + noise, + knocks_out: false, + } +} + +fn map(noise: f32) -> Map { + shadow_map(&document_shape(), &shadow(noise), &GlobalLight::default(), true, (0, 0)) +} + +/// The G channel of the orange layer under a black Normal inner shadow of coverage `c`. +fn g_u8(c: f32) -> u8 { + (128.0 * (1.0 - c)).round().clamp(0.0, 128.0) as u8 +} + +/// The issue's band, y 75..=83 and x 110..=289 (1620 px), as G channel values. +fn band(m: &Map) -> Vec { + let mut out = Vec::with_capacity(180 * 9); + for y in 75..=83 { + for x in 110..=289 { + out.push(g_u8(m.get(x, y))); + } + } + out +} + +/// Done when: Noise 50 on that band leaves 400..580 pixels at G 128 (no shadow at all), at +/// most 30 pixels equal to the noiseless result, and a minimum G of at most 15. Today the +/// multiplicative law never removes coverage: 0 pixels sit at G 128. +#[test] +fn noise_fifty_scatters_the_shadow_across_the_band() { + let plain = band(&map(0.0)); + let noisy = band(&map(0.5)); + let gone = noisy.iter().filter(|v| **v == 128).count(); + let equal = noisy.iter().zip(&plain).filter(|(a, b)| a == b).count(); + let min = noisy.iter().copied().min().unwrap_or(255); + assert!((400..=580).contains(&gone), "Noise 50: {gone} pixels without shadow, want 400..580 (reference: 491)"); + assert!(equal <= 30, "Noise 50: {equal} pixels equal to the noiseless result, want at most 30 (reference: 11)"); + assert!(min <= 15, "Noise 50: minimum G {min}, want at most 15 (reference: 7)"); +} + +/// Done when: Noise 100 leaves 550..720 pixels at G 128 and reaches G 0 (reference: 632 px +/// without shadow, minimum G 0). Today: 55 pixels at G 128 and minimum G 13. +#[test] +fn noise_hundred_spans_full_shadow_and_no_shadow() { + let noisy = band(&map(1.0)); + let gone = noisy.iter().filter(|v| **v == 128).count(); + let min = noisy.iter().copied().min().unwrap_or(255); + assert!((550..=720).contains(&gone), "Noise 100: {gone} pixels without shadow, want 550..720 (reference: 632)"); + assert_eq!(min, 0, "Noise 100: minimum G {min}, want 0"); +} + +/// Done when: the interior beyond the shadow's reach stays 128. Every pixel at least 10 px in +/// from all four edges (y 85..214, x 115..285 inside the layer) has zero coverage without noise +/// (the Size 10 falloff ends at depth 10, see the #14933 ramp), and noise must not light any of +/// them up. +#[test] +fn noise_keeps_the_unshadowed_interior_clean() { + let plain = map(0.0); + for noise in [0.5f32, 1.0] { + let noisy = map(noise); + for y in (85..=214).step_by(3) { + for x in (115..=285).step_by(7) { + assert_eq!(plain.get(x, y), 0.0, "noiseless coverage at ({x},{y}) is not empty"); + assert_eq!(noisy.get(x, y), 0.0, "noise {noise} lit up ({x},{y}): {}", noisy.get(x, y)); + assert_eq!(g_u8(noisy.get(x, y)), 128, "noise {noise} moved the interior at ({x},{y}) off 128"); + } + } + } +} + +/// Done when: the same settings give the identical image twice. +#[test] +fn the_same_noise_renders_identically_twice() { + for noise in [0.5f32, 1.0] { + let a = map(noise); + let b = map(noise); + assert_eq!(a.v, b.v, "noise {noise} is not deterministic"); + } +} + +/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is. +fn bit_hash(m: &Map) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for v in &m.v { + h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Noise 0 stays bit-identical: this is the whole-map FNV hash `shadow_map` gives for the +/// issue's document with Noise 0 on upstream/main, so the new law must not touch it. +#[test] +fn noise_zero_maps_stay_bit_identical() { + assert_eq!(bit_hash(&map(0.0)), 0x2200_2b2d_61bc_9c2d, "the Noise 0 inner shadow map moved"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 3403ebddb9..e8bc3f2d4a 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -84,9 +84,14 @@ pub fn hash_noise(x: i64, y: i64) -> f32 { } /// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, -/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is -/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's -/// near-zero tail out to the edge of its rectangular reach (#7833). +/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. A pixel drops out +/// entirely with probability `min(1, amount x (1 - v) x (0.22 + 0.024 / v))` and otherwise its +/// coverage deepens by up to `1 + 2 x amount` (measured on the Inner Shadow and Outer Glow falloff +/// bands, #14936 and #14952: the reference application scatters far stronger than the old +/// multiplicative jitter, which never removed a pixel at Noise 50). The dropout probability grows +/// as coverage falls, so the speckle fades out with the effect instead of lighting up the blur's +/// near-zero tail out to the edge of its rectangular reach (#7833); pixels with no coverage are +/// never touched. pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { if !amount.is_finite() || amount <= 0.0 { return; @@ -98,7 +103,12 @@ pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { continue; } let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); - *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + let kill = (amount * (1.0 - *v) * (0.22 + 0.024 / *v)).min(1.0); + if n < kill { + *v = 0.0; + } else { + *v = (*v * (1.0 + 2.0 * amount * n)).clamp(0.0, 1.0); + } } } } From 2738fc6e5af593eb2bcea448b1185f39a88d73f7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 08:00:29 -0800 Subject: [PATCH 130/385] Align Artboards to Files order control with current filename contract --- crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs index 49356105a6..4f0a38691a 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs @@ -54,5 +54,7 @@ fn artboards_to_files_keeps_its_top_first_order() { let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir.to_string_lossy(), "prefix": "p"})).unwrap(); let _ = std::fs::remove_dir_all(&dir); let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); - assert!(files[0].ends_with("p_0000_Empty Board.png") && files[2].ends_with("p_0002_Red Board.png"), "{files:?}"); + // #13633: the prefix is followed directly by the board name, with PNG spaces hyphenated. + let names: Vec<&str> = files.iter().map(|path| std::path::Path::new(path).file_name().unwrap().to_str().unwrap()).collect(); + assert_eq!(names, ["pEmpty-Board.png", "pBlue-Board.png", "pRed-Board.png"]); } From 91bde3617103085d46af637bb260a45a860b08a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 16:41:17 +0100 Subject: [PATCH 131/385] Artboards to Files order test: expect the file names (#15170) #13641 renamed the exported files to with spaces as hyphens; the order test from #13670 still expected the old p_0000_Empty Board.png names and failed on main. Assert all three names in top-first order. (cherry picked from commit 42e9467bf9d746140a7ecd7a8b7b6382b1b5769b) --- crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs index 49356105a6..0541f8e456 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs @@ -54,5 +54,7 @@ fn artboards_to_files_keeps_its_top_first_order() { let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir.to_string_lossy(), "prefix": "p"})).unwrap(); let _ = std::fs::remove_dir_all(&dir); let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); - assert!(files[0].ends_with("p_0000_Empty Board.png") && files[2].ends_with("p_0002_Red Board.png"), "{files:?}"); + // Files are named , spaces as hyphens (#13633); top artboard first. + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f)).collect(); + assert_eq!(names, ["pEmpty-Board.png", "pBlue-Board.png", "pRed-Board.png"], "{files:?}"); } From 91149ac8e21df5e7dcfebb0a47033b7d85655b80 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Sun, 15 Nov 2026 21:39:30 +0530 Subject: [PATCH 132/385] Object Selection: Refresh and gear buttons in one helper, keeping options_bar under the complexity limit --- crates/ui-egui/src/tools/object_finder.rs | 11 ++++++++++- crates/ui-egui/src/tools/retouch_ui.rs | 6 +----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 3764578a6e..8adf645ce6 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -224,8 +224,17 @@ fn start(app: &PhotocraftApp) -> Option { }) } +/// The options bar's Refresh and gear buttons (#12857). +pub(crate) fn bar_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let clicked = crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Click to refresh object finder.")).clicked(); + gear(&mut app.ui.tool_options, ui); + if clicked { + refresh(app); + } +} + /// The options bar's gear button and its menu (#12857). -pub(crate) fn gear(o: &mut ToolOptions, ui: &mut egui::Ui) { +fn gear(o: &mut ToolOptions, ui: &mut egui::Ui) { let r = crate::icons::button(ui, "settings", 24.0, false, tl!("Set additional options")); egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder")); diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 5bc5df8e05..7473c7b229 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1227,12 +1227,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut o.sample_all.object_selection, tl!("Sample All Layers")); crate::widgets::checkbox(ui, &mut o.object_hard_edge, tl!("Hard Edge")); - let refresh = crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Click to refresh object finder.")).clicked(); - crate::object_finder::gear(o, ui); + crate::object_finder::bar_buttons(app, ui); crate::widgets::vline(ui, 22.0); - if refresh { - crate::object_finder::refresh(app); - } if crate::widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { let r = app.run("select.subject", json!({})); report_smart_result(app, r, tl!("No subject found — try a rectangle around the object")); From a76326467cdac7a31b44b90482aa438abdff7ff8 Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 15 Nov 2026 16:22:47 +0000 Subject: [PATCH 133/385] Use an action row in the shortcut set switch test --- .../src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index dafa8be560..7512acee99 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,7 +165,13 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + let app = h.state_mut(); + app.run("actions.record", json!({"name": "Sepia"})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + let row = app.session.actions.list.iter().position(|action| action.name == "Sepia").unwrap(); + crate::actions::assign_shortcut(app, row, "F2").unwrap(); + let action_id = app.session.actions.list[row].action_id.as_deref().unwrap(); + let shortcut_id = photocraft_engine::actions_cmds::occurrence_key(action_id); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); @@ -173,6 +179,7 @@ fn an_action_function_key_is_no_edit() { pick_set(&mut h, "PhotoCraft Defaults"); assert!(!asking(&h)); assert_eq!(field(&h, id, "activeSet"), json!("")); + assert_eq!(field(&h, id, "overrides")[shortcut_id], "F2"); } #[test] From d044a83b077c09003b4f04e3595282f09e6d2f60 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:45:37 +0300 Subject: [PATCH 134/385] Canvas Size: truncate the half-pixel offset of a centred anchor (#14536) An odd size change on the centre axis moved the layers by (new - old) / 2 rounded away from zero, one pixel further than the reference application, which truncates toward zero. Even changes and the corner anchors give whole pixels and are unchanged. --- crates/engine/src/cmd/image_cmds.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 571f4754ac..3aacc27644 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -719,8 +719,9 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { if (nw, nh) == (ow as u32, oh as u32) { return Ok(json!({ "width": nw, "height": nh, "offset": [0, 0] })); } - let dx = ((nw as f64 - ow) * ax).round() as i32; - let dy = ((nh as f64 - oh) * ay).round() as i32; + // An odd change on a centred axis drops the half pixel toward zero, as the reference does (#14536). + let dx = ((nw as f64 - ow) * ax).trunc() as i32; + let dy = ((nh as f64 - oh) * ay).trunc() as i32; let ext = extension_color(s, p); s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); s.edit("Canvas Size", |doc, _| { From 3eb7dddc48d5e13f33325c8b4059e46264d165aa Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:45:37 +0300 Subject: [PATCH 135/385] Canvas Size: test the centred anchor offset on odd size changes (#14536) --- crates/engine/src/cmd/image_cmds.rs | 3 + .../canvas_size_center_offset_tests.rs | 76 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 crates/engine/src/cmd/image_cmds/canvas_size_center_offset_tests.rs diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 3aacc27644..6d3843aeec 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1326,3 +1326,6 @@ mod image_size_drops_selection_tests; #[cfg(test)] mod canvas_size_noop_history_tests; + +#[cfg(test)] +mod canvas_size_center_offset_tests; diff --git a/crates/engine/src/cmd/image_cmds/canvas_size_center_offset_tests.rs b/crates/engine/src/cmd/image_cmds/canvas_size_center_offset_tests.rs new file mode 100644 index 0000000000..8381818864 --- /dev/null +++ b/crates/engine/src/cmd/image_cmds/canvas_size_center_offset_tests.rs @@ -0,0 +1,76 @@ +//! #14536: on a centred axis Canvas Size moves the layers by (new - old) / 2 truncated toward +//! zero, as the reference application does, so an odd change never shifts them the extra half +//! pixel. Even changes and the corner anchors keep their whole-pixel offsets. + +use serde_json::{Value, json}; + +use crate::Session; + +/// The issue's document: 400 x 300 px with a 50 x 50 layer at 175,125. +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 175, "y": 125, "width": 50, "height": 50})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// Runs Canvas Size on a fresh document; returns the reported offset and the layer's new origin. +fn run_canvas_size(p: Value) -> (Value, (i32, i32)) { + let mut s = doc(); + let r = s.execute("image.canvasSize", p).unwrap(); + let b = s.active().unwrap().doc.layers[1].surface().unwrap().content_bounds(); + (r["offset"].clone(), (b.x0, b.y0)) +} + +#[test] +fn an_odd_change_with_the_centre_anchor_truncates_the_half_pixel() { + for (w, h, off, at) in [(401, 301, [0, 0], (175, 125)), (403, 303, [1, 1], (176, 126)), (399, 299, [0, 0], (175, 125)), (397, 297, [-1, -1], (174, 124))] { + let p = json!({"width": w, "height": h, "anchor": "center"}); + assert_eq!(run_canvas_size(p), (json!(off), at), "{w} x {h}"); + } +} + +#[test] +fn shrinking_to_one_pixel_moves_the_layers_by_minus_199_minus_149() { + for p in [ + json!({"width": 1, "height": 1}), + json!({"width": 0, "height": 0}), + json!({"width": -5, "height": -5}), + json!({"width": -400, "height": -300, "relative": true}), + ] { + assert_eq!(run_canvas_size(p.clone()), (json!([-199, -149]), (-24, -24)), "{p}"); + } +} + +#[test] +fn the_middle_edge_anchors_truncate_on_their_centred_axis() { + for (anchor, grow, shrink) in [("top", [1, 0], [-1, 0]), ("bottom", [1, 3], [-1, -3]), ("left", [0, 1], [0, -1]), ("right", [3, 1], [-3, -1])] { + let (off, _) = run_canvas_size(json!({"width": 403, "height": 303, "anchor": anchor})); + assert_eq!(off, json!(grow), "{anchor} to 403 x 303"); + let (off, _) = run_canvas_size(json!({"width": 397, "height": 297, "anchor": anchor})); + assert_eq!(off, json!(shrink), "{anchor} to 397 x 297"); + } +} + +#[test] +fn even_changes_and_the_corner_anchors_keep_their_offsets() { + let (off, at) = run_canvas_size(json!({"width": 404, "height": 302, "anchor": "center"})); + assert_eq!((off, at), (json!([2, 1]), (177, 126))); + let (off, _) = run_canvas_size(json!({"width": 396, "height": 298, "anchor": "center"})); + assert_eq!(off, json!([-2, -1])); + for (anchor, even) in [("top", [2, 0]), ("bottom", [2, 2]), ("left", [0, 1]), ("right", [4, 1])] { + let (off, _) = run_canvas_size(json!({"width": 404, "height": 302, "anchor": anchor})); + assert_eq!(off, json!(even), "{anchor} to 404 x 302"); + } + for (anchor, grow, shrink) in + [("topLeft", [0, 0], [0, 0]), ("topRight", [3, 0], [-3, 0]), ("bottomLeft", [0, 3], [0, -3]), ("bottomRight", [3, 3], [-3, -3])] + { + let (off, _) = run_canvas_size(json!({"width": 403, "height": 303, "anchor": anchor})); + assert_eq!(off, json!(grow), "{anchor} to 403 x 303"); + let (off, _) = run_canvas_size(json!({"width": 397, "height": 297, "anchor": anchor})); + assert_eq!(off, json!(shrink), "{anchor} to 397 x 297"); + } +} From 88b17a9c96842402bd6513a4c871e82c8a53c71e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 08:48:02 -0800 Subject: [PATCH 136/385] Update keyboard shortcut set test for occurrence API --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index dafa8be560..31bc9bf711 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,7 +165,9 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + let sepia = h.state().session.actions.list.len(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); + crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From b335d18281654157a9249f71ecb5625aa4d147d7 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 18:26:44 +0100 Subject: [PATCH 137/385] fix(compose): keep today's noise jitter on solid coverage The new scatter law measures falloff bands (#14936, #14952). A solid interior (coverage >= 0.95, e.g. a big drop shadow's core) is not part of those measurements, so it keeps the old multiplicative jitter: at Noise 100 the core still spans both sides of 0.5. Adds the guard test solid_core_keeps_todays_jitter pinning that case. --- .../src/effects/inner_shadow_noise_tests.rs | 27 +++++++++++++++++++ crates/compose/src/effects/paint.rs | 22 +++++++++------ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/effects/inner_shadow_noise_tests.rs b/crates/compose/src/effects/inner_shadow_noise_tests.rs index f0a4f11674..a4fff75bc1 100644 --- a/crates/compose/src/effects/inner_shadow_noise_tests.rs +++ b/crates/compose/src/effects/inner_shadow_noise_tests.rs @@ -132,3 +132,30 @@ fn bit_hash(m: &Map) -> u64 { fn noise_zero_maps_stay_bit_identical() { assert_eq!(bit_hash(&map(0.0)), 0x2200_2b2d_61bc_9c2d, "the Noise 0 inner shadow map moved"); } + +/// The issues measure falloff bands only. A big Drop Shadow's solid interior (coverage exactly +/// 1.0 in the Size 40 blur plateau) keeps today's multiplicative jitter: at Noise 100 the core +/// still spans both sides of 0.5 and still holds full coverage. +/// Guard test, passes before and after the law change - it pins the unmeasured case. +#[test] +fn solid_core_keeps_todays_jitter() { + let mut shape = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + shape.v[y * DOC_W + x] = 1.0; + } + } + // The plateau of the Size 40 blur at Distance 0 (measured: coverage is exactly 1.0 on these + // samples, at least 45 px in from every edge). + let core = |noise: f32| { + let s = Shadow { size: 40.0, noise, ..shadow(0.0) }; + let m = shadow_map(&shape, &s, &GlobalLight::default(), false, (0, 0)); + (145..=176).step_by(3).flat_map(|y| (150..=250).step_by(5).map(move |x| (x, y))).map(|(x, y)| m.get(x, y)).collect::>() + }; + let plain = core(0.0); + assert!(plain.iter().all(|v| *v == 1.0), "the Size 40 drop shadow plateau is solid: {plain:?}"); + let half = core(0.5); + assert!(half.iter().any(|v| *v < 1.0) && half.contains(&1.0), "Noise 50 speckles the solid core: {half:?}"); + let heavy = core(1.0); + assert!(heavy.iter().any(|v| *v < 0.5) && heavy.contains(&1.0), "Noise 100 spans both sides of 0.5 in the solid core: {heavy:?}"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index e8bc3f2d4a..ca64b204ab 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -84,14 +84,16 @@ pub fn hash_noise(x: i64, y: i64) -> f32 { } /// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, -/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. A pixel drops out -/// entirely with probability `min(1, amount x (1 - v) x (0.22 + 0.024 / v))` and otherwise its -/// coverage deepens by up to `1 + 2 x amount` (measured on the Inner Shadow and Outer Glow falloff -/// bands, #14936 and #14952: the reference application scatters far stronger than the old -/// multiplicative jitter, which never removed a pixel at Noise 50). The dropout probability grows -/// as coverage falls, so the speckle fades out with the effect instead of lighting up the blur's -/// near-zero tail out to the edge of its rectangular reach (#7833); pixels with no coverage are -/// never touched. +/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. In a falloff a +/// pixel drops out entirely with probability `min(1, amount x (1 - v) x (0.22 + 0.024 / v))` +/// and otherwise its coverage deepens by up to `1 + 2 x amount` (measured on the Inner Shadow +/// and Outer Glow falloff bands, #14936 and #14952: the reference application scatters far +/// stronger than the multiplicative jitter, which never removed a band pixel at Noise 50). +/// The dropout probability grows as coverage falls, so the speckle fades out with the effect +/// instead of lighting up the blur's near-zero tail out to the edge of its rectangular reach +/// (#7833); pixels with no coverage are never touched. Solid coverage (>= 0.95, e.g. a big +/// drop shadow's interior) keeps today's multiplicative jitter: the issues measure falloff +/// bands only, and jittering the interior is a behaviour they do not ask to change. pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { if !amount.is_finite() || amount <= 0.0 { return; @@ -103,6 +105,10 @@ pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { continue; } let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); + if *v >= 0.95 { + *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + continue; + } let kill = (amount * (1.0 - *v) * (0.22 + 0.024 / *v)).min(1.0); if n < kill { *v = 0.0; From 27a99b955a038c4e31ee88ee03c1831d0efa286b Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 10:38:10 -0800 Subject: [PATCH 138/385] Apply exact hosted CI canonical lock ordering --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From e1e3877fb7587cff1fa5ef6d417a409cad4a7751 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 10:38:11 -0800 Subject: [PATCH 139/385] Apply exact hosted CI canonical lock ordering --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From 970943ff026115e514d640c5fd34a2f865719e2c Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 10:38:13 -0800 Subject: [PATCH 140/385] Apply exact hosted CI canonical lock ordering --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From bce9d58a6f7dccb0b06e3a7faded2d8d277b827e Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 19:46:50 +0100 Subject: [PATCH 141/385] fix(layer-style): keep Inner Shadow values inside the page's ranges The Inner Shadow page stopped its Distance field at 300 px and its Angle field at half a turn, and `layer.layerStyle.innerShadow` stored whatever it was given: distance 40000, size -3, angle 200. The page now types Distance 0..30000 px on a track measured at the reference application's thumb positions (half its travel at 47 px, three quarters at 93 px) and takes an Angle of -360..360, while the command clamps distance and size to those ranges and wraps an angle past half a turn into -180..180 (200 -> -160, -200 -> 160). Values already inside keep today's stored params and pixels; the Drop Shadow path is left to #14893. --- crates/engine/src/layer_style.rs | 26 ++++- .../layer_style/inner_shadow_ranges_tests.rs | 106 ++++++++++++++++++ crates/ui-egui/src/dialogs/layer_style.rs | 33 +++++- .../ui-egui/src/dialogs/layer_style/tests.rs | 58 ++++++++++ crates/ui-egui/src/widgets.rs | 4 +- crates/ui-egui/src/widgets/slider.rs | 94 +++++++++++++++- 6 files changed, 309 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/layer_style/inner_shadow_ranges_tests.rs diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 9f7c2c7873..934c6a260d 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -722,23 +722,39 @@ fn overlay_common(c: &mut FxCommon, p: &Value) { } } +/// The Inner Shadow page's typed ranges (#14940): Distance 0..30000 px, Size 0..250 px and an +/// Angle of -360..360. `layer.layerStyle.innerShadow` follows them, as the epic's measured +/// clamping table says; the Drop Shadow page's own ranges are #14893. +const INNER_DISTANCE_RANGE: (f32, f32) = (0.0, 30_000.0); +const INNER_SIZE_RANGE: (f32, f32) = (0.0, 250.0); +const INNER_ANGLE_RANGE: (f32, f32) = (-360.0, 360.0); + +/// The angle Photoshop stores for an Inner Shadow typed past half a turn: 200 becomes -160 and +/// -200 becomes 160 (#14940). An angle already inside -180..180 is kept exactly, so in-range +/// params, imported PSD values and the shared light angle stay as they were (a plain +/// `rem_euclid` would move a stored 180 to -180). +fn inner_shadow_angle(a: f32) -> f32 { + let a = a.clamp(INNER_ANGLE_RANGE.0, INNER_ANGLE_RANGE.1); + if (-180.0..=180.0).contains(&a) { a } else { (a + 180.0).rem_euclid(360.0) - 180.0 } +} + fn overlay_shadow(s: &mut Shadow, p: &Value, inner: bool) { overlay_common(&mut s.common, p); overlay_color(p, "color", &mut s.color); if let Some(x) = f_of(p, "angle") { - s.angle = x; + s.angle = if inner { inner_shadow_angle(x) } else { x }; } if let Some(x) = b_of(p, "useGlobalLight") { s.use_global_light = x; } if let Some(x) = f_of(p, "distance") { - s.distance = x; + s.distance = if inner { x.clamp(INNER_DISTANCE_RANGE.0, INNER_DISTANCE_RANGE.1) } else { x }; } if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) { s.spread = (x / 100.0).clamp(0.0, 1.0); } if let Some(x) = f_of(p, "size") { - s.size = x; + s.size = if inner { x.clamp(INNER_SIZE_RANGE.0, INNER_SIZE_RANGE.1) } else { x }; } overlay_contour(p, "contour", &mut s.contour); overlay_bool(p, "antiAlias", &mut s.anti_alias); @@ -1147,7 +1163,7 @@ pub fn specs() -> Vec { style_cmd!( "innerShadow", "Inner Shadow…", - r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":deg,"distance":px,"choke":0..100,"size":px,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## + r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":-360..360 (stored wrapped into -180..180),"distance":0..30000,"choke":0..100,"size":0..250,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## ), style_cmd!( "outerGlow", @@ -1265,6 +1281,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { Ok(Value::Null) } +#[cfg(test)] +mod inner_shadow_ranges_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/layer_style/inner_shadow_ranges_tests.rs b/crates/engine/src/layer_style/inner_shadow_ranges_tests.rs new file mode 100644 index 0000000000..a2860a0f8a --- /dev/null +++ b/crates/engine/src/layer_style/inner_shadow_ranges_tests.rs @@ -0,0 +1,106 @@ +//! #14940: the Inner Shadow page's ranges on the command side. The page types Distance +//! 0..30000 px, Size 0..250 px and an Angle of -360..360; `layer.layerStyle.innerShadow` keeps +//! those values inside the page's ranges and wraps an Angle past half a turn into -180..180 when +//! it stores it. Values already inside keep today's params and pixels. + +use super::*; +use crate::Session; +use serde_json::json; + +fn session(width: u32, height: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": width, "height": height, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one Inner Shadow the active layer carries. +fn inner_shadow(s: &Session) -> Shadow { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [Effect::InnerShadow(sh)] => sh.clone(), + other => panic!("no inner shadow: {other:?}"), + } +} + +/// #14940: a typed Angle of 200 is stored as -160 and -200 as 160; past the field's ±360 the +/// value is clamped first, as every other out-of-range entry on the page is. +#[test] +fn inner_shadow_wraps_an_angle_past_half_a_turn() { + for (typed, stored) in [(200.0, -160.0), (-200.0, 160.0), (270.0, -90.0), (360.0, 0.0), (400.0, 0.0), (-400.0, 0.0)] { + let mut s = session(32, 32); + s.execute("layer.layerStyle.innerShadow", json!({"angle": typed, "useGlobalLight": false})).unwrap(); + let angle = inner_shadow(&s).angle; + assert!((angle - stored).abs() < 1e-4, "angle {typed} stored as {angle}, not {stored}"); + } +} + +/// The other half of #14940: an Angle already inside half a turn each way is stored exactly as +/// it is today, so in-range params, imported PSD values and the shared light angle stay as they +/// were. 180 stays 180 rather than becoming -180. +#[test] +fn an_inner_shadow_angle_inside_half_a_turn_is_kept_exactly() { + for angle in [0.0, 45.0, -45.0, 179.5, 180.0, -180.0] { + let mut s = session(32, 32); + s.execute("layer.layerStyle.innerShadow", json!({"angle": angle, "useGlobalLight": false})).unwrap(); + assert_eq!(inner_shadow(&s).angle, angle, "angle {angle}"); + } +} + +/// #14940: the command keeps Distance inside the page's 0..30000 px, a negative value at 0. +#[test] +fn inner_shadow_clamps_distance_to_the_page_range() { + for (sent, kept) in [(40000.0, 30000.0), (-5.0, 0.0), (30000.0, 30000.0)] { + let mut s = session(32, 32); + s.execute("layer.layerStyle.innerShadow", json!({"distance": sent})).unwrap(); + assert_eq!(inner_shadow(&s).distance, kept, "distance {sent}"); + } +} + +/// #14940: and Size inside 0..250 px, 0 included. +#[test] +fn inner_shadow_clamps_size_to_the_page_range() { + for (sent, kept) in [(300.0, 250.0), (-3.0, 0.0), (0.0, 0.0), (250.0, 250.0)] { + let mut s = session(32, 32); + s.execute("layer.layerStyle.innerShadow", json!({"size": sent})).unwrap(); + assert_eq!(inner_shadow(&s).size, kept, "size {sent}"); + } +} + +/// #14940 names the Drop Shadow's ranges for #14893, so that path stores what it is given +/// today: no clamp on Distance 40000 or Size 300, no wrap on Angle 200. +#[test] +fn a_drop_shadow_still_stores_what_it_is_given() { + let mut s = session(32, 32); + s.execute("layer.layerStyle.dropShadow", json!({"distance": 40000.0, "size": 300.0, "angle": 200.0, "useGlobalLight": false})).unwrap(); + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!("{:?}", l.effects.items) }; + assert_eq!((sh.distance, sh.size, sh.angle), (40000.0, 300.0, 200.0)); +} + +/// #14940: in-range values keep today's pixels. The measured far-distance case (Size 0, +/// Distance 500 on a 200 x 150 px layer) paints the whole layer with the shadow colour; these +/// levels are the ones the compositor already gave, so the range change moves no pixel. +#[test] +fn an_inner_shadow_reaching_past_the_layer_paints_it_as_before() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 100, "y": 75, "width": 200, "height": 150})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff8000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.layerStyle.innerShadow", json!({"distance": 500.0, "size": 0.0})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let level = |x: usize, y: usize| px[y * 400 + x].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as i32); + // Inside the layer: Multiply black at the factory 75 %, so the orange stays only at a quarter. + for (x, y) in [(200, 150), (105, 80), (295, 220)] { + assert_eq!(level(x, y), [64, 32, 0, 255], "inside the layer at ({x}, {y})"); + } + // Outside it, nothing: the inner shadow never leaves the layer, and the canvas stays white. + for (x, y) in [(200, 74), (97, 72), (5, 5)] { + assert_eq!(level(x, y), [255, 255, 255, 255], "outside the layer at ({x}, {y})"); + } +} diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 65772e1573..c4685afeaa 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -32,6 +32,10 @@ mod gradient_method_tests; #[derive(Clone, Copy)] enum P { Slider(f32, f32, &'static str), + /// A slider whose track is measured at `track` (see [`widgets::slider_line_with`]) while its + /// field takes the whole `min..=max`: Photoshop's Inner Shadow Distance, where most of the + /// travel is the first few pixels (#14940). + TrackSlider(f32, f32, &'static str, &'static [(f32, f32)]), Color, Blend, Choice(&'static [(&'static str, &'static str)]), @@ -39,6 +43,9 @@ enum P { Gradient, Check, Angle, + /// An Angle field that types a full turn each way (-360..360); the engine stores it wrapped + /// into half a turn (#14940). The dial itself still points anywhere on the circle. + WideAngle, /// A pattern from the dialog's `patternList` field (`[[id, name], …]`). Pattern, /// A contour (thumbnail, preset picker, Contour Editor), with the key of its Anti-aliased @@ -102,6 +109,12 @@ fn fresh_params(kind: &str, light: f32, user: Option<&Value>) -> Value { p } +/// Photoshop's Inner Shadow Distance track, measured (#14940): the thumb at half its travel sits +/// at 47 px, at three quarters at 93 px and at the right end at 30000 px. The curve between the +/// points is the page's own (the reference application's exact one was not measured); it keeps +/// the fine control at the low end the measured points show. +const INNER_SHADOW_DISTANCE: &[(f32, f32)] = &[(0.0, 0.0), (0.5, 47.0), (0.75, 93.0), (1.0, 30000.0)]; + fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { const POS: &[(&str, &str)] = &[("outside", "Outside"), ("inside", "Inside"), ("center", "Center")]; const GSTYLE: &[(&str, &str)] = &[("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")]; @@ -129,9 +142,9 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { ("blend", "Blend Mode", P::Blend), ("color", "Color", P::Color), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), - ("angle", "Angle", P::Angle), + ("angle", "Angle", P::WideAngle), ("useGlobalLight", "Use Global Light", P::Check), - ("distance", "Distance", P::Slider(0.0, 300.0, "px")), + ("distance", "Distance", P::TrackSlider(0.0, 30000.0, "px", INNER_SHADOW_DISTANCE)), ("choke", "Choke", P::Slider(0.0, 100.0, "%")), ("size", "Size", P::Slider(0.0, 250.0, "px")), ("contour", "Contour", CONTOUR), @@ -1645,9 +1658,12 @@ fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, } for &(key, label, kind_p) in spec(&sel_kind) { match kind_p { - P::Angle => { + // The Inner Shadow page types a full turn each way and stores it wrapped (#14940); + // the other pages' Angle fields keep Photoshop's half turn each way. + P::Angle | P::WideAngle => { + let (lo, hi) = if matches!(kind_p, P::WideAngle) { (-360.0, 360.0) } else { (-180.0, 180.0) }; let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; - if widgets::angle_dial_line(ui, label, Some(LABEL_W), &mut v, -180.0..=180.0).changed() { + if widgets::angle_dial_line(ui, label, Some(LABEL_W), &mut v, lo..=hi).changed() { let value = json!(v); disp[key] = value.clone(); set_param(f, selected, key, value); @@ -1661,6 +1677,15 @@ fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, set_param(f, selected, key, value); } } + P::TrackSlider(min, max, unit, track) => { + let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(min as f64) as f32; + let g = widgets::RowGestures { track: Some(track), ..Default::default() }; + if widgets::slider_line_with(ui, label, LABEL_W, &mut v, min..=max, unit, g).changed() { + let value = json!(v.round()); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + } P::Color => { ui.horizontal(|ui| { widgets::row_label(ui, label, LABEL_W); diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 95ccbed22c..f30c08944c 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -1313,3 +1313,61 @@ fn style_click_does_not_mutate_document_until_confirm() { confirm(&mut app, &f).unwrap(); assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 1); } + +/// #14940: the Inner Shadow page's Distance field and track reach 30000 px, and its Angle field +/// types a full turn each way. The other pages keep Photoshop's older ranges (#14893 is the +/// Drop Shadow's own ticket). +#[test] +fn the_inner_shadow_page_types_the_measured_ranges() { + let row = |kind: &str, key: &str| spec(kind).iter().find(|(k, _, _)| *k == key).map(|(_, _, p)| *p); + let Some(P::TrackSlider(lo, hi, unit, track)) = row("innerShadow", "distance") else { + panic!("Inner Shadow's Distance is not a tracked slider"); + }; + assert_eq!((lo, hi, unit), (0.0, 30000.0, "px")); + assert_eq!(track, INNER_SHADOW_DISTANCE, "the track runs through the measured thumb positions"); + assert!(matches!(row("innerShadow", "angle"), Some(P::WideAngle)), "the Angle field types -360..360"); + let Some(P::Slider(lo, hi, unit)) = row("innerShadow", "size") else { panic!("Inner Shadow's Size is not a plain slider") }; + assert_eq!((lo, hi, unit), (0.0, 250.0, "px"), "Size keeps its 0..250 px"); + // Untouched pages: the Drop Shadow's Distance still stops at 300 px and its Angle at half a + // turn, as does every other page's angle field. + let Some(P::Slider(lo, hi, _)) = row("dropShadow", "distance") else { panic!("Drop Shadow's Distance changed") }; + assert_eq!(lo..=hi, 0.0..=300.0, "the Drop Shadow page is #14893's"); + for kind in ["dropShadow", "gradientOverlay", "patternOverlay", "bevelEmboss", "satin"] { + assert!(matches!(row(kind, "angle"), Some(P::Angle)), "{kind}'s Angle field changed"); + } +} + +/// #14940: the Distance track passes through the measured points (half the travel at 47 px, +/// three quarters at 93 px, the right end at 30000 px), never goes backwards, and puts the knob +/// back where a dragged value came from. +#[test] +fn the_inner_shadow_distance_track_passes_its_measured_points() { + let close = |got: f32, want: f32| (got - want).abs() <= (want.abs() * 1e-5).max(1e-3); + for &(fraction, value) in INNER_SHADOW_DISTANCE { + assert!( + close(crate::widgets::track_value(fraction, INNER_SHADOW_DISTANCE), value), + "thumb at {fraction} shows {}", + crate::widgets::track_value(fraction, INNER_SHADOW_DISTANCE) + ); + assert!( + close(crate::widgets::track_fraction(value, INNER_SHADOW_DISTANCE), fraction), + "value {value} sits at {}", + crate::widgets::track_fraction(value, INNER_SHADOW_DISTANCE) + ); + } + let mut last = -1.0; + for i in 0..=100 { + let v = crate::widgets::track_value(i as f32 / 100.0, INNER_SHADOW_DISTANCE); + assert!(v >= last, "the track went backwards at {i} %: {v} after {last}"); + last = v; + } + assert!(close(last, 30000.0), "the right end of the track reaches the field's maximum, not {last}"); + // The fine end: a quarter of the travel is still under 24 px. + assert!(crate::widgets::track_value(0.25, INNER_SHADOW_DISTANCE) < 24.0, "the low end lost its fine steps"); + // A drag round-trips: the value the knob paints sits at that knob again. + for fraction in [0.05f32, 0.3, 0.55, 0.8, 0.95] { + let v = crate::widgets::track_value(fraction, INNER_SHADOW_DISTANCE); + let back = crate::widgets::track_fraction(v, INNER_SHADOW_DISTANCE); + assert!((back - fraction).abs() < 1e-4, "{fraction} -> {v} -> {back}"); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5e22305dce..11b2cd49a6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -67,9 +67,11 @@ pub use scrub::{scrub_label, scrub_option_icon, scrub_option_label}; #[cfg(test)] use slider::DOUBLE_CLICK_S; pub(crate) use slider::count_notches; -pub use slider::{RowGestures, row_label, second_click, slider, slider_line, slider_row, slider_row_prec, slider_row_with}; +pub use slider::{RowGestures, row_label, second_click, slider, slider_line, slider_line_with, slider_row, slider_row_prec, slider_row_with}; #[cfg(test)] pub(crate) use slider::{curve_fraction, curve_value}; +#[cfg(test)] +pub(crate) use slider::{track_fraction, track_value}; pub use text_field::{ INPUT_EVENT_LIMIT, TEXT_FIELD_H, TEXT_FIELD_LIMIT, cap_text_events, focus_first_field, text_field, text_field_ex, text_field_with_trailing, }; diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index 0a4922e03b..4e7b409c2d 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -24,6 +24,74 @@ pub struct RowGestures { /// values get fine steps (Photoshop's mask Feather, #6545). Typed, scrubbed and stepped /// values stay linear; only the track maps through the curve. pub curve: Option, + /// A track measured at thumb positions instead of a power: `(fraction, value)` pairs, + /// ascending, first at fraction 0 and last at 1 (see [`track_value`] and [`track_fraction`]). + /// Photoshop's Layer Style Distance sliders are measured this way (#14940). Takes + /// precedence over `curve`; typed, scrubbed and stepped values stay linear as well. + pub track: Option<&'static [(f32, f32)]>, +} + +/// The value at fraction `f` of a track measured at `points`: each segment between two measured +/// points is the power curve through them (so the low end keeps its fine steps); a segment +/// starting at 0 is straight, as a power of 0 would be 0 everywhere. [`track_fraction`] inverts it. +pub(crate) fn track_value(f: f32, points: &[(f32, f32)]) -> f32 { + let (Some(first), Some(last)) = (points.first(), points.last()) else { + return f; + }; + if !f.is_finite() { + return if f > 0.0 { last.1 } else { first.1 }; + } + let f = f.clamp(first.0, last.0); + for w in points.windows(2) { + let (f0, v0) = w[0]; + let (f1, v1) = w[1]; + if f <= f1 { + return segment_value(f, f0, v0, f1, v1); + } + } + last.1 +} + +/// Where the value `v` sits on the track [`track_value`] describes, as a fraction. An unset (NaN) +/// value puts the knob at the start, as a plain track does. +pub(crate) fn track_fraction(v: f32, points: &[(f32, f32)]) -> f32 { + let (Some(first), Some(last)) = (points.first(), points.last()) else { + return 0.0; + }; + if v.is_nan() || v <= first.1 { + return first.0; + } + if v >= last.1 { + return last.0; + } + for w in points.windows(2) { + let (f0, v0) = w[0]; + let (f1, v1) = w[1]; + if v <= v1 { + return segment_fraction(v, f0, v0, f1, v1); + } + } + last.0 +} + +fn segment_value(f: f32, f0: f32, v0: f32, f1: f32, v1: f32) -> f32 { + if v0 > 0.0 && f0 > 0.0 && v1 > v0 && f1 > f0 { + v0 * (f / f0).powf((v1 / v0).ln() / (f1 / f0).ln()) + } else if f1 > f0 { + v0 + (f - f0) * (v1 - v0) / (f1 - f0) + } else { + v1 + } +} + +fn segment_fraction(v: f32, f0: f32, v0: f32, f1: f32, v1: f32) -> f32 { + if v0 > 0.0 && f0 > 0.0 && v1 > v0 && f1 > f0 { + f0 * (v / v0).powf((f1 / f0).ln() / (v1 / v0).ln()) + } else if v1 > v0 { + f0 + (v - v0) * (f1 - f0) / (v1 - v0) + } else { + f1 + } } /// The value at fraction `f` of a track over `lo..=hi`, through `curve` (see [`RowGestures`]). @@ -136,7 +204,10 @@ fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive track_value(f, points), + None => curve_value(f, lo, hi, g.curve), + }; if (nv - *value).abs() > f32::EPSILON { *value = nv; resp.mark_changed(); @@ -159,7 +230,10 @@ fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive track_fraction(*value, points), + None => curve_fraction(*value, lo, hi, g.curve), + }; let knob_x = track.left() + f * track.width(); let painter = ui.painter(); match gradient { @@ -290,6 +364,20 @@ pub fn row_label(ui: &mut Ui, label: &str, width: f32) -> Response { /// [`slider_row`] on one line, as Photoshop lays out Layer Style: the label in a `label_w` column /// ([`row_label`]), the slider, then the value field. The label still scrubs the field. pub fn slider_line(ui: &mut Ui, label: &str, label_w: f32, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str) -> Response { + slider_line_with(ui, label, label_w, value, range, suffix, RowGestures::default()) +} + +/// [`slider_line`] with Photoshop's extra gestures ([`RowGestures`]): a Layer Style row whose +/// track is measured rather than straight, while its field takes the whole range (#14940). +pub fn slider_line_with( + ui: &mut Ui, + label: &str, + label_w: f32, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + g: RowGestures, +) -> Response { const FIELD_W: f32 = 64.0; let mut field = None; let s = ui @@ -299,7 +387,7 @@ pub fn slider_line(ui: &mut Ui, label: &str, label_w: f32, value: &mut f32, rang let w = (ui.available_width() - FIELD_W - ui.spacing().item_spacing.x).max(60.0); let s = ui .allocate_ui_with_layout(vec2(w, VALUE_FIELD_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { - slider_with(ui, value, range.clone(), None, RowGestures::default()) + slider_with(ui, value, range.clone(), None, g) }) .inner; field = Some(value_field_in(ui, value, range.clone(), suffix, FIELD_W, 0.0, FieldOpts::default(), Some(label)).0); From 117d2e54f261563a86f87e40b43325dca7999c27 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 19:52:35 +0100 Subject: [PATCH 142/385] fix(layer-style): start a new Outer Glow at the measured defaults A new Outer Glow started at Opacity 75 %, colour #ffffbe and Size 5 px, while the reference application's page starts at Screen, 35 %, white and Size 7 px, and its rows sat in one flat list with Noise last. The dialog's seed (effect_defaults) and the command's fresh effect (fresh_effect, scoped by the inner flag so the Inner Glow keeps today's values for #14917) now carry the measured values, and the page titles its Structure, Elements and Quality groups with Noise under Opacity. An Outer Glow a document already carries keeps the values it was read with. On the grey test document the factory glow gives the measured top edge 121 104 91 80 72 66 64 and corner 69, within 2 levels. --- crates/engine/src/layer_style.rs | 19 ++- .../layer_style/outer_glow_defaults_tests.rs | 140 ++++++++++++++++++ crates/ui-egui/src/dialogs/layer_style.rs | 19 ++- .../ui-egui/src/dialogs/layer_style/tests.rs | 82 +++++++++- 4 files changed, 251 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/layer_style/outer_glow_defaults_tests.rs diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 9f7c2c7873..ba021bfc8c 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -154,7 +154,7 @@ pub fn effect_defaults(kind: &str) -> Value { json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "choke": 0, "size": 5, "contour": "Linear", "antiAlias": false, "noise": 0}) } "outerGlow" => { - json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "technique": "softer", "spread": 0, "size": 5, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) + json!({"blend": "Screen", "opacity": 35, "color": "#ffffff", "technique": "softer", "spread": 0, "size": 7, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) } "innerGlow" => { json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "technique": "softer", "source": "edge", "choke": 0, "size": 5, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0}) @@ -566,12 +566,15 @@ fn fresh_effect(kind: &str) -> Option { noise: 0.0, knocks_out: !inner, }; - let glow = || Glow { - common: FxCommon::new(BlendMode::Screen, 0.75), - paint: FxPaint::Color(Color::rgb(1.0, 1.0, 190.0 / 255.0)), + // The two glows share their shape, but not their factory values: the Outer Glow starts at + // the reference application's white 35 % Size 7 (#14944), the Inner Glow at today's values + // until #14917 measures its own. + let glow = |inner: bool| Glow { + common: FxCommon::new(BlendMode::Screen, if inner { 0.75 } else { 0.35 }), + paint: FxPaint::Color(if inner { Color::rgb(1.0, 1.0, 190.0 / 255.0) } else { Color::WHITE }), technique: GlowTechnique::Softer, spread: 0.0, - size: 5.0, + size: if inner { 5.0 } else { 7.0 }, contour: Contour::Linear, anti_alias: false, range: 0.5, @@ -582,8 +585,8 @@ fn fresh_effect(kind: &str) -> Option { Some(match kind { "dropShadow" => Effect::DropShadow(shadow(false)), "innerShadow" => Effect::InnerShadow(shadow(true)), - "outerGlow" => Effect::OuterGlow(glow()), - "innerGlow" => Effect::InnerGlow(glow()), + "outerGlow" => Effect::OuterGlow(glow(false)), + "innerGlow" => Effect::InnerGlow(glow(true)), "stroke" => Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size: 1.0, @@ -1265,6 +1268,8 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { Ok(Value::Null) } +#[cfg(test)] +mod outer_glow_defaults_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/layer_style/outer_glow_defaults_tests.rs b/crates/engine/src/layer_style/outer_glow_defaults_tests.rs new file mode 100644 index 0000000000..3fdac39f7e --- /dev/null +++ b/crates/engine/src/layer_style/outer_glow_defaults_tests.rs @@ -0,0 +1,140 @@ +//! #14944: the Outer Glow page's factory values (Screen, 35 %, white, Softer, Spread 0, Size 7, +//! Linear, Anti-aliased off, Range 50) and the rule that a glow already stored keeps its own +//! values. The measured pixels of the factory glow sit within 2 levels of the reference +//! application's on the grey test document. + +use super::*; +use crate::Session; +use serde_json::json; + +/// The issue's test document: 400 x 300 px at 72 ppi, RGB 8 bit, a filled (64,64,64) +/// Background and a pixel layer with an orange (255,128,0) rectangle at x 100..299, y 75..224. +fn test_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "background": "#404040"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 100, "y": 75, "width": 200, "height": 150})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff8000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// The one glow the active layer carries, as an outer glow. +fn outer_glow(s: &Session) -> Glow { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match l.effects.items.as_slice() { + [Effect::OuterGlow(g)] => g.clone(), + other => panic!("no outer glow: {other:?}"), + } +} + +/// #14944: Layer > Layer Style > Outer Glow... on a layer without one starts from the reference +/// application's factory values. The dialog seeds a new instance from `effect_defaults`, and the +/// command without params builds the same effect, so both are checked here. +#[test] +fn a_new_outer_glow_starts_at_the_factory_values() { + let d = effect_defaults("outerGlow"); + assert_eq!(d["blend"], json!("Screen"), "blend"); + assert_eq!(d["opacity"], json!(35), "opacity"); + assert_eq!(d["color"], json!("#ffffff"), "colour"); + assert_eq!(d["technique"], json!("softer"), "technique"); + assert_eq!(d["spread"], json!(0), "spread"); + assert_eq!(d["size"], json!(7), "size"); + assert_eq!(d["contour"], json!("Linear"), "contour"); + assert_eq!(d["antiAlias"], json!(false), "anti-aliased"); + assert_eq!(d["range"], json!(50), "range"); + assert_eq!(d["noise"], json!(0), "noise"); +} + +/// #14944: `layer.layerStyle.outerGlow` without params makes the same effect the page starts at. +#[test] +fn an_outer_glow_command_without_params_makes_the_factory_effect() { + let mut s = session(); + s.execute("layer.layerStyle.outerGlow", json!({})).unwrap(); + let g = outer_glow(&s); + assert_eq!(g.common.blend, BlendMode::Screen, "blend mode"); + assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4, "opacity {} %", g.common.opacity * 100.0); + let FxPaint::Color(c) = g.paint else { panic!("not a plain colour: {:?}", g.paint) }; + let rgb = c.to_rgb(); + assert!(rgb.iter().all(|v| (v - 1.0).abs() < 1e-4), "colour {rgb:?} is not white"); + assert_eq!((g.technique, g.spread, g.size), (GlowTechnique::Softer, 0.0, 7.0)); + assert!(matches!(g.contour, Contour::Linear), "contour {:?}", g.contour); + assert!(!g.anti_alias, "anti-aliased"); + assert!((g.range - 0.5).abs() < 1e-4, "range {}", g.range); + assert_eq!(g.noise, 0.0, "noise"); +} + +/// #14944: Reset to Default reads these factory values through `layer.layerStyle.defaultFor` +/// until a Make Default stores other ones; the saved values keep winning (the Make Default path +/// is not re-measured, so it keeps today's behaviour). +#[test] +fn reset_to_default_restores_the_outer_glow_factory_values() { + let mut s = session(); + let d = s.execute("layer.layerStyle.defaultFor", json!({"kind": "outerGlow"})).unwrap(); + assert_eq!(d["user"], json!(false)); + assert_eq!((d["params"]["opacity"].as_f64(), d["params"]["color"].as_str(), d["params"]["size"].as_f64()), (Some(35.0), Some("#ffffff"), Some(7.0))); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "outerGlow", "params": {"opacity": 12, "size": 3}})).unwrap(); + let saved = s.execute("layer.layerStyle.defaultFor", json!({"kind": "outerGlow"})).unwrap(); + assert_eq!(saved["user"], json!(true)); + assert_eq!((saved["params"]["opacity"].as_f64(), saved["params"]["size"].as_f64()), (Some(12.0), Some(3.0)), "a saved default still wins"); +} + +/// #14944 measured: OK on the factory values over the grey test document. Top edge at x 200, +/// y 74 outwards to 68, and the corner pixel (97, 72), as grey levels; the reference +/// application's are 121 104 91 80 72 66 64 and 69, within 2 levels. +#[test] +fn the_factory_outer_glow_paints_the_measured_edge() { + let mut s = test_document(); + s.execute("layer.layerStyle.outerGlow", json!({})).unwrap(); + let d = s.active().unwrap(); + let px = photocraft_compose::render(&d.doc, d.doc.bounds()).into_px(); + let level = |x: usize, y: usize| (px[y * 400 + x][0] * 255.0).round() as i32; + for (y, want) in [(74, 121), (73, 104), (72, 91), (71, 80), (70, 72), (69, 66), (68, 64)] { + let got = level(200, y); + assert!((got - want).abs() <= 2, "top edge at (200, {y}): {got}, the reference gives {want}"); + } + let corner = level(97, 72); + assert!((corner - 69).abs() <= 2, "corner (97, 72): {corner}, the reference gives 69"); +} + +/// #14944: an Outer Glow the document already carries keeps the values it was read with. The +/// Layer Style dialog's OK (and so a PSD or `.pcraft` effect edited in it) goes through +/// `layer.layerStyle.replace` with the effect's own snapshot: absent params leave it alone. +#[test] +fn a_stored_outer_glow_keeps_its_own_values_through_replace() { + let mut s = session(); + s.execute("layer.layerStyle.outerGlow", json!({"opacity": 75, "color": "#ffffbe", "size": 5})).unwrap(); + let stored = outer_glow(&s); + let snapshot = serde_json::to_value(Effect::OuterGlow(stored.clone())).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "outerGlow", "params": {}, "fx": snapshot}]})).unwrap(); + let kept = outer_glow(&s); + assert_eq!(kept, stored, "an edited effect list left the glow's values alone"); + assert!((kept.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (kept.size - 5.0).abs() < 1e-4, "kept {kept:?}"); +} + +/// #14944 is only about the Outer Glow page; the Inner Glow's factory values are #14917 and stay +/// as they are today (the two glows share their fresh effect in the engine). +#[test] +fn an_inner_glow_still_starts_at_todays_values() { + let d = effect_defaults("innerGlow"); + assert_eq!((d["opacity"].as_f64(), d["color"].as_str(), d["size"].as_f64()), (Some(75.0), Some("#ffffbe"), Some(5.0))); + let mut s = session(); + s.execute("layer.layerStyle.innerGlow", json!({})).unwrap(); + let g = match &s.active().unwrap().doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().effects.items[0] { + Effect::InnerGlow(g) => g.clone(), + other => panic!("{other:?}"), + }; + assert!((g.common.opacity * 100.0 - 75.0).abs() < 1e-4, "opacity {}", g.common.opacity); + assert_eq!(g.size, 5.0, "size"); + let FxPaint::Color(c) = g.paint else { panic!("{:?}", g.paint) }; + let rgb = c.to_rgb(); + assert!((rgb[0] - 1.0).abs() < 1e-3 && (rgb[1] - 1.0).abs() < 1e-3 && (rgb[2] - 190.0 / 255.0).abs() < 1e-3, "colour {rgb:?}"); +} diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 65772e1573..88086f0ce7 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -102,6 +102,16 @@ fn fresh_params(kind: &str, light: f32, user: Option<&Value>) -> Value { p } +/// Photoshop's titled groups on an effect page: for each kind, the title above the row that +/// starts a group (#14944: the Outer Glow page's Structure, Elements and Quality). Only the +/// pages Photoshop groups are listed; the others stay one flat list. +const GROUP_TITLES: &[(&str, &[(&str, &str)])] = &[("outerGlow", &[("Structure", "blend"), ("Elements", "technique"), ("Quality", "contour")])]; + +/// The group title the page shows above the row `key`, for the effect kind `kind`. +fn group_title(kind: &str, key: &str) -> Option<&'static str> { + GROUP_TITLES.iter().find(|(k, _)| *k == kind).and_then(|(_, titles)| titles.iter().find(|(_, start)| *start == key)).map(|(title, _)| *title) +} + fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { const POS: &[(&str, &str)] = &[("outside", "Outside"), ("inside", "Inside"), ("center", "Center")]; const GSTYLE: &[(&str, &str)] = &[("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")]; @@ -138,16 +148,18 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { ("noise", "Noise", P::Slider(0.0, 100.0, "%")), ], // Photoshop's order (#6698): Technique before the spread or choke, Range after the contour. + // #14944: Noise sits right under Opacity, and the rows fall into the Structure, Elements + // and Quality groups the page titles above them (GROUP_TITLES). "outerGlow" => &[ ("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), + ("noise", "Noise", P::Slider(0.0, 100.0, "%")), ("color", "Color", P::Color), ("technique", "Technique", P::Choice(GLOW_TECHNIQUE)), ("spread", "Spread", P::Slider(0.0, 100.0, "%")), ("size", "Size", P::Slider(0.0, 250.0, "px")), ("contour", "Contour", CONTOUR), ("range", "Range", P::Slider(1.0, 100.0, "%")), - ("noise", "Noise", P::Slider(0.0, 100.0, "%")), ], "innerGlow" => &[ ("blend", "Blend Mode", P::Blend), @@ -1644,6 +1656,11 @@ fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, } } for &(key, label, kind_p) in spec(&sel_kind) { + // Photoshop's group titles, above the row that starts each block (#14944). + if let Some(title) = group_title(&sel_kind, key) { + widgets::section_label(ui, title); + ui.add_space(2.0); + } match kind_p { P::Angle => { let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 95ccbed22c..331d47e825 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -888,11 +888,12 @@ fn inner_glow_center_source_survives_ok() { /// #6698: Inner Glow lacked Photoshop's Technique and Range, Outer Glow its Technique. They /// show in Photoshop's order, the dialog loads them, and OK keeps them. +/// #14944 moved the Outer Glow's Noise under Opacity, so its order here is the grouped page's. #[test] fn glows_show_and_keep_technique_and_range() { let keys = |kind: &str| spec(kind).iter().map(|(k, _, _)| *k).collect::>(); assert_eq!(keys("innerGlow"), ["blend", "opacity", "color", "technique", "source", "choke", "size", "contour", "range", "noise"]); - assert_eq!(keys("outerGlow"), ["blend", "opacity", "color", "technique", "spread", "size", "contour", "range", "noise"]); + assert_eq!(keys("outerGlow"), ["blend", "opacity", "noise", "color", "technique", "spread", "size", "contour", "range"]); let mut s = session(); s.execute("layer.layerStyle.innerGlow", json!({"technique": "precise", "range": 30})).unwrap(); s.execute("layer.layerStyle.outerGlow", json!({"technique": "precise"})).unwrap(); @@ -1313,3 +1314,82 @@ fn style_click_does_not_mutate_document_until_confirm() { confirm(&mut app, &f).unwrap(); assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 1); } + +/// #14944: the Outer Glow page carries Photoshop's Structure / Elements / Quality titles, each +/// above the row that starts its block, with Noise right under Opacity. No other page is grouped +/// yet (#14917 is the Inner Glow's own ticket). +#[test] +fn the_outer_glow_page_shows_photoshops_group_titles() { + let mut blocks: Vec<(&'static str, Vec<&'static str>)> = Vec::new(); + for &(key, _, _) in spec("outerGlow") { + match group_title("outerGlow", key) { + Some(title) => blocks.push((title, vec![key])), + None => blocks.last_mut().expect("the page's first row starts a group").1.push(key), + } + } + assert_eq!( + blocks, + [("Structure", vec!["blend", "opacity", "noise", "color"]), ("Elements", vec!["technique", "spread", "size"]), ("Quality", vec!["contour", "range"]),] + ); + for kind in ["innerShadow", "dropShadow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "bevelEmboss", "satin"] { + assert_eq!(group_title(kind, "blend"), None, "{kind} gained a group title"); + } +} + +/// #14944: a new Outer Glow opens at the reference application's factory values, and OK stores +/// exactly those. +#[test] +fn a_new_outer_glow_opens_at_the_factory_values_and_ok_keeps_them() { + let p = fresh_params("outerGlow", 120.0, None); + assert_eq!( + ( + p["blend"].as_str(), + p["opacity"].as_f64(), + p["color"].as_str(), + p["technique"].as_str(), + p["size"].as_f64(), + p["range"].as_f64(), + p["antiAlias"].as_bool() + ), + (Some("Screen"), Some(35.0), Some("#ffffff"), Some("softer"), Some(7.0), Some(50.0), Some(false)), + "the page's own seed" + ); + let mut s = session(); + let layer = s.active().unwrap().active_layer.unwrap(); + let mut f = initial_fields(s.active().unwrap().doc.layer(layer).unwrap(), None, 120.0); + add_instance(&mut f, "outerGlow"); + let e = &effects_of(&f)[0]; + assert_eq!( + (e["params"]["opacity"].as_f64(), e["params"]["color"].as_str(), e["params"]["size"].as_f64()), + (Some(35.0), Some("#ffffff"), Some(7.0)), + "a new instance on the list starts there" + ); + apply(&f, |cmd, params| s.execute(cmd, params).map_err(|err| err.to_string())).unwrap(); + let d = s.active().unwrap(); + let Effect::OuterGlow(g) = &d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items[0] else { + panic!("{:?}", d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items) + }; + assert!((g.common.opacity * 100.0 - 35.0).abs() < 1e-4 && (g.size - 7.0).abs() < 1e-4, "OK stored {g:?}"); + let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) }; + assert!(c.to_rgb().iter().all(|v| (v - 1.0).abs() < 1e-3), "OK stored the colour {:?}", c.to_rgb()); +} + +/// #14944: the factory values never reach an Outer Glow the layer already carries: the page shows +/// its own values and OK keeps them, as it does for a glow read from a PSD or `.pcraft`. +#[test] +fn an_existing_outer_glow_is_edited_with_its_own_values() { + let mut s = session(); + s.execute("layer.layerStyle.outerGlow", json!({"opacity": 75, "color": "#ffffbe", "size": 5})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let f = initial_fields(s.active().unwrap().doc.layer(layer).unwrap(), None, 120.0); + let e = &effects_of(&f)[0]; + assert_eq!( + (e["params"]["opacity"].as_f64(), e["params"]["color"].as_str(), e["params"]["size"].as_f64()), + (Some(75.0), Some("#ffffbe"), Some(5.0)), + "the page shows what the layer has" + ); + apply(&f, |cmd, params| s.execute(cmd, params).map_err(|err| err.to_string())).unwrap(); + let d = s.active().unwrap(); + let Effect::OuterGlow(g) = &d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items[0] else { panic!("no outer glow") }; + assert!((g.common.opacity * 100.0 - 75.0).abs() < 1e-4 && (g.size - 5.0).abs() < 1e-4, "OK kept {g:?}"); +} From 8e5c712d438c708c9ac7e433af02d9f935b0bb6b Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 19:56:07 +0100 Subject: [PATCH 143/385] fix(compose): scatter Outer Glow noise at the measured strength Outer Glow noise only scaled the coverage (1 + (n - 0.5) * 2 * amount), so the speckle seldom removed glow: 0 of 1620 band pixels at R 255 with Noise 50 on the issue document (14 at Noise 100). Replace the law in paint.rs noise(): in a falloff a pixel drops out with probability min(1, amount * (1 - v) * (0.22 + 0.024 / v)) and otherwise its coverage deepens by up to 1 + 2 * amount. Deterministic per document coordinate (same hash_noise), Noise 0 stays bit-identical, empty pixels are never touched (#7833, #7846, #6112), solid coverage (>= 0.95, unmeasured by the issue) keeps today's jitter. Identical law text to the #14936 sibling branch; one shared change as both issues ask to coordinate. Tests: effects/outer_glow_noise_tests.rs pins the measured windows for Noise 50 (240..400 px at R 255, at most 30 equal, min R 0; measured 254/0/0) and Noise 100 (400..600; measured 513), the untouched backdrop past the falloff, determinism and a whole-map FNV hash pin for Noise 0. --- crates/compose/src/effects.rs | 2 + .../src/effects/outer_glow_noise_tests.rs | 131 ++++++++++++++++++ crates/compose/src/effects/paint.rs | 24 +++- 3 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 crates/compose/src/effects/outer_glow_noise_tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index adf0b7a7b0..d465e923ec 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -245,5 +245,7 @@ impl FxMaps { } } +#[cfg(test)] +mod outer_glow_noise_tests; #[cfg(test)] mod tests; diff --git a/crates/compose/src/effects/outer_glow_noise_tests.rs b/crates/compose/src/effects/outer_glow_noise_tests.rs new file mode 100644 index 0000000000..1b32cbb7bb --- /dev/null +++ b/crates/compose/src/effects/outer_glow_noise_tests.rs @@ -0,0 +1,131 @@ +//! #14952 - BUG-LAYER-STYLE-OUTER-GLOW-NOISE-TOO-WEAK. +//! +//! Measured on the issue's test document: 400 x 300 px, RGB 8 bit, white Background, an orange +//! (255, 128, 0) pixel layer covering x 100..299, y 75..224. Outer Glow black, Normal, 100 %, +//! Softer, Spread 0, Size 10, Contour Linear, Range 50 %. The issue counts the R channel of the +//! flattened band just above the rectangle, y 66..74, x 110..289 (1620 px): R 255 is the white +//! backdrop (no glow), R 0 is full black glow. Today `noise` only scales the coverage by +//! `1 + (n - 0.5) * 2 * amount`, so Noise 50 removes the glow nowhere (0 px at R 255) while the +//! reference application shows 314 px without glow there. + +use super::*; + +const DOC_W: usize = 400; +const DOC_H: usize = 300; + +/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224. +fn document_shape() -> Map { + let mut m = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + m.v[y * DOC_W + x] = 1.0; + } + } + m +} + +/// The issue's Outer Glow settings: black, Normal, 100 %, Softer, Spread 0, Size 10, Contour +/// Linear, Range 50 %, Jitter 0, Anti-aliased off, Noise `noise`. +fn glow(noise: f32) -> Glow { + Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(photocraft_color::Color::BLACK), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + } +} + +fn map(noise: f32) -> Map { + glow_map(&document_shape(), &glow(noise), false, (0, 0)) +} + +/// The R channel of the white backdrop under a black Normal outer glow of coverage `c`. +fn r_u8(c: f32) -> u8 { + (255.0 * (1.0 - c)).round().clamp(0.0, 255.0) as u8 +} + +/// The issue's band, y 66..=74 and x 110..=289 (1620 px), as R channel values. +fn band(m: &Map) -> Vec { + let mut out = Vec::with_capacity(180 * 9); + for y in 66..=74 { + for x in 110..=289 { + out.push(r_u8(m.get(x, y))); + } + } + out +} + +/// Done when: Noise 50 on that band leaves 240..400 pixels at R 255 (no glow at all), at most +/// 30 pixels equal to the noiseless result, and reaches R 0. Today the multiplicative law +/// removes the glow nowhere: 0 pixels sit at R 255. +#[test] +fn noise_fifty_scatters_the_glow_across_the_band() { + let plain = band(&map(0.0)); + let noisy = band(&map(0.5)); + let gone = noisy.iter().filter(|v| **v == 255).count(); + let equal = noisy.iter().zip(&plain).filter(|(a, b)| a == b).count(); + let min = noisy.iter().copied().min().unwrap_or(255); + assert!((240..=400).contains(&gone), "Noise 50: {gone} pixels without glow, want 240..400 (reference: 314)"); + assert!(equal <= 30, "Noise 50: {equal} pixels equal to the noiseless result, want at most 30 (reference: 9)"); + assert_eq!(min, 0, "Noise 50: minimum R {min}, want 0"); +} + +/// Done when: Noise 100 leaves 400..600 pixels at R 255 (reference: 498). Today: 14. +#[test] +fn noise_hundred_thins_the_glow_further() { + let noisy = band(&map(1.0)); + let gone = noisy.iter().filter(|v| **v == 255).count(); + let min = noisy.iter().copied().min().unwrap_or(255); + assert!((400..=600).contains(&gone), "Noise 100: {gone} pixels without glow, want 400..600 (reference: 498)"); + assert_eq!(min, 0, "Noise 100: minimum R {min}, want 0"); +} + +/// Done when: the noise does not reach beyond the glow's falloff: the row y 40 (25 px above the +/// rectangle, ten times the Size 10 reach) stays 255. +#[test] +fn noise_keeps_the_backdrop_beyond_the_glow_clean() { + let plain = map(0.0); + for noise in [0.5f32, 1.0] { + let noisy = map(noise); + for y in (16..=64).step_by(6) { + for x in (110..=289).step_by(7) { + assert_eq!(plain.get(x, y), 0.0, "noiseless coverage at ({x},{y}) is not empty"); + assert_eq!(noisy.get(x, y), 0.0, "noise {noise} lit up ({x},{y}): {}", noisy.get(x, y)); + assert_eq!(r_u8(noisy.get(x, y)), 255, "noise {noise} moved the backdrop at ({x},{y}) off 255"); + } + } + } +} + +/// Done when: the same settings give the identical image twice. +#[test] +fn the_same_noise_renders_identically_twice() { + for noise in [0.5f32, 1.0] { + let a = map(noise); + let b = map(noise); + assert_eq!(a.v, b.v, "noise {noise} is not deterministic"); + } +} + +/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is. +fn bit_hash(m: &Map) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for v in &m.v { + h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Noise 0 stays bit-identical: this is the whole-map FNV hash `glow_map` gives for the +/// issue's document with Noise 0 on upstream/main, so the new law must not touch it. +#[test] +fn noise_zero_maps_stay_bit_identical() { + assert_eq!(bit_hash(&map(0.0)), 0x340b_6ce5_05c9_a71d, "the Noise 0 outer glow map moved"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 3403ebddb9..ca64b204ab 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -84,9 +84,16 @@ pub fn hash_noise(x: i64, y: i64) -> f32 { } /// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, -/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is -/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's -/// near-zero tail out to the edge of its rectangular reach (#7833). +/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. In a falloff a +/// pixel drops out entirely with probability `min(1, amount x (1 - v) x (0.22 + 0.024 / v))` +/// and otherwise its coverage deepens by up to `1 + 2 x amount` (measured on the Inner Shadow +/// and Outer Glow falloff bands, #14936 and #14952: the reference application scatters far +/// stronger than the multiplicative jitter, which never removed a band pixel at Noise 50). +/// The dropout probability grows as coverage falls, so the speckle fades out with the effect +/// instead of lighting up the blur's near-zero tail out to the edge of its rectangular reach +/// (#7833); pixels with no coverage are never touched. Solid coverage (>= 0.95, e.g. a big +/// drop shadow's interior) keeps today's multiplicative jitter: the issues measure falloff +/// bands only, and jittering the interior is a behaviour they do not ask to change. pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { if !amount.is_finite() || amount <= 0.0 { return; @@ -98,7 +105,16 @@ pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { continue; } let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); - *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + if *v >= 0.95 { + *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + continue; + } + let kill = (amount * (1.0 - *v) * (0.22 + 0.024 / *v)).min(1.0); + if n < kill { + *v = 0.0; + } else { + *v = (*v * (1.0 + 2.0 * amount * n)).clamp(0.0, 1.0); + } } } } From d856020472592809d2edf9e099daea5d9b7e825b Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 10:59:02 -0800 Subject: [PATCH 144/385] Keep CI-produced photocraft-text lock dependencies canonical --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From 578f596528ac568fdcb9198347a6a68930943cae Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 20:28:49 +0100 Subject: [PATCH 145/385] Adapt to main: the Load supply tests unwrap apply_mixer_stroke's Result --- crates/paint/src/mixer_load_supply_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/paint/src/mixer_load_supply_tests.rs b/crates/paint/src/mixer_load_supply_tests.rs index 7da317db92..6078902a6b 100644 --- a/crates/paint/src/mixer_load_supply_tests.rs +++ b/crates/paint/src/mixer_load_supply_tests.rs @@ -24,7 +24,7 @@ fn paint(load: f32, x0: f64, x1: f64, spacing: f32) -> (impl Fn(i32) -> i32, f32 let mut st = MixerState::default(); st.load([0.0, 0.0, 0.0, 1.0]); let m = MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }; - apply_mixer_stroke(&mut s, None, &stroke(x0, x1, spacing), &m, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(x0, x1, spacing), &m, &mut st, None, false).unwrap(); (move |x: i32| (s.rgba(x, Y as i32)[3] * 255.0).round() as i32, st.amount) } @@ -83,9 +83,9 @@ fn each_stroke_measures_its_own_length() { let mut st = MixerState::default(); st.load([0.0, 0.0, 0.0, 1.0]); let m = MixerSettings { wet: 0.0, load: 0.05, mix: 0.0, flow: 1.0, ..Default::default() }; - apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false).unwrap(); assert_eq!(st.amount, 1.0, "300 px of a 570 px supply"); - apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(30.0, 330.0, 0.25), &m, &mut st, None, false).unwrap(); assert_eq!(st.amount, 1.0, "the second stroke starts its own 570 px"); } From 02f60896009e08c874c7818c205a12f7d8ba846c Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 15 Nov 2026 21:20:43 +0100 Subject: [PATCH 146/385] Flat import: a cancel during the palette index read fails the open The second read of a palette PNG whose entries share a colour runs after the last cancellation check of the import, so a cancel raised during it was ignored and the open succeeded. Check once more before returning the document. --- crates/io/src/flat.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 4ba4191b2d..1201590ded 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -127,6 +127,9 @@ fn import_flat_impl_with_options( } }; apply_flat_format(&mut r, bytes, format, img.as_ref())?; + // A palette PNG whose entries share a colour is read again there for its indices (#14342), + // a pass that doesn't watch for a cancel: one raised meanwhile still fails the open. + ctl.check().map_err(|_| IoError::Cancelled)?; Ok(r) } @@ -3143,6 +3146,20 @@ mod fused_tile_tests { assert!(matches!(&r, Err(e) if !matches!(e, IoError::Cancelled)), "{:?}", r.map(|_| ())); } + #[test] + fn a_cancel_while_a_palette_png_is_read_for_its_indices_fails_the_open() { + // Red, white, white: two entries share a colour, so once the pixels are built the open + // reads the file again for each pixel's entry (#14342). A cancel raised then still counts. + let png = codecs::encode_png_indexed(4, 2, &[0, 1, 2, 2, 0, 1, 2, 2], &[[255, 0, 0], [255, 255, 255], [255, 255, 255]], None, None, None).unwrap(); + let last = std::sync::Mutex::new(0.0f32); + let progress = |f: f32| *last.lock().unwrap() = f; + let pixels_built = || *last.lock().unwrap() >= 0.95; + let r = import_flat_with("t.png", &png, &Interrupt::new(&pixels_built, &progress)); + assert!(matches!(r, Err(IoError::Cancelled)), "{:?}", r.map(|_| ())); + let r = import_flat_with("t.png", &png, &Interrupt::NONE).unwrap(); + assert!(r.document.color_indices.is_some(), "the file was read for its indices"); + } + #[test] fn progress_is_reported_and_never_goes_backwards() { let bytes = codecs::encode(&pixels(64, 64, false), Format::Png, &codecs::EncodeOptions::default()).unwrap(); From 2f268cc0f6aa6478bdd934912b3ea768642d0764 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 12:23:09 -0800 Subject: [PATCH 147/385] Keep popup presses out of raw Type transform dispatch --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0d3153acbe..aaf06cb88d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1063,7 +1063,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: // This raw press bypasses egui's widget ownership. Leave presses on the Free Transform bar to its controls. let on_transform_bar = app.session.active_index() == Some(idx) && crate::transform_task_bar::shown_rect(app, ctx).is_some_and(|[x0, y0, x1, y1]| Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)).contains(p)); - if !on_transform_bar { + if !on_transform_bar && !egui::Popup::is_any_open(ctx) { let d = xf.to_doc(p); tool_input::tool_event_with_view( app, From 3e73d0244d2e361d96a5d3e69eee8ed92cafc91d Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 13:37:06 -0800 Subject: [PATCH 148/385] Match upstream shortcut fixture initializer without changing assertions --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index 31bc9bf711..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,9 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - let sepia = h.state().session.actions.list.len(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); - crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From f72c60f82fb67a39ab1f8d218cd35b9371a2663b Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 13:37:13 -0800 Subject: [PATCH 149/385] Match upstream shortcut fixture initializer without changing assertions --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index 31bc9bf711..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,9 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - let sepia = h.state().session.actions.list.len(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); - crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From 8663d7f1146af7e5a8650ad729d45c400d46c7a1 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 13:37:14 -0800 Subject: [PATCH 150/385] Match upstream shortcut fixture initializer without changing assertions --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index 31bc9bf711..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,9 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - let sepia = h.state().session.actions.list.len(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); - crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From 2255b817ef198141f256eca4ded1936578555486 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 13:37:16 -0800 Subject: [PATCH 151/385] Match upstream shortcut fixture initializer without changing assertions --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index 31bc9bf711..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,9 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - let sepia = h.state().session.actions.list.len(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); - crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From 71914e89b7a9dcce29e77285538a694246500311 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 16:47:59 -0500 Subject: [PATCH 152/385] Layers to Files PNG name tests: export into a temporary folder that is removed afterwards (#13963) Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- .../layers_to_files_png_names_tests.rs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs index bf549642a8..1b1c105ff4 100644 --- a/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_png_names_tests.rs @@ -3,13 +3,6 @@ use super::*; -fn tmp(name: &str) -> String { - let d = std::env::temp_dir().join(format!("photocraft-l2f-png-names-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d.to_string_lossy().into_owned() -} - /// Background, `Blue Half`, and a hidden layer `Hid den` on top. fn session() -> Session { let mut s = Session::new(); @@ -20,10 +13,12 @@ fn session() -> Session { s } -fn export(test: &str, format: &str) -> serde_json::Value { - let dir = tmp(&format!("{test}-{format}")); +/// Runs Layers to Files into a fresh temporary folder, removed with its files once the export is +/// done (also when an assertion or the command fails); only the file names are kept. +fn export(format: &str) -> serde_json::Value { + let dir = tempfile::tempdir().unwrap(); let mut s = session(); - s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "p 1", "format": format})).unwrap() + s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "prefix": "p 1", "format": format})).unwrap() } fn file_names(result: &serde_json::Value) -> Vec { @@ -32,14 +27,14 @@ fn file_names(result: &serde_json::Value) -> Vec { #[test] fn png_names_use_dashes_for_spaces() { - let result = export("dashes", "png"); + let result = export("png"); assert_eq!(file_names(&result), vec!["p-1_0001_Blue-Half.png".to_string(), "p-1_0002_Background.png".to_string()]); } #[test] fn other_formats_keep_spaces() { for format in ["psd", "jpg", "tif"] { - let result = export("keep", format); + let result = export(format); assert_eq!(file_names(&result), vec![format!("p 1_0001_Blue Half.{format}"), format!("p 1_0002_Background.{format}")], "{format}"); } } @@ -47,7 +42,7 @@ fn other_formats_keep_spaces() { #[test] fn skipped_layers_keep_the_original_name() { for format in ["png", "psd"] { - let result = export("skipped", format); + let result = export(format); let skipped = result["skipped"].as_array().unwrap(); assert_eq!(skipped.len(), 1, "{format}"); assert_eq!(skipped[0]["name"], json!("Hid den"), "{format}"); From 6fa1c373c360255236bfa1235aa560e045aab3a7 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 16:54:05 -0500 Subject: [PATCH 153/385] Batch stop-on-error test: check the error log's whole File path, then the Error line (#13665) Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/engine/src/cmd/file_cmds/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 83e2e1fc44..2ffb464bee 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -896,7 +896,9 @@ fn batch_stop_on_error_reports_skipped_inputs_and_writes_the_error_log() { assert_eq!(result["stopped"], json!(missing), "{result}"); assert_eq!(result["skipped"], json!([good]), "{result}"); let text = batch_log(&log); - assert!(text.starts_with("Start Batch\r\n\r\n") && text.contains("missing.png") && text.contains("File: \"") && text.contains("Error: "), "{text}"); + // The whole path as given, in the platform's separators (`native_separators`), then the error. + let file = if cfg!(windows) { missing.replace('/', "\\") } else { missing.clone() }; + assert!(text.starts_with("Start Batch\r\n\r\n") && text.contains(&format!("File: \"{file}\"\r\nError: ")), "{text}"); assert!(text.ends_with("End Batch\r\n"), "{text}"); assert!(!std::path::Path::new(&join(&output, "good.png")).exists()); } From c3fa1c57de6b35824050d6ca16976dd2c040c0b3 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 12:58:34 -0600 Subject: [PATCH 154/385] Merge to HDR Pro: Remove ghosts catches a moved object where frames are clipped (#14020) Each frame's value bounds the log radiance (one-sided where clipped or black); a pixel whose frame interval misses the base's by more than a factor of two in any channel is a ghost too, so a moved bright patch is taken from the base image even where no frame is well exposed. Unmoved areas and ghost-free sets are unchanged. --- crates/algo/src/hdr.rs | 28 +++++- crates/algo/src/hdr_ghost_clipped_tests.rs | 108 +++++++++++++++++++++ 2 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 crates/algo/src/hdr_ghost_clipped_tests.rs diff --git a/crates/algo/src/hdr.rs b/crates/algo/src/hdr.rs index ddd9a8fc73..08119ad7a2 100644 --- a/crates/algo/src/hdr.rs +++ b/crates/algo/src/hdr.rs @@ -296,8 +296,30 @@ pub fn merge(w: usize, h: usize, imgs: &[&[[f32; 4]]], opts: &MergeOptions) -> M let m = s / sw; ((s2 / sw - m * m).max(0.0)).sqrt() as f32 }); + // A frame whose radiance can't agree with the base's is a ghost too, also where the frames + // are clipped or black and so carry no weight above (#14020): each value bounds the log + // radiance (an interval; one-sided where it is clipped), and a pixel is a ghost when some + // frame's interval misses the base's by more than a factor of two in any channel. + let clash: Vec = crate::photo_util::par_map(w * h, |i| { + let bounds = |j: usize, c: usize| -> (f64, f64) { + let v = imgs[j][i][c].clamp(0.0, 1.0); + let l = g_at(&response[c], v) - log_dt[j]; + match v { + _ if v >= 0.98 => (l, f64::INFINITY), + _ if v <= 0.02 => (f64::NEG_INFINITY, l), + _ => (l, l), + } + }; + (0..3).any(|c| { + let (blo, bhi) = bounds(base, c); + (0..p).filter(|&j| j != base).any(|j| { + let (lo, hi) = bounds(j, c); + lo - bhi > std::f64::consts::LN_2 || blo - hi > std::f64::consts::LN_2 + }) + }) + }); for i in 0..w * h { - ghost[i] = if score[i] > 0.35 { 1.0 } else { 0.0 }; + ghost[i] = if score[i] > 0.35 || clash[i] { 1.0 } else { 0.0 }; } // Grow and feather the mask. let r = (w.max(h) as f32 / 200.0).max(2.0); @@ -539,3 +561,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "hdr_ghost_clipped_tests.rs"] +mod hdr_ghost_clipped_tests; diff --git a/crates/algo/src/hdr_ghost_clipped_tests.rs b/crates/algo/src/hdr_ghost_clipped_tests.rs new file mode 100644 index 0000000000..0fc67da182 --- /dev/null +++ b/crates/algo/src/hdr_ghost_clipped_tests.rs @@ -0,0 +1,108 @@ +//! #14020: Remove ghosts catches a moved bright object even where its pixels are clipped or black +//! in every frame (so no frame is well exposed there), and leaves unmoved areas alone. + +use super::*; + +const W: usize = 300; +const H: usize = 200; + +/// The issue's scene in linear light: a grey ramp (y 0-99), a mid-grey band (y 100-119) and red, +/// green, blue, white and black 60 x 60 patches at y 120-179 (x 0/60/120/180/240), on mid grey. +/// `ghost`: the white patch moved 30 px right and no black patch. +fn scene(ghost: bool) -> Vec<[f32; 3]> { + let mut px = vec![[0.0f32; 3]; W * H]; + for y in 0..H { + for x in 0..W { + let s = |v: f32| srgb_to_linear(v); + let c = if y < 100 { + let v = s(((x / 10) as f32 * 10.0 / 299.0).min(1.0)); + [v, v, v] + } else if !(120..180).contains(&y) { + [s(0.5); 3] + } else { + let (white, black) = if ghost { (210..270, 300..300) } else { (180..240, 240..300) }; + match x { + _ if white.contains(&x) => [1.0, 1.0, 1.0], + _ if black.contains(&x) => [0.0, 0.0, 0.0], + 0..60 => [s(0.8), s(0.05), s(0.05)], + 60..120 => [s(0.05), s(0.8), s(0.05)], + 120..180 => [s(0.05), s(0.05), s(0.8)], + _ => [s(0.5); 3], + } + }; + px[y * W + x] = c; + } + } + px +} + +/// One frame made with Exposure `ev`: the scene times 2^ev in linear light, clipped, as 8-bit sRGB. +fn frame(scene: &[[f32; 3]], ev: f32) -> Vec<[f32; 4]> { + scene + .iter() + .map(|c| { + let e = |v: f32| (linear_to_srgb((v * 2f32.powf(ev)).clamp(0.0, 1.0)) * 255.0).round() / 255.0; + [e(c[0]), e(c[1]), e(c[2]), 1.0] + }) + .collect() +} + +/// The merge of frames EV -2, 0 and +2 (the +2 one moved when `ghost`), base EV -2. +fn run(ghost: bool, remove_ghosts: bool) -> Merged { + let still = scene(false); + let frames = [frame(&still, -2.0), frame(&still, 0.0), frame(&scene(ghost), 2.0)]; + let refs: Vec<&[[f32; 4]]> = frames.iter().map(|f| f.as_slice()).collect(); + let opts = MergeOptions { exposures: vec![0.25, 1.0, 4.0], remove_ghosts, ghost_base: Some(0), response: None }; + merge(W, H, &refs, &opts) +} + +/// A radiance pixel as 8-bit sRGB levels (the merge is scaled so the base keeps its values). +fn levels(q: [f32; 4]) -> [f32; 3] { + [0, 1, 2].map(|c| linear_to_srgb(q[c].clamp(0.0, 1.0)) * 255.0) +} + +fn diff(a: [f32; 4], b: [f32; 4]) -> f32 { + let (a, b) = (levels(a), levels(b)); + (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max) +} + +fn moved(i: usize) -> bool { + let (x, y) = (i % W, i / W); + (120..180).contains(&y) && x >= 180 +} + +#[test] +fn the_moved_patch_comes_from_the_base_image() { + let on = run(true, true); + let off = run(true, false); + // What the merge gives when nothing moved: the patch where the base image has it. + let still = run(false, false); + let at = |x: usize, y: usize| y * W + x; + // Where the base has the black patch, and where the white patch was left behind. + for (x, y) in [(270, 150), (250, 150), (195, 150)] { + let i = at(x, y); + assert!(diff(on.px[i], still.px[i]) <= 10.0, "({x},{y}): {:?} vs {:?}", levels(on.px[i]), levels(still.px[i])); + assert!(diff(off.px[i], still.px[i]) > 10.0, "({x},{y}) was a ghost without the fix"); + } + // The white patch shows in one place only: almost the whole moved area matches the still merge. + let area: Vec = (0..W * H).filter(|&i| moved(i)).collect(); + let near = area.iter().filter(|&&i| diff(on.px[i], still.px[i]) <= 10.0).count(); + assert!(near * 100 >= area.len() * 95, "{near} of {}", area.len()); +} + +#[test] +fn unmoved_areas_are_left_alone() { + let on = run(true, true); + let off = run(true, false); + let worst = (0..W * H).filter(|&i| !moved(i) && (i % W < 170 || i / W < 110)).map(|i| diff(on.px[i], off.px[i])).fold(0.0, f32::max); + assert!(worst <= 2.0, "an unmoved pixel changed by {worst} levels"); +} + +#[test] +fn without_a_ghost_or_with_remove_ghosts_off_nothing_changes() { + let still_on = run(false, true); + let still_off = run(false, false); + let worst = (0..W * H).map(|i| diff(still_on.px[i], still_off.px[i])).fold(0.0, f32::max); + assert!(worst <= 2.0, "a ghost-free set changed by {worst} levels"); + assert_eq!(still_on.ghost_fraction, 0.0); +} From 1a0d5ac029a783db89bba233e1c39065dcdc860e Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 22:06:11 -0600 Subject: [PATCH 155/385] Export As: Resample lists Preserve Details, in the reference order (#13737) --- crates/engine/src/cmd/export_preset_cmds.rs | 14 ++-- crates/ui-egui/src/dialogs/export_dialog.rs | 4 + .../export_dialog/preserve_details_tests.rs | 84 +++++++++++++++++++ 3 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs diff --git a/crates/engine/src/cmd/export_preset_cmds.rs b/crates/engine/src/cmd/export_preset_cmds.rs index 7378e703ab..cc92eb73dd 100644 --- a/crates/engine/src/cmd/export_preset_cmds.rs +++ b/crates/engine/src/cmd/export_preset_cmds.rs @@ -12,15 +12,17 @@ const MAX_PRESETS: usize = 256; const MAX_PX: u32 = 300_000; const FORMATS: [&str; 6] = ["png", "jpg", "webp", "tif", "tga", "ico"]; -/// Export As › Image Size › Resample, in Photoshop's order: the `image.imageSize` method each -/// choice sends, and its menu label. The first one is the default. -pub const RESAMPLE: [(&str, &str); 6] = [ - ("bicubicAutomatic", "Bicubic Automatic"), +/// Export As › Image Size › Resample, in the reference application's menu order (#13737): the +/// `image.imageSize` method each choice sends, and its menu label. The default is +/// [`DEFAULT_RESAMPLE`]; Preserve Details is Image Size's `preserveDetails` resampler. +pub const RESAMPLE: [(&str, &str); 7] = [ ("bicubic", "Bicubic"), - ("bicubicSmoother", "Bicubic Smoother"), + ("bicubicAutomatic", "Bicubic Automatic"), ("bicubicSharper", "Bicubic Sharper"), + ("bicubicSmoother", "Bicubic Smoother"), ("bilinear", "Bilinear"), ("nearest", "Nearest Neighbor"), + ("preserveDetails", "Preserve Details"), ]; /// Photoshop's Export As default: Bicubic Automatic. @@ -228,7 +230,7 @@ pub fn specs() -> Vec { label: "Save Export Preset", menu: &[], shortcut: None, - params: r#"{"name":str,"settings":{"format":"png|jpg|webp|tif|tga|ico","quality":1..100,"lossless":bool,"transparency":bool,"scale":1..1000,"width":px,"height":px,"lockAspect":bool,"sizing":"scale|pixels","metadata":"none|exif|all","profile":"document|srgb","embedProfile":bool,"tgaBits":"auto|24|32","resample":"bicubicAutomatic|bicubic|bicubicSmoother|bicubicSharper|bilinear|nearest"="bicubicAutomatic"}} (a saved name is replaced)"#, + params: r#"{"name":str,"settings":{"format":"png|jpg|webp|tif|tga|ico","quality":1..100,"lossless":bool,"transparency":bool,"scale":1..1000,"width":px,"height":px,"lockAspect":bool,"sizing":"scale|pixels","metadata":"none|exif|all","profile":"document|srgb","embedProfile":bool,"tgaBits":"auto|24|32","resample":"bicubic|bicubicAutomatic|bicubicSharper|bicubicSmoother|bilinear|nearest|preserveDetails"="bicubicAutomatic"}} (a saved name is replaced)"#, enabled: always, run: save, journal: false, diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 1fbf7b2217..29e1d16353 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -945,10 +945,14 @@ fn resample_label(label: &str) -> &'static str { "Bicubic Sharper" => tl!("Bicubic Sharper"), "Bilinear" => tl!("Bilinear"), "Nearest Neighbor" => tl!("Nearest Neighbor"), + "Preserve Details" => tl!("Preserve Details"), _ => tl!("Bicubic Automatic"), } } +#[cfg(test)] +mod preserve_details_tests; + fn apply_preset(f: &mut Map, settings: &photocraft_engine::export_preset_cmds::ExportPresetSettings, src_w: f64, src_h: f64) { f.insert("format".into(), json!(settings.format)); f.insert("quality".into(), json!(settings.quality)); diff --git a/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs new file mode 100644 index 0000000000..1796998571 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs @@ -0,0 +1,84 @@ +//! #13737: Export As's Resample lists seven methods in the reference order, Preserve Details +//! last, with Bicubic Automatic still the default. Preserve Details is Image Size's +//! `preserveDetails` resampler; presets and recorded steps accept it. + +use super::*; +use egui::accesskit::Role; +use egui_kittest::{Harness, kittest::Queryable}; +use photocraft_doc::{Color, SampleType, Size}; +use photocraft_geom::Rect; + +/// 12 x 8 RGB/8 with a one-pixel checker, so resamplers differ when it is enlarged. +fn checker() -> Document { + let mut doc = Document::with_background("Checker", Size::new(12, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let surface = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surface.format(), [0.0, 0.0, 0.0, 1.0]); + for y in 0..8 { + for x in (y % 2..12).step_by(2) { + surface.fill_rect(Rect::new(x, y, x + 1, y + 1), &black); + } + } + doc +} + +fn pixels(doc: &Document) -> Vec<[f32; 4]> { + photocraft_compose::flatten(doc).into_px() +} + +fn export_with(resample: &str) -> Document { + let doc = checker(); + let f = json!({"scale": 300, "resample": resample, "profile": "document"}).as_object().unwrap().clone(); + export_document(&doc, &f, None, &photocraft_engine::color_cmds::document_profile(&doc)).unwrap() +} + +#[test] +fn seven_methods_in_the_reference_order_with_bicubic_automatic_the_default() { + let keys: Vec<&str> = RESAMPLE.iter().map(|(k, _)| *k).collect(); + assert_eq!(keys, ["bicubic", "bicubicAutomatic", "bicubicSharper", "bicubicSmoother", "bilinear", "nearest", "preserveDetails"]); + let labels: Vec<&str> = RESAMPLE.iter().map(|(_, l)| resample_label(l)).collect(); + assert_eq!(labels, ["Bicubic", "Bicubic Automatic", "Bicubic Sharper", "Bicubic Smoother", "Bilinear", "Nearest Neighbor", "Preserve Details"]); + assert_eq!(DEFAULT_RESAMPLE, "bicubicAutomatic"); + assert_eq!(resample_method(&Map::new(), None).unwrap(), "bicubicAutomatic"); +} + +#[test] +fn preserve_details_is_image_sizes_resampler_and_differs_from_bicubic() { + let preserve = export_with("preserveDetails"); + assert_eq!((preserve.size.width, preserve.size.height), (36, 24)); + let mut s = photocraft_engine::Session::new(); + s.add_document(checker(), None); + s.execute("image.imageSize", json!({"width": 36, "height": 24, "resample": "preserveDetails"})).unwrap(); + assert_eq!(pixels(&preserve), pixels(&s.active().unwrap().doc), "the same pixels as Image Size's Preserve Details"); + assert_ne!(pixels(&preserve), pixels(&export_with("bicubic")), "an enlarged export differs from Bicubic"); +} + +#[test] +fn presets_and_recorded_steps_accept_preserve_details_and_unknown_names_still_fail() { + assert!(valid_setting("resample", &json!("preserveDetails"))); + let mut s = photocraft_engine::Session::new(); + s.execute("file.export.presets.save", json!({"name": "Detail", "settings": {"format": "png", "resample": "preserveDetails"}})).unwrap(); + let err = photocraft_engine::export_preset_cmds::export_resample("lanczos").unwrap_err(); + assert!(err.contains("preserveDetails") && err.contains("bicubicAutomatic"), "{err}"); + assert!(!valid_setting("resample", &json!("lanczos"))); +} + +#[test] +fn the_dialog_offers_preserve_details_last() { + let mut h = Harness::builder().with_size(egui::vec2(1100.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.add_document(checker(), None); + app + }); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + h.run_steps(6); + h.get_by_role_and_label(Role::ComboBox, "Resample").click(); + h.run_steps(4); + let y = |label: &str| h.get_by_label(label).rect().min.y; + assert!(y("Nearest Neighbor") < y("Preserve Details"), "Preserve Details is last"); + assert!(y("Bicubic") < y("Bicubic Automatic"), "Bicubic comes first"); + h.get_by_label("Preserve Details").click(); + h.run_steps(4); + assert_eq!(h.state().ui.dialogs.last().unwrap().fields["resample"], "preserveDetails"); +} From 02d1cbed9f3c4d1f646ede383aa90f95fd67e67c Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 18:35:44 -0600 Subject: [PATCH 156/385] Straighten Layer: with a selection, the whole layer turns and the selection is kept (#11993) --- crates/engine/src/cmd/analysis_cmds.rs | 18 ++++ .../analysis_straighten_selection_tests.rs | 83 +++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 crates/engine/src/cmd/analysis_straighten_selection_tests.rs diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 451cdeaf67..cbb0885183 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -813,7 +813,22 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let (sn, cs) = rot.to_radians().sin_cos(); // Clockwise on screen (y down) about the canvas centre. let m = [cs, sn, -sn, cs, cx - (cs * cx - sn * cy), cy - (sn * cx + cs * cy)]; + // The whole layer turns even with a selection, which comes back as it was (#11993): the + // reference saves it, deselects, transforms and loads it again, all one step here. + let saved = doc(s)?.selection.clone(); + if saved.is_some() { + s.edit("Deselect", |doc, _| { + doc.selection = None; + Ok(()) + })?; + } s.execute("edit.transform", json!({"matrix": m}))?; + if let Some(selection) = saved { + s.edit("Load Selection", move |doc, _| { + doc.selection = Some(selection); + Ok(()) + })?; + } } // The ruler is cleared after straightening, as in Photoshop. set_quiet(s, |d| d.measurement.ruler = None) @@ -1440,4 +1455,7 @@ pub fn specs() -> Vec { #[path = "analysis_straighten_enabled_tests.rs"] mod analysis_straighten_enabled_tests; #[cfg(test)] +#[path = "analysis_straighten_selection_tests.rs"] +mod analysis_straighten_selection_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/analysis_straighten_selection_tests.rs b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs new file mode 100644 index 0000000000..631d2e5487 --- /dev/null +++ b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs @@ -0,0 +1,83 @@ +//! #11993: with a selection active, Straighten Layer turns the whole active layer, exactly as +//! without one, and the selection is the same afterwards. One undo brings both back, and no +//! channel is left behind (the reference saves the selection to a channel and deletes it again). + +use photocraft_doc::LayerId; + +use super::*; + +const CMD: &str = "image.analysis.straightenLayer"; + +/// An 800 × 600 document with a pixel layer "Colors" painted at 100,100 to 400,300, active, and a +/// ruler that tilts it by a few degrees. +fn session() -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let l = LayerId(s.execute("layer.new.layer", json!({"name": "Colors"})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + let surf = doc.layer_mut(l).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(100, 100, 400, 300), &[0.86, 0.12, 0.12, 1.0]); + surf.fill_rect(Rect::new(250, 180, 310, 220), &[0.1, 0.3, 0.9, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [100, 300], "end": [500, 270]})).unwrap(); + (s, l) +} + +fn select_square(s: &mut Session) { + s.execute("select.rect", json!({"x": 150, "y": 150, "width": 50, "height": 50})).unwrap(); +} + +fn layer(s: &Session, l: LayerId) -> photocraft_doc::Surface { + s.active().unwrap().doc.layer(l).unwrap().surface().unwrap().clone() +} + +fn selection(s: &Session) -> Option { + s.active().unwrap().doc.selection.clone() +} + +#[test] +fn the_whole_layer_turns_as_without_a_selection() { + let (mut plain, l) = session(); + plain.execute(CMD, json!({})).unwrap(); + let (mut with, l2) = session(); + select_square(&mut with); + with.execute(CMD, json!({})).unwrap(); + let (a, b) = (layer(&plain, l), layer(&with, l2)); + assert_eq!(a.content_bounds(), b.content_bounds(), "same bounds"); + assert!(a.content_bounds().width() > 300, "the whole layer turned, not a 50 px piece: {:?}", b.content_bounds()); + assert!(a == b, "same pixels"); +} + +#[test] +fn the_selection_is_the_same_afterwards() { + let (mut s, _) = session(); + select_square(&mut s); + let before = selection(&s); + assert!(before.is_some()); + s.execute(CMD, json!({})).unwrap(); + assert!(selection(&s) == before, "same bounds and mask"); +} + +#[test] +fn one_undo_brings_back_the_layer_and_the_selection() { + let (mut s, l) = session(); + select_square(&mut s); + let (layer_before, sel_before) = (layer(&s, l), selection(&s)); + let ruler_before = s.active().unwrap().doc.measurement.ruler; + s.execute(CMD, json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(layer(&s, l) == layer_before, "the layer as it was"); + assert!(selection(&s) == sel_before, "and the selection"); + assert_eq!(s.active().unwrap().doc.measurement.ruler, ruler_before); +} + +#[test] +fn no_channel_is_left_behind() { + let (mut s, _) = session(); + select_square(&mut s); + let channels = s.active().unwrap().doc.channels.len(); + s.execute(CMD, json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.channels.len(), channels); +} From d8e1bd92b7c679c4bec82d6b8a8788563911efb5 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 21:26:14 -0600 Subject: [PATCH 157/385] Straighten Layer: the whole-layer turn only for a plain rectangular selection (CodeRabbit on analysis_cmds.rs:819) Test: an_elliptical_or_feathered_selection_keeps_turning_only_its_pixels --- crates/engine/src/cmd/analysis_cmds.rs | 10 +++++++- .../analysis_straighten_selection_tests.rs | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index cbb0885183..2999499ec4 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -776,6 +776,12 @@ pub fn straighten_angle(r: &Ruler) -> f64 { a - 90.0 * (a / 90.0).round() } +/// Is `sel` a plain rectangle: the pixels inside its bounds all fully selected? +fn plain_rectangle(sel: &photocraft_raster::Surface) -> bool { + let bounds = sel.content_bounds(); + !bounds.is_empty() && sel.read_region(bounds).iter().all(|v| *v >= 0.999) +} + fn straighten(s: &mut Session, p: &Value) -> Result { let d = doc(s)?; let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line".into()))?; @@ -815,7 +821,9 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let m = [cs, sn, -sn, cs, cx - (cs * cx - sn * cy), cy - (sn * cx + cs * cy)]; // The whole layer turns even with a selection, which comes back as it was (#11993): the // reference saves it, deselects, transforms and loads it again, all one step here. - let saved = doc(s)?.selection.clone(); + // Only a plain rectangle (every pixel fully selected) is the measured case; an elliptical or + // feathered selection keeps today's behaviour (only its pixels turn). + let saved = doc(s)?.selection.clone().filter(plain_rectangle); if saved.is_some() { s.edit("Deselect", |doc, _| { doc.selection = None; diff --git a/crates/engine/src/cmd/analysis_straighten_selection_tests.rs b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs index 631d2e5487..b719332027 100644 --- a/crates/engine/src/cmd/analysis_straighten_selection_tests.rs +++ b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs @@ -81,3 +81,26 @@ fn no_channel_is_left_behind() { s.execute(CMD, json!({})).unwrap(); assert_eq!(s.active().unwrap().doc.channels.len(), channels); } + +/// CodeRabbit on #14986: only a plain rectangle (every pixel fully selected) gets the whole-layer +/// turn. An elliptical or feathered selection was not measured and keeps today's behaviour: only the +/// selected pixels turn. +#[test] +fn an_elliptical_or_feathered_selection_keeps_turning_only_its_pixels() { + for kind in ["ellipse", "feathered"] { + let (mut s, l) = session(); + match kind { + "ellipse" => { + s.execute("select.rect", json!({"x": 150, "y": 150, "width": 50, "height": 50, "ellipse": true})).unwrap(); + } + _ => { + select_square(&mut s); + s.execute("select.modify.feather", json!({"radius": 8})).unwrap(); + } + } + s.execute(CMD, json!({})).unwrap(); + let (mut plain, pl) = session(); + plain.execute(CMD, json!({})).unwrap(); + assert!(layer(&s, l) != layer(&plain, pl), "{kind}: not the whole-layer turn a plain rectangle gets"); + } +} From 37b54d65b2abe29cd21a666b8fec7f5d2d2e944d Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 23:19:42 -0600 Subject: [PATCH 158/385] Straighten Layer: scan the selection row by row and require exact full coverage --- crates/engine/src/cmd/analysis_cmds.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 2999499ec4..5b2f021fae 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -779,7 +779,10 @@ pub fn straighten_angle(r: &Ruler) -> f64 { /// Is `sel` a plain rectangle: the pixels inside its bounds all fully selected? fn plain_rectangle(sel: &photocraft_raster::Surface) -> bool { let bounds = sel.content_bounds(); - !bounds.is_empty() && sel.read_region(bounds).iter().all(|v| *v >= 0.999) + // Row by row: a sparse selection over a big area is refused at its first gap, and only one row + // is ever read. Full coverage means exactly 1.0 (a partly selected edge pixel is not a plain + // rectangle, however close to 1). + !bounds.is_empty() && (bounds.y0..bounds.y1).all(|y| sel.read_region(Rect::new(bounds.x0, y, bounds.x1, y + 1)).iter().all(|v| *v >= 1.0)) } fn straighten(s: &mut Session, p: &Value) -> Result { From 5ba7345d914b0d15ab0efab182951225f257d05d Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 01:50:09 -0600 Subject: [PATCH 159/385] Straighten Layer: test an F32 selection with a barely partial pixel --- .../analysis_straighten_selection_tests.rs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/engine/src/cmd/analysis_straighten_selection_tests.rs b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs index b719332027..5435de0c48 100644 --- a/crates/engine/src/cmd/analysis_straighten_selection_tests.rs +++ b/crates/engine/src/cmd/analysis_straighten_selection_tests.rs @@ -104,3 +104,32 @@ fn an_elliptical_or_feathered_selection_keeps_turning_only_its_pixels() { assert!(layer(&s, l) != layer(&plain, pl), "{kind}: not the whole-layer turn a plain rectangle gets"); } } + +/// CodeRabbit on #14986: a floating-point selection (the XCF importer makes F32 ones) can hold 0.9995, +/// which is not fully selected: only a plain rectangle of exactly 1.0 gets the whole-layer turn. The old +/// 0.999 threshold took this one for a plain rectangle. +#[test] +fn an_f32_selection_with_a_barely_partial_pixel_is_not_a_plain_rectangle() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + let f32_selection = |edge: f32| { + let mut sel = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + sel.fill_rect(Rect::new(150, 150, 200, 200), &[1.0]); + sel.write_pixel(150, 150, &[edge]); + sel + }; + let turned = |edge: f32| { + let (mut s, l) = session(); + s.edit("selection", |doc, _| { + doc.selection = Some(f32_selection(edge)); + Ok(()) + }) + .unwrap(); + s.execute(CMD, json!({})).unwrap(); + layer(&s, l) + }; + let (mut plain, pl) = session(); + plain.execute(CMD, json!({})).unwrap(); + let whole = layer(&plain, pl); + assert!(turned(1.0) == whole, "exactly 1.0 everywhere is a plain rectangle: the whole layer turns"); + assert!(turned(0.9995) != whole, "0.9995 is not: only the selected pixels turn"); +} From 5c1357b46dd355cb73dd21da83c2673c5daffc44 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Sun, 15 Nov 2026 23:31:14 +0100 Subject: [PATCH 160/385] Palette PNG indices: no second full-image buffer, and a memory check The index read kept every index in one vector and then copied it into the index surface, two bytes per pixel that the open's memory check never counted. Write the indices into the surface one band of rows at a time instead, and check that they and one band fit in free memory before reading. When they don't, no indices are recorded and Color Table falls back to the nearest entry; the open itself goes on. --- .../cmd/mode_cmds/color_table_index_tests.rs | 12 +++++++ crates/io/src/flat.rs | 32 +++++++++++++------ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs index 184d43cbb0..02770d88ce 100644 --- a/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs +++ b/crates/engine/src/cmd/mode_cmds/color_table_index_tests.rs @@ -244,6 +244,18 @@ fn a_transparent_entry_keeps_its_index() { assert_eq!([0, 1, 2].map(|x| surf.rgba(x, 0)), [[0.0; 4], WHITE, GREEN]); } +#[test] +fn indices_taller_than_one_band_of_rows_land_in_place() { + // Rows past the first band (one tile high) go in with the next one, and the last band is short. + let (w, h) = (3, photocraft_geom::TILE_SIZE as usize * 2 + 5); + let indices: Vec = (0..w * h).map(|k| ((k / w + k % w) % 2) as u8).collect(); + let png = palette_png(w as u32, &indices, png::BitDepth::Eight, &[[255, 255, 255], [255, 255, 255]], None); + let doc = photocraft_io::import("tall.png", &png).unwrap().document; + let layer = &doc.layers[0]; + let known = doc.color_indices.as_ref().unwrap().known(layer.id, layer.surface().unwrap(), doc.bounds()); + assert_eq!(known.as_deref(), Some(&indices[..])); +} + #[test] fn a_palette_png_without_shared_colours_is_not_read_again() { // Every entry its own colour: the colours already name the entries, so the open skips the diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 1201590ded..cff18fb53a 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -265,8 +265,10 @@ impl FlatBuilder { /// tell entries of one colour apart (#14342). `None`, and Color Table falls back to the nearest /// entry, when the document's one layer doesn't show each pixel's entry at the file's place for /// it (an EXIF orientation turned the pixels, which colours alone can't show when entries repeat, -/// or a colour conversion changed them), or when the file is interlaced (not read here). One row at a time: -/// next to the layer, only the indices themselves (a byte per pixel) are held. +/// or a colour conversion changed them), or when the file is interlaced (not read here). One row +/// at a time, into tiles one band of rows at a time: next to the layer, only the indices +/// themselves (a byte per pixel) and one band are held. `None` too when memory can't hold them: +/// the open's own memory check didn't count them. fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { let table = doc.color_table.as_ref()?; // Only entries that share a colour need the file. When every entry has its own colour, each @@ -290,13 +292,18 @@ fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { return None; } let width = usize::try_from(w).ok()?; - let count = width.checked_mul(usize::try_from(h).ok()?)?; - let mut indices = Vec::new(); - indices.try_reserve_exact(count).ok()?; + let rows = usize::try_from(TILE_SIZE).ok()?; + let band_len = width.checked_mul(rows)?; + let needed = u64::from(w).checked_mul(u64::from(h))?.checked_add(u64::try_from(band_len).ok()?)?; + crate::memory::check_fits(w, h, needed, crate::memory::available()).ok()?; + let mut band = Vec::new(); + band.try_reserve_exact(band_len).ok()?; + let mut map = Surface::new(PixelFormat::GRAY8); let mut shown = vec![[0u8; 4]; width]; - let mut y = 0; + let (mut y, mut band_y) = (0i32, 0i32); + let height = i32::try_from(h).ok()?; while let Some(row) = reader.next_row().ok()? { - if indices.len() >= count { + if y >= height { return None; } surface.read_rgba8_into(Rect::from_xywh(0, y, w, 1), &mut shown); @@ -309,16 +316,21 @@ fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { if !ok { return None; } - indices.push(i); + band.push(i); } y += 1; + if band.len() >= band_len || y == height { + map.try_write_interleaved(Rect::from_xywh(0, band_y, w, u32::try_from(y - band_y).ok()?), &band).ok()?; + band.clear(); + band_y = y; + } } // An eXIf after the pixels counts too. reader.finish().ok()?; - if reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || indices.len() != count { + if reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || y != height { return None; } - ColorIndices::new(layer.id, surface, doc.bounds(), &indices) + Some(ColorIndices { layer: layer.id, pixels: surface.clone(), indices: map }) } /// What every flat format does to the document of its pixels: the palette mode, the save From 6c795466063315f1c674128cf1fbe9751d970bc8 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 11:06:27 -0600 Subject: [PATCH 161/385] Quick Selection: a stroke drops the active layer's transparent pixels from the selection (#12919) With Sample All Layers off and a pixel or type layer's pixels targeted, every Quick Selection stroke intersects the selection it leaves with the layer's alpha > 0, in every mode, so the layer's fully transparent pixels drop out of the existing selection. Sample All Layers on, the Background, other layer kinds and a targeted mask or channel keep today's result. Tests: crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs. --- crates/engine/src/cmd/smartselect_cmds.rs | 32 +++- .../quick_drop_transparent_tests.rs | 138 ++++++++++++++++++ 2 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index 32af4656f6..06668b6480 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -134,7 +134,8 @@ fn quick_selection(s: &mut Session, p: &Value) -> Result { _ => SelectionMode::Add, }; let enhance = b(p, "enhanceEdge", false); - let region = with_quick_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { + let all_layers = b(p, "sampleAllLayers", false); + let region = with_quick_sampler(s, all_layers, |smp, doc| { let canvas = doc.bounds(); let Some(r) = quick::quick_select(smp, canvas, &pts, size) else { return Ok(None) }; let surface = matting::region_surface(&r); @@ -142,6 +143,10 @@ fn quick_selection(s: &mut Session, p: &Value) -> Result { })??; let Some(region) = region else { return apply(s, "Quick Selection", None, m) }; let bounds = region.content_bounds(); + // Only for the layer's pixels as the target: a targeted layer mask or a single channel (not + // measured) keeps today's result. + let pixels_targeted = !s.tools.mask_targeted && s.active().is_some_and(|d| d.channel_view.target == crate::channel_cmds::ChannelTarget::Composite); + let active = s.active().and_then(|d| d.active_layer).filter(|_| pixels_targeted); let selected = s.edit("Quick Selection", |doc, _| { let empty = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); let old = doc.selection.as_ref().unwrap_or(&empty); @@ -152,12 +157,35 @@ fn quick_selection(s: &mut Session, p: &Value) -> Result { SelectionMode::Subtract => photocraft_algo::selection::combine_sparse(old, ®ion, area, |a, b| (a - b).max(0.0)), SelectionMode::Intersect => photocraft_algo::selection::combine_surfaces(old, ®ion, area, f32::min), }; + // Sample All Layers off on a pixel or type layer: the stroke also drops the layer's fully + // transparent pixels from the selection it leaves, in every mode (#12919). + let out = match active.filter(|_| !all_layers).and_then(|id| doc.layer(id)) { + Some(layer) => drop_transparent(layer, out), + None => out, + }; doc.selection = (!out.content_bounds().is_empty()).then_some(out); Ok(doc.selection.is_some()) })?; Ok(json!({"selected": selected, "changed": true, "bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()]})) } +/// `sel` without the pixels that are fully transparent on `layer`, for a pixel or type layer +/// (Quick Selection with Sample All Layers off, #12919). Other layers (smart objects, shapes, +/// fills, groups; not measured) leave it as it is. +fn drop_transparent(layer: &Layer, sel: photocraft_raster::Surface) -> photocraft_raster::Surface { + if !matches!(layer.content, LayerContent::Raster(_) | LayerContent::Text(_)) { + return sel; + } + let Some(surf) = layer.surface() else { return sel }; + let area = sel.content_bounds(); + if area.is_empty() { + return sel; + } + let mask: Vec = SurfaceSampler(surf).rgba(area).iter().map(|p| if p[3] > 0.0 { 255 } else { 0 }).collect(); + let opaque = matting::region_surface(&Region { bbox: area, mask }); + photocraft_algo::selection::combine_surfaces(&sel, &opaque, area, f32::min) +} + fn rect_param(p: &Value) -> Option { let a = p.get("rect")?.as_array()?; let v: Vec = a.iter().filter_map(Value::as_f64).collect(); @@ -714,4 +742,6 @@ mod tests; #[cfg(test)] mod object_mode_refusal_tests; #[cfg(test)] +mod quick_drop_transparent_tests; +#[cfg(test)] mod quick_group_target_tests; diff --git a/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs b/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs new file mode 100644 index 0000000000..a611ba2c07 --- /dev/null +++ b/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs @@ -0,0 +1,138 @@ +//! #12919: with Sample All Layers off and a pixel layer active, a Quick Selection stroke also +//! drops the layer's fully transparent pixels from the selection it leaves, in every mode. With +//! Sample All Layers on, or with the opaque Background active, the old selection keeps its +//! transparent parts. One "Quick Selection" history step per stroke. +//! +//! The document is the one the issue measured: white Background; pixel layer Shapes with red +//! (220,30,30) rectangles 100,100-300,250 ("red 1") and 500,100-600,200 ("red 2") on +//! transparency, active. + +use super::*; + +const W: i32 = 800; +const H: i32 = 600; +const RED1: [i32; 4] = [100, 100, 300, 250]; +const RED2: [i32; 4] = [500, 100, 600, 200]; + +fn issue_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Shapes"})).unwrap(); + for [x0, y0, x1, y1] in [RED1, RED2] { + s.execute("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap(); + s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn marquee(s: &mut Session, [x0, y0, x1, y1]: [i32; 4]) { + s.execute("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap(); +} + +/// One Quick Selection click with the default 30 px brush. +fn click(s: &mut Session, at: [f32; 2], mode: &str, sample_all: bool) -> Value { + s.execute("select.quick", json!({"points": [at], "size": 30, "mode": mode, "sampleAllLayers": sample_all})).unwrap() +} + +fn at(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn inside([x0, y0, x1, y1]: [i32; 4], x: i32, y: i32) -> bool { + (x0..x1).contains(&x) && (y0..y1).contains(&y) +} + +/// (fully selected, partly selected) pixels outside both red rectangles, where Shapes is fully +/// transparent. +fn on_transparency(s: &Session) -> (usize, usize) { + let mut n = (0, 0); + for y in 0..H { + for x in 0..W { + if inside(RED1, x, y) || inside(RED2, x, y) { + continue; + } + let v = at(s, x, y); + if v >= 0.999 { + n.0 += 1; + } else if v > 0.0 { + n.1 += 1; + } + } + } + n +} + +/// Fully selected pixels of `rect`. +fn full_in(s: &Session, [x0, y0, x1, y1]: [i32; 4]) -> usize { + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|(x, y)| at(s, *x, *y) >= 0.999).count() +} + +#[test] +fn adding_red_2_drops_the_marquees_transparent_frame() { + let mut s = issue_document(); + marquee(&mut s, [50, 50, 350, 300]); + let before = s.active().unwrap().history.past_len(); + click(&mut s, [550.0, 150.0], "add", false); + assert_eq!(on_transparency(&s), (0, 0), "no pixel that is transparent on Shapes stays selected"); + assert_eq!(full_in(&s, RED1), 200 * 150, "red 1 with the marquee's hard edge"); + assert!(full_in(&s, RED2) >= 9000, "red 2 from the stroke"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Quick Selection")); +} + +#[test] +fn subtracting_red_1_leaves_nothing_of_the_marquee() { + let mut s = issue_document(); + marquee(&mut s, [50, 50, 350, 300]); + click(&mut s, [200.0, 175.0], "subtract", false); + assert_eq!(on_transparency(&s), (0, 0), "the transparent frame is gone"); + assert_eq!(full_in(&s, RED1), 0, "and red 1 was subtracted"); +} + +#[test] +fn a_transparent_only_selection_minus_red_1_is_no_selection() { + let mut s = issue_document(); + marquee(&mut s, [400, 50, 480, 300]); + click(&mut s, [200.0, 175.0], "subtract", false); + assert!(s.active().unwrap().doc.selection.is_none(), "no selection"); +} + +#[test] +fn a_new_stroke_drops_transparent_pixels_too() { + let mut s = issue_document(); + click(&mut s, [550.0, 150.0], "new", false); + assert_eq!(on_transparency(&s), (0, 0)); + assert!(full_in(&s, RED2) >= 9000); +} + +#[test] +fn sample_all_layers_keeps_the_transparent_frame() { + let mut s = issue_document(); + marquee(&mut s, [50, 50, 350, 300]); + click(&mut s, [200.0, 175.0], "subtract", true); + assert!(at(&s, 60, 60) >= 0.999 && at(&s, 340, 290) >= 0.999, "the frame stays"); +} + +#[test] +fn the_background_loses_only_the_brush_disc() { + let mut s = issue_document(); + let d = s.active_mut().unwrap(); + d.active_layer = Some(d.doc.layers[0].id); + marquee(&mut s, [50, 50, 350, 300]); + click(&mut s, [70.0, 280.0], "subtract", false); + assert!(at(&s, 70, 280) < 0.5, "the disc is subtracted"); + assert!(at(&s, 340, 60) >= 0.999 && at(&s, 200, 175) >= 0.999, "the rest of the marquee stays"); +} + +#[test] +fn a_stroke_that_finds_nothing_changes_nothing() { + let mut s = issue_document(); + marquee(&mut s, [50, 50, 350, 300]); + let before = s.active().unwrap().history.past_len(); + // Off the canvas: no region, so the transparent frame stays and no step is added. + let out = s.execute("select.quick", json!({"points": [[-500.0, -500.0]], "size": 30, "mode": "add"})).unwrap(); + assert_eq!(out["changed"], json!(false)); + assert!(at(&s, 60, 60) >= 0.999); + assert_eq!(s.active().unwrap().history.past_len(), before); +} From 02f8702443c54817dc4d384f1080a50dfebc7f19 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 13:00:06 -0600 Subject: [PATCH 162/385] Quick Selection: drop transparent pixels tile by tile (CodeRabbit on smartselect_cmds.rs:182) The filter now visits the selection's own tiles instead of sampling its whole bounding box, and a partly transparent patch has its own test (CodeRabbit nitpick). Tests: partly_transparent_pixels_stay_selected, two_selected_pieces_far_apart_each_drop_their_transparent_pixels --- crates/engine/src/cmd/smartselect_cmds.rs | 22 +++++++++---- .../quick_drop_transparent_tests.rs | 31 +++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index 06668b6480..909279bc28 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -172,18 +172,28 @@ fn quick_selection(s: &mut Session, p: &Value) -> Result { /// `sel` without the pixels that are fully transparent on `layer`, for a pixel or type layer /// (Quick Selection with Sample All Layers off, #12919). Other layers (smart objects, shapes, /// fills, groups; not measured) leave it as it is. +/// +/// It visits the selection's own tiles, one at a time, so a stroke costs the tiles the selection +/// holds, not its bounding box: two small pieces far apart don't make a canvas-sized RGBA buffer. fn drop_transparent(layer: &Layer, sel: photocraft_raster::Surface) -> photocraft_raster::Surface { if !matches!(layer.content, LayerContent::Raster(_) | LayerContent::Text(_)) { return sel; } let Some(surf) = layer.surface() else { return sel }; - let area = sel.content_bounds(); - if area.is_empty() { - return sel; + let coords: Vec = sel.tiles().map(|(tc, _)| *tc).collect(); + let mut out = sel.clone(); + for tc in coords { + let rect = tc.rect(); + let mask: Vec = SurfaceSampler(surf).rgba(rect).iter().map(|p| if p[3] > 0.0 { 255 } else { 0 }).collect(); + let opaque = matting::region_surface(&Region { bbox: rect, mask }); + let kept = photocraft_algo::selection::combine_surfaces(&sel, &opaque, rect, f32::min); + match kept.tile(tc) { + Some(tile) => out.put_tiles([(tc, std::sync::Arc::clone(tile))]), + // `take_tiles` only allocates for a tile that is missing; this one is there. + None => drop(out.take_tiles(rect)), + } } - let mask: Vec = SurfaceSampler(surf).rgba(area).iter().map(|p| if p[3] > 0.0 { 255 } else { 0 }).collect(); - let opaque = matting::region_surface(&Region { bbox: area, mask }); - photocraft_algo::selection::combine_surfaces(&sel, &opaque, area, f32::min) + out } fn rect_param(p: &Value) -> Option { diff --git a/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs b/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs index a611ba2c07..8c8e0c0e4c 100644 --- a/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs +++ b/crates/engine/src/cmd/smartselect_cmds/quick_drop_transparent_tests.rs @@ -136,3 +136,34 @@ fn a_stroke_that_finds_nothing_changes_nothing() { assert!(at(&s, 60, 60) >= 0.999); assert_eq!(s.active().unwrap().history.past_len(), before); } + +/// CodeRabbit on #14672: only fully transparent pixels drop out. A faint patch (alpha 0.2) beside +/// the red rectangles stays selected, and a similar-looking patch of fully transparent pixels next +/// to it does not. +#[test] +fn partly_transparent_pixels_stay_selected() { + let mut s = issue_document(); + // A faint patch on the Shapes layer: 20 % red over 350,100-450,200. + marquee(&mut s, [350, 100, 450, 200]); + s.execute("edit.fill", json!({"color": "#dc1e1e", "opacity": 20})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + marquee(&mut s, [50, 50, 480, 300]); + click(&mut s, [550.0, 150.0], "add", false); + assert_eq!(full_in(&s, [350, 100, 450, 200]), 100 * 100, "the faint patch stays selected"); + assert_eq!(full_in(&s, [450, 100, 480, 200]), 0, "the transparent pixels beside it drop out"); +} + +/// CodeRabbit on #14672: the filter works on the selection's own tiles, so two pieces far apart +/// (in different tiles, with nothing selected between them) each lose only their transparent +/// pixels. +#[test] +fn two_selected_pieces_far_apart_each_drop_their_transparent_pixels() { + let mut s = issue_document(); + marquee(&mut s, [10, 10, 130, 130]); + s.execute("select.rect", json!({"x": 560, "y": 440, "width": 120, "height": 120, "mode": "add"})).unwrap(); + // A stroke that adds nothing new on transparency. + click(&mut s, [550.0, 150.0], "add", false); + assert_eq!(full_in(&s, [100, 100, 130, 130]), 30 * 30, "red 1's corner under the first piece"); + assert_eq!(full_in(&s, [10, 10, 100, 100]), 0, "the first piece's transparent part drops out"); + assert_eq!(full_in(&s, [560, 440, 680, 560]), 0, "the second piece lies on transparency and drops out"); +} From bdd484a35a818dc508626ad1a6c5e82b5c8fe59b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 19:09:11 -0600 Subject: [PATCH 163/385] 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 164/385] 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 165/385] 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 166/385] 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 167/385] 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 168/385] 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 bd425b9495d26e2b14dbc84c866e5685c195f3b9 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 12:05:49 -0600 Subject: [PATCH 169/385] Notes panel: empty state with no selection, "N / M" counter, blank author, caret in a new note (#11793) With no note selected the Notes panel shows an inactive empty text box with the placeholder "Click a note to view or edit", a blank counter and greyed controls instead of falling back to note 1. The author line is empty for a note without an author, the counter reads "N / M", and a note made with a click takes the keyboard. The panel flyout and docking are left for a follow-up. --- crates/ui-egui/src/tools/analysis_ui.rs | 47 ++++++++-- .../src/tools/notes_panel_layout_tests.rs | 85 +++++++++++++++++++ 2 files changed, 123 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/tools/notes_panel_layout_tests.rs diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 7ecb43286b..0825960128 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -84,6 +84,9 @@ pub struct AnalysisUi { pub dialog: Option<(String, Map)>, #[serde(skip)] pub drag: Option, + /// A note was just made with a click: the Notes panel focuses its text next frame (#11793). + #[serde(skip)] + pub focus_note_text: bool, } impl Default for AnalysisUi { @@ -98,6 +101,7 @@ impl Default for AnalysisUi { use_measurement_scale: false, dialog: None, drag: None, + focus_note_text: false, } } } @@ -327,6 +331,7 @@ pub(crate) fn create_note(app: &mut PhotocraftApp, x: f64, y: f64) -> Result 0).then_some(0)); + // No note selected (after Delete, Clear All, a new document) stays unselected (#11793). + let mut sel = app.ui.analysis.note_selected.filter(|i| *i < n); + let focus_text = std::mem::take(&mut app.ui.analysis.focus_note_text); let mut close = false; let mut edit: Option = None; let mut delete = false; @@ -1053,31 +1060,44 @@ fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) { panel_window(app, ctx, "notes-panel", tl!("Notes"), vec2(-40.0, 300.0), 260.0, |ui| { close = title_row(ui, tl!("Notes")); match sel { + // No note selected: an empty, inactive text box with the reference's placeholder. None => { - ui.label(RichText::new(tl!("Click with the Note tool to add a note.")).color(t.text_dim).size(11.0)); + ui.label(RichText::new(" ").size(11.0)); + let mut empty = String::new(); + ui.add_enabled( + false, + egui::TextEdit::multiline(&mut empty).desired_rows(6).desired_width(f32::INFINITY).hint_text(tl!("Click a note to view or edit")), + ) + .accessible_name(tl!("Notes")); } Some(i) => { let note = ¬es[i]; - ui.label(RichText::new(if note.author.is_empty() { tl!("No author").to_string() } else { note.author.clone() }).color(t.text_dim).size(11.0)); + // The author line as stored: empty for a note without author (#11793). + ui.label(RichText::new(if note.author.is_empty() { " ".to_string() } else { note.author.clone() }).color(t.text_dim).size(11.0)); let mut text = note.text.clone(); - if ui.add(egui::TextEdit::multiline(&mut text).desired_rows(6).desired_width(f32::INFINITY)).accessible_name(tl!("Notes")).changed() { + let resp = ui.add(egui::TextEdit::multiline(&mut text).desired_rows(6).desired_width(f32::INFINITY)).accessible_name(tl!("Notes")); + // A note just made with a click: the caret goes into its text, ready to type. + if focus_text { + resp.request_focus(); + } + if resp.changed() { edit = Some(json!({"index": i, "text": text, "coalesce": format!("note-{i}")})); } } } crate::widgets::hairline(ui); ui.horizontal(|ui| { - if ui.add_enabled_ui(n > 1, |ui| crate::icons::button(ui, "chevrons-left", 22.0, false, tl!("Previous note"))).inner.clicked() { + let step = n > 1 && sel.is_some(); + if ui.add_enabled_ui(step, |ui| crate::icons::button(ui, "chevrons-left", 22.0, false, tl!("Previous note"))).inner.clicked() { sel = sel.map(|i| (i + n - 1) % n); navigated = true; } - if ui.add_enabled_ui(n > 1, |ui| crate::icons::button(ui, "chevrons-right", 22.0, false, tl!("Next note"))).inner.clicked() { + if ui.add_enabled_ui(step, |ui| crate::icons::button(ui, "chevrons-right", 22.0, false, tl!("Next note"))).inner.clicked() { sel = sel.map(|i| (i + 1) % n); navigated = true; } - let template = "{index} of {total}"; - let position = crate::i18n::fmt(tl!(template), &[("index", &sel.map_or(0, |i| i + 1).to_string()), ("total", &n.to_string())]); - ui.label(RichText::new(position).color(t.text_dim).size(11.0)); + // "N / M", blank with no note selected (#11793). + ui.label(RichText::new(note_counter(sel, n)).color(t.text_dim).size(11.0)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add_enabled_ui(sel.is_some(), |ui| crate::icons::button(ui, "trash", 22.0, false, tl!("Delete note"))).inner.clicked() { delete = true; @@ -1100,6 +1120,11 @@ fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) { } } +/// The Notes panel's counter: "N / M" for note N of M, blank with no note selected (#11793). +pub(crate) fn note_counter(sel: Option, n: usize) -> String { + sel.filter(|i| *i < n).map_or_else(String::new, |i| format!("{} / {n}", i + 1)) +} + fn num_field(ui: &mut egui::Ui, f: &mut Map, key: &str, label: &str, range: std::ops::RangeInclusive, suffix: &str) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { @@ -1267,6 +1292,10 @@ pub(crate) mod tests; #[cfg(test)] #[path = "count_group_name_tests.rs"] mod count_group_name_tests; + +#[cfg(test)] +#[path = "notes_panel_layout_tests.rs"] +mod notes_panel_layout_tests; #[cfg(test)] mod sampler_drag_tests; diff --git a/crates/ui-egui/src/tools/notes_panel_layout_tests.rs b/crates/ui-egui/src/tools/notes_panel_layout_tests.rs new file mode 100644 index 0000000000..ec50b44ff5 --- /dev/null +++ b/crates/ui-egui/src/tools/notes_panel_layout_tests.rs @@ -0,0 +1,85 @@ +//! #11793: the Notes panel with no note selected shows an empty, inactive text box with the +//! placeholder "Click a note to view or edit", a blank counter and greyed arrows and trash, +//! and selects no note by itself; the author line is empty for a note without author; the +//! counter reads "N / M"; a note made with a click puts the caret in its text. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::*; + +/// A 300 × 200 document with two notes (the second without author) and the Notes panel open, +/// nothing selected; the harness draws the analysis windows. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("notes.add", json!({"x": 20, "y": 20, "author": "Ann", "text": "first"})).unwrap(); + app.run("notes.add", json!({"x": 120, "y": 80, "author": "", "text": "second"})).unwrap(); + app.ui.analysis.notes = true; + app.ui.analysis.note_selected = None; + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + super::windows(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().is_disabled() +} + +#[test] +fn the_counter_reads_n_of_m_with_a_slash() { + assert_eq!(note_counter(Some(0), 4), "1 / 4"); + assert_eq!(note_counter(Some(3), 4), "4 / 4"); + assert_eq!(note_counter(None, 4), ""); + assert_eq!(note_counter(Some(5), 4), "", "a stale selection reads as none"); +} + +#[test] +fn no_selection_stays_empty_with_greyed_controls() { + let h = harness(); + assert_eq!(h.state().ui.analysis.note_selected, None, "note 1 isn't selected by itself"); + assert!(h.query_by_label("1 / 2").is_none() && h.query_by_label("2 / 2").is_none(), "blank counter"); + for label in ["Previous note", "Next note", "Delete note"] { + assert!(disabled(&h, label), "{label} is greyed out"); + } + assert!(h.query_by_label("first").is_none(), "no note's text is shown"); +} + +#[test] +fn a_selected_note_shows_its_counter_and_an_empty_author_line() { + let mut h = harness(); + h.state_mut().ui.analysis.note_selected = Some(1); + h.run_steps(3); + assert!(h.query_by_label("2 / 2").is_some()); + assert!(h.query_by_label("No author").is_none(), "an empty author stays empty"); + assert!(!disabled(&h, "Next note") && !disabled(&h, "Delete note")); + h.state_mut().ui.analysis.note_selected = Some(0); + h.run_steps(3); + assert!(h.query_by_label("1 / 2").is_some()); + assert!(h.query_by_label("Ann").is_some(), "the stored author"); +} + +#[test] +fn a_note_made_with_a_click_takes_the_keyboard() { + let mut h = harness(); + h.state_mut().ui.tool = Tool::Note; + crate::canvas::tool_event(h.state_mut(), ToolEvent::Down { x: 200.0, y: 150.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::canvas::tool_event(h.state_mut(), ToolEvent::Up { x: 200.0, y: 150.0 }, egui::Modifiers::NONE); + h.run_steps(3); + assert_eq!(h.state().ui.analysis.note_selected, Some(2)); + assert!(h.ctx.memory(|m| m.focused().is_some()), "the note's text box has the keyboard"); + h.event(egui::Event::Text("hello".into())); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.notes[2].text, "hello", "typing goes into the new note"); +} From b9e246864a7565fe91989e2cfdba131e5a1195ed Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 12:13:26 -0600 Subject: [PATCH 170/385] Import Notes: place notes by target height / source height, no clamping, alert off-canvas (#13914) File > Import > Notes... multiplies each note's icon and popup top-left by target canvas height / source height, keeps their sizes and no longer clamps them inside the canvas. When an icon's top-left lands outside, the shell shows "Some notes are placed outside the canvas." once. --- crates/engine/src/cmd/notes_cmds.rs | 42 +++++++-- .../src/cmd/notes_import_placement_tests.rs | 88 +++++++++++++++++++ crates/ui-egui/src/tools/analysis_ui.rs | 7 +- 3 files changed, 128 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/cmd/notes_import_placement_tests.rs diff --git a/crates/engine/src/cmd/notes_cmds.rs b/crates/engine/src/cmd/notes_cmds.rs index 6520305229..590df80131 100644 --- a/crates/engine/src/cmd/notes_cmds.rs +++ b/crates/engine/src/cmd/notes_cmds.rs @@ -214,14 +214,7 @@ pub fn import_notes_from(s: &mut Session, name: &str, bytes: &[u8]) -> Result Result, target: [u32; 2], source_height: u32) -> Result<(Vec, bool)> { + if source_height == 0 { + return Err(EngineError::Other("the notes' source has no height".into())); + } + let scale = f64::from(target[1]) / f64::from(source_height); + let (w, h) = (f64::from(target[0]), f64::from(target[1])); + let mut outside = false; + for n in &mut notes { + let [px, py] = [n.position[0] * scale, n.position[1] * scale]; + let [l, t] = [n.popup[0] * scale, n.popup[1] * scale]; + let [r, b] = [l + (n.popup[2] - n.popup[0]), t + (n.popup[3] - n.popup[1])]; + if ![scale, px, py, l, t, r, b].iter().all(|v| v.is_finite()) { + return Err(EngineError::Other("the notes' positions overflow on this canvas".into())); + } + n.position = [px, py]; + n.popup = [l, t, r, b]; + outside |= !((0.0..w).contains(&px) && (0.0..h).contains(&py)); + } + Ok((notes, outside)) +} + pub fn specs() -> Vec { vec![ CommandSpec { @@ -291,6 +313,10 @@ pub fn specs() -> Vec { #[path = "notes_import_message_tests.rs"] mod notes_import_message_tests; +#[cfg(test)] +#[path = "notes_import_placement_tests.rs"] +mod notes_import_placement_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/notes_import_placement_tests.rs b/crates/engine/src/cmd/notes_import_placement_tests.rs new file mode 100644 index 0000000000..d28eb96eff --- /dev/null +++ b/crates/engine/src/cmd/notes_import_placement_tests.rs @@ -0,0 +1,88 @@ +//! #13914: File › Import › Notes… multiplies each note's icon and popup top-left by the target +//! canvas height over the source height, keeps their sizes, clamps nothing, and reports when an +//! icon's top-left lands outside the canvas. + +use super::*; + +/// The issue's three notes on a 600 × 400 source page: icon top-left (92, 90), (292, 190) and +/// (582, 370); popups 240 × 140 next to each. +fn source() -> Vec { + [[92.0, 90.0], [292.0, 190.0], [582.0, 370.0]] + .into_iter() + .map(|[x, y]| Note { position: [x, y], popup: [x + 20.0, y, x + 260.0, y + 140.0], ..Default::default() }) + .collect() +} + +fn placed(target: [u32; 2]) -> (Vec, bool) { + place_notes(source(), target, 400).unwrap() +} + +#[test] +fn the_measured_targets_give_the_measured_positions() { + // (target, s, note 1, note 3) as measured in the issue. + let cases: [([u32; 2], [f64; 2], [f64; 2]); 6] = [ + ([600, 400], [92.0, 90.0], [582.0, 370.0]), + ([1200, 800], [184.0, 180.0], [1164.0, 740.0]), + ([300, 200], [46.0, 45.0], [291.0, 185.0]), + ([1200, 200], [46.0, 45.0], [291.0, 185.0]), + ([2400, 400], [92.0, 90.0], [582.0, 370.0]), + ([1200, 1600], [368.0, 360.0], [2328.0, 1480.0]), + ]; + for (target, n1, n3) in cases { + let (notes, _) = placed(target); + assert_eq!(notes[0].position, n1, "{target:?}"); + assert_eq!(notes[2].position, n3, "{target:?}"); + } +} + +#[test] +fn icon_and_popup_sizes_stay_and_the_popup_moves_with_the_scale() { + let (notes, _) = placed([1200, 800]); + let p = notes[0].popup; + assert_eq!([p[0], p[1]], [224.0, 180.0], "the popup's top-left is scaled too"); + assert_eq!([p[2] - p[0], p[3] - p[1]], [240.0, 140.0], "its size stays"); +} + +#[test] +fn nothing_is_clamped_and_off_canvas_notes_are_reported() { + let (notes, outside) = placed([1200, 1600]); + assert_eq!(notes[2].position[0], 2328.0, "past the right edge, kept"); + assert!(outside, "note 3's top-left is outside the 1200 px wide canvas"); + // Note 3's icon sticks out over the edge at 300 × 200, but its top-left is inside: no report. + let (_, outside) = placed([300, 200]); + assert!(!outside); +} + +#[test] +fn fractions_are_not_rounded() { + let (notes, _) = place_notes(source(), [700, 700], 400).unwrap(); + assert_eq!(notes[0].position, [92.0 * 1.75, 90.0 * 1.75]); + let (notes, _) = place_notes(source(), [100, 300], 400).unwrap(); + assert_eq!(notes[0].position, [69.0, 67.5]); +} + +#[test] +fn a_zero_height_source_or_an_overflow_is_an_error() { + assert!(place_notes(source(), [600, 400], 0).is_err()); + let huge = vec![Note { position: [f64::MAX, 1.0], popup: [0.0, 0.0, 1.0, 1.0], ..Default::default() }]; + assert!(place_notes(huge, [600, u32::MAX], 1).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_import_reports_outside_and_keeps_the_history_step() { + let mut src = Document::new("src", photocraft_doc::Size::new(600, 400), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + src.notes = source(); + let bytes = photocraft_format::save_to_bytes(&src, &Default::default()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 1600})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let r = import_notes_from(&mut s, "notes.pcraft", &bytes).unwrap(); + assert_eq!(r["imported"], json!(3)); + assert_eq!(r["outside"], json!(true)); + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(s.active().unwrap().doc.notes[2].position, [2328.0, 1480.0]); + s.execute("file.new", json!({"width": 300, "height": 200})).unwrap(); + let r = import_notes_from(&mut s, "notes.pcraft", &bytes).unwrap(); + assert_eq!(r["outside"], json!(false)); +} diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 7ecb43286b..74b257dcc7 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -198,9 +198,14 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option app.pick_file_bytes(move |app, name, bytes| { app.refocus(doc)?; let r = photocraft_engine::notes_cmds::import_notes_from(&mut app.session, &name, &bytes).map_err(|e| e.to_string()); - if r.is_ok() { + if let Ok(v) = &r { app.ui.analysis.notes = true; app.sync_views(); + // Notes whose icon landed off the canvas stay there; the alert says so (#13914). + if v["outside"] == json!(true) { + let params = json!({"message": tl!("Some notes are placed outside the canvas.")}).as_object().cloned().unwrap_or_default(); + app.ui.open_dialog(crate::state::DialogKind::Error, params); + } } r }), From 0e3c0b8da27276624a1fb1c137c5cc5ec7c6b509 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 16:05:13 -0800 Subject: [PATCH 171/385] Preserve shared digit pairing outside issue #11927 --- .../src/color_replacement_digit_keys_tests.rs | 38 ++++++++++++------- crates/ui-egui/src/input/opacity_keys.rs | 32 ++-------------- 2 files changed, 29 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs index e5cd63dabf..64e0442b35 100644 --- a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs +++ b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs @@ -72,18 +72,30 @@ fn modifiers_and_double_zero_preserve_color_replacement_and_layer_state() { assert_eq!(a.ui.tool_options.bg_tolerance, bg_tolerance); } #[test] -fn digits_do_not_pair_across_tools() { - let mut brush_to_color = app(Tool::Brush); - press(&mut brush_to_color, 4, false, 0.0); - brush_to_color.ui.tool = Tool::ColorReplacement; - press(&mut brush_to_color, 5, false, 300.0); - assert_eq!(brush_to_color.session.tools.brush.opacity, 0.4); - assert_eq!(brush_to_color.ui.tool_options.cr_tolerance, 50.0); +fn digit_pairs_preserve_the_existing_shared_cross_tool_sequence() { + // The new target inherits the same pending-digit sequence as Main's existing tools. + let mut brush_to_selected = app(Tool::Brush); + press(&mut brush_to_selected, 4, false, 0.0); + brush_to_selected.ui.tool = Tool::ColorReplacement; + press(&mut brush_to_selected, 5, false, 300.0); + assert_eq!(brush_to_selected.session.tools.brush.opacity, 0.4); + assert_eq!(brush_to_selected.ui.tool_options.cr_tolerance, 45.0); - let mut color_to_brush = app(Tool::ColorReplacement); - press(&mut color_to_brush, 4, false, 0.0); - color_to_brush.ui.tool = Tool::Brush; - press(&mut color_to_brush, 5, false, 300.0); - assert_eq!(color_to_brush.ui.tool_options.cr_tolerance, 40.0); - assert_eq!(color_to_brush.session.tools.brush.opacity, 0.5); + // A selected-tool digit still contributes to the unchanged legacy Brush sequence. + let mut selected_to_brush = app(Tool::ColorReplacement); + press(&mut selected_to_brush, 4, false, 0.0); + selected_to_brush.ui.tool = Tool::Brush; + press(&mut selected_to_brush, 5, false, 300.0); + assert_eq!(selected_to_brush.ui.tool_options.cr_tolerance, 40.0); + assert_eq!(selected_to_brush.session.tools.brush.opacity, 0.45); + + // Consuming the first pair must also leave the next legacy digit unpaired. + let mut through_selected = app(Tool::Brush); + press(&mut through_selected, 4, false, 0.0); + through_selected.ui.tool = Tool::ColorReplacement; + press(&mut through_selected, 5, false, 300.0); + through_selected.ui.tool = Tool::Brush; + press(&mut through_selected, 6, false, 400.0); + assert_eq!(through_selected.ui.tool_options.cr_tolerance, 45.0); + assert_eq!(through_selected.session.tools.brush.opacity, 0.6); } diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 8727122495..2034a50060 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -16,8 +16,8 @@ use crate::state::Tool; /// A second digit within this long of the first makes a two-digit value. const TWO_DIGITS_MS: f64 = 800.0; -/// The first digit of a possible two-digit value: (digit, ⇧ held, when, originating tool). -pub type Pending = Option<(u8, bool, f64, Tool)>; +/// The first digit of a possible two-digit value: (digit, ⇧ held, when). +pub type Pending = Option<(u8, bool, f64)>; /// What a tool's number keys change. #[derive(Clone, Copy, Debug, PartialEq)] @@ -132,11 +132,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { /// One digit press at `now` (ms). pub fn press(app: &mut PhotocraftApp, d: u8, shift: bool, now: f64) { - let tool = app.ui.tool; let percent = match app.opacity_keys.take() { - Some((first, s, at, started_with)) if started_with == tool && s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), + Some((first, s, at)) if s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), _ => { - app.opacity_keys = Some((d, shift, now, tool)); + app.opacity_keys = Some((d, shift, now)); if d == 0 { 100.0 } else { f32::from(d) * 10.0 } } }; @@ -203,29 +202,6 @@ mod tests { (l.opacity, l.fill_opacity) } - #[test] - fn two_digits_do_not_pair_across_tools() { - // Brush and Eraser both target shared brush opacity, but a tool switch starts a new value. - let mut brush_then_eraser = app(Tool::Brush); - press(&mut brush_then_eraser, 4, false, 0.0); - brush_then_eraser.ui.tool = Tool::Eraser; - press(&mut brush_then_eraser, 5, false, 300.0); - assert_eq!(brush_then_eraser.session.tools.brush.opacity, 0.5); - - // Gradient and Paint Bucket share their opacity option but still have separate sequences. - let mut gradient_then_bucket = app(Tool::Gradient); - press(&mut gradient_then_bucket, 4, false, 0.0); - gradient_then_bucket.ui.tool = Tool::PaintBucket; - press(&mut gradient_then_bucket, 5, false, 300.0); - assert_eq!(gradient_then_bucket.ui.tool_options.fill_opacity, 50.0); - - // Same-tool pairs remain exact. - let mut same_tool = app(Tool::Brush); - press(&mut same_tool, 4, false, 0.0); - press(&mut same_tool, 5, false, 300.0); - assert_eq!(same_tool.session.tools.brush.opacity, 0.45); - } - #[test] fn digits_set_the_brush_opacity_and_shift_digits_its_flow() { let mut a = app(Tool::Brush); From fce0beda0afb8d9849bfeb744d038e57a2ee94a2 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 16:05:14 -0800 Subject: [PATCH 172/385] Preserve shared digit pairing outside issue #11999 --- .../input/magic_eraser_digit_keys_tests.rs | 38 ++++++++++++------- crates/ui-egui/src/input/opacity_keys.rs | 32 ++-------------- 2 files changed, 29 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs index 9609c657a3..4411d1a73e 100644 --- a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs +++ b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs @@ -54,18 +54,30 @@ fn magic_eraser_digits_leave_tolerance_layer_and_brush_alone() { assert_eq!(a.ui.tool_options.magic_eraser_opacity, 100.0, "unmeasured 00 keeps the first zero's value"); } #[test] -fn digits_do_not_pair_across_tools() { - let mut brush_to_magic = app(Tool::Brush); - press(&mut brush_to_magic, 4, false, 0.0); - brush_to_magic.ui.tool = Tool::MagicEraser; - press(&mut brush_to_magic, 5, false, 300.0); - assert_eq!(brush_to_magic.session.tools.brush.opacity, 0.4); - assert_eq!(brush_to_magic.ui.tool_options.magic_eraser_opacity, 50.0); +fn digit_pairs_preserve_the_existing_shared_cross_tool_sequence() { + // The new target inherits the same pending-digit sequence as Main's existing tools. + let mut brush_to_selected = app(Tool::Brush); + press(&mut brush_to_selected, 4, false, 0.0); + brush_to_selected.ui.tool = Tool::MagicEraser; + press(&mut brush_to_selected, 5, false, 300.0); + assert_eq!(brush_to_selected.session.tools.brush.opacity, 0.4); + assert_eq!(brush_to_selected.ui.tool_options.magic_eraser_opacity, 45.0); - let mut magic_to_brush = app(Tool::MagicEraser); - press(&mut magic_to_brush, 4, false, 0.0); - magic_to_brush.ui.tool = Tool::Brush; - press(&mut magic_to_brush, 5, false, 300.0); - assert_eq!(magic_to_brush.ui.tool_options.magic_eraser_opacity, 40.0); - assert_eq!(magic_to_brush.session.tools.brush.opacity, 0.5); + // A selected-tool digit still contributes to the unchanged legacy Brush sequence. + let mut selected_to_brush = app(Tool::MagicEraser); + press(&mut selected_to_brush, 4, false, 0.0); + selected_to_brush.ui.tool = Tool::Brush; + press(&mut selected_to_brush, 5, false, 300.0); + assert_eq!(selected_to_brush.ui.tool_options.magic_eraser_opacity, 40.0); + assert_eq!(selected_to_brush.session.tools.brush.opacity, 0.45); + + // Consuming the first pair must also leave the next legacy digit unpaired. + let mut through_selected = app(Tool::Brush); + press(&mut through_selected, 4, false, 0.0); + through_selected.ui.tool = Tool::MagicEraser; + press(&mut through_selected, 5, false, 300.0); + through_selected.ui.tool = Tool::Brush; + press(&mut through_selected, 6, false, 400.0); + assert_eq!(through_selected.ui.tool_options.magic_eraser_opacity, 45.0); + assert_eq!(through_selected.session.tools.brush.opacity, 0.6); } diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 471ec00acd..de88690dc9 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -16,8 +16,8 @@ use crate::state::Tool; /// A second digit within this long of the first makes a two-digit value. const TWO_DIGITS_MS: f64 = 800.0; -/// The first digit of a possible two-digit value: (digit, ⇧ held, when, originating tool). -pub type Pending = Option<(u8, bool, f64, Tool)>; +/// The first digit of a possible two-digit value: (digit, ⇧ held, when). +pub type Pending = Option<(u8, bool, f64)>; /// What a tool's number keys change. #[derive(Clone, Copy, Debug, PartialEq)] @@ -132,11 +132,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { /// One digit press at `now` (ms). pub fn press(app: &mut PhotocraftApp, d: u8, shift: bool, now: f64) { - let tool = app.ui.tool; let percent = match app.opacity_keys.take() { - Some((first, s, at, started_with)) if started_with == tool && s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), + Some((first, s, at)) if s == shift && now - at < TWO_DIGITS_MS && now >= at => f32::from(first * 10 + d), _ => { - app.opacity_keys = Some((d, shift, now, tool)); + app.opacity_keys = Some((d, shift, now)); if d == 0 { 100.0 } else { f32::from(d) * 10.0 } } }; @@ -203,29 +202,6 @@ mod tests { (l.opacity, l.fill_opacity) } - #[test] - fn two_digits_do_not_pair_across_tools() { - // Brush and Eraser both target shared brush opacity, but a tool switch starts a new value. - let mut brush_then_eraser = app(Tool::Brush); - press(&mut brush_then_eraser, 4, false, 0.0); - brush_then_eraser.ui.tool = Tool::Eraser; - press(&mut brush_then_eraser, 5, false, 300.0); - assert_eq!(brush_then_eraser.session.tools.brush.opacity, 0.5); - - // Gradient and Paint Bucket share their opacity option but still have separate sequences. - let mut gradient_then_bucket = app(Tool::Gradient); - press(&mut gradient_then_bucket, 4, false, 0.0); - gradient_then_bucket.ui.tool = Tool::PaintBucket; - press(&mut gradient_then_bucket, 5, false, 300.0); - assert_eq!(gradient_then_bucket.ui.tool_options.fill_opacity, 50.0); - - // Same-tool pairs remain exact. - let mut same_tool = app(Tool::Brush); - press(&mut same_tool, 4, false, 0.0); - press(&mut same_tool, 5, false, 300.0); - assert_eq!(same_tool.session.tools.brush.opacity, 0.45); - } - #[test] fn digits_set_the_brush_opacity_and_shift_digits_its_flow() { let mut a = app(Tool::Brush); From 682ff6bf15d0cde043c4da9a112bbe59ff105dba Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:13:36 +0100 Subject: [PATCH 173/385] 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 c7544cd080fb092036eb0ee82ead753fee7a4e4b Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:31:42 +0100 Subject: [PATCH 174/385] Address CodeRabbit review: never save Apply Data Set's Preview File > Save and the unsaved-changes prompt's Save write through invoke_unguarded without run_command, so they skipped end_preview and could write the previewed data set into the file. invoke_unguarded now ends the preview first; the dialog shows it again on the next frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/invoke.rs | 3 ++ .../tests/it/apply_data_set_preview.rs | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 4e184eff02..8ad765715c 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -398,6 +398,9 @@ fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, /// Dispatch UI actions and dialogs, falling back to the engine for other commands. pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + // File › Save and the unsaved-changes prompt's Save write from here without `run`: they must + // not write Apply Data Set's Preview either. The dialog shows it again on the next frame. + crate::panels::apply_data_set_ui::end_preview(app); if let Some(result) = crate::smart_svg_ui::intercept(app, id, ¶ms) { return result; } diff --git a/crates/ui-egui/tests/it/apply_data_set_preview.rs b/crates/ui-egui/tests/it/apply_data_set_preview.rs index 2e77633646..6161cb156c 100644 --- a/crates/ui-egui/tests/it/apply_data_set_preview.rs +++ b/crates/ui-egui/tests/it/apply_data_set_preview.rs @@ -109,6 +109,7 @@ fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { return; } photocraft_ui_egui::dialogs::show(app, &ctx); + photocraft_ui_egui::discard_ui::show(app, &ctx); }, app, ); @@ -418,3 +419,52 @@ fn autosave_waits_while_previewing() { assert_eq!(saved.len(), 1); assert_eq!(*saved[0], *before, "the document itself"); } + +/// Services that keep every document they are asked to encode, and a document with unsaved work +/// and its own file, so File › Save writes it back in place. +fn saving_app() -> (PhotocraftApp, Layers, Arc>>) { + let encoded: Arc>> = Default::default(); + let log = encoded.clone(); + let services = photocraft_ui_egui::Services { + export: Some(Box::new(move |d: &Document, _path: &str, _settings: &photocraft_ui_egui::ExportSettings| { + log.lock().unwrap().push(d.clone()); + Ok((Vec::new(), Vec::new())) + })), + write: Some(Box::new(|_path: &str, _bytes: &[u8]| Ok(()))), + ..Default::default() + }; + let (mut a, l) = app_with(services); + let dir = std::env::temp_dir().join(format!("pc-apply-data-set-preview-{}-save", std::process::id())); + a.session.active_mut().unwrap().path = Some(dir.join("own.psd").to_string_lossy().into_owned()); + a.run("layer.new.layer", json!({"name": "Work"})).unwrap(); + (a, l, encoded) +} + +/// Save on the unsaved-changes prompt (closing the document or quitting while the dialog shows a +/// set) and File › Save run from the menu or the control channel write the document itself, +/// never the preview. +#[test] +fn saving_while_previewing_writes_the_document_itself() { + for via_prompt in [true, false] { + let (a, l, encoded) = saving_app(); + let mut h = harness(a); + let before = doc(&h); + open(&mut h); + click(&mut h, "Preview"); + assert_eq!(shown(&h, &l).1, "Alpha"); + let ctx = h.ctx.clone(); + if via_prompt { + photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.close", json!({})).unwrap(); + h.run_steps(3); + assert!(photocraft_ui_egui::discard_ui::inspect(h.state()).is_some(), "closing unsaved work asks first"); + // Save: Yes on Windows and Linux, S on macOS; the test context is not macOS. + h.key_press(egui::Key::Y); + h.run_steps(3); + } else { + photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap(); + } + let encoded = encoded.lock().unwrap(); + assert_eq!(encoded.len(), 1, "via_prompt={via_prompt}"); + assert_eq!(encoded[0], *before, "via_prompt={via_prompt}: the document itself, nothing of Zed"); + } +} From 9bd2d6efd3998a8651a15f59f55b9b8d519b2675 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:33:10 +0100 Subject: [PATCH 175/385] 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 3f838a9d38f7fcd2ebcf3486b8cd95a8bc0b74db Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 23:06:03 -0600 Subject: [PATCH 176/385] Object Selection mode test: the rest of the selection is checked on an opaque pixel, as Quick Selection now drops the layer's transparent ones (CI on #14672) --- crates/ui-egui/src/tools/object_selection_mode_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/object_selection_mode_tests.rs b/crates/ui-egui/src/tools/object_selection_mode_tests.rs index 53be1b163f..214dfad374 100644 --- a/crates/ui-egui/src/tools/object_selection_mode_tests.rs +++ b/crates/ui-egui/src/tools/object_selection_mode_tests.rs @@ -204,7 +204,9 @@ fn object_finder_off_dab_subtracts_with_alt_and_in_subtract_mode() { app.ui.selection_mode = bar; click(&mut app, RED, mods); assert!(!selected(&app, RED), "bar mode {bar}, {mods:?} subtracts"); - assert!(selected(&app, [20.0, 20.0]), "bar mode {bar}, {mods:?} keeps the rest"); + // The rest is what the layer has: (20, 20) is transparent on it, which a Quick Selection stroke now drops from + // the selection (#12919); the blue disc is opaque and stays. + assert!(selected(&app, BLUE), "bar mode {bar}, {mods:?} keeps the rest"); } } From 0baf7182ceb654b8e78fb912d7af18d726376688 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Mon, 16 Nov 2026 06:47:17 +0100 Subject: [PATCH 177/385] chore(ci): re-run checks against green main From 3d11c5fc520fba0a67ae5d81544fe7288c167966 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 08:18:34 +0100 Subject: [PATCH 178/385] Palette PNG indices: the memory check counts whole tiles and the row buffer --- crates/io/src/flat.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index cff18fb53a..e4521f3288 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -294,7 +294,8 @@ fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { let width = usize::try_from(w).ok()?; let rows = usize::try_from(TILE_SIZE).ok()?; let band_len = width.checked_mul(rows)?; - let needed = u64::from(w).checked_mul(u64::from(h))?.checked_add(u64::try_from(band_len).ok()?)?; + // The index surface's whole tiles, the band, and the row of the layer read beside it. + let needed = tile_bytes(w, h, 1).saturating_add(u64::from(w).saturating_mul(rows as u64 + 4)); crate::memory::check_fits(w, h, needed, crate::memory::available()).ok()?; let mut band = Vec::new(); band.try_reserve_exact(band_len).ok()?; From 8baf4639ca98f15604f329bbdf8cbbd41ce87ef4 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Mon, 16 Nov 2026 08:32:44 +0100 Subject: [PATCH 179/385] fix(algo): continue straight bands and stripes through the fill's hole Content-Aware Fill copies the sampling area with a 7x7 patch. On the document #14191 measured, the straight features are 10 px bands and 20 px stripes: a 7x7 patch fits inside one stripe or inside one band gap, so it carries no phase information and the completion decides from colour alone. The blue half of that document ran down into the green one (300,205 gave 65,127,205 where the reference application shows 80,180,90) and the light band was not continued at all (300,165 gave 64,124,201 instead of 120,170,230). The fill now works the option set #14191 measured out with an 11x11 patch, which covers a feature and the one next to it and keeps their phase through the hole: all nine measured samples land within 4 levels of the reference values (the issue asks for 12), and every one of the 10000 hole pixels carries the document's own colour within 12 levels. High and Very High colour adaptation, the rotation levels, Scale and Mirror are marked "not measured" in #14191, so they keep the old patch radius; the new tests pin their samples as main gives them today. --- crates/algo/src/content_aware.rs | 22 +- .../content_aware/structure_continue_tests.rs | 278 ++++++++++++++++++ 2 files changed, 299 insertions(+), 1 deletion(-) create mode 100644 crates/algo/src/content_aware/structure_continue_tests.rs diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 955a911119..0eb8cbb6c0 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -244,6 +244,21 @@ pub fn fill_owned( fill_cow(w, h, ch, Cow::Owned(img), hole, source, opts, ctl) } +/// The patch radius of the fill for the option set #14191 measured (Default colour adaptation, +/// no rotation, no scale, no mirror). The straight features of its document are 10 px bands and +/// 20 px stripes: the default 7x7 patch fits inside one stripe or inside one band gap, so it +/// carries no phase information and the completion decides from colour alone and runs one region +/// into the other. An 11x11 patch covers a feature and the one next to it, which is what keeps +/// their phase through the hole. Every other option set is marked "not measured" in #14191 and +/// keeps [`CompleteParams`]' default radius. +const MEASURED_STRUCTURE_PATCH_RADIUS: usize = 5; + +/// Whether `opts` holds the option set #14191 measured on its test document: Default colour +/// adaptation, no rotation, no scale and no mirror. +fn structure_measured(opts: &FillOptions) -> bool { + opts.color_adaptation == color_level("default") && opts.rotations.is_empty() && !opts.scale && !opts.mirror +} + #[allow(clippy::too_many_arguments)] fn fill_cow( w: usize, @@ -261,7 +276,10 @@ fn fill_cow( if !hole.iter().any(|h| *h) { return Ok(img.into_owned()); } - let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + let mut params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + if structure_measured(opts) { + params.patch_radius = MEASURED_STRUCTURE_PATCH_RADIUS; + } let gap = 2 * params.patch_radius + 2; let ok: Vec = par::map(w * h, true, |i| !hole[i] && source[i]); let src = Src { w, h, ch, img: &img, ok: &ok }; @@ -722,5 +740,7 @@ pub fn default_brush_size(hole: Rect) -> f64 { (0.4 * (w * h).sqrt()).round() } +#[cfg(test)] +mod structure_continue_tests; #[cfg(test)] mod tests; diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs new file mode 100644 index 0000000000..7c9b50becc --- /dev/null +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -0,0 +1,278 @@ +//! #14191: the fill continues straight bands and stripes through the hole. +//! +//! The measured document (both the reference application and PhotoCraft main f143ce5849): +//! 600 x 400, RGB, 8 bit, one Background layer. Top half blue 60,120,200 with a light 120,170,230 +//! band 10 px high every 40 px (at y 0, 40, 80, 120, 160); bottom half vertical stripes 20 px wide, +//! 40,140,60 at x = 0 mod 40 and 80,180,90 at x = 20 mod 40; a red 220,30,30 square from 260,160 to +//! 340,240; selection 250,150 to 350,250 (the square plus 10 px). The sampling window is 100,0 to +//! 500,400, which is what [`sampling_window`] gives for that selection, and Auto covers the same +//! area as Rectangular on this document. +//! +//! The reference application keeps the bands and the stripes in their original phase through the +//! hole and keeps the blue / green boundary at y 200. PhotoCraft main runs the blue half down into +//! the green one: 300,165 -> 64,124,201 instead of the light band 120,170,230, and 300,205 -> +//! 65,127,205, 285,220 -> 64,127,205, 300,240 -> 62,124,202 instead of the green stripes. + +use super::*; + +const DOC_W: usize = 600; +const DOC_H: usize = 400; +/// The measured selection: the red square plus 10 px. +const SEL: (i32, i32, i32, i32) = (250, 150, 350, 250); +/// The red square inside it. +const SQUARE: (usize, usize, usize, usize) = (260, 160, 340, 240); + +/// The document's colours without the square, in levels of 255: what the reference application +/// shows through the hole again. +fn background_levels(x: usize, y: usize) -> [i32; 3] { + if y < 200 { + if y % 40 < 10 { [120, 170, 230] } else { [60, 120, 200] } + } else if x % 40 < 20 { + [40, 140, 60] + } else { + [80, 180, 90] + } +} + +/// The measured document as interleaved normalised floats (`ch = 3`). +fn document() -> Vec { + let at = |x: usize, y: usize| -> [f32; 3] { + let v = if (SQUARE.0..SQUARE.2).contains(&x) && (SQUARE.1..SQUARE.3).contains(&y) { [220, 30, 30] } else { background_levels(x, y) }; + [v[0] as f32 / 255.0, v[1] as f32 / 255.0, v[2] as f32 / 255.0] + }; + (0..DOC_H).flat_map(|y| (0..DOC_W).flat_map(move |x| at(x, y))).collect() +} + +/// The sampling window of the measured selection on the measured canvas. +fn window() -> Rect { + sampling_window(Rect::new(SEL.0, SEL.1, SEL.2, SEL.3), Rect::new(0, 0, DOC_W as i32, DOC_H as i32)) +} + +/// The measured window's buffer and its hole: `edit.contentAwareFill` fills the sampling window, +/// with the selection as the hole and (for Auto) the area `auto_sampling` keeps within it. +fn window_buffers() -> (Vec, Vec, usize) { + let doc = document(); + let win = window(); + let (ww, wh) = (win.width() as usize, win.height() as usize); + let mut img = vec![0.0f32; ww * wh * 3]; + let mut hole = vec![false; ww * wh]; + for y in 0..wh { + let dy = (win.y0 + y as i32) as usize; + let s = (dy * DOC_W + win.x0 as usize) * 3; + img[y * ww * 3..(y + 1) * ww * 3].copy_from_slice(&doc[s..s + ww * 3]); + for x in 0..ww { + hole[y * ww + x] = (SEL.0..SEL.2).contains(&(win.x0 + x as i32)) && (SEL.1..SEL.3).contains(&(win.y0 + y as i32)); + } + } + (img, hole, ww) +} + +/// Fill the measured document the way the command does with `opts` and Auto or Rectangular +/// sampling, and return the filled window. +fn fill_measured_document(sampling: &str, opts: &FillOptions) -> Vec { + let (img, hole, ww) = window_buffers(); + let source = match sampling { + "auto" => auto_sampling(ww, 400, 3, &img, &hole), + _ => hole.iter().map(|h| !h).collect(), + }; + fill(ww, 400, 3, &img, &hole, &source, opts) +} + +/// The filled colour at document coordinates `(x, y)`, in levels of 255. +fn filled_at(win: &[f32], x: usize, y: usize) -> [i32; 3] { + let w = window().width() as usize; + let i = ((y - window().y0 as usize) * w + (x - window().x0 as usize)) * 3; + [0, 1, 2].map(|c| (win[i + c] * 255.0).round() as i32) +} + +/// The nine pixel samples of #14191, measured in the reference application (document coordinates +/// and the reference colour in levels of 255), in the order the issue lists them. +const SAMPLES: [((usize, usize), [i32; 3]); 9] = [ + ((300, 165), [120, 170, 230]), + ((300, 180), [60, 120, 200]), + ((300, 195), [60, 120, 200]), + ((300, 205), [80, 180, 90]), + ((285, 220), [40, 140, 60]), + ((265, 220), [77, 177, 88]), + ((300, 240), [80, 180, 90]), + ((255, 155), [60, 120, 200]), + ((345, 245), [80, 180, 90]), +]; + +/// The measured samples that are more than 12 levels per channel from the reference value. +fn samples_off(out: &[f32]) -> Vec { + SAMPLES + .iter() + .filter_map(|((x, y), want)| { + let got = filled_at(out, *x, *y); + let off = (0..3).map(|c| (got[c] - want[c]).abs()).max().unwrap_or(0); + (off > 12).then(|| format!("({x},{y}) -> {got:?}, reference {want:?}, off by {off}")) + }) + .collect() +} + +/// How far the fill is from the document's own background, over the whole hole: (worst deviation +/// in levels, number of pixels within 12, number of pixels counted). Every pixel of the hole +/// carries the colour the document has at that place, which is what "the bands and stripes run +/// through the hole with their original phase" means. +fn phase_through_the_hole(out: &[f32]) -> (i32, usize, usize) { + let (mut worst, mut within, mut n) = (0, 0, 0); + for y in 150..250 { + for x in 250..350 { + let want = background_levels(x, y); + let got = filled_at(out, x, y); + let off = (0..3).map(|c| (got[c] - want[c]).abs()).max().unwrap_or(0); + worst = worst.max(off); + within += usize::from(off <= 12); + n += 1; + } + } + (worst, within, n) +} + +/// The blue / light half and the green half of the document, by the palette colour a filled pixel +/// took: the boundary between them. +const PALETTE: [(&str, [i32; 3]); 5] = + [("blue", [60, 120, 200]), ("light", [120, 170, 230]), ("green-a", [40, 140, 60]), ("green-b", [80, 180, 90]), ("red", [220, 30, 30])]; + +fn palette_name(v: [i32; 3]) -> &'static str { + PALETTE.iter().min_by_key(|(_, c)| c.iter().zip(v).map(|(a, b): (&i32, i32)| (a - b) * (a - b)).sum::()).map(|(n, _)| *n).unwrap_or("?") +} + +fn cold(name: &str) -> bool { + name == "blue" || name == "light" +} + +fn green(name: &str) -> bool { + name == "green-a" || name == "green-b" +} + +/// Over the inside of the hole: how many pixels above y 200 took a colour of the green half, and +/// how many below it took a colour of the blue half. Rows within 3 px of the boundary are left +/// out: there the seams between copied pieces blend. +fn boundary_mismatches(out: &[f32]) -> (usize, usize) { + let (mut green_above, mut cold_below) = (0, 0); + for y in 153..248 { + if (197..204).contains(&y) { + continue; + } + for x in 253..348 { + let n = palette_name(filled_at(out, x, y)); + if y < 200 && green(n) { + green_above += 1; + } + if y > 200 && cold(n) { + cold_below += 1; + } + } + } + (green_above, cold_below) +} + +#[test] +fn auto_fill_continues_the_bands_and_stripes_at_the_measured_samples() { + assert_eq!(window(), Rect::new(100, 0, 500, 400), "the sampling window #14191 measured"); + let out = fill_measured_document("auto", &FillOptions::default()); + let off = samples_off(&out); + assert!(off.is_empty(), "Auto sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); +} + +#[test] +fn rectangular_fill_continues_the_bands_and_stripes_at_the_measured_samples() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let off = samples_off(&out); + assert!(off.is_empty(), "Rectangular sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); +} + +#[test] +fn auto_fill_keeps_the_blue_green_boundary_at_y_200() { + let out = fill_measured_document("auto", &FillOptions::default()); + let (green_above, cold_below) = boundary_mismatches(&out); + assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); + assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); +} + +#[test] +fn rectangular_fill_keeps_the_blue_green_boundary_at_y_200() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let (green_above, cold_below) = boundary_mismatches(&out); + assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); + assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); +} + +#[test] +fn auto_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { + let out = fill_measured_document("auto", &FillOptions::default()); + let (worst, within, n) = phase_through_the_hole(&out); + assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); +} + +#[test] +fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let (worst, within, n) = phase_through_the_hole(&out); + assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); +} + +/// The option sets #14191 marks *not measured* on this document keep today's fill: these are the +/// nine samples as main f143ce5849 (and as this branch without the change) gives them. Guard +/// tests: they pass before and after the change and pin it, so widening the new patch radius later +/// has to say what these settings now do. +fn unmeasured_colour_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27])> { + let at = |level: &str| FillOptions { color_adaptation: color_level(level), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }; + vec![ + ("None", at("none"), [60, 120, 200, 60, 120, 200, 60, 120, 200, 60, 120, 200, 60, 120, 200, 80, 180, 90, 60, 120, 200, 60, 120, 200, 80, 180, 90]), + ("High", at("high"), [65, 122, 191, 65, 119, 186, 64, 117, 183, 48, 132, 70, 77, 162, 98, 70, 163, 91, 47, 129, 76, 60, 120, 198, 80, 180, 90]), + ( + "Very High", + at("veryHigh"), + [63, 121, 192, 64, 119, 187, 64, 117, 182, 80, 155, 103, 78, 152, 112, 65, 152, 94, 73, 146, 122, 60, 120, 199, 80, 180, 90], + ), + ] +} + +fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27])> { + let base = || FillOptions { color_adaptation: color_level("default"), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }; + vec![ + ( + "rotation Low", + FillOptions { rotations: rotation_level("low"), ..base() }, + [61, 118, 192, 62, 119, 192, 62, 119, 198, 61, 119, 203, 60, 119, 206, 77, 172, 95, 60, 119, 208, 60, 120, 198, 80, 180, 90], + ), + ( + "rotation Full", + FillOptions { rotations: rotation_level("full"), ..base() }, + [65, 124, 200, 65, 123, 199, 64, 122, 199, 82, 184, 92, 63, 122, 192, 63, 122, 193, 61, 121, 194, 60, 120, 199, 80, 180, 90], + ), + ( + "Scale on", + FillOptions { scale: true, ..base() }, + [115, 163, 219, 58, 117, 190, 59, 118, 190, 77, 172, 88, 63, 126, 206, 76, 172, 94, 62, 124, 203, 60, 119, 197, 80, 179, 90], + ), + ( + "Mirror on", + FillOptions { mirror: true, ..base() }, + [64, 122, 198, 63, 121, 196, 62, 119, 194, 43, 137, 62, 62, 124, 202, 75, 172, 92, 61, 123, 201, 60, 120, 199, 80, 180, 90], + ), + ] +} + +fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) { + let out = fill_measured_document("auto", opts); + let got: Vec = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect(); + assert_eq!(got.as_slice(), &want[..], "{what}: the nine samples changed, although #14191 marks that case not measured"); +} + +#[test] +fn unmeasured_colour_adaptation_keeps_todays_fill() { + for (what, opts, want) in unmeasured_colour_adaptation() { + check_unmeasured(what, &opts, &want); + } +} + +#[test] +fn unmeasured_geometric_adaptation_keeps_todays_fill() { + for (what, opts, want) in unmeasured_geometric_adaptation() { + check_unmeasured(what, &opts, &want); + } +} From b84eb0fc744c88e8546aa353b95294118af539ad Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Mon, 16 Nov 2026 08:08:38 +0000 Subject: [PATCH 180/385] Layer Style: Satin's Invert flips the result after the contour (#14981) satin_map inverted the coverage before the contour LUT, so a curved contour with Invert on was not the opposite of the same Satin without Invert. Invert now applies after the contour on the CPU, and the GPU satin stage uses fs_mfinish's existing after-contour mode. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- crates/compose/src/effects.rs | 2 + crates/compose/src/effects/bevel.rs | 5 +- .../src/effects/satin_invert_contour_tests.rs | 80 +++++++++++++++++++ crates/gpu/src/fx.rs | 3 +- 4 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 crates/compose/src/effects/satin_invert_contour_tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 077fae98b2..f4e3590c39 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -249,5 +249,7 @@ impl FxMaps { #[cfg(test)] mod tests; +#[cfg(test)] +mod satin_invert_contour_tests; #[cfg(test)] mod satin_size_one_tests; diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs index 266c3f7613..42bd98de01 100644 --- a/crates/compose/src/effects/bevel.rs +++ b/crates/compose/src/effects/bevel.rs @@ -277,11 +277,12 @@ pub(super) fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map tent(&mut a, s.size); tent(&mut b, s.size); } - let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; + let m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; + let mut m = apply_lut(m, satin_lut(&s.contour)); if s.invert { + // #14981: Photoshop inverts after the contour, so Invert is the exact opposite of the same Satin without it. m = m.map(|v| 1.0 - v); } - let mut m = apply_lut(m, satin_lut(&s.contour)); for (v, a) in m.v.iter_mut().zip(&shape.v) { *v *= a; } diff --git a/crates/compose/src/effects/satin_invert_contour_tests.rs b/crates/compose/src/effects/satin_invert_contour_tests.rs new file mode 100644 index 0000000000..82094f17b8 --- /dev/null +++ b/crates/compose/src/effects/satin_invert_contour_tests.rs @@ -0,0 +1,80 @@ +use super::{Contour, Map, satin_map}; +use photocraft_color::{BlendMode, Color}; +use photocraft_doc::adjust::CurvePoint; +use photocraft_doc::{FxCommon, Satin}; + +/// The built-in Gaussian contour (input, output, smooth). +const GAUSSIAN: [(f32, f32, bool); 11] = [ + (0.0, 0.0, false), + (0.117, 0.023, true), + (0.172, 0.055, true), + (0.234, 0.117, true), + (0.305, 0.234, true), + (0.383, 0.414, true), + (0.523, 0.688, true), + (0.617, 0.812, true), + (0.703, 0.891, true), + (0.805, 0.953, true), + (1.0, 1.0, false), +]; + +fn gaussian() -> Contour { + Contour::Custom { + name: "Gaussian".into(), + points: GAUSSIAN.iter().map(|&(input, output, _)| CurvePoint { input, output }).collect(), + corners: GAUSSIAN.iter().map(|p| p.2).collect(), + } +} + +/// #14981: black Satin (Angle 90, Distance 20, Size 10) over an orange rectangle, G channel down +/// its centre column x 200 from y 75 (128 = no satin, 0 = full black). +fn green_column(contour: Contour, invert: bool) -> Vec { + let mut shape = Map::new(400, 300, 0.0); + for row in shape.v.as_chunks_mut::<400>().0.iter_mut().skip(75).take(150) { + row[100..300].fill(1.0); + } + let satin = Satin { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: Color::BLACK, + angle: 90.0, + distance: 20.0, + size: 10.0, + contour, + anti_alias: false, + invert, + }; + let coverage = satin_map(&shape, &satin); + (75..225).map(|y| (128.0 * (1.0 - coverage.get(200, y))).round() as u8).collect() +} + +/// `edge` from y 75 inwards, the middle value up to the mirrored edge. +fn mirrored(edge: &[u8], middle: u8) -> Vec { + let mut column = edge.to_vec(); + column.resize(150 - edge.len(), middle); + column.extend(edge.iter().rev()); + column +} + +fn assert_close(actual: &[u8], expected: &[u8], tolerance: u8, case: &str) { + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert!(a.abs_diff(*e) <= tolerance, "{case}, y {}: expected G {e}, got {a}", i + 75); + } +} + +#[test] +fn inverted_gaussian_satin_is_the_opposite_of_the_plain_one() { + let mut edge = vec![128; 13]; + edge.extend([127, 126, 123, 116, 103, 82, 58, 35, 21, 13, 8, 5, 3, 2, 1, 1]); + let inverted = green_column(gaussian(), true); + assert_close(&inverted, &mirrored(&edge, 0), 3, "Gaussian, Invert on"); + let plain = green_column(gaussian(), false); + let opposite: Vec = plain.iter().map(|g| 128 - g).collect(); + assert_close(&inverted, &opposite, 1, "Gaussian, Invert on vs 128 - Invert off"); +} + +#[test] +fn inverted_linear_satin_keeps_its_profile() { + let mut edge = vec![128; 11]; + edge.extend([127, 124, 120, 115, 109, 101, 92, 82, 71, 58, 46, 36, 27, 20, 13, 8, 4, 2]); + assert_close(&green_column(Contour::Linear, true), &mirrored(&edge, 0), 2, "Linear, Invert on"); +} diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 4f265a3202..2e949a42e1 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -255,9 +255,10 @@ impl B { self.stages.push(s); } + /// `invert` flips the coverage after the contour (`fs_mfinish` mode 2), as the CPU's `satin_map` (#14981). fn finish_lut(&mut self, a: In, b: Option, invert: bool, lut: Option>, times_shape: bool, out: usize) { let flag = |v: bool| f32::from(u8::from(v)); - let mut s = stage(Kernel::MFinish, Some(a), b, [flag(b.is_some()), flag(invert), flag(lut.is_some()), flag(times_shape)], 0); + let mut s = stage(Kernel::MFinish, Some(a), b, [flag(b.is_some()), 2.0 * flag(invert), flag(lut.is_some()), flag(times_shape)], 0); s.lut = lut.map(Arc::new); if times_shape { s.s = Some(In::Shape); From fe4b5f968c12bd2f6a7f3ae331771b699b6d3ee9 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:00:08 +0300 Subject: [PATCH 181/385] lens correction batch: close the open sources the run corrected Photoshop closes a listed source that is open when the run starts. A document with unsaved changes, a source that failed, a document a background job is editing and Folder mode keep their documents open. --- crates/engine/src/cmd/lens_cmds.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/engine/src/cmd/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs index 8ce6d4c689..0ec8ecb650 100644 --- a/crates/engine/src/cmd/lens_cmds.rs +++ b/crates/engine/src/cmd/lens_cmds.rs @@ -445,6 +445,24 @@ fn lens_batch(s: &mut Session, p: &Value) -> Result { scratch.execute(LENS, params.clone())?; Ok(()) }); + // Photoshop closes a listed source that is open in the app, as file.close does (#13991). + // Unsaved changes, failed sources and Folder mode were not measured, so those documents stay + // open; so does one a background job is editing, which closing would cancel. + if p.get("input").or_else(|| p.get("files")).is_some_and(Value::is_array) { + let failed: Vec<&str> = r["errors"].as_array().into_iter().flatten().filter_map(|e| e["file"].as_str()).collect(); + let corrected: Vec<&String> = inputs.iter().filter(|input| !failed.contains(&input.as_str())).collect(); + let sources: Vec = s + .documents() + .iter() + .enumerate() + .filter(|(_, d)| !d.is_dirty() && s.job_on(d.doc.id).is_none()) + .filter(|(_, d)| d.path.as_deref().is_some_and(|path| corrected.iter().any(|input| crate::file_cmds::same_file(input, path)))) + .map(|(i, _)| i) + .collect(); + for i in sources.into_iter().rev() { + s.close(i); + } + } Ok(r) } From 2d5a5e6271e64c34db6416962788174ccfdf8200 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:00:08 +0300 Subject: [PATCH 182/385] lens correction batch: test closing open sources --- .../engine/src/cmd/lens_batch_close_tests.rs | 184 ++++++++++++++++++ crates/engine/src/cmd/lens_cmds.rs | 4 + 2 files changed, 188 insertions(+) create mode 100644 crates/engine/src/cmd/lens_batch_close_tests.rs diff --git a/crates/engine/src/cmd/lens_batch_close_tests.rs b/crates/engine/src/cmd/lens_batch_close_tests.rs new file mode 100644 index 0000000000..6cc4465389 --- /dev/null +++ b/crates/engine/src/cmd/lens_batch_close_tests.rs @@ -0,0 +1,184 @@ +//! File › Automate › Lens Correction closes a listed source that is open in the app (#13991). + +use super::*; + +type Res = std::result::Result>; + +/// A fresh folder holding `a.png`, `b.png` and `c.png` (40 x 30, flat), and the output folder. +fn fixture(name: &str) -> Res<(std::path::PathBuf, [String; 3], String)> { + let dir = std::env::temp_dir().join(format!("pc-lens-close-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir)?; + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "#808080"}))?; + let files = ["a.png", "b.png", "c.png"].map(|f| dir.join(f).to_string_lossy().into_owned()); + let doc = &s.active().ok_or("no document")?.doc; + for path in &files { + crate::file_cmds::save_doc(doc, path, None)?; + } + let output = dir.join("out").to_string_lossy().into_owned(); + Ok((dir, files, output)) +} + +fn open(s: &mut Session, path: &str) -> Res<()> { + s.execute("file.openAs", json!({"path": path}))?; + Ok(()) +} + +/// An Untitled document with a second layer, the document the run must leave alone. +fn untitled(s: &mut Session) -> Res { + s.execute("file.new", json!({"width": 20, "height": 20}))?; + s.execute("layer.new.layer", json!({"name": "kept"}))?; + Ok(s.active_index().ok_or("no active document")?) +} + +fn run(s: &mut Session, input: Value, output: &str) -> Res { + let r = s.execute(LENS_BATCH, json!({"input": input, "output": output}))?; + assert!(r["errors"].as_array().is_some_and(Vec::is_empty), "{r}"); + Ok(r) +} + +fn paths(s: &Session) -> Vec> { + s.documents().iter().map(|d| d.path.clone()).collect() +} + +#[test] +fn an_open_unmodified_source_is_closed_and_the_other_documents_stay() { + let (dir, [a, b, _], out) = fixture("open").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + let kept = untitled(&mut s).unwrap(); + assert!(!s.documents()[0].is_dirty(), "the opened source is saved and unmodified"); + let steps = s.active().unwrap().history.entries().len(); + + let r = run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + assert_eq!(paths(&s), [None], "only the Untitled document is left open"); + assert_eq!(s.active_index(), Some(kept - 1), "the Untitled document is still the active one"); + let d = s.active().unwrap(); + assert_eq!(d.doc.layers.len(), 2, "its layers are untouched"); + assert_eq!(d.history.entries().len(), steps, "its history is untouched"); + assert!(d.is_dirty(), "it keeps its unsaved state"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_open_source_that_is_the_active_document_is_closed() { + let (dir, [a, b, _], out) = fixture("active").unwrap(); + let mut s = Session::new(); + untitled(&mut s).unwrap(); + open(&mut s, &b).unwrap(); + + run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(paths(&s), [None]); + assert_eq!(s.active_index(), Some(0)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn two_open_sources_are_both_closed_and_the_active_untitled_document_stays_active() { + let (dir, [a, b, _], out) = fixture("both").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + let kept = untitled(&mut s).unwrap(); + open(&mut s, &b).unwrap(); + s.set_active(kept); + + run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(paths(&s), [None]); + assert_eq!(s.active_index(), Some(0), "the Untitled document is still the active one"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_source_listed_under_another_spelling_of_its_path_is_closed() { + let (dir, [a, b, _], out) = fixture("alias").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + // `..` (unlike `.`) is not dropped when paths are compared, so only the file on disk matches. + std::fs::create_dir(dir.join("sub")).unwrap(); + let alias = dir.join("sub").join("..").join("a.png").to_string_lossy().into_owned(); + assert_ne!(std::path::Path::new(&alias), std::path::Path::new(&a)); + + run(&mut s, json!([alias, b]), &out).unwrap(); + + assert!(s.documents().is_empty(), "{:?}", paths(&s)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_open_saved_document_that_is_not_a_source_stays_open() { + let (dir, [a, b, c], out) = fixture("other").unwrap(); + let mut s = Session::new(); + open(&mut s, &c).unwrap(); + + run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(paths(&s), [Some(c.clone())]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_open_source_with_unsaved_changes_stays_open() { + let (dir, [a, b, _], out) = fixture("dirty").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + s.execute("layer.new.layer", json!({"name": "unsaved"})).unwrap(); + let revision = s.active().unwrap().revision; + assert!(s.active().unwrap().is_dirty()); + + run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(paths(&s), [Some(a.clone())], "the modified source is not closed"); + let d = s.active().unwrap(); + assert!(d.is_dirty() && d.revision == revision, "its changes are kept, not discarded"); + assert_eq!(d.doc.layers.len(), 2); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Not measured: the document may be the only copy left once its file is gone. +#[test] +fn an_open_source_whose_correction_fails_stays_open() { + let (dir, [a, b, _], out) = fixture("failed").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + std::fs::remove_file(&a).unwrap(); + + let r = s.execute(LENS_BATCH, json!({"input": [a, b], "output": out})).unwrap(); + + let errors = r["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1, "{r}"); + assert_eq!(errors[0]["file"], json!(a), "{r}"); + assert_eq!(paths(&s), [Some(a.clone())], "the failed source is not closed"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn sources_that_are_not_open_leave_nothing_open() { + let (dir, [a, b, _], out) = fixture("closed").unwrap(); + let mut s = Session::new(); + + let r = run(&mut s, json!([a, b]), &out).unwrap(); + + assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + assert!(s.documents().is_empty()); + assert!(std::path::Path::new(&out).join("a.png").is_file() && std::path::Path::new(&out).join("b.png").is_file()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Not measured: Folder mode with a document from that folder open keeps today's behaviour. +#[test] +fn folder_mode_keeps_an_open_source_open() { + let (dir, [a, _, _], out) = fixture("folder").unwrap(); + let mut s = Session::new(); + open(&mut s, &a).unwrap(); + + run(&mut s, json!(dir.to_string_lossy()), &out).unwrap(); + + assert_eq!(paths(&s), [Some(a.clone())]); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs index 0ec8ecb650..52673bcf32 100644 --- a/crates/engine/src/cmd/lens_cmds.rs +++ b/crates/engine/src/cmd/lens_cmds.rs @@ -774,3 +774,7 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "lens_batch_close_tests.rs"] +mod lens_batch_close_tests; From b1caae664d67068107a7f22865b2c0ca25304d63 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:11:33 +0300 Subject: [PATCH 183/385] Artboard from Group: size the board to the group's visible layers Hidden layers, and the layers of a hidden group inside, no longer widen the board; they stay in it, hidden. A group whose layers are all hidden gets the canvas, as an empty group does (#14553). --- crates/engine/src/cmd/artboard_cmds.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 55966ce97a..4f67d916d8 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -370,7 +370,8 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("artboards are made from a top-level layer group".into())); } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas); + // A hidden group keeps today's measure (not measured in the reference). + let rect = if l.visible { shown_children_bounds(l) } else { crate::layer_multi_cmds::layer_bounds(l) }.unwrap_or(canvas); set_artboard(l, Artboard { rect, background, preset }); let shift = fit_canvas(doc); *active = Some(id); @@ -381,6 +382,16 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// [`layer_multi_cmds::layer_bounds`](crate::layer_multi_cmds::layer_bounds) of what shows: a +/// group unions only its visible children, so hidden layers (and a hidden group's children) don't +/// size the board Artboard from Group makes (#14553). +fn shown_children_bounds(l: &Layer) -> Option { + match l.children() { + Some(children) => children.iter().filter(|c| c.visible).filter_map(shown_children_bounds).reduce(|a, b| a.union(&b)), + None => crate::layer_multi_cmds::layer_bounds(l), + } +} + /// The layers' union bounds, or the canvas when they have none: the board Artboard from Layers /// makes when no size is given. fn union_bounds<'a>(layers: impl IntoIterator, canvas: Rect) -> Rect { From 9aae481cda37502c7975e873ba54bec9ca8ad9ed Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:11:33 +0300 Subject: [PATCH 184/385] Test Artboard from Group with hidden layers --- crates/engine/src/cmd/artboard_cmds.rs | 3 + .../from_group_hidden_bounds_tests.rs | 132 ++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 crates/engine/src/cmd/artboard_cmds/from_group_hidden_bounds_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 4f67d916d8..87e951bdb9 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -916,6 +916,9 @@ mod file_names_tests; #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"] +mod from_group_hidden_bounds_tests; +#[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/artboard_cmds/from_group_hidden_bounds_tests.rs b/crates/engine/src/cmd/artboard_cmds/from_group_hidden_bounds_tests.rs new file mode 100644 index 0000000000..3a1e7e34c6 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/from_group_hidden_bounds_tests.rs @@ -0,0 +1,132 @@ +//! Artboard from Group sizes the board to the group's visible layers only (#14553); hidden layers +//! stay inside it, in place and hidden. + +use super::*; +use photocraft_geom::Rect; + +const RED: Rect = Rect { x0: 100, y0: 100, x1: 300, y1: 250 }; +const BLUE: Rect = Rect { x0: 400, y0: 300, x1: 600, y1: 450 }; + +fn square(doc: &Document, name: &str, r: Rect, rgba: [f32; 4]) -> Layer { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, rgba)); + l +} + +/// 800 x 600 with the white Background and "Group 1" holding Blue above Red; with `inner`, Blue +/// sits in its own group "Inner". Returns the session and the ids of Group 1, Red and Blue. +fn session(inner: bool) -> (Session, [LayerId; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let ids = s + .edit("Group 1", |doc, active| { + let red = square(doc, "Red", RED, [1.0, 0.0, 0.0, 1.0]); + let blue = square(doc, "Blue", BLUE, [0.0, 0.0, 1.0, 1.0]); + let ids = (red.id, blue.id); + let top = if inner { Layer::group("Inner", vec![blue]) } else { blue }; + let g = doc.insert_above(None, Layer::group("Group 1", vec![red, top])); + *active = Some(g); + Ok([g, ids.0, ids.1]) + }) + .unwrap(); + (s, ids) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn hide(s: &mut Session, id: LayerId) { + s.execute("layer.hideLayers", json!({"layer": id.0})).unwrap(); +} + +fn from_group(s: &mut Session, g: LayerId) -> Value { + let r = s.execute("layer.new.artboardFromGroup", json!({"layer": g.0})).unwrap(); + assert_eq!(r["rect"], json!(board_xywh(s, g)), "the reply matches the board"); + r["rect"].clone() +} + +fn board_xywh(s: &Session, g: LayerId) -> [i64; 4] { + xywh(doc(s).layer(g).unwrap().artboard().unwrap().rect) +} + +fn names(layers: &[Layer]) -> Vec<&str> { + layers.iter().map(|l| l.name.as_str()).collect() +} + +#[test] +fn both_visible_the_board_covers_both_layers() { + let (mut s, [g, ..]) = session(false); + assert_eq!(from_group(&mut s, g), json!([100, 100, 500, 350])); +} + +#[test] +fn a_hidden_layer_does_not_size_the_board_and_stays_inside_it_hidden() { + let (mut s, [g, red, blue]) = session(false); + hide(&mut s, blue); + assert_eq!(from_group(&mut s, g), json!([100, 100, 200, 150])); + let d = doc(&s); + let board = d.layer(g).unwrap(); + assert_eq!(names(board.children().unwrap()), ["Red", "Blue"], "Blue keeps its place above Red"); + assert_eq!(d.artboard_of(blue), Some(g)); + let b = d.layer(blue).unwrap(); + assert!(!b.visible, "Blue stays hidden"); + assert_eq!(b.surface().unwrap().content_bounds(), BLUE, "Blue's pixels don't move"); + assert!(d.layer(red).unwrap().visible); +} + +#[test] +fn a_hidden_group_inside_hides_its_children_too() { + let (mut s, [g, _, blue]) = session(true); + let inner = doc(&s).layer(g).unwrap().children().unwrap()[1].id; + hide(&mut s, inner); + assert_eq!(from_group(&mut s, g), json!([100, 100, 200, 150])); + let d = doc(&s); + assert!(!d.layer(inner).unwrap().visible && d.layer(blue).unwrap().visible); + assert_eq!(d.artboard_of(blue), Some(g)); + + // A visible group whose only layer is hidden adds nothing either. + let (mut s, [g, _, blue]) = session(true); + hide(&mut s, blue); + assert_eq!(from_group(&mut s, g), json!([100, 100, 200, 150])); +} + +#[test] +fn a_group_with_every_layer_hidden_is_handled_like_an_empty_group() { + let mut empty = Session::new(); + empty.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let e = empty.edit("Group 1", |doc, _| Ok(doc.insert_above(None, Layer::group("Group 1", vec![])))).unwrap(); + let today = from_group(&mut empty, e); + assert_eq!(today, json!([0, 0, 800, 600]), "an empty group gets the canvas"); + + let (mut s, [g, red, blue]) = session(false); + hide(&mut s, red); + hide(&mut s, blue); + assert_eq!(from_group(&mut s, g), today); + assert_eq!(names(doc(&s).layer(g).unwrap().children().unwrap()), ["Red", "Blue"]); +} + +/// Pins today: layer effects don't widen the board (not measured in the reference, #14553). +#[test] +fn layer_effects_keep_todays_rect() { + let (mut s, [g, red, _]) = session(false); + s.edit("Shadow", |doc, _| { + for id in [red, g] { + doc.layer_mut(id).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + } + Ok(()) + }) + .unwrap(); + assert_eq!(from_group(&mut s, g), json!([100, 100, 500, 350])); +} + +/// Pins today: a hidden group as the active layer is measured as before, hidden layers included +/// (not measured in the reference, #14553). +#[test] +fn a_hidden_active_group_keeps_todays_rect() { + let (mut s, [g, _, blue]) = session(false); + hide(&mut s, blue); + hide(&mut s, g); + assert_eq!(from_group(&mut s, g), json!([100, 100, 500, 350])); +} From f85acd7773449fa363fae85c6cee2e0884a5524f Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 10:58:57 +0100 Subject: [PATCH 185/385] Palette PNG indices: a band of rows per step on web, a cancel check between bands, and a fallible row buffer --- crates/io/src/flat.rs | 197 ++++++++++++++++++++------------ crates/io/src/png_steps.rs | 54 +++++++-- crates/io/tests/it/png_steps.rs | 16 +++ 3 files changed, 187 insertions(+), 80 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index e4521f3288..1c74f645e7 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -127,9 +127,9 @@ fn import_flat_impl_with_options( } }; apply_flat_format(&mut r, bytes, format, img.as_ref())?; - // A palette PNG whose entries share a colour is read again there for its indices (#14342), - // a pass that doesn't watch for a cancel: one raised meanwhile still fails the open. - ctl.check().map_err(|_| IoError::Cancelled)?; + if format == Some(Format::Png) { + read_png_indices(&mut r, bytes, ctl)?; + } Ok(r) } @@ -241,7 +241,8 @@ impl FlatBuilder { /// The document, after copying and pruning whatever is left: the one-shot result and the last /// step of a stepped one. Like the one-shot import, it records how many images the file holds - /// when the decoder read only the first, so Save doesn't write over the rest (#5733). + /// when the decoder read only the first, so Save doesn't write over the rest (#5733). A palette + /// PNG's indices are left to [`PngIndices`]. pub(crate) fn finish(mut self, bytes: &[u8], format: Option) -> Result { let copied = self.copy_done(); while !self.copy_done() { @@ -261,82 +262,135 @@ impl FlatBuilder { } } -/// Each pixel's palette index in the palette PNG `bytes`, opened as `doc`, so Color Table can -/// tell entries of one colour apart (#14342). `None`, and Color Table falls back to the nearest -/// entry, when the document's one layer doesn't show each pixel's entry at the file's place for -/// it (an EXIF orientation turned the pixels, which colours alone can't show when entries repeat, -/// or a colour conversion changed them), or when the file is interlaced (not read here). One row -/// at a time, into tiles one band of rows at a time: next to the layer, only the indices -/// themselves (a byte per pixel) and one band are held. `None` too when memory can't hold them: -/// the open's own memory check didn't count them. -fn png_color_indices(bytes: &[u8], doc: &Document) -> Option { - let table = doc.color_table.as_ref()?; - // Only entries that share a colour need the file. When every entry has its own colour, each - // pixel's colour names its entry and Color Table's nearest entry finds it. Reading the file - // again is one pass over all its rows that neither a stepped import (the web build) splits - // up nor a cancel stops, so it is skipped when it can't add anything. - let mut colors = table.colors.clone(); - colors.sort_unstable(); - if !colors.windows(2).any(|w| w[0] == w[1]) { - return None; - } - let [layer] = doc.layers.as_slice() else { return None }; - let surface = layer.surface()?; - let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); - decoder.set_transformations(png::Transformations::IDENTITY); - decoder.set_ignore_text_chunk(true); - let mut reader = decoder.read_info().ok()?; - let info = reader.info(); - let (w, h, bits) = (info.width, info.height, info.bit_depth as usize); - if info.color_type != png::ColorType::Indexed || info.interlaced || !matches!(bits, 1 | 2 | 4 | 8) || (w, h) != (doc.size.width, doc.size.height) { - return None; - } - let width = usize::try_from(w).ok()?; - let rows = usize::try_from(TILE_SIZE).ok()?; - let band_len = width.checked_mul(rows)?; - // The index surface's whole tiles, the band, and the row of the layer read beside it. - let needed = tile_bytes(w, h, 1).saturating_add(u64::from(w).saturating_mul(rows as u64 + 4)); - crate::memory::check_fits(w, h, needed, crate::memory::available()).ok()?; - let mut band = Vec::new(); - band.try_reserve_exact(band_len).ok()?; - let mut map = Surface::new(PixelFormat::GRAY8); - let mut shown = vec![[0u8; 4]; width]; - let (mut y, mut band_y) = (0i32, 0i32); - let height = i32::try_from(h).ok()?; - while let Some(row) = reader.next_row().ok()? { - if y >= height { +/// Each pixel's palette index in the palette PNG `bytes`, opened as `doc`, read again a band of +/// rows per [`PngIndices::step`], so Color Table can tell entries of one colour apart (#14342). +/// No indices, and Color Table falls back to the nearest entry, when the document's one layer +/// doesn't show each pixel's entry at the file's place for it (an EXIF orientation turned the +/// pixels, which colours alone can't show when entries repeat, or a colour conversion changed +/// them), or when the file is interlaced (not read here). One row at a time, into tiles one band +/// of rows at a time: next to the layer, only the indices themselves (a byte per pixel) and one +/// band are held. None either when memory can't hold them: the open's own memory check didn't +/// count them. +pub(crate) struct PngIndices> { + reader: png::Reader>, + table: photocraft_doc::ColorTable, + layer: photocraft_doc::LayerId, + surface: Surface, + map: Surface, + band: Vec, + shown: Vec<[u8; 4]>, + bits: usize, + width: u32, + height: i32, + y: i32, +} + +impl> PngIndices { + /// Starts reading `bytes` for `doc`'s indices; `None` when they can't be recorded, or needn't + /// be. + pub(crate) fn new(bytes: B, doc: &Document) -> Option { + let table = doc.color_table.as_ref()?; + // Only entries that share a colour need the file. When every entry has its own colour, + // each pixel's colour names its entry and Color Table's nearest entry finds it, so the + // pass over all the file's rows is skipped. + let mut colors = table.colors.clone(); + colors.sort_unstable(); + if !colors.windows(2).any(|w| w[0] == w[1]) { return None; } - surface.read_rgba8_into(Rect::from_xywh(0, y, w, 1), &mut shown); - for (x, px) in shown.iter().enumerate() { - let bit = x * bits; - let byte = *row.data().get(bit / 8)?; - let i = (byte >> (8 - bits - bit % 8)) & (0xff >> (8 - bits)); - let entry = table.colors.get(usize::from(i))?; - let ok = if px[3] == 0 { table.transparent == Some(i) } else { px[..3] == entry[..] }; - if !ok { - return None; + let [layer] = doc.layers.as_slice() else { return None }; + let surface = layer.surface()?; + let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); + decoder.set_transformations(png::Transformations::IDENTITY); + decoder.set_ignore_text_chunk(true); + let reader = decoder.read_info().ok()?; + let info = reader.info(); + let (w, h, bits) = (info.width, info.height, info.bit_depth as usize); + if info.color_type != png::ColorType::Indexed || info.interlaced || !matches!(bits, 1 | 2 | 4 | 8) || (w, h) != (doc.size.width, doc.size.height) { + return None; + } + let width = usize::try_from(w).ok()?; + let band_len = width.checked_mul(usize::try_from(TILE_SIZE).ok()?)?; + // The index surface's whole tiles, the band, and the row of the layer read beside it. + let needed = tile_bytes(w, h, 1).saturating_add(u64::from(w).saturating_mul(TILE_SIZE as u64 + 4)); + crate::memory::check_fits(w, h, needed, crate::memory::available()).ok()?; + let mut band = Vec::new(); + band.try_reserve_exact(band_len).ok()?; + let mut shown = Vec::new(); + shown.try_reserve_exact(width).ok()?; + shown.resize(width, [0u8; 4]); + Some(Self { + reader, + table: table.clone(), + layer: layer.id, + surface: surface.clone(), + map: Surface::new(PixelFormat::GRAY8), + band, + shown, + bits, + width: w, + height: i32::try_from(h).ok()?, + y: 0, + }) + } + + /// Reads the next band of rows into the indices: `Some(true)` once every row is read (then + /// [`Self::finish`]), `Some(false)` while rows are left, `None` when no indices can be recorded. + pub(crate) fn step(&mut self) -> Option { + let Self { reader, table, surface, map, band, shown, bits, width, height, y, .. } = self; + let (bits, w, band_y) = (*bits, *width, *y); + while *y < *height && *y - band_y < TILE_SIZE { + let row = reader.next_row().ok()??; + surface.read_rgba8_into(Rect::from_xywh(0, *y, w, 1), shown); + for (x, px) in shown.iter().enumerate() { + let bit = x * bits; + let byte = *row.data().get(bit / 8)?; + let i = (byte >> (8 - bits - bit % 8)) & (0xff >> (8 - bits)); + let entry = table.colors.get(usize::from(i))?; + let ok = if px[3] == 0 { table.transparent == Some(i) } else { px[..3] == entry[..] }; + if !ok { + return None; + } + band.push(i); } - band.push(i); + *y += 1; } - y += 1; - if band.len() >= band_len || y == height { - map.try_write_interleaved(Rect::from_xywh(0, band_y, w, u32::try_from(y - band_y).ok()?), &band).ok()?; - band.clear(); - band_y = y; + map.try_write_interleaved(Rect::from_xywh(0, band_y, w, u32::try_from(*y - band_y).ok()?), band).ok()?; + band.clear(); + Some(*y == *height) + } + + /// The indices, once [`Self::step`] has read every row. + pub(crate) fn finish(mut self) -> Option { + // An eXIf after the pixels counts too. + self.reader.finish().ok()?; + if self.reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || self.y != self.height { + return None; + } + Some(ColorIndices { layer: self.layer, pixels: self.surface, indices: self.map }) + } +} + +/// The indices of a palette PNG opened as `r` (see [`PngIndices`]), read with a cancel check +/// between bands of rows. +fn read_png_indices(r: &mut ImportResult, bytes: &[u8], ctl: &Interrupt) -> Result<(), IoError> { + let Some(mut read) = PngIndices::new(bytes, &r.document) else { return Ok(()) }; + loop { + ctl.check().map_err(|_| IoError::Cancelled)?; + match read.step() { + Some(false) => {} + Some(true) => break, + None => return Ok(()), } } - // An eXIf after the pixels counts too. - reader.finish().ok()?; - if reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || y != height { - return None; - } - Some(ColorIndices { layer: layer.id, pixels: surface.clone(), indices: map }) + r.document.color_indices = read.finish(); + Ok(()) } /// What every flat format does to the document of its pixels: the palette mode, the save /// settings, a Targa's alpha channel and the profile an untagged image needs. `img` is the -/// decoded image, when the document was built from one (a streamed PNG has none). +/// decoded image, when the document was built from one (a streamed PNG has none). A palette +/// PNG's indices are read after it, by [`PngIndices`], which a stepped import can step. pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Option, img: Option<&Image>) -> Result<(), IoError> { // A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in // Photoshop (#3802, #4804, #7886). A GIF is always palette-based: the first frame's table. @@ -351,9 +405,6 @@ pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Opti { r.document.mode = ColorMode::Indexed; r.document.color_table = Some(photocraft_doc::ColorTable { colors, transparent }); - if format == Some(Format::Png) { - r.document.color_indices = png_color_indices(bytes, &r.document); - } } // The decoder's count of frames or pages left out (set above) stays alongside the encoding. let encoding = file_encoding_as(format, bytes); diff --git a/crates/io/src/png_steps.rs b/crates/io/src/png_steps.rs index b5a5f34914..c9c0127246 100644 --- a/crates/io/src/png_steps.rs +++ b/crates/io/src/png_steps.rs @@ -13,7 +13,7 @@ use photocraft_codecs::{self as codecs, DecodeOptions, Format, Limits, OrientSte use photocraft_geom::TILE_SIZE; use photocraft_raster::{Interrupt, PruneCursor}; -use crate::flat::{FlatBuilder, PngStream, apply_flat_format}; +use crate::flat::{FlatBuilder, PngIndices, PngStream, apply_flat_format}; use crate::{ImportResult, IoError, Route}; /// The rows of a file being streamed into the tiles of its layer. @@ -29,6 +29,15 @@ struct Pruning { extras: PngExtras, } +/// A palette PNG's document, its file being read again for the indices of entries that share a +/// colour (#14342). +struct Indexing { + result: ImportResult, + read: PngIndices, + /// Whether the layer was streamed. + streamed: bool, +} + enum Stage { /// The rows becoming tiles as they are decoded. Stream(Box), @@ -40,6 +49,8 @@ enum Stage { Orient(Box), /// The decoded image becoming the document, a band of rows and a batch of tiles at a time. Build(Box), + /// The palette indices, a band of rows at a time. + Indices(Box), Spent, } @@ -85,7 +96,11 @@ impl PngImport { /// image never exists whole. False for a file whose rows can't come in final order, and from /// the moment a late `eXIf` sends a streamed one back to a whole decode. pub fn streams(&self) -> bool { - matches!(self.stage, Stage::Stream(_) | Stage::Prune(_)) + match &self.stage { + Stage::Stream(_) | Stage::Prune(_) => true, + Stage::Indices(i) => i.streamed, + _ => false, + } } /// How much of the import is done, `0.0..=1.0`. @@ -94,13 +109,14 @@ impl PngImport { Stage::Stream(s) => s.rows.progress(), Stage::Rows(rows) => rows.progress(), Stage::Orient(steps) => steps.progress(), - Stage::Prune(_) | Stage::Build(_) | Stage::Spent => 1.0, + Stage::Prune(_) | Stage::Build(_) | Stage::Indices(_) | Stage::Spent => 1.0, } } /// Works while `more()` returns true (at least one bounded piece per call): rows (into tiles - /// as they come, or into the whole image), the turn upright, the copy into tiles, then the - /// prune scan. `Some` once the document is built, after which the import is spent. + /// as they come, or into the whole image), the turn upright, the copy into tiles, the prune + /// scan, then a palette's indices. `Some` once the document is built, after which the import + /// is spent. pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result, IoError> { match std::mem::replace(&mut self.stage, Stage::Spent) { Stage::Stream(mut s) => { @@ -131,7 +147,7 @@ impl PngImport { let Pruning { stream, extras, .. } = *p; let mut r = stream.into_document(&self.name, extras)?; apply_flat_format(&mut r, &self.bytes, Some(Format::Png), None)?; - return Ok(Some(r)); + return self.indices(r, true, more); } if !more() { self.stage = Stage::Prune(p); @@ -175,9 +191,33 @@ impl PngImport { } continue; } - return build.finish(self.bytes.as_slice(), Some(Format::Png)).map(Some); + let r = build.finish(self.bytes.as_slice(), Some(Format::Png))?; + return self.indices(r, false, more); + }, + Stage::Indices(mut i) => loop { + match i.read.step() { + Some(false) if more() => {} + Some(false) => { + self.stage = Stage::Indices(i); + return Ok(None); + } + Some(true) => { + let Indexing { mut result, read, .. } = *i; + result.document.color_indices = read.finish(); + return Ok(Some(result)); + } + None => return Ok(Some(i.result)), + } }, Stage::Spent => Err(IoError::Unsupported("the PNG was already imported".into())), } } + + /// The built document `result`, or, for a palette whose entries share a colour, the stage that + /// reads its indices, entered in this call while `more()` allows. + fn indices(&mut self, result: ImportResult, streamed: bool, more: &mut dyn FnMut() -> bool) -> Result, IoError> { + let Some(read) = PngIndices::new(SharedBytes(Arc::clone(&self.bytes)), &result.document) else { return Ok(Some(result)) }; + self.stage = Stage::Indices(Box::new(Indexing { result, read, streamed })); + if more() { self.step(more) } else { Ok(None) } + } } diff --git a/crates/io/tests/it/png_steps.rs b/crates/io/tests/it/png_steps.rs index f62e3bc57a..cd01899299 100644 --- a/crates/io/tests/it/png_steps.rs +++ b/crates/io/tests/it/png_steps.rs @@ -88,6 +88,22 @@ fn stepped_png_import_keeps_a_palette_as_indexed_colour() { assert_stepped_equals_import("p.png", &bytes, "palette"); } +/// A palette whose entries share a colour is read again for its indices a band of rows per step, +/// and gives the indices the one-shot import gives (#14342). +#[test] +fn a_palette_png_is_read_for_its_indices_a_band_of_rows_per_step() { + let (w, h) = (3, photocraft_geom::TILE_SIZE as u32 * 3 + 5); + let idx: Vec = (0..w * h).map(|i| (i % 2) as u8).collect(); + let shared = photocraft_codecs::encode_png_indexed(w, h, &idx, &[[255; 3], [255; 3]], None, None, None).unwrap(); + let distinct = photocraft_codecs::encode_png_indexed(w, h, &idx, &[[255; 3], [0; 3]], None, None, None).unwrap(); + assert!(whole("p.png", &shared).document.color_indices.is_some(), "the one-shot import records them"); + assert_stepped_equals_import("p.png", &shared, "entries sharing a colour"); + let (_, with) = stepped_zero_budget("p.png", &shared); + let (_, without) = stepped_zero_budget("p.png", &distinct); + // Four bands of rows, each a call of its own with an empty budget. + assert_eq!(with, without + 4); +} + #[test] fn stepped_png_import_takes_a_step_per_row_and_bounded_steps_to_build_the_document() { let bytes = encode(&noise(8, 20, ChannelLayout::Rgba, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap(); From 73dc8e2f82fa2c072c0fcda71d97ffbd215d5a61 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Mon, 16 Nov 2026 14:33:22 +0100 Subject: [PATCH 186/385] test(algo): keep the unmeasured #14191 guards pinned across libms The two guard tests failed on the ubuntu-24.04 gate job (run 43833457124) while they pass bit for bit on Windows: colour adaptation High gives (300,180) 64 instead of 65, rotation Low gives (285,220) 118 instead of 119, every other channel matches. Not a change from main: no commit between f143ce5849, where the samples were captured, and the branch parent eea585958 touches content_aware or inpaint, and the pins also hold here at RAYON_NUM_THREADS 4, 2 and 1. The vote that blends the seams between the copied pieces weights the patches with (-cost / (2 sigma2)).exp() of the host C library (inpaint/solver.rs); two samples sit right on a level boundary and round one level apart between glibc and the Windows runtime. Compare the nine samples of each option set within 2 levels per channel instead of bit for bit, list every sample over that slack in the failure message, and say in the code why. All 27 pinned values stay and the guard intent stays: unmeasured option sets keep today's fill. The pin still bites, because the structure path this PR adds moves these samples by tens of levels, 60 at (300,165) alone. --- .../content_aware/structure_continue_tests.rs | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 7c9b50becc..42ce605c12 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -214,10 +214,25 @@ fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); } +/// Per-channel slack for the unmeasured pins below. The exact values hold bit for bit on Windows +/// (also at RAYON_NUM_THREADS 4, 2 and 1), but not on every C library: the vote that blends the +/// seams between the copied pieces weights the patches with `(-cost / (2 sigma2)).exp()` of the +/// host C library (`inpaint/solver.rs`), and a filled pixel sitting right on a level boundary +/// rounds one level apart between glibc and the Windows runtime. CI run 43833457124 on +/// ubuntu-24.04 showed (300,180) under colour adaptation High at 64 instead of 65, and (285,220) +/// under rotation Low at 118 instead of 119, while all other 52 channels matched exactly. Nothing +/// on main changed these fills: between f143ce5849 and the branch parent eea585958 no commit +/// touches `content_aware` or `inpaint`. 2 levels is still a hard pin against what the guards +/// guard against: if the new patch radius leaked into one of these option sets, its fill would +/// move the way the measured set moves, and at (300,165) alone that is 60 levels (the None pin +/// 60,120,200 against the 120,170,230 the measured fill gives there). +const UNMEASURED_TOLERANCE: i32 = 2; + /// The option sets #14191 marks *not measured* on this document keep today's fill: these are the /// nine samples as main f143ce5849 (and as this branch without the change) gives them. Guard /// tests: they pass before and after the change and pin it, so widening the new patch radius later -/// has to say what these settings now do. +/// has to say what these settings now do. Compared within [`UNMEASURED_TOLERANCE`] levels per +/// channel, see there for why. fn unmeasured_colour_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27])> { let at = |level: &str| FillOptions { color_adaptation: color_level(level), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }; vec![ @@ -260,7 +275,20 @@ fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27 fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) { let out = fill_measured_document("auto", opts); let got: Vec = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect(); - assert_eq!(got.as_slice(), &want[..], "{what}: the nine samples changed, although #14191 marks that case not measured"); + let off: Vec = SAMPLES + .iter() + .enumerate() + .filter_map(|(k, ((x, y), _))| { + let (g, w) = (&got[k * 3..k * 3 + 3], &want[k * 3..k * 3 + 3]); + let dev = (0..3).map(|c| (g[c] - w[c]).abs()).max().unwrap_or(0); + (dev > UNMEASURED_TOLERANCE).then(|| format!("({x},{y}) -> {g:?}, today's fill {w:?}, off by {dev}")) + }) + .collect(); + assert!( + off.is_empty(), + "{what}: the nine samples moved by more than {UNMEASURED_TOLERANCE} levels, although #14191 marks that case not measured\n{}", + off.join("\n") + ); } #[test] From bfa92d405000c31843034c2bd6cf805429843f6f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:29:24 +0100 Subject: [PATCH 187/385] Duplicate Layer: leave Indexed documents out of the destination list (#14612) The Destination > Document list offered every open document, but layer.copyToDocument refuses Indexed Color (and Bitmap, Multichannel, Duotone) destinations, so picking one failed on OK. List only the documents whose mode `layered` accepts, in tab order and keyed by their own index, plus the source itself. `layered` becomes public so the dialog and the command share one rule. --- crates/engine/src/cmd/layer_copy_cmds.rs | 2 +- .../dialogs/duplicate_layer_indexed_tests.rs | 86 +++++++++++++++++++ .../ui-egui/src/dialogs/duplicate_layer_ui.rs | 21 ++++- 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index f8a4f06276..3a94615ce9 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -52,7 +52,7 @@ fn point(p: &Value, key: &str) -> Result> { } /// Modes whose layers convert through the colour engine. -pub(crate) fn layered(mode: ColorMode) -> bool { +pub fn layered(mode: ColorMode) -> bool { matches!(mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab) } diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs new file mode 100644 index 0000000000..2df45587bc --- /dev/null +++ b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs @@ -0,0 +1,86 @@ +//! Duplicate Layer's Destination › Document list leaves out documents a layer can't be copied +//! into, as Photoshop leaves out Indexed Color documents (#14612). The rest keep tab order and +//! their own document index on OK. +use super::destinations; +use crate::PhotocraftApp; +use photocraft_color::ColorMode; +use serde_json::json; + +/// A command id and its params. +type Step = (&'static str, serde_json::Value); + +/// Poster (RGB, active, with an Ink layer), then one document per `(name, mode, steps)`: a new +/// 8-bit document of `mode` with the mode commands in `steps` run on it. +fn app_with(docs: &[(&str, &str, &[Step])]) -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "name": "Poster"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); + for (name, mode, steps) in docs { + s.execute("file.new", json!({"width": 8, "height": 8, "name": name, "mode": mode})).unwrap(); + for (id, params) in *steps { + s.execute(id, params.clone()).unwrap(); + } + } + s.set_active(0); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn indexed() -> Step { + ("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})) +} + +fn keys(app: &PhotocraftApp) -> Vec { + destinations(app).into_iter().map(|(key, _)| key).collect() +} + +#[test] +fn indexed_documents_are_left_out_and_the_other_modes_keep_tab_order() { + let app = app_with(&[ + ("Palette", "rgb", &[indexed()]), + ("Print", "cmyk", &[]), + ("Gray", "grayscale", &[]), + ("Lab", "rgb", &[("image.mode.lab", json!({}))]), + ("Deep", "rgb", &[("image.mode.bits16", json!({}))]), + ]); + let modes: Vec<_> = app.session.documents().iter().map(|d| (d.doc.mode, d.doc.depth.bits())).collect(); + assert_eq!(modes[1].0, ColorMode::Indexed); + assert_eq!(modes[4].0, ColorMode::Lab); + assert_eq!(modes[5], (ColorMode::Rgb, 16)); + let names: Vec<_> = destinations(&app).into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["Poster", "Print", "Gray", "Lab", "Deep"]); + assert_eq!(keys(&app), ["0", "2", "3", "4", "5"], "each entry keeps its document's index"); +} + +#[test] +fn bitmap_and_multichannel_documents_are_left_out_too() { + let app = app_with(&[ + ("Mono", "grayscale", &[("image.mode.bitmap", json!({"method": "threshold"}))]), + ("Plates", "rgb", &[("image.mode.multichannel", json!({}))]), + ("Card", "rgb", &[]), + ]); + assert_eq!(app.session.documents()[1].doc.mode, ColorMode::Bitmap); + assert_eq!(app.session.documents()[2].doc.mode, ColorMode::Multichannel); + assert_eq!(keys(&app), ["0", "3"], "layer.copyToDocument refuses both modes"); +} + +#[test] +fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { + let mut app = app_with(&[("Palette", "rgb", &[indexed()]), ("Card", "rgb", &[])]); + assert_eq!(keys(&app), ["0", "2"]); + let ctx = egui::Context::default(); + let dialog = crate::menus::invoke(&mut app, &ctx, "layer.duplicate", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let palette_layers = app.session.documents()[1].doc.layer_count(); + app.ui.dialog_mut(dialog).unwrap().fields.insert("destination".into(), json!(2)); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + let names: Vec<_> = app.session.documents()[2].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); + assert!(names.contains(&"Ink copy".to_string()), "Card receives the copy: {names:?}"); + assert_eq!(app.session.documents()[1].doc.layer_count(), palette_layers, "the Indexed document is untouched"); + assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "the source is untouched"); +} + +#[test] +fn the_source_stays_listed_whatever_its_mode() { + let mut app = app_with(&[("Palette", "rgb", &[indexed()]), ("Card", "rgb", &[])]); + app.session.set_active(1); + assert_eq!(keys(&app), ["0", "1", "2"], "duplicating within the source is a plain duplicate"); +} diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index 3d9b0edc8f..78fdbaee28 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -36,8 +36,23 @@ pub fn open(app: &mut PhotocraftApp) -> Result { Ok(json!({"dialog": id})) } +/// The Destination › Document entries before New: the open documents in tab order, keyed by +/// their index, without those `layer.copyToDocument` refuses (Indexed Color and the other modes +/// outside `layered`), as Photoshop leaves them out (#14612). The source stays: copying within it +/// is a plain duplicate. +pub(crate) fn destinations(app: &PhotocraftApp) -> Vec<(String, String)> { + let source = app.session.active_index(); + app.session + .documents() + .iter() + .enumerate() + .filter(|(i, d)| Some(*i) == source || photocraft_engine::layer_copy_cmds::layered(d.doc.mode)) + .map(|(i, d)| (i.to_string(), d.doc.name.clone())) + .collect() +} + pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map) { - let documents: Vec<(String, String)> = app.session.documents().iter().enumerate().map(|(i, d)| (i.to_string(), d.doc.name.clone())).collect(); + let documents = destinations(app); let mut options: Vec<(String, &str)> = documents.iter().map(|(k, n)| (k.clone(), n.as_str())).collect(); options.push(("new".to_string(), tl!("New"))); let mut destination = match fields.get("destination") { @@ -198,3 +213,7 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.layer_count(), 4); } } + +#[cfg(test)] +#[path = "duplicate_layer_indexed_tests.rs"] +mod duplicate_layer_indexed_tests; From c8bef7880c47e9ca99e36d60d37c78770e853180 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Mon, 16 Nov 2026 17:53:24 +0100 Subject: [PATCH 188/385] fix(algo): keep the 7x7 patch when the sampling area is not the Rectangular one #14191 measured Rectangular, and Auto where it keeps that same area. Auto where its content-based choice differs from Rectangular is marked not measured and keeps today's radius. fill_cow now takes the 11x11 patch only when the source mask is every pixel outside the hole. --- crates/algo/src/content_aware.rs | 13 ++++-- .../content_aware/structure_continue_tests.rs | 44 +++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 0eb8cbb6c0..51cdfd436e 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -249,8 +249,8 @@ pub fn fill_owned( /// 20 px stripes: the default 7x7 patch fits inside one stripe or inside one band gap, so it /// carries no phase information and the completion decides from colour alone and runs one region /// into the other. An 11x11 patch covers a feature and the one next to it, which is what keeps -/// their phase through the hole. Every other option set is marked "not measured" in #14191 and -/// keeps [`CompleteParams`]' default radius. +/// their phase through the hole. Every other option set, and a sampling area other than the +/// Rectangular one, is marked "not measured" in #14191 and keeps [`CompleteParams`]' default radius. const MEASURED_STRUCTURE_PATCH_RADIUS: usize = 5; /// Whether `opts` holds the option set #14191 measured on its test document: Default colour @@ -259,6 +259,13 @@ fn structure_measured(opts: &FillOptions) -> bool { opts.color_adaptation == color_level("default") && opts.rotations.is_empty() && !opts.scale && !opts.mirror } +/// Whether `source` is the Rectangular sampling area of the buffer: every pixel outside the hole. +/// #14191 measured Rectangular, and Auto where it keeps that same area; Auto where its +/// content-based choice differs (or any other area) is not measured. +fn rectangular_area(hole: &[bool], source: &[bool]) -> bool { + hole.iter().zip(source).all(|(h, s)| *h || *s) +} + #[allow(clippy::too_many_arguments)] fn fill_cow( w: usize, @@ -277,7 +284,7 @@ fn fill_cow( return Ok(img.into_owned()); } let mut params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; - if structure_measured(opts) { + if structure_measured(opts) && rectangular_area(hole, source) { params.patch_radius = MEASURED_STRUCTURE_PATCH_RADIUS; } let gap = 2 * params.patch_radius + 2; diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 42ce605c12..30ff8111ae 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -304,3 +304,47 @@ fn unmeasured_geometric_adaptation_keeps_todays_fill() { check_unmeasured(what, &opts, &want); } } + +#[test] +fn measured_auto_area_is_the_rectangular_one() { + // What the measured Auto and Rectangular fills above rest on: on this document Auto keeps the + // whole window, as in the reference application. + let (img, hole, ww) = window_buffers(); + assert_eq!(auto_sampling(ww, 400, 3, &img, &hole), hole.iter().map(|h| !h).collect::>()); +} + +/// #14191 marks Auto on a document where its content-based choice differs from Rectangular as not +/// measured, so that fill keeps today's 7x7 patch even with the measured options. The document: the +/// measured one with a white column 40 px wide at x 440 to 480 in the window, which Auto leaves +/// out. Today's fill is the completion with [`CompleteParams`]' default radius on the same roles. +#[test] +fn auto_fill_whose_area_differs_from_rectangular_keeps_todays_patch_radius() { + let (mut img, hole, ww) = window_buffers(); + let column = |i: usize| (440..480).contains(&(window().x0 as usize + i % ww)); + for (i, px) in img.chunks_mut(3).enumerate() { + if column(i) { + px.copy_from_slice(&[250.0 / 255.0; 3]); + } + } + let source = auto_sampling(ww, 400, 3, &img, &hole); + let rectangular: Vec = hole.iter().map(|h| !h).collect(); + assert_ne!(source, rectangular, "Auto must choose an area other than the Rectangular one here"); + let opts = FillOptions::default(); + let out = fill(ww, 400, 3, &img, &hole, &source, &opts); + let roles: Vec = (0..ww * 400) + .map(|i| { + if hole[i] { + Px::Hole + } else if source[i] { + Px::Source + } else { + Px::Known + } + }) + .collect(); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "today's radius"); + let today = complete_masked(ww, 400, 3, &img, &roles, ¶ms, &Interrupt::NONE).unwrap().unwrap(); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "{moved} channel values differ from today's radius-3 fill"); +} From 81657abadfa8c310f8c341c6616133cc982d6128 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 23:06:42 -0600 Subject: [PATCH 189/385] Color lookup export: bake the whole visible stack over the canvas, masks included (#13742) --- crates/engine/src/cmd/file_cmds/export.rs | 111 ++++++++++- .../cmd/file_cmds/export_clut_stack_tests.rs | 178 ++++++++++++++++++ 2 files changed, 284 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index b1cdbe0f62..b01e4c7692 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -186,10 +186,103 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocra craft_cms::lutfile::write_cube_export("PhotoCraft", title, n, !matches!(depth, photocraft_color::SampleType::F32), rows) } -/// Backwards-compatible helper for exporting all visible top-level adjustments. +/// Most renders [`bake_cube_stack`] makes: a canvas far smaller than the lattice needs one pass +/// per lattice entry sharing a pixel, and the bake refuses rather than run for minutes. +const MAX_STACK_RENDERS: usize = 1 << 16; + +/// A lattice entry in [`bake_cube_stack`]: its lattice column (`b·n + r`), row (`g`) and the +/// canvas pixel it is laid on. +type LatticeEntry = (usize, usize, (usize, usize)); + +/// The visible layers above the Background that a whole-stack table bakes (#13742). +fn stack_layers(doc: &Document) -> Vec<&Layer> { + let bg = doc.background().map(|l| l.id); + doc.layers.iter().filter(|l| l.visible && Some(l.id) != bg).collect() +} + +/// Bake the document's whole visible stack, as the reference application does (#13742): the +/// lattice image takes the place of the Background's pixels, laid out over the canvas (lattice +/// column `b·n + r`, row `g`, stretched to the canvas size; each entry is read at its block's first +/// pixel), and every visible layer above it is composited over it as the document renders, with +/// opacity, blend mode, masks and clipping. A canvas smaller than the lattice takes several +/// passes. Only the rows holding entries are rendered, so a huge canvas stays cheap. +fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { + const CMD: &str = "file.export.colorLookupTables"; + let n = size; + let (w, h) = (doc.size.width as usize, doc.size.height as usize); + if w == 0 || h == 0 { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: "the canvas is empty".into() }); + } + let cols = n * n; + let at = |c: usize, g: usize| (c * w / cols, g * h / n); + // Entries sharing a canvas pixel go to successive passes. + let mut seen = std::collections::HashMap::new(); + let mut passes: Vec> = Vec::new(); + for g in 0..n { + for c in 0..cols { + let pos = at(c, g); + let k = seen.entry(pos).or_insert(0usize); + if passes.len() <= *k { + passes.push(Vec::new()); + } + passes[*k].push((c, g, pos)); + *k += 1; + } + } + let rows: usize = passes.iter().map(|p| p.iter().map(|e| e.2.1).collect::>().len()).sum(); + if rows > MAX_STACK_RENDERS { + return Err(EngineError::BadParams { + cmd: CMD.into(), + msg: format!("the canvas is too small for a {n}-point table; use fewer grid points or a larger canvas"), + }); + } + let step = 1.0 / (n - 1) as f32; + let colour = |c: usize, g: usize| [(c % n) as f32 * step, g as f32 * step, (c / n) as f32 * step]; + // The lattice and the composite in floating point, whatever the document's depth: the + // reference's tables of 8-bit documents are exact to their 1/32768 steps (mid grey is 0.5). + let depth = photocraft_color::SampleType::F32; + let fmt = photocraft_color::PixelFormat::new(ColorMode::Rgb, depth, true); + let mut out = vec![[0.0f32; 3]; cols * n]; + for pass in &passes { + let mut surf = Surface::new(fmt); + for &(c, g, (x, y)) in pass { + let rgb = colour(c, g); + surf.write_region(Rect::new(x as i32, y as i32, x as i32 + 1, y as i32 + 1), &photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0])); + } + let mut grid = doc.clone(); + grid.selection = None; + grid.depth = depth; + let lattice = Layer::new("Lattice", LayerContent::Raster(surf)); + match grid.layers.iter().position(|l| Some(l.id) == doc.background().map(|b| b.id)) { + Some(i) => grid.layers[i] = lattice, + None => grid.layers.insert(0, lattice), + } + let ys: std::collections::BTreeSet = pass.iter().map(|e| e.2.1).collect(); + for y in ys { + let band = photocraft_compose::render(&grid, Rect::new(0, y as i32, w as i32, y as i32 + 1)); + for &(c, g, (x, _)) in pass.iter().filter(|e| e.2.1 == y) { + let px = band.px[x]; + out[g * cols + c] = [px[0], px[1], px[2]]; + } + } + } + // The shared writer owns CUBE syntax and precision; red changes fastest, then green, then blue. + let rows = (0..n).flat_map(|b| (0..n).flat_map(move |g| (0..n).map(move |r| (b, g, r)))).map(|(b, g, r)| out[g * cols + b * n + r]); + Ok(craft_cms::lutfile::write_cube_export("PhotoCraft", title, n, !matches!(doc.depth, photocraft_color::SampleType::F32), rows)) +} + +/// The table `file.export.colorLookupTables` bakes by default: the whole visible stack of an RGB +/// document (#13742). Other modes, and a canvas too small for the lattice, keep the earlier +/// table of the visible top-level adjustments. pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String { + let size = size.clamp(2, craft_cms::lutfile::MAX_SIZE); + if doc.mode == ColorMode::Rgb + && let Ok(cube) = bake_cube_stack(size, title, doc) + { + return cube; + } let layers: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); - bake_cube_layers(size.clamp(2, craft_cms::lutfile::MAX_SIZE), title, &layers, doc.depth) + bake_cube_layers(size, title, &layers, doc.depth) } /// Export either the whole visible stack (backward-compatible default), the Layers panel's @@ -228,10 +321,15 @@ pub(super) fn color_lookup_tables(s: &mut Session, p: &Value) -> Result { } else { None }; - let layers = lut_layers(&d.doc, explicit.as_deref())?; - let count = layers.len(); let title = p.get("title").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); - let cube = bake_cube_layers(size as usize, &title, &layers, d.doc.depth); + // The default bakes the whole visible stack of an RGB document (#13742); an explicit list or + // the selection, and other modes, keep the adjustment-only table. + let (cube, count) = if explicit.is_none() && d.doc.mode == ColorMode::Rgb { + (bake_cube_stack(size as usize, &title, &d.doc)?, stack_layers(&d.doc).len()) + } else { + let layers = lut_layers(&d.doc, explicit.as_deref())?; + (bake_cube_layers(size as usize, &title, &layers, d.doc.depth), layers.len()) + }; match p.get("path").and_then(Value::as_str) { Some(path) => { write_file(path, cube.as_bytes())?; @@ -252,3 +350,6 @@ pub(super) fn push_unique(v: &mut Vec, x: f64) { #[cfg(test)] #[path = "layers_to_files_prefix_tests.rs"] mod layers_to_files_prefix_tests; +#[cfg(test)] +#[path = "export_clut_stack_tests.rs"] +mod export_clut_stack_tests; diff --git a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs new file mode 100644 index 0000000000..5fd8e277e8 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs @@ -0,0 +1,178 @@ +//! #13742: an exported colour lookup table holds the whole visible stack above the Background, +//! pixel layers and masks included, with the lattice laid out over the canvas in place of the +//! Background's pixels. Values from the issue's measurements, within 1/4096. + +use super::*; +use photocraft_doc::LayerMask; +use serde_json::json; + +const RED: [f32; 4] = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 160.0 / 255.0, 0.0, 1.0]; + +/// The issue's document: 200 x 150 RGB/8, Background red on the left half and white on the +/// right, an Invert adjustment layer on top. Returns the session and the Invert's id. +fn session() -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150})).unwrap(); + { + let st = s.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let surface = doc.layers[0].surface_mut().unwrap(); + let red = photocraft_raster::from_rgba(&surface.format(), RED); + surface.fill_rect(Rect::new(0, 0, 100, 150), &red); + } + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let invert = s.active().unwrap().active_layer.unwrap(); + (s, invert) +} + +fn edit(s: &mut Session, f: impl FnOnce(&mut Document)) { + let st = s.active_mut().unwrap(); + f(std::sync::Arc::make_mut(&mut st.doc)); +} + +/// A filled 200 x 150 green pixel layer at `opacity`. +fn green(doc: &Document, opacity: f32) -> Layer { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Green", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 150), &photocraft_raster::from_rgba(&fmt, GREEN)); + l.opacity = opacity; + l +} + +/// The table's entries, indexed `b·n² + g·n + r`. +fn entries(s: &mut Session) -> Vec<[f32; 3]> { + let r = s.execute("file.export.colorLookupTables", json!({"size": 7})).unwrap(); + parse(r["cube"].as_str().unwrap()) +} + +fn parse(cube: &str) -> Vec<[f32; 3]> { + cube.lines() + .filter(|l| l.chars().next().is_some_and(|c| c.is_ascii_digit())) + .map(|l| { + let v: Vec = l.split(' ').map(|x| x.parse().unwrap()).collect(); + [v[0], v[1], v[2]] + }) + .collect() +} + +fn at(e: &[[f32; 3]], r: usize, g: usize, b: usize) -> [f32; 3] { + e[b * 49 + g * 7 + r] +} + +fn near(got: [f32; 3], want: [f32; 3]) -> bool { + got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.0 / 4096.0) +} + +fn input(r: usize, g: usize, b: usize) -> [f32; 3] { + [r as f32 / 6.0, g as f32 / 6.0, b as f32 / 6.0] +} + +#[test] +fn an_invert_over_the_background_is_the_exact_inverse_whatever_the_backgrounds_pixels() { + let (mut s, _) = session(); + let e = entries(&mut s); + assert_eq!(e.len(), 343); + assert!(near(at(&e, 0, 0, 0), [1.0; 3]) && near(at(&e, 6, 6, 6), [0.0; 3])); + for b in 0..7 { + for g in 0..7 { + for r in 0..7 { + let i = input(r, g, b); + assert!(near(at(&e, r, g, b), i.map(|v| 1.0 - v)), "({r},{g},{b})"); + } + } + } +} + +#[test] +fn a_hidden_invert_gives_the_identity_with_no_error() { + let (mut s, invert) = session(); + edit(&mut s, |d| d.layer_mut(invert).unwrap().visible = false); + // The command itself stays disabled without a visible adjustment layer (its menu rules are + // #13743's); the table it bakes is the identity, not an error. + let doc = s.active().unwrap().doc.clone(); + let e = parse(&bake_cube_stack(7, "t", &doc).unwrap()); + assert!(near(at(&e, 0, 0, 0), [0.0; 3]) && near(at(&e, 3, 3, 3), [0.5; 3]) && near(at(&e, 6, 6, 6), [1.0; 3])); +} + +/// A PSD's 50 % opacity is 128/255. +#[test] +fn pixel_layers_above_and_below_the_invert_count() { + let (mut s, _) = session(); + edit(&mut s, |d| { + let l = green(d, 128.0 / 255.0); + d.layers.push(l); + }); + let e = entries(&mut s); + assert!(near(at(&e, 0, 0, 0), [0.498047, 0.812988, 0.498047]), "{:?}", at(&e, 0, 0, 0)); + assert!(near(at(&e, 6, 6, 6), [0.0, 0.314941, 0.0]), "{:?}", at(&e, 6, 6, 6)); + + let (mut s, _) = session(); + edit(&mut s, |d| { + let l = green(d, 1.0); + d.layers.push(l); + }); + assert!(entries(&mut s).iter().all(|v| near(*v, [0.0, 0.627441, 0.0])), "opaque green on top: a constant"); + + let (mut s, _) = session(); + edit(&mut s, |d| { + let l = green(d, 1.0); + d.layers.insert(1, l); + }); + assert!(entries(&mut s).iter().all(|v| near(*v, [1.0, 0.372559, 1.0])), "opaque green under the Invert: a constant"); +} + +#[test] +fn a_half_masked_invert_inverts_the_entries_laid_on_its_revealed_half() { + let (mut s, invert) = session(); + edit(&mut s, |d| { + let mut mask = LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(0, 0, 100, 150), &[0.0]); + d.layer_mut(invert).unwrap().mask = Some(mask); + }); + let e = entries(&mut s); + let (mut inverted, mut identity) = (0, 0); + for b in 0..7 { + for g in 0..7 { + for r in 0..7 { + let (v, i) = (at(&e, r, g, b), input(r, g, b)); + if near(v, i.map(|x| 1.0 - x)) { + inverted += 1; + } else if near(v, i) { + identity += 1; + } + } + } + } + assert_eq!((inverted, identity), (169, 174), "as measured (the grey centre counts as inverted)"); +} + +#[test] +fn explicit_layers_and_the_selection_keep_the_adjustment_only_table() { + let (mut s, invert) = session(); + edit(&mut s, |d| { + let l = green(d, 1.0); + d.layers.push(l); + }); + let r = s.execute("file.export.colorLookupTables", json!({"size": 3, "layers": [invert.0]})).unwrap(); + assert_eq!(r["layerCount"], 1); + assert!(r["cube"].as_str().unwrap().contains("1.000000 1.000000 1.000000"), "the Invert alone, as before"); + let r = s.execute("file.export.colorLookupTables", json!({"size": 3, "scope": "selected"})); + assert!(r.is_ok() || r.unwrap_err().to_string().contains("adjustment"), "the selection path is unchanged"); +} + +#[test] +fn small_and_large_canvases_never_panic() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let err = s.execute("file.export.colorLookupTables", json!({"size": 129})).unwrap_err(); + assert!(err.to_string().contains("too small"), "{err}"); + let e = entries(&mut s); + assert!(near(at(&e, 2, 4, 5), input(2, 4, 5).map(|v| 1.0 - v)), "a 1 x 1 canvas takes one pass per entry"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 12000, "height": 9000})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let e = entries(&mut s); + assert!(near(at(&e, 0, 0, 0), [1.0; 3]), "only the lattice rows are rendered"); +} From 1a38b92f17d4f2654d163a141f761ea7500be66a Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 03:09:55 -0600 Subject: [PATCH 190/385] Color lookup stack bake: 64-bit lattice positions, work limit counted before allocating passes, bounded lattice tiles --- crates/engine/src/cmd/file_cmds/export.rs | 70 +++++++++++++++++-- .../cmd/file_cmds/export_clut_stack_tests.rs | 55 +++++++++++++++ 2 files changed, 120 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index b01e4c7692..73fadca32a 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -190,10 +190,66 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocra /// per lattice entry sharing a pixel, and the bake refuses rather than run for minutes. const MAX_STACK_RENDERS: usize = 1 << 16; +/// Most 256 × 256 tiles one render's lattice surface may hold (64 MiB as F32 RGBA). +const MAX_LATTICE_TILES: usize = 64; + /// A lattice entry in [`bake_cube_stack`]: its lattice column (`b·n + r`), row (`g`) and the /// canvas pixel it is laid on. type LatticeEntry = (usize, usize, (usize, usize)); +/// The canvas pixel lattice entry (`c`, `g`) is laid on, for an `n`-point table on a `w` × `h` canvas. +/// 64-bit products: `c * w` overflows `usize` on a 32-bit target (wasm32) for a wide canvas and would +/// read the wrong pixel. The quotients are below `w` and `h`, so they fit back. +fn lattice_pos(n: usize, w: usize, h: usize, c: usize, g: usize) -> (usize, usize) { + let cols = (n * n) as u64; + ((c as u64 * w as u64 / cols) as usize, (g as u64 * h as u64 / n as u64) as usize) +} + +/// How many renders a whole-stack bake needs: a pass renders one entry per canvas pixel, so a pixel +/// shared by `k` entries is in `k` passes, and a row is rendered once per pass that reaches it, the +/// most any of its pixels share. Counted from the entries per pixel alone, so a request over the +/// limit costs no pass allocation. +fn stack_render_rows(n: usize, w: usize, h: usize) -> usize { + let mut shared: std::collections::HashMap<(usize, usize), usize> = std::collections::HashMap::new(); + for g in 0..n { + for c in 0..n * n { + *shared.entry(lattice_pos(n, w, h, c, g)).or_insert(0) += 1; + } + } + let mut per_row: std::collections::HashMap = std::collections::HashMap::new(); + for (&(_, y), &k) in &shared { + let m = per_row.entry(y).or_insert(0); + *m = (*m).max(k); + } + per_row.values().sum() +} + +/// A sample written into the lattice surface allocates its whole tile (1 MiB as F32 RGBA), so a pass +/// whose entries lie in many tiles of a huge canvas (35937 samples at 33 points, one tile each, is 35 +/// GiB) is cut into chunks of at most [`MAX_LATTICE_TILES`] tiles, each rendered on its own. Entries +/// are in row order, so a chunk is a run of one row. +fn split_by_tiles(passes: Vec>) -> Vec> { + let tile = photocraft_geom::TILE_SIZE as usize; + let mut chunks: Vec> = Vec::new(); + for pass in passes { + let mut tiles = std::collections::HashSet::new(); + let mut current: Vec = Vec::new(); + for e in pass { + let t = (e.2.0 / tile, e.2.1 / tile); + if !tiles.contains(&t) && tiles.len() >= MAX_LATTICE_TILES { + chunks.push(std::mem::take(&mut current)); + tiles.clear(); + } + tiles.insert(t); + current.push(e); + } + if !current.is_empty() { + chunks.push(current); + } + } + chunks +} + /// The visible layers above the Background that a whole-stack table bakes (#13742). fn stack_layers(doc: &Document) -> Vec<&Layer> { let bg = doc.background().map(|l| l.id); @@ -214,7 +270,13 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { return Err(EngineError::BadParams { cmd: CMD.into(), msg: "the canvas is empty".into() }); } let cols = n * n; - let at = |c: usize, g: usize| (c * w / cols, g * h / n); + let at = |c: usize, g: usize| lattice_pos(n, w, h, c, g); + let too_many = + || EngineError::BadParams { cmd: CMD.into(), msg: format!("the canvas is too small for a {n}-point table; use fewer grid points or a larger canvas") }; + // The work limit is checked from the entries-per-pixel counts, before any pass is allocated. + if stack_render_rows(n, w, h) > MAX_STACK_RENDERS { + return Err(too_many()); + } // Entries sharing a canvas pixel go to successive passes. let mut seen = std::collections::HashMap::new(); let mut passes: Vec> = Vec::new(); @@ -229,12 +291,10 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { *k += 1; } } + let passes = split_by_tiles(passes); let rows: usize = passes.iter().map(|p| p.iter().map(|e| e.2.1).collect::>().len()).sum(); if rows > MAX_STACK_RENDERS { - return Err(EngineError::BadParams { - cmd: CMD.into(), - msg: format!("the canvas is too small for a {n}-point table; use fewer grid points or a larger canvas"), - }); + return Err(too_many()); } let step = 1.0 / (n - 1) as f32; let colour = |c: usize, g: usize| [(c % n) as f32 * step, g as f32 * step, (c / n) as f32 * step]; diff --git a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs index 5fd8e277e8..0c7f4de1bc 100644 --- a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs +++ b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs @@ -176,3 +176,58 @@ fn small_and_large_canvases_never_panic() { let e = entries(&mut s); assert!(near(at(&e, 0, 0, 0), [1.0; 3]), "only the lattice rows are rendered"); } + +/// CodeRabbit on #15045: the column is computed in 64 bits (`c * w` overflows a 32-bit `usize`: with +/// 129 points and a 300000 px canvas the last column's product is 4,992,000,000). +#[test] +fn a_wide_canvas_reads_the_right_column() { + assert_eq!(lattice_pos(129, 300_000, 300_000, 16_640, 128), (299_981, 297_674)); + assert_eq!(lattice_pos(33, 200, 150, 0, 0), (0, 0)); + assert_eq!(lattice_pos(33, 200, 150, 1088, 32), (199, 145)); +} + +/// CodeRabbit on #15045: the work limit comes from counts alone, so a 1 x 1 canvas at 129 points is +/// refused without a pass per entry (2146689 of them) being allocated. +#[test] +fn the_work_limit_is_known_before_any_pass_is_built() { + assert!(stack_render_rows(129, 1, 1) > MAX_STACK_RENDERS, "2146689 entries share one pixel"); + assert_eq!(stack_render_rows(33, 1, 1), 33 * 33 * 33); + assert!(stack_render_rows(33, 12_000, 9_000) <= MAX_STACK_RENDERS); +} + +/// CodeRabbit on #15045: no render's lattice holds more than 64 tiles, however large the canvas (35937 +/// samples in tiles of their own would be 35 GiB), and every entry is still in exactly one chunk. +#[test] +fn a_huge_canvas_is_rendered_in_bounded_chunks() { + let (n, w, h) = (33usize, 300_000usize, 300_000usize); + let mut pass = Vec::new(); + for g in 0..n { + for c in 0..n * n { + pass.push((c, g, lattice_pos(n, w, h, c, g))); + } + } + let total = pass.len(); + let chunks = split_by_tiles(vec![pass]); + assert_eq!(chunks.iter().map(Vec::len).sum::(), total, "no entry lost or repeated"); + let tile = photocraft_geom::TILE_SIZE as usize; + for chunk in &chunks { + let tiles: std::collections::HashSet<_> = chunk.iter().map(|e| (e.2.0 / tile, e.2.1 / tile)).collect(); + assert!(tiles.len() <= MAX_LATTICE_TILES, "{} tiles", tiles.len()); + } + assert!(chunks.len() > 100, "{} chunks", chunks.len()); +} + +/// The bake itself on a canvas that needed 35 GiB of lattice tiles: it finishes and is still the +/// inverse, with only chunked renders. +#[test] +fn a_huge_canvas_still_bakes_the_stack() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200_000, "height": 150_000})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + // The default 33 points: 35937 entries, each in a tile of its own at this size. + let cube = s.execute("file.export.colorLookupTables", json!({"size": 33})).unwrap(); + let e = parse(cube["cube"].as_str().unwrap()); + assert_eq!(e.len(), 33 * 33 * 33); + assert!(near(e[0], [1.0; 3]) && near(e[e.len() - 1], [0.0; 3]), "the inverse at both corners"); + assert!(near(e[33 * 33 * 16 + 33 * 16 + 16], [0.5; 3]), "and the middle"); +} From 991d35d3591e9f15480d8476dcd04bbbb3df2c41 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 04:57:56 -0600 Subject: [PATCH 191/385] Color lookup stack bake: write the lattice with fallible tile allocation --- crates/engine/src/cmd/file_cmds/export.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 73fadca32a..3f0f6ae70b 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -307,7 +307,11 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { let mut surf = Surface::new(fmt); for &(c, g, (x, y)) in pass { let rgb = colour(c, g); - surf.write_region(Rect::new(x as i32, y as i32, x as i32 + 1, y as i32 + 1), &photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0])); + // A tile that cannot be allocated is an error of this export, not an abort. + surf.try_write_region( + Rect::new(x as i32, y as i32, x as i32 + 1, y as i32 + 1), + &photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]), + )?; } let mut grid = doc.clone(); grid.selection = None; From 96d895045092b55c572ff60644493a48b8c2afae Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Mon, 16 Nov 2026 11:23:08 -0600 Subject: [PATCH 192/385] cargo fmt after rebasing #15045 onto main (module order) --- crates/engine/src/cmd/file_cmds/export.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 3f0f6ae70b..685572d459 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -411,9 +411,9 @@ pub(super) fn push_unique(v: &mut Vec, x: f64) { } } -#[cfg(test)] -#[path = "layers_to_files_prefix_tests.rs"] -mod layers_to_files_prefix_tests; #[cfg(test)] #[path = "export_clut_stack_tests.rs"] mod export_clut_stack_tests; +#[cfg(test)] +#[path = "layers_to_files_prefix_tests.rs"] +mod layers_to_files_prefix_tests; From 44d25f7fbb5fab4dd8860b0e286e16ad95eef7dc Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Mon, 16 Nov 2026 12:15:18 -0600 Subject: [PATCH 193/385] Color lookup stack bake: the lattice keeps the Background's locks, bake_cube returns the bake's errors (CodeRabbit review on #15045) --- crates/engine/src/cmd/file_cmds/export.rs | 27 +++++++++++------ .../cmd/file_cmds/export_clut_stack_tests.rs | 29 +++++++++++++++++++ 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 685572d459..4a637cc484 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -318,7 +318,13 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { grid.depth = depth; let lattice = Layer::new("Lattice", LayerContent::Raster(surf)); match grid.layers.iter().position(|l| Some(l.id) == doc.background().map(|b| b.id)) { - Some(i) => grid.layers[i] = lattice, + Some(i) => { + // The lattice takes the Background's place and its identity (locked transparency and position), so a + // deep-knockout layer above it still knocks out to the lattice. + let mut lattice = lattice; + lattice.locks = grid.layers[i].locks; + grid.layers[i] = lattice; + } None => grid.layers.insert(0, lattice), } let ys: std::collections::BTreeSet = pass.iter().map(|e| e.2.1).collect(); @@ -336,17 +342,20 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { } /// The table `file.export.colorLookupTables` bakes by default: the whole visible stack of an RGB -/// document (#13742). Other modes, and a canvas too small for the lattice, keep the earlier -/// table of the visible top-level adjustments. -pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String { +/// document (#13742). Other modes, and a canvas too small for the lattice (the bake's own refusal), +/// keep the earlier table of the visible top-level adjustments; any other error of the stack bake, +/// an allocation failure included, is returned rather than hidden behind that table. +pub fn bake_cube(doc: &Document, size: usize, title: &str) -> Result { let size = size.clamp(2, craft_cms::lutfile::MAX_SIZE); - if doc.mode == ColorMode::Rgb - && let Ok(cube) = bake_cube_stack(size, title, doc) - { - return cube; + if doc.mode == ColorMode::Rgb { + match bake_cube_stack(size, title, doc) { + Ok(cube) => return Ok(cube), + Err(EngineError::BadParams { .. }) => {} + Err(e) => return Err(e), + } } let layers: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); - bake_cube_layers(size, title, &layers, doc.depth) + Ok(bake_cube_layers(size, title, &layers, doc.depth)) } /// Export either the whole visible stack (backward-compatible default), the Layers panel's diff --git a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs index 0c7f4de1bc..91874e5d51 100644 --- a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs +++ b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs @@ -231,3 +231,32 @@ fn a_huge_canvas_still_bakes_the_stack() { assert!(near(e[0], [1.0; 3]) && near(e[e.len() - 1], [0.0; 3]), "the inverse at both corners"); assert!(near(e[33 * 33 * 16 + 33 * 16 + 16], [0.5; 3]), "and the middle"); } + +/// CodeRabbit on #15045: the lattice that replaces the Background keeps its locks, so a deep-knockout layer above it +/// (0 % fill: the knocked-out area shows bare) knocks out to the lattice, not to transparency: the Invert on top still +/// gives the exact inverse of every entry. +#[test] +fn a_deep_knockout_layer_knocks_out_to_the_lattice() { + let (mut s, _) = session(); + edit(&mut s, |d| { + let mut l = green(d, 1.0); + l.advanced.knockout = photocraft_doc::Knockout::Deep; + l.fill_opacity = 0.0; + d.layers.insert(1, l); + }); + let e = entries(&mut s); + for (r, g, b) in [(0, 0, 0), (6, 0, 3), (2, 5, 1), (6, 6, 6)] { + assert!(near(at(&e, r, g, b), input(r, g, b).map(|v| 1.0 - v)), "({r},{g},{b}): {:?}", at(&e, r, g, b)); + } +} + +/// CodeRabbit on #15045: the public helper keeps the earlier adjustment table only for a canvas too small for the +/// lattice (and other modes); it returns a table, not a hidden failure. +#[test] +fn bake_cube_keeps_the_adjustment_table_on_a_canvas_too_small_for_the_lattice() { + let (mut s, _) = session(); + s.execute("image.canvasSize", json!({"width": 2, "height": 2, "anchor": "center"})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let cube = bake_cube(&doc, 33, "t").expect("the earlier table"); + assert!(cube.contains("LUT_3D_SIZE 33")); +} From f09a8b6ae72b63f0113b03b23c0d05f6a5f191bb Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Mon, 16 Nov 2026 14:31:33 -0600 Subject: [PATCH 194/385] Color lookup stack bake: bake_cube falls back only for the canvas-too-small refusal; the test uses a canvas that exceeds the render limit (CodeRabbit review on #15045) --- crates/engine/src/cmd/file_cmds/export.rs | 9 +++++++-- .../engine/src/cmd/file_cmds/export_clut_stack_tests.rs | 9 ++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 4a637cc484..376be5819b 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -186,6 +186,9 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocra craft_cms::lutfile::write_cube_export("PhotoCraft", title, n, !matches!(depth, photocraft_color::SampleType::F32), rows) } +/// How the refusal of a canvas too small for the lattice begins ([`bake_cube`] keeps the adjustment table for it alone). +const CANVAS_TOO_SMALL: &str = "the canvas is too small"; + /// Most renders [`bake_cube_stack`] makes: a canvas far smaller than the lattice needs one pass /// per lattice entry sharing a pixel, and the bake refuses rather than run for minutes. const MAX_STACK_RENDERS: usize = 1 << 16; @@ -272,7 +275,7 @@ fn bake_cube_stack(size: usize, title: &str, doc: &Document) -> Result { let cols = n * n; let at = |c: usize, g: usize| lattice_pos(n, w, h, c, g); let too_many = - || EngineError::BadParams { cmd: CMD.into(), msg: format!("the canvas is too small for a {n}-point table; use fewer grid points or a larger canvas") }; + || EngineError::BadParams { cmd: CMD.into(), msg: format!("{CANVAS_TOO_SMALL} for a {n}-point table; use fewer grid points or a larger canvas") }; // The work limit is checked from the entries-per-pixel counts, before any pass is allocated. if stack_render_rows(n, w, h) > MAX_STACK_RENDERS { return Err(too_many()); @@ -350,7 +353,9 @@ pub fn bake_cube(doc: &Document, size: usize, title: &str) -> Result { if doc.mode == ColorMode::Rgb { match bake_cube_stack(size, title, doc) { Ok(cube) => return Ok(cube), - Err(EngineError::BadParams { .. }) => {} + // Only the work-limit refusal (a canvas too small for the lattice) falls back: an empty canvas, an + // allocation failure and the rest are the caller's. + Err(EngineError::BadParams { msg, .. }) if msg.starts_with(CANVAS_TOO_SMALL) => {} Err(e) => return Err(e), } } diff --git a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs index 91874e5d51..6c9d2b9eb4 100644 --- a/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs +++ b/crates/engine/src/cmd/file_cmds/export_clut_stack_tests.rs @@ -255,8 +255,11 @@ fn a_deep_knockout_layer_knocks_out_to_the_lattice() { #[test] fn bake_cube_keeps_the_adjustment_table_on_a_canvas_too_small_for_the_lattice() { let (mut s, _) = session(); - s.execute("image.canvasSize", json!({"width": 2, "height": 2, "anchor": "center"})).unwrap(); + // 1 x 1 at 41 points needs more renders than the limit: the stack bake refuses, the helper keeps the earlier table. + s.execute("image.canvasSize", json!({"width": 1, "height": 1, "anchor": "center"})).unwrap(); let doc = s.active().unwrap().doc.clone(); - let cube = bake_cube(&doc, 33, "t").expect("the earlier table"); - assert!(cube.contains("LUT_3D_SIZE 33")); + assert!(bake_cube_stack(41, "t", &doc).is_err(), "the stack bake refuses a canvas this small"); + let cube = bake_cube(&doc, 41, "t").expect("the earlier table"); + let adjustments: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); + assert_eq!(cube, bake_cube_layers(41, "t", &adjustments, doc.depth), "the adjustment-only table"); } From b236632e97dfcaac8bd9aa8fcee98047ecaf4ba1 Mon Sep 17 00:00:00 2001 From: Lcoding15 <125505497+Lcoding15@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:22:30 +0000 Subject: [PATCH 195/385] Revert the Image Processor part: the export path gets its own issue and PR (#14263) The pre-merge scope check asks for `processing.rs` and `image_processor_formats_tests.rs` to leave this PR, so that it touches only the files #14263 names under "Where". The Convert to Profile fix for a Bitmap document stays; the Image Processor's own sRGB conversion goes to a change of its own. A revert rather than a rewrite: the work and its test are kept whole in aff1af0d2, so the new PR can take that commit as it stands instead of being retyped from the diff. --- .../file_cmds/image_processor_formats_tests.rs | 17 ----------------- crates/engine/src/cmd/file_cmds/processing.rs | 5 ----- 2 files changed, 22 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs index 9753f91456..134acee8af 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_formats_tests.rs @@ -160,20 +160,3 @@ fn legacy_format_and_resize_parameters_still_work() { let png = reopen(&files[0]).unwrap(); assert_eq!((png.size.width, png.size.height), (20, 10)); } - -/// CodeRabbit on #14826: a Bitmap document still goes out as an sRGB JPEG. Convert to Profile -/// refuses Bitmap now, so the run takes it to RGB first, as the single-format run does. -#[test] -fn a_bitmap_document_is_written_as_an_srgb_jpeg() { - let dir = tempfile::tempdir().unwrap(); - let mut s = Session::new(); - s.execute("file.new", json!({"name": "Line art", "width": 16, "height": 16, "background": "white"})).unwrap(); - s.execute("image.mode.grayscale", json!({})).unwrap(); - s.execute("image.mode.bitmap", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.mode, ColorMode::Bitmap); - let result = s.execute(COMMAND, json!({"source": "current", "output": dir.path(), "jpeg": {"convertToSrgb": true}})).unwrap(); - assert_eq!(result["errors"], json!([]), "{result}"); - let files = paths(&result).unwrap(); - assert_eq!(files, [dir.path().join("Line art.jpg")]); - assert_eq!(reopen(&files[0]).unwrap().mode, ColorMode::Rgb); -} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 384ce764af..5e0d6b2ddb 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -241,11 +241,6 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - fit_image(scratch, fit)?; } if format.srgb { - // Convert to Profile refuses a Bitmap document (#14263): it goes to RGB first, as - // the single-format run does, and is then converted. - if scratch.active().is_some_and(|d| d.doc.mode == ColorMode::Bitmap) { - scratch.execute("image.mode.rgb", json!({}))?; - } scratch.execute("edit.convertToProfile", json!({"profile": "srgb", "flatten": true}))?; } Ok(false) From 7534824bc4c5f5fdd5984d7c4697aa7681a67c5c Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Tue, 17 Nov 2026 00:03:03 +0100 Subject: [PATCH 196/385] fix(ui-egui): a point grabbed outside the graph survives the release CodeRabbit found that the 16-point Curves grab radius reaches further than the 12-point band where a drag removes a point. In the Curves dialog at its default 300-point graph side (276 points of graph, the allocated area reaching 19 points past the left edge), a press 13 points left of the graph edge grabs the interior point at input 2 - 15.2 points away - and the release, with the pointer never having moved, treated that position as off the graph and deleted the point it had just selected, which the editor then committed. The removal band is now at least the host's active grab radius (DRAG_OFF.max(hit_radius)), so the band where a drag deletes a point can never sit inside the band where a press still selects one. A host that keeps today's 9-point radius keeps the 12-point band exactly; the Curves graph now removes a point only once the pointer is more than 16 points past the graph edge, where no press could have selected it in the first place. --- crates/ui-egui/src/widgets/point_curve.rs | 5 +- .../widgets/point_curve_hit_radius_tests.rs | 81 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets/point_curve.rs b/crates/ui-egui/src/widgets/point_curve.rs index 508f07e4a9..c7816f1d1c 100644 --- a/crates/ui-egui/src/widgets/point_curve.rs +++ b/crates/ui-egui/src/widgets/point_curve.rs @@ -167,7 +167,10 @@ pub fn interact_with_hit_radius( && !press && let (Some(PointCurveDrag { index, offset: off, removed }), Some(pos)) = (state.drag, ui.input(|i| i.pointer.interact_pos())) { - let outside = !graph.expand(DRAG_OFF).contains(pos); + // A press grabs a point up to `hit_radius` away, which can be that far outside the graph, + // so the band where a drag removes a point must never sit inside the band where a press + // still selects one: it is at least the host's active grab radius. + let outside = !graph.expand(DRAG_OFF.max(hit_radius)).contains(pos); let g = to_val(pos); let target = [g[0] + off[0], g[1] + off[1]]; match index { diff --git a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs index b474025a9a..db6fef9a68 100644 --- a/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs +++ b/crates/ui-egui/src/widgets/point_curve_hit_radius_tests.rs @@ -53,6 +53,45 @@ fn click(h: &mut Harness<'static, Host>, pos: Pos2) { h.run_steps(2); } +/// Press at `from`, move to `to`, release there: one drag. +fn drag(h: &mut Harness<'static, Host>, from: Pos2, to: Pos2) { + h.event(Event::PointerMoved(from)); + h.run_steps(1); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerMoved(to)); + h.run_steps(1); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The Curves dialog's own geometry (#8984): `curves()` allocates a square of `side` plus the 14 +/// points of the vertical bar and draws the graph 5 points inside that, so with the default 300 +/// points the graph is 276 points wide and the allocated area reaches 19 points left of it and 33 +/// points below it. +const DIALOG_SIDE: f32 = 300.0; + +/// The same bare graph as [`graph`], laid out the way the Curves dialog lays it out, with an +/// interior point at input 2, right against the left edge of the graph. +fn curves_dialog_graph(radius: f32) -> Harness<'static, Host> { + let mut h = Harness::builder().with_size(vec2(600.0, 600.0)).build_ui_state( + |ui, host: &mut Host| { + let (full, resp) = ui.allocate_exact_size(vec2(DIALOG_SIDE, DIALOG_SIDE + 14.0), Sense::click_and_drag()); + host.graph = Rect::from_min_max(full.min + vec2(19.0, 5.0), full.min + vec2(DIALOG_SIDE - 5.0, DIALOG_SIDE - 19.0)); + point_curve::interact_with_hit_radius(ui, &resp, host.graph, &mut host.pts, &mut host.gesture, host.radius); + }, + Host { pts: vec![[0.0, 0.0], [2.0, 128.0], [255.0, 255.0]], gesture: PointCurveState::default(), graph: Rect::NOTHING, radius }, + ); + h.run_steps(2); + h +} + +/// Screen position of the level pair `v` in the current host's graph, at that graph's scale. +fn at_scaled(host: &Host, v: [f32; 2]) -> Pos2 { + let g = host.graph; + Pos2::new(g.left() + v[0] / 255.0 * g.width(), g.bottom() - v[1] / 255.0 * g.height()) +} + /// A click `d` px right of the middle point. fn click_right_of_point(h: &mut Harness<'static, Host>, d: f32) { let pos = at(h.state(), [128.0 + d, 128.0]); @@ -119,3 +158,45 @@ fn the_unmeasured_hosts_keep_todays_nine_pixel_radius() { assert_eq!(host.gesture.selected, Some(if added { 2 } else { 1 }), "a click {d} px away selects the wrong point"); } } + +/// The review case: the Curves graph now grabs 16 points, which reaches past the 12-point band where +/// a drag removes a point. An interior point at input 2 (2.2 points inside the left edge of the +/// 276-point graph), pressed 13 points left of that edge - inside the allocated area, 15.2 points +/// from the point, so the grab radius reaches it - and released without the pointer moving. The +/// press selects the point, so the release must not delete it. +#[test] +fn a_stationary_click_that_grabs_a_point_outside_the_graph_does_not_delete_it() { + let mut h = curves_dialog_graph(CURVES_HIT_RADIUS); + let y = at_scaled(h.state(), [2.0, 128.0]).y; + let pos = Pos2::new(h.state().graph.left() - 13.0, y); + click(&mut h, pos); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [2.0, 128.0], [255.0, 255.0]], "the stationary click outside the graph deleted or moved the point it grabbed"); + assert_eq!(host.gesture.selected, Some(1), "the grabbed point is not selected after the release"); +} + +/// The removal band has to stay where it is for a host that keeps today's 9-point grab radius: a +/// point dragged 13 points past the graph edge still goes. Guard test, green before and after. +#[test] +fn a_nine_pixel_host_still_removes_a_point_dragged_thirteen_points_off_the_graph() { + let mut h = graph(TODAY); + let from = at(h.state(), [128.0, 128.0]); + let to = Pos2::new(h.state().graph.left() - 13.0, from.y); + drag(&mut h, from, to); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [255.0, 255.0]], "the 9 px host stopped removing a point past its 12 point band"); + assert_eq!(host.gesture.selected, None, "the removed point is still selected"); +} + +/// The Curves graph can still remove a point by dragging it off, one point further out: 20 points +/// past the edge is outside the 16-point grab radius. Guard test, green before and after. +#[test] +fn the_curves_graph_still_removes_a_point_dragged_past_its_grab_radius() { + let mut h = curves_dialog_graph(CURVES_HIT_RADIUS); + let from = at_scaled(h.state(), [2.0, 128.0]); + let to = Pos2::new(h.state().graph.left() - 20.0, from.y); + drag(&mut h, from, to); + let host = h.state(); + assert_eq!(host.pts, vec![[0.0, 0.0], [255.0, 255.0]], "a point dragged 20 points off the Curves graph is not removed"); + assert_eq!(host.gesture.selected, None, "the removed point is still selected"); +} From 9dfc375dc8b0173e0965f9d212b403dee9a07784 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:48:38 +0100 Subject: [PATCH 197/385] Place Embedded: a file keeps its physical size at the document's resolution (#14105) --- crates/engine/src/cmd/file_cmds.rs | 4 + crates/engine/src/cmd/file_cmds/open.rs | 3 + .../cmd/file_cmds/place_resolution_tests.rs | 135 ++++++++++++++++++ .../engine/src/cmd/file_cmds/place_steps.rs | 15 +- 4 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/place_resolution_tests.rs diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 7d3f1b021f..f4036951b3 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -473,6 +473,10 @@ mod open_as_smart_object_tests; #[path = "file_cmds/open_as_error_name_tests.rs"] mod open_as_error_name_tests; +#[cfg(test)] +#[path = "file_cmds/place_resolution_tests.rs"] +mod place_resolution_tests; + #[cfg(test)] mod aces_exr_tests { use super::*; diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 959ff3a15b..4766058dd3 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -372,6 +372,8 @@ pub(crate) struct PlaceInput { pub(super) linked: Option, pub(super) params: Value, pub(super) canvas: (f64, f64), + /// The document's resolution (ppi): a placed file keeps its physical size in it. + pub(super) ppi: f64, pub(super) fmt: PixelFormat, pub(super) opts: photocraft_io::ImportOptions, /// Preferences ▸ General ▸ Resize Image During Place, unless the params say otherwise. @@ -429,6 +431,7 @@ impl PlaceInput { Ok(Self { name: name.to_string(), canvas, + ppi: f64::from(d.doc.resolution_dpi), fmt: d.doc.pixel_format(), opts, // The implicit `fit` is Preferences ▸ General ▸ Resize Image During Place (on by default). diff --git a/crates/engine/src/cmd/file_cmds/place_resolution_tests.rs b/crates/engine/src/cmd/file_cmds/place_resolution_tests.rs new file mode 100644 index 0000000000..9245e77c35 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/place_resolution_tests.rs @@ -0,0 +1,135 @@ +//! File › Place Embedded keeps a placed file's physical size (#14105): a 100 × 60 px file at +//! 300 ppi placed into a 400 × 300 px document at 72 ppi comes in at 24 × 14.4 px (0.24), as in +//! the reference application, with the smart object's contents still the 100 × 60 px file. + +use super::*; + +/// A new `w` × `h` document at `ppi`. +fn session(w: u32, h: u32, ppi: f64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "resolution": ppi, "depth": 8})).unwrap(); + s +} + +/// A `w` × `h` image at `ppi`, written as `name`'s format (PNG keeps it in `pHYs`, TIFF in its +/// resolution tags). Checked to read back at that resolution, so a test can't pass on a file +/// that lost it. +fn file_at(name: &str, w: u32, h: u32, ppi: f64) -> Vec { + let s = session(w, h, ppi); + let bytes = photocraft_io::export(&s.active().unwrap().doc, name, &photocraft_io::ExportOptions::default()).unwrap().bytes; + let back = photocraft_io::import(name, &bytes).unwrap().document; + assert_eq!((back.size.width, back.size.height, f64::from(back.resolution_dpi)), (w, h, ppi), "{name} keeps its size and resolution"); + bytes +} + +/// Places `bytes` as `name` through `file.placeEmbedded`'s bytes path (as the menu does). +fn place(s: &mut Session, name: &str, bytes: Vec) -> Value { + place_bytes(s, name, bytes, None, &json!({})).unwrap() +} + +/// The place's reported scale (%) and box. +fn scale_and_bounds(r: &Value) -> (f64, [f64; 4]) { + let b: Vec = r["bounds"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + (r["scale"].as_f64().unwrap(), [b[0], b[1], b[2], b[3]]) +} + +/// The placed smart object. +fn placed(s: &Session) -> SmartObject { + let d = s.active().unwrap(); + match &d.doc.layer(d.active_layer.unwrap()).unwrap().content { + LayerContent::Smart(so) => so.clone(), + _ => panic!("the place made a smart object"), + } +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +/// The measured case, as PNG and as TIFF: 0.24, 24 × 14.4 px centred on the canvas (188 to 212 +/// across; the box starts on a whole pixel, 143 for the measured 142.8, as every place does). +#[test] +fn a_300_ppi_file_placed_into_72_ppi_comes_in_at_its_physical_size() { + for name in ["src.png", "src.tif"] { + let mut s = session(400, 300, 72.0); + let (scale, [x0, y0, x1, y1]) = scale_and_bounds(&place(&mut s, name, file_at(name, 100, 60, 300.0))); + assert!(close(scale, 24.0), "{name}: scale {scale}"); + assert!(close(x0, 188.0) && close(x1, 212.0), "{name}: across {x0}..{x1}"); + assert!(close(x1 - x0, 24.0) && close(y1 - y0, 14.4), "{name}: {}×{}", x1 - x0, y1 - y0); + assert!(close(y0, 143.0), "{name}: top {y0}"); + // The pixels are the resampled 24 × 14.4 (its last row partly covered), not the file's 100 × 60. + let cache = placed(&s).cache.unwrap().content_bounds(); + assert_eq!((cache.x0, cache.y0, cache.x1, cache.y1), (188, 143, 212, 158), "{name}: rendered pixels"); + } +} + +/// The smart object keeps the full-resolution file: its contents are the 100 × 60 px, 300 ppi +/// file, scaled by 0.24 to land, and Edit Contents opens them at that size and resolution. +#[test] +fn the_smart_object_keeps_the_full_resolution_contents() { + let mut s = session(400, 300, 72.0); + let bytes = file_at("src.png", 100, 60, 300.0); + place(&mut s, "src.png", bytes.clone()); + let so = placed(&s); + match &so.source { + SmartSource::Embedded { bytes: kept, .. } => assert_eq!(kept.as_slice(), bytes.as_slice(), "the file is embedded as it is"), + _ => panic!("an embedded smart object"), + } + let [a, b, c, d, e, f] = so.transform.m; + assert!(close(a, 0.24) && close(d, 0.24) && close(b, 0.0) && close(c, 0.0), "scaled by 0.24: {:?}", so.transform.m); + assert!(close(e, 188.0) && close(f, 143.0), "at 188,143: {:?}", so.transform.m); + + s.execute("layer.smartObjects.editContents", json!({})).unwrap(); + let contents = &s.active().unwrap().doc; + assert_eq!((contents.size.width, contents.size.height), (100, 60), "Edit Contents shows the file's own size"); + assert!(close(f64::from(contents.resolution_dpi), 300.0), "at its own resolution: {}", contents.resolution_dpi); +} + +/// The resolution comes first: a file larger than the canvas in pixels that fits once at its +/// physical size isn't fitted (1000 × 600 px at 300 ppi: 240 × 144, not today's 0.4), while one +/// still larger than the canvas at that size is fitted to it as before (2000 × 1500 at 300 ppi: +/// 480 × 360, fitted to 400 × 300). +#[test] +fn the_resolution_scale_comes_before_the_fit_to_the_canvas() { + let mut s = session(400, 300, 72.0); + let (scale, [x0, y0, x1, y1]) = scale_and_bounds(&place(&mut s, "big.png", file_at("big.png", 1000, 600, 300.0))); + assert!(close(scale, 24.0), "fits at its physical size: scale {scale}"); + assert!(close(x1 - x0, 240.0) && close(y1 - y0, 144.0), "{}×{}", x1 - x0, y1 - y0); + assert!(close(x0, 80.0) && close(y0, 78.0), "centred: {x0},{y0}"); + + let mut s = session(400, 300, 72.0); + let (scale, [x0, y0, x1, y1]) = scale_and_bounds(&place(&mut s, "huge.png", file_at("huge.png", 2000, 1500, 300.0))); + assert!(close(scale, 20.0), "fitted to the canvas: scale {scale}"); + assert_eq!([x0, y0, x1, y1], [0.0, 0.0, 400.0, 300.0]); +} + +/// A file at the document's resolution, or one at a lower resolution (not measured), places at +/// its pixel size as before; so does a file with no resolution stored, which reads as 72 ppi. +#[test] +fn a_file_at_or_below_the_document_resolution_places_as_before() { + for (doc_ppi, file_ppi) in [(72.0, 72.0), (300.0, 300.0), (300.0, 72.0), (72.0, 36.0)] { + let mut s = session(400, 300, doc_ppi); + let (scale, bounds) = scale_and_bounds(&place(&mut s, "src.png", file_at("src.png", 100, 60, file_ppi))); + assert!(close(scale, 100.0), "{file_ppi} ppi into {doc_ppi} ppi: scale {scale}"); + assert_eq!(bounds, [150.0, 120.0, 250.0, 180.0], "{file_ppi} ppi into {doc_ppi} ppi"); + } + // A PNG without `pHYs`. + let img = photocraft_codecs::Image::from_u8(100, 60, photocraft_codecs::ChannelLayout::Rgb, vec![128; 100 * 60 * 3]).unwrap(); + let bare = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for doc_ppi in [72.0, 300.0] { + let mut s = session(400, 300, doc_ppi); + let (scale, bounds) = scale_and_bounds(&place(&mut s, "bare.png", bare.clone())); + assert!(close(scale, 100.0), "no resolution into {doc_ppi} ppi: scale {scale}"); + assert_eq!(bounds, [150.0, 120.0, 250.0, 180.0], "no resolution into {doc_ppi} ppi"); + } +} + +/// An explicit `scale` is the caller's, of the file's pixels, as before. +#[test] +fn an_explicit_scale_is_not_changed_by_the_resolution() { + let mut s = session(400, 300, 72.0); + let r = place_bytes(&mut s, "src.png", file_at("src.png", 100, 60, 300.0), None, &json!({"scale": 50})).unwrap(); + let (scale, [x0, y0, x1, y1]) = scale_and_bounds(&r); + assert!(close(scale, 50.0), "scale {scale}"); + assert_eq!([x0, y0, x1, y1], [175.0, 135.0, 225.0, 165.0]); +} diff --git a/crates/engine/src/cmd/file_cmds/place_steps.rs b/crates/engine/src/cmd/file_cmds/place_steps.rs index f4e49a67ce..6953d55a9f 100644 --- a/crates/engine/src/cmd/file_cmds/place_steps.rs +++ b/crates/engine/src/cmd/file_cmds/place_steps.rs @@ -163,11 +163,15 @@ impl PlaceSteps { let (w, h) = (src.size.width as f64, src.size.height as f64); let (cw, ch) = self.input.canvas; let p = &self.input.params; + // A file at a higher resolution than the document keeps its physical size: 300 ppi into + // 72 ppi comes in at 0.24 (#14105). Before the fit to the canvas, which only a file still + // larger than the canvas at that size gets. A frame's image is sized by the frame. + let base = if self.input.frame.is_none() { physical_scale(f64::from(src.resolution_dpi), self.input.ppi) } else { 1.0 }; let scale = match f64_param(p, "scale") { Some(k) => (k / 100.0).max(1e-4), None if self.input.frame.is_some() && self.input.fit => (cw / w).max(ch / h), - None if self.input.fit && (w > cw || h > ch) => (cw / w).min(ch / h), - None => 1.0, + None if self.input.fit && (w * base > cw || h * base > ch) => (cw / w).min(ch / h), + None => base, }; let center = match p.get("center").and_then(Value::as_array) { Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), @@ -285,6 +289,13 @@ impl PlaceSteps { } } +/// The scale that gives a file at `src_ppi` its physical size in a document at `doc_ppi`: below 1 +/// for a file at the higher resolution, else 1 (a file at a lower resolution places at its pixel +/// size, as one with no resolution stored does). +fn physical_scale(src_ppi: f64, doc_ppi: f64) -> f64 { + if doc_ppi > 0.0 && src_ppi > doc_ppi && src_ppi.is_finite() { doc_ppi / src_ppi } else { 1.0 } +} + impl StepWork for PlaceSteps { /// Runs units of work until `deadline` (at least one), checking for a cancel between them. fn step(&mut self, ctx: &JobCtx, deadline: Instant) -> Result> { From 8d0a1e6f86d51d6f5e008e25167ccce3560b3b50 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 17 Nov 2026 11:04:08 +0530 Subject: [PATCH 198/385] Vertical Type tools: the I-beam turns on its side (#12063) The Vertical Type tool shows a sideways I-beam inside a dotted box over the canvas, pasteboard and text, the hotspot 9 right of and 4 below the box's top-left corner. The Vertical Type Mask tool shows the system's vertical text cursor. The horizontal tools, the area-type and type-on-a-path pointers and Precise Other Cursors keep their cursors. --- crates/ui-egui/src/canvas.rs | 10 +- crates/ui-egui/src/canvas/tool_cursor.rs | 29 +++++ .../src/canvas/vertical_type_cursor_tests.rs | 121 ++++++++++++++++++ 3 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2aaca6a456..c638b582f8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2152,7 +2152,11 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(painter, p), _ => crate::tool_cursor::path_type(painter, p), }, - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text, + // The vertical tools turn the I-beam on its side (#12063): the Vertical Type tool's sits in + // a dotted box, over text too; the Vertical Type Mask tool's has no box. + Tool::VerticalType => crate::tool_cursor::vertical_type(painter, p), + Tool::VerticalTypeMask => egui::CursorIcon::VerticalText, + Tool::Type | Tool::HorizontalTypeMask => egui::CursorIcon::Text, Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, painter, p, xf.zoom), Tool::RedEye => { let pupil = app.ui.tool_options.red_eye_pupil_size.clamp(1.0, 100.0); @@ -3262,10 +3266,14 @@ mod blend_viewport_regression; #[cfg(test)] #[path = "canvas/perspective_crop_cursor_tests.rs"] mod perspective_crop_cursor_tests; + #[cfg(test)] #[path = "canvas/pixel_alignment_tests.rs"] mod pixel_alignment_tests; #[cfg(test)] +#[path = "canvas/vertical_type_cursor_tests.rs"] +mod vertical_type_cursor_tests; +#[cfg(test)] mod lasso_preview_tests { use super::*; diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 400346ceb7..2b658fe8bd 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -264,6 +264,35 @@ pub(crate) fn path_type_rings() -> Vec> { rings } +/// Closed outline of an I-beam on its side (stem across, serifs at the ends), centred on the hotspot. +fn sideways_i_beam() -> Vec { + [(-6.0, -2.5), (-5.0, -2.5), (-5.0, -0.5), (5.0, -0.5), (5.0, -2.5), (6.0, -2.5), (6.0, 2.5), (5.0, 2.5), (5.0, 0.5), (-5.0, 0.5), (-5.0, 2.5), (-6.0, 2.5)] + .into_iter() + .map(|(x, y)| vec2(x, y)) + .collect() +} + +/// The dotted box of the Vertical Type tool's pointer: its top-left corner 9 points left of and +/// 4 above the hotspot (the reference's hotspot is (9,4) in its cursor image), 18 wide and 16 +/// tall, so the column the text runs down sits below the sideways I-beam. +const VERTICAL_TYPE_BOX: [f32; 4] = [-9.0, -4.0, 9.0, 12.0]; + +/// The Vertical Type tool's pointer over the canvas (#12063): the sideways I-beam inside a +/// dotted box, the hotspot in the middle of the I-beam's stem. +pub(crate) fn vertical_type_rings() -> Vec> { + let [x0, y0, x1, y1] = VERTICAL_TYPE_BOX; + let mut rings = vec![sideways_i_beam()]; + // Four dots along each edge, corners shared, spaced so none touches the I-beam's serifs. + rings.extend((0..4).map(|i| x0 + (x1 - x0) * i as f32 / 3.0).flat_map(|x| [dot(vec2(x, y0)), dot(vec2(x, y1))])); + rings.extend((1..3).map(|i| y0 + (y1 - y0) * i as f32 / 3.0).flat_map(|y| [dot(vec2(x0, y)), dot(vec2(x1, y))])); + rings +} + +/// The Vertical Type tool's pointer over the canvas, the pasteboard and existing text. +pub(crate) fn vertical_type(painter: &Painter, at: Pos2) -> CursorIcon { + outline(painter, at, vertical_type_rings(), false) +} + /// The Type tool over the inside of a closed path: a click starts area type there. pub(crate) fn area_type(painter: &Painter, at: Pos2) -> CursorIcon { outline(painter, at, area_type_rings(), false) diff --git a/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs b/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs new file mode 100644 index 0000000000..c4f456bf76 --- /dev/null +++ b/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs @@ -0,0 +1,121 @@ +//! The vertical type tools' cursors (#12063): the Vertical Type tool shows an I-beam turned on its +//! side inside a dotted box, the Vertical Type Mask tool the sideways I-beam alone. The horizontal +//! tools keep the upright I-beam and Preferences › Cursors › Other Cursors = Precise keeps the +//! crosshair. Tests drive the real canvas (`document_area`) and read the cursor it asks for. + +use egui::CursorIcon; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A cursor icon, and its bitmap's size, hotspot and pixels. +type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec)>); + +/// The canvas at 100 % with `tool`, the pointer over its centre. +fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.tool = tool; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + h.run_steps(2); + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(3); + h +} + +fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor { + let out = h.output(); + let image = out.platform_output.cursor_image.as_ref().map(|i| (i.size, i.hotspot, i.rgba.to_vec())); + (out.platform_output.cursor_icon, image) +} + +fn precise(h: &mut Harness<'_, PhotocraftApp>) { + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + h.run_steps(2); +} + +/// Whether the bitmap draws something at (`dx`, `dy`) logical points from its hotspot. +fn drawn(c: &Cursor, scale: f32, dx: f32, dy: f32) -> bool { + let Some((size, hot, rgba)) = &c.1 else { return false }; + let x = f32::from(hot[0]) + (dx * scale).round(); + let y = f32::from(hot[1]) + (dy * scale).round(); + if x < 0.0 || y < 0.0 || x >= f32::from(size[0]) || y >= f32::from(size[1]) { + return false; + } + let i = (y as usize * usize::from(size[0]) + x as usize) * 4 + 3; + rgba.get(i).is_some_and(|a| *a > 200) +} + +#[test] +fn vertical_type_shows_a_sideways_i_beam_in_a_dotted_box() { + let h = harness(Tool::VerticalType); + let c = cursor(&h); + assert_eq!(c.0, CursorIcon::None, "our own bitmap, not a system cursor"); + assert!(c.1.is_some(), "the cursor bitmap"); + let scale = crate::tool_cursor::native_scale(&h.ctx); + // The stem runs across through the hotspot, not up and down. + assert!(drawn(&c, scale, 0.0, 0.0), "the stem under the hotspot"); + assert!(drawn(&c, scale, -4.0, 0.0) && drawn(&c, scale, 4.0, 0.0), "the stem left and right of the hotspot"); + assert!(!drawn(&c, scale, 0.0, -4.0) && !drawn(&c, scale, 0.0, 4.0), "nothing above or below the hotspot"); + // The serifs stand up and down at the stem's ends. + assert!(drawn(&c, scale, -5.5, -2.0) && drawn(&c, scale, 5.5, 2.0), "the serifs"); + // The dotted box: its corners 9 left/right of the hotspot, 4 above and 12 below. + for (dx, dy) in [(-9.0, -4.0), (9.0, -4.0), (-9.0, 12.0), (9.0, 12.0)] { + assert!(drawn(&c, scale, dx, dy), "a box corner dot at ({dx}, {dy})"); + } + // Dotted, not a line: gaps between the dots on the bottom edge. + assert!(!drawn(&c, scale, -6.0, 12.0) && !drawn(&c, scale, 9.0, 9.5), "gaps between the dots"); + assert_ne!(c, cursor(&harness(Tool::Type)), "not the horizontal tool's cursor"); +} + +#[test] +fn vertical_type_mask_shows_the_sideways_i_beam_without_a_box() { + let h = harness(Tool::VerticalTypeMask); + let c = cursor(&h); + assert_eq!(c.0, CursorIcon::VerticalText); + assert!(c.1.is_none(), "the system's sideways I-beam, no bitmap"); +} + +#[test] +fn the_horizontal_type_tools_keep_the_upright_i_beam() { + for tool in [Tool::Type, Tool::HorizontalTypeMask] { + let c = cursor(&harness(tool)); + assert_eq!(c.0, CursorIcon::Text, "{tool:?}"); + assert!(c.1.is_none(), "{tool:?}: no bitmap"); + } +} + +#[test] +fn precise_other_cursors_keep_the_crosshair_for_both_vertical_tools() { + let mut reference = harness(Tool::Type); + precise(&mut reference); + let crosshair = cursor(&reference); + assert_ne!(crosshair.0, CursorIcon::Text, "Precise: not the I-beam"); + for tool in [Tool::VerticalType, Tool::VerticalTypeMask] { + let mut h = harness(tool); + let standard = cursor(&h); + precise(&mut h); + let shown = cursor(&h); + assert_eq!(shown, crosshair, "{tool:?}: the same crosshair as the other tools"); + assert_ne!(shown, standard, "{tool:?}: not the sideways I-beam"); + } +} From 487bd1bad7e7ab0bcfe95deb97dd3d01f5f06e11 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 22:41:47 -0800 Subject: [PATCH 199/385] 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 411fbd24ff44e3ecfcf57ed2b69ec5903199597f Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 17 Nov 2026 12:15:53 +0530 Subject: [PATCH 200/385] Vertical type cursor test: a bitmap cursor reports the crosshair fallback icon --- crates/ui-egui/src/canvas.rs | 1 - .../src/canvas/vertical_type_cursor_tests.rs | 20 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c638b582f8..1bc0a3179c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3266,7 +3266,6 @@ mod blend_viewport_regression; #[cfg(test)] #[path = "canvas/perspective_crop_cursor_tests.rs"] mod perspective_crop_cursor_tests; - #[cfg(test)] #[path = "canvas/pixel_alignment_tests.rs"] mod pixel_alignment_tests; diff --git a/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs b/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs index c4f456bf76..f56e7a6f0f 100644 --- a/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/vertical_type_cursor_tests.rs @@ -65,25 +65,31 @@ fn drawn(c: &Cursor, scale: f32, dx: f32, dy: f32) -> bool { rgba.get(i).is_some_and(|a| *a > 200) } +/// Whether the bitmap draws something within a pixel of (`dx`, `dy`), allowing for where the +/// hotspot falls inside its pixel. +fn near(c: &Cursor, scale: f32, dx: f32, dy: f32) -> bool { + [-1.0, 0.0, 1.0].into_iter().any(|ox| [-1.0, 0.0, 1.0].into_iter().any(|oy| drawn(c, scale, dx + ox / scale, dy + oy / scale))) +} + #[test] fn vertical_type_shows_a_sideways_i_beam_in_a_dotted_box() { let h = harness(Tool::VerticalType); let c = cursor(&h); - assert_eq!(c.0, CursorIcon::None, "our own bitmap, not a system cursor"); - assert!(c.1.is_some(), "the cursor bitmap"); + // Our own bitmap: the end of the pass reports it with the crosshair as the fallback icon. + assert!(c.1.is_some(), "the cursor bitmap, not a system cursor"); let scale = crate::tool_cursor::native_scale(&h.ctx); // The stem runs across through the hotspot, not up and down. - assert!(drawn(&c, scale, 0.0, 0.0), "the stem under the hotspot"); - assert!(drawn(&c, scale, -4.0, 0.0) && drawn(&c, scale, 4.0, 0.0), "the stem left and right of the hotspot"); + assert!(near(&c, scale, 0.0, 0.0), "the stem under the hotspot"); + assert!(near(&c, scale, -4.0, 0.0) && near(&c, scale, 4.0, 0.0), "the stem left and right of the hotspot"); assert!(!drawn(&c, scale, 0.0, -4.0) && !drawn(&c, scale, 0.0, 4.0), "nothing above or below the hotspot"); // The serifs stand up and down at the stem's ends. - assert!(drawn(&c, scale, -5.5, -2.0) && drawn(&c, scale, 5.5, 2.0), "the serifs"); + assert!(near(&c, scale, -5.5, -2.0) && near(&c, scale, 5.5, 2.0), "the serifs"); // The dotted box: its corners 9 left/right of the hotspot, 4 above and 12 below. for (dx, dy) in [(-9.0, -4.0), (9.0, -4.0), (-9.0, 12.0), (9.0, 12.0)] { - assert!(drawn(&c, scale, dx, dy), "a box corner dot at ({dx}, {dy})"); + assert!(near(&c, scale, dx, dy), "a box corner dot at ({dx}, {dy})"); } // Dotted, not a line: gaps between the dots on the bottom edge. - assert!(!drawn(&c, scale, -6.0, 12.0) && !drawn(&c, scale, 9.0, 9.5), "gaps between the dots"); + assert!(!drawn(&c, scale, -6.0, 12.0) && !drawn(&c, scale, 6.0, 12.0), "gaps between the dots"); assert_ne!(c, cursor(&harness(Tool::Type)), "not the horizontal tool's cursor"); } From 660426e5415c2c254e344e7bd546dfe9c4971ce3 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 17 Nov 2026 13:52:48 +0530 Subject: [PATCH 201/385] Pen in Shape mode: make the shape layer on the first click and fill the open path (#12909) The first Pen click in Shape mode with New Layer creates the shape layer at once (History: New Shape Layer). The draft then carries that layer's path, and each anchor placed updates the layer, so the fill shows while the path is still open. Enter or Esc finishes it with no extra step; closing gives it the closed-path stroke. Undo and Redo while drawing step the layer and the draft follows it. --- .../ui-egui/src/pen_path_ownership_tests.rs | 6 +- .../src/tools/path_components/tests.rs | 2 +- crates/ui-egui/src/tools/vector_ui.rs | 6 + .../vector_ui/freeform_history_name_tests.rs | 9 + crates/ui-egui/src/tools/vector_ui/pen.rs | 169 ++++++++++++- .../ui-egui/src/tools/vector_ui/pen_resume.rs | 2 +- .../src/tools/vector_ui/pen_resume_tests.rs | 21 +- .../vector_ui/pen_shape_first_click_tests.rs | 239 ++++++++++++++++++ 8 files changed, 437 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs diff --git a/crates/ui-egui/src/pen_path_ownership_tests.rs b/crates/ui-egui/src/pen_path_ownership_tests.rs index 47d01882ab..2ddc369b7a 100644 --- a/crates/ui-egui/src/pen_path_ownership_tests.rs +++ b/crates/ui-egui/src/pen_path_ownership_tests.rs @@ -111,7 +111,8 @@ fn captured_path_and_shape_mode_do_not_follow_later_ui_selection() { assert_eq!(path(&app, "Saved drawing").subpaths.len(), 2); assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); } - assert_eq!(steps(&app), n + 1); + // A Shape draft made its layer on the first anchor and edited it for the second (#12909). + assert_eq!(steps(&app), n + if shape { 2 } else { 1 }); } } @@ -137,7 +138,8 @@ fn captured_pen_paint_preserves_float_colour_and_alpha_after_toolbar_changes() { let st = app.session.active().unwrap(); let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("expected Pen shape") }; let paint = |c: [f32; 4]| photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])); - assert_eq!(shape.fill, closed.then(|| paint(foreground))); + // The layer is made on the first click with the fill, open or not (#12909). + assert_eq!(shape.fill, Some(paint(foreground))); // Open and closed shapes both take the captured stroke paint. assert_eq!(shape.stroke.as_ref().unwrap().paint, paint(background)); } diff --git a/crates/ui-egui/src/tools/path_components/tests.rs b/crates/ui-egui/src/tools/path_components/tests.rs index b6aeec08a6..168d52554d 100644 --- a/crates/ui-egui/src/tools/path_components/tests.rs +++ b/crates/ui-egui/src/tools/path_components/tests.rs @@ -262,7 +262,7 @@ fn the_pen_carries_on_an_open_shape_path() { } assert!(pen_commit(&mut app, false)); let (id, sh) = shape(&app); - assert!(sh.fill.is_none() && sh.stroke.is_some(), "an open path is stroked"); + assert!(sh.fill.is_some() && sh.stroke.is_some(), "an open path is stroked, and filled from the first click (#12909)"); let count = app.session.active().unwrap().doc.layers.len(); let steps = history(&app); click(&mut app, 120.0, 120.0); // its last anchor: carry on diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 1efea99a67..271863cf04 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -183,6 +183,10 @@ pub struct PenPath { /// endpoint drawing carries on from; only its outgoing handle bends into the new segment. #[serde(default)] pub fixed: Vec<[[f64; 2]; 3]>, + /// The draft's shape layer was made on its first click (#12909) and its path follows the + /// draft anchor by anchor; `resumes` names that layer and its subpath. + #[serde(skip)] + pub(crate) live_layer: bool, } /// The subpath a Pen path carries on: where it is and what it was when drawing resumed. The @@ -363,6 +367,8 @@ pub(crate) fn pen_can_undo(app: &PhotocraftApp) -> bool { /// Commit a valid source-owned draft on a tab switch; otherwise cancel with an actionable diagnostic. pub(crate) fn cancel_stale_pen(app: &mut PhotocraftApp) -> bool { + // A live shape layer's draft follows the document through Undo, Redo and History (#12909). + pen::sync_live_draft_from_layer(app); let Some(pen) = app.ui.pen.as_ref() else { return false }; if pen.owner.as_ref().is_some_and(|o| o.valid(app)) { return false; diff --git a/crates/ui-egui/src/tools/vector_ui/freeform_history_name_tests.rs b/crates/ui-egui/src/tools/vector_ui/freeform_history_name_tests.rs index 7891fc7046..808a39d53b 100644 --- a/crates/ui-egui/src/tools/vector_ui/freeform_history_name_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/freeform_history_name_tests.rs @@ -104,6 +104,15 @@ fn pen_and_curvature_keep_default_history_names_even_with_freeform_selected_at_c } app.ui.tool = Tool::FreeformPen; assert!(pen_commit(&mut app, false)); + if mode == "shape" && !curvature { + // The Pen's shape layer came with its first anchor and took each further one as a + // step (#12909); the commit adds none, and no step takes the Freeform name. + let h = &app.session.active().unwrap().history; + assert_eq!(h.past_len(), n + 3); + assert_eq!(h.undo_label(), Some("Edit Shape")); + assert!(!app.ui.status_error, "{}", app.ui.status); + continue; + } assert_step(&app, n, if mode == "path" { "Work Path" } else { "New Shape Layer" }); } } diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index e28058af8a..36a57014b4 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -107,6 +107,7 @@ pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { pen.knots.push([p; 3]); pen.dragging = true; pen.adjusting_last = false; + start_live_shape(app); } /// Pen drag: pull out the handles of the anchor just placed. ⇧ (read live, as it is held) @@ -160,6 +161,10 @@ pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { return false; } let Some(pen) = app.ui.pen.as_mut() else { return false }; + // The anchors of a live shape layer are History steps: Undo takes one back (#12909). + if pen.live_layer { + return undo_live_step(app); + } // A resumed path's own anchors are not the draft's to take back: undoing past the ones added // since it resumed drops the draft and leaves the path as it was (#6593). if pen.resumes.as_ref().is_some_and(|r| pen.knots.len() <= r.was.knots.len()) { @@ -192,6 +197,147 @@ pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { true } +/// A fresh Pen draft in Shape mode with New Layer makes its shape layer on the first click, as the +/// reference application does (#12909). The draft then carries that layer's first subpath +/// (`resumes`, `live_layer`) and the layer follows it anchor by anchor +/// ([`sync_live_layer_from_draft`]). If the document refuses the layer, the draft is as before: +/// the shape is made when the path is committed. +fn start_live_shape(app: &mut PhotocraftApp) { + let Some(pen) = app.ui.pen.as_ref().filter(|p| p.knots.len() == 1 && p.resumes.is_none() && !p.live_layer && !p.curvature && !p.commit_failed) else { + return; + }; + let o = &app.ui.tool_options; + if app.ui.tool != Tool::Pen || o.vector_mode != "shape" || pen_path_op(o).is_some() { + return; + } + let params = json!({"kind": "path", "path": pen_to_json(pen, false), "fill": fill_param(app), "stroke": super::shapes::open_pen_stroke_param(app)}); + let made = match run_beside_draft(app, "shape.create", params) { + Ok(made) => made, + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + return; + } + }; + let Some(mut pen) = app.ui.pen.take() else { return }; + let made = made.get("layer").and_then(Value::as_u64).and_then(|id| { + let st = app.session.active()?; + let sub = match &st.doc.layer(photocraft_doc::LayerId(id))?.content { + LayerContent::Shape(sh) => sh.path.subpaths.first().cloned(), + _ => None, + }?; + Some((st.doc.id.0, id, sub)) + }); + let Some((doc, id, was)) = made else { + // Not the layer it asked for: the draft goes on as before, made into a shape on commit. + super::pen_resume::rebind_owner(app, &mut pen); + app.ui.pen = Some(pen); + return; + }; + pen.resumes = Some(Resumed { doc, path: "layer".into(), layer: Some(id), index: 0, was }); + pen.live_layer = true; + super::pen_resume::rebind_owner(app, &mut pen); + // Committing makes the layer the active one, not the layer drawing began above. + if let Some(owner) = pen.owner.as_mut() { + owner.layer = Some(photocraft_doc::LayerId(id)); + } + app.ui.pen = Some(pen); +} + +/// Run `id` on the live draft's layer with the draft set aside: after every command +/// `PhotocraftApp::run` reconciles the Pen draft with the document (`sync_views`), and would cancel +/// one whose document just changed as stale. The draft comes back as it was; callers rebind it. +fn run_beside_draft(app: &mut PhotocraftApp, id: &str, params: Value) -> Result { + let pen = app.ui.pen.take(); + let r = app.run(id, params); + app.ui.pen = pen; + r +} + +/// Does `sub` have the closing and anchors of the one subpath of `drawn`? +fn subpath_is(sub: &photocraft_doc::vector::Subpath, drawn: &Value) -> bool { + let mine = photocraft_engine::vector_cmds::path_json(&Path::new(vec![sub.clone()])); + let (Some(a), Some(b)) = (mine.pointer("/subpaths/0"), drawn.pointer("/subpaths/0")) else { return false }; + ["closed", "knots"].iter().all(|key| a.get(*key) == b.get(*key)) +} + +/// The live draft has taken in the document the last command made: its owner and the subpath it +/// carries are that state's. +fn follow_live_layer(app: &mut PhotocraftApp) { + let Some(mut pen) = app.ui.pen.take() else { return }; + let was = pen.resumes.as_ref().and_then(|r| { + let doc = &app.session.active()?.doc; + resumed_path(doc, r)?.subpaths.get(r.index).cloned() + }); + if let (Some(r), Some(was)) = (pen.resumes.as_mut(), was) { + r.was = was; + } + super::pen_resume::rebind_owner(app, &mut pen); + app.ui.pen = Some(pen); +} + +/// Put the live draft's anchors into its shape layer, one History step, when they differ (#12909). +/// A refused edit is reported and retried by the next anchor or by the commit. +fn sync_live_layer_from_draft(app: &mut PhotocraftApp) { + let Some(pen) = app.ui.pen.as_ref().filter(|p| p.live_layer && !p.commit_failed) else { return }; + let Some((r, id)) = pen.resumes.as_ref().and_then(|r| Some((r, r.layer?))) else { return }; + let drawn = pen_to_json(pen, false); + let Some(doc) = app.session.active().map(|st| &st.doc) else { return }; + if resumed_path(doc, r).and_then(|p| p.subpaths.get(r.index)).is_some_and(|sub| subpath_is(sub, &drawn)) { + return; + } + let Some(path) = with_resumed_subpath(doc, r, &drawn) else { return }; + match run_beside_draft(app, "shape.edit", json!({"layer": id, "path": path})) { + Ok(_) => follow_live_layer(app), + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +/// Edit › Undo while a live shape layer is being drawn takes back its last History step, which +/// is its last anchor (or the layer itself with the first), and the draft follows (#12909). +fn undo_live_step(app: &mut PhotocraftApp) -> bool { + if let Err(e) = run_beside_draft(app, "edit.undo", json!({})) { + app.ui.status = e; + app.ui.status_error = true; + } + sync_live_draft_from_layer(app); + true +} + +/// A live draft whose document moved on (Undo, Redo, the History panel…) is rebuilt from its +/// layer's open subpath, or dropped when the layer or the subpath is gone or closed (#12909). +pub(super) fn sync_live_draft_from_layer(app: &mut PhotocraftApp) { + let Some(pen) = app.ui.pen.as_ref().filter(|p| p.live_layer && !p.commit_failed) else { return }; + let (Some(owner), Some(r)) = (pen.owner.as_ref(), pen.resumes.as_ref()) else { return }; + let Some(st) = app.session.active() else { return }; + if st.doc.id != owner.document || owner.valid(app) { + return; + } + let sub = resumed_path(&st.doc, r).and_then(|p| p.subpaths.get(r.index)).filter(|s| !s.closed && !s.knots.is_empty()); + let rebuilt = sub.map(|s| { + let mut draft = resumed(r.doc, "layer".into(), r.layer, r.index, s, false); + draft.live_layer = true; + draft.owner = Some(owner.clone()); + draft + }); + match rebuilt { + Some(draft) => { + app.ui.pen = Some(draft); + follow_live_layer(app); + } + None => { + app.ui.pen = None; + app.ui.pen_doc = None; + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + } + } +} + pub fn pen_up(app: &mut PhotocraftApp) { cancel_stale_pen(app); let jitter = 2.0 / f64::from(app.point_zoom().max(0.01)); @@ -210,6 +356,8 @@ pub fn pen_up(app: &mut PhotocraftApp) { k[2] = k[0]; } pen_commit(app, true); + } else { + sync_live_layer_from_draft(app); } } @@ -448,7 +596,8 @@ pub fn pen_end(app: &mut PhotocraftApp) { /// /// The Freeform history override applies to document paths and new shape layers only. fn commit_path_current(app: &mut PhotocraftApp, pen: &PenPath, closed: bool, freeform: bool) -> bool { - if pen.knots.is_empty() || (pen.knots.len() < 2 && app.ui.tool_options.vector_mode == "shape") { + // A live draft's one anchor is a shape layer already (#12909): finishing it needs no new one. + if pen.knots.is_empty() || (pen.knots.len() < 2 && app.ui.tool_options.vector_mode == "shape" && !pen.live_layer) { return true; } let path = pen_to_json(pen, closed); @@ -668,13 +817,23 @@ fn commit_resumed_on_layer(app: &mut PhotocraftApp, pen: &PenPath, path: &Value, let r = pen.resumes.as_ref()?; let id = r.layer?; let st = app.session.active()?; - let p = with_resumed_subpath(&st.doc, r, path)?; + let Some(p) = with_resumed_subpath(&st.doc, r, path) else { + // A live draft never makes a second layer: its subpath changed under it. + return pen.live_layer.then(|| Err("Pen draft target is stale; no path was changed".to_string())); + }; let layer = st.doc.layer(photocraft_doc::LayerId(id))?; let LayerContent::Shape(sh) = &layer.content else { return Some(app.run("layer.vectorMask.edit", json!({"layer": id, "path": p}))); }; + // Finishing a live draft open leaves its layer as it is: no step when the anchors are in it (#12909). + if pen.live_layer && !closed && resumed_path(&st.doc, r).and_then(|p| p.subpaths.get(r.index)).is_some_and(|sub| subpath_is(sub, path)) { + return Some(Ok(Value::Null)); + } let mut params = json!({"layer": id, "path": p}); - if closed && sh.fill.is_none() && sh.path.subpaths.iter().all(|s| !s.closed) { + // Closing a shape made of open paths gives it the options bar's fill and stroke, as drawing it + // closed would have. A live layer has a fill already (#12909), so it counts by its draft and + // a shape made of open paths whatever its fill: the stroke was the open path's. + if closed && (pen.live_layer || sh.path.subpaths.iter().all(|s| !s.closed)) { params["fill"] = fill_param(app); params["stroke"] = stroke_param(app); } @@ -1104,3 +1263,7 @@ mod pen_alt_drag_segment_tests; #[cfg(test)] #[path = "freeform_close_tolerance_tests.rs"] mod freeform_close_tolerance_tests; + +#[cfg(test)] +#[path = "pen_shape_first_click_tests.rs"] +mod pen_shape_first_click_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume.rs index 3d7d96c0fd..2be857f86b 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_resume.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume.rs @@ -79,7 +79,7 @@ pub(super) fn remember_finish(app: &mut PhotocraftApp, draft: PenPath, before: & /// The draft given back belongs to the document state Undo went back to: its owner moves to that /// state (same target, options and colours), or `cancel_stale_pen` would take it for another /// document's and finish it on the next frame. -fn rebind_owner(app: &PhotocraftApp, draft: &mut PenPath) { +pub(super) fn rebind_owner(app: &PhotocraftApp, draft: &mut PenPath) { let Some(st) = app.session.active() else { return }; match draft.owner.as_mut() { Some(owner) if owner.document == st.doc.id => { diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs index a76f889657..aba7d6528f 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs @@ -413,7 +413,8 @@ fn pen_undo_after_closing_a_shape_reopens_the_path() { let knots = close_triangle(&mut app); assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); menu(&mut app, "edit.undo"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the shape layer is gone"); + // The shape layer was made on the first click (#12909): Undo takes back only the closing. + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the shape layer stays, open again"); assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); } @@ -588,11 +589,9 @@ fn redo_leaves_the_same_anchors_redrawn_in_shape_mode_alone() { } assert!(app.ui.pen.is_none()); app.ui.tool_options.vector_mode = "shape".into(); - for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { - pen_down(&mut app, x, y, false); - pen_up(&mut app); - } - assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); + // Not through clicks: they would make the shape layer at once (#12909), a History step that + // clears Redo. This is a draft that has not been committed anywhere. + app.ui.pen = Some(PenPath { knots: knots.clone(), owner: capture_pen_owner(&app), ..Default::default() }); assert!(!crate::menus::is_enabled(&app, "edit.redo"), "Redo greys out over the new draft"); menu(&mut app, "edit.redo"); assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots), "the Shape draft is still being drawn"); @@ -628,6 +627,11 @@ fn failed_library_draft(tool: Tool, shape: bool) -> PhotocraftApp { app.run("actions.clearAll", json!({"confirm": true})).unwrap(); app.ui.tool = tool; app.ui.tool_options.vector_mode = if shape { "shape" } else { "path" }.into(); + // A refused shape is refused from the first click on: the Pen makes its layer then (#12909). + if shape { + app.session.authorize = + Some(|id, _| if id == "shape.create" { Err(photocraft_engine::EngineError::Other("refused shape fixture".into())) } else { Ok(()) }); + } for (x, y) in [(20.0, 20.0), (80.0, 60.0)] { if tool == Tool::CurvaturePen { curvature_down(&mut app, x, y); @@ -636,10 +640,7 @@ fn failed_library_draft(tool: Tool, shape: bool) -> PhotocraftApp { pen_up(&mut app); } } - if shape { - app.session.authorize = - Some(|id, _| if id == "shape.create" { Err(photocraft_engine::EngineError::Other("refused shape fixture".into())) } else { Ok(()) }); - } else { + if !shape { app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("refused path fixture".into())) } else { Ok(()) }); } assert!(!pen_commit(&mut app, false), "the fixture must actually refuse the commit"); diff --git a/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs new file mode 100644 index 0000000000..bafade6965 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs @@ -0,0 +1,239 @@ +//! #12909: the Pen in Shape mode with New Layer makes its shape layer on the first click, and the +//! layer follows the path anchor by anchor, so the fill shows before the path is closed. +use super::*; + +/// An 800 by 600 document with a pixel layer above the Background, the Pen in Shape mode. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Pen; + app.ui.tool_options.vector_mode = "shape".into(); + app +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64) { + pen_down(app, x, y, false); + pen_up(app); +} + +/// Edit › Undo and Redo as the menu, the shortcut and the control channel run them. +fn menu(app: &mut PhotocraftApp, id: &str) { + crate::menus::invoke(app, &egui::Context::default(), id, json!({})).unwrap(); +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn undo_label(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.undo_label().map(str::to_string) +} + +/// Every shape layer of the document, bottom to top: its name and shape. +fn shapes(app: &PhotocraftApp) -> Vec<(String, photocraft_doc::ShapeLayer)> { + let doc = &app.session.active().unwrap().doc; + doc.layers + .iter() + .filter_map(|l| match &l.content { + LayerContent::Shape(sh) => Some((l.name.clone(), sh.clone())), + _ => None, + }) + .collect() +} + +/// The anchors of each subpath of a shape and whether it is closed. +fn subpaths(sh: &photocraft_doc::ShapeLayer) -> Vec<(bool, Vec<[f64; 2]>)> { + sh.path.subpaths.iter().map(|s| (s.closed, s.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect())).collect() +} + +fn draft_len(app: &PhotocraftApp) -> Option { + app.ui.pen.as_ref().map(|p| p.knots.len()) +} + +fn covered(path: &Path, x: i32, y: i32) -> f32 { + photocraft_vector::fill_rasterizer(path, photocraft_vector::DEFAULT_TOLERANCE).render(photocraft_geom::Rect::from_xywh(x, y, 1, 1))[0] +} + +#[test] +fn the_first_click_makes_the_shape_layer_right_away() { + let mut app = app(); + let (before, below) = (steps(&app), app.session.active().unwrap().active_layer.unwrap()); + click(&mut app, 500.0, 100.0); + let list = shapes(&app); + assert_eq!(list.len(), 1); + assert_eq!(list[0].0, "Shape 1"); + assert_eq!(subpaths(&list[0].1), [(false, vec![[500.0, 100.0]])]); + assert_eq!(steps(&app), before + 1); + assert_eq!(undo_label(&app).as_deref(), Some("New Shape Layer")); + assert!(app.ui.pen.as_ref().is_some_and(|p| p.live_layer), "the path is still being drawn"); + let st = app.session.active().unwrap(); + let at = |id| st.doc.layers.iter().position(|l| l.id == id); + assert_eq!(st.active_layer.and_then(at), at(below).map(|i| i + 1), "above the layer that was active"); +} + +#[test] +fn the_layer_fills_the_open_path_anchor_by_anchor() { + let mut app = app(); + let before = steps(&app); + for (x, y) in [(500.0, 100.0), (700.0, 100.0), (700.0, 300.0)] { + click(&mut app, x, y); + } + let list = shapes(&app); + assert_eq!(list.len(), 1, "one layer, not one per anchor"); + let sh = &list[0].1; + assert_eq!(subpaths(sh), [(false, vec![[500.0, 100.0], [700.0, 100.0], [700.0, 300.0]])], "an open path, not closed yet"); + assert!(sh.fill.is_some(), "it has the options bar's fill"); + assert_eq!(covered(&sh.path, 650, 150), 1.0, "the triangle is filled before it is closed"); + assert_eq!(covered(&sh.path, 550, 250), 0.0, "and only the triangle"); + assert_eq!(steps(&app), before + 3, "the layer, then one step per further anchor"); + assert_eq!(undo_label(&app).as_deref(), Some("Edit Shape")); + assert_eq!(draft_len(&app), Some(3)); +} + +#[test] +fn one_click_then_enter_leaves_a_one_anchor_shape_layer() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + let before = steps(&app); + pen_enter(&mut app); + assert!(app.ui.pen.is_none()); + let list = shapes(&app); + assert_eq!(list.len(), 1); + assert_eq!(subpaths(&list[0].1), [(false, vec![[500.0, 100.0]])]); + assert_eq!(steps(&app), before, "finishing adds no step"); +} + +#[test] +fn finishing_with_enter_or_esc_then_clicking_elsewhere_starts_a_new_layer() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + pen_enter(&mut app); + click(&mut app, 100.0, 400.0); + assert_eq!(shapes(&app).iter().map(|s| s.0.as_str()).collect::>(), ["Shape 1", "Shape 2"]); + click(&mut app, 300.0, 400.0); + pen_end(&mut app); + click(&mut app, 600.0, 500.0); + let list = shapes(&app); + assert_eq!(list.iter().map(|s| s.0.as_str()).collect::>(), ["Shape 1", "Shape 2", "Shape 3"]); + let anchors: Vec<_> = list.iter().map(|s| subpaths(&s.1)[0].1.len()).collect(); + assert_eq!(anchors, [2, 2, 1]); +} + +#[test] +fn clicking_the_first_anchor_closes_the_same_layer_and_keeps_its_fill() { + let mut app = app(); + for (x, y) in [(500.0, 100.0), (700.0, 100.0), (700.0, 300.0)] { + click(&mut app, x, y); + } + click(&mut app, 500.0, 100.0); + assert!(app.ui.pen.is_none(), "closing commits"); + let list = shapes(&app); + assert_eq!(list.len(), 1, "no second layer"); + let sh = &list[0].1; + assert_eq!(subpaths(sh), [(true, vec![[500.0, 100.0], [700.0, 100.0], [700.0, 300.0]])]); + assert!(sh.fill.is_some()); + assert_eq!(covered(&sh.path, 650, 150), 1.0); + let st = app.session.active().unwrap(); + assert_eq!(st.active_layer.and_then(|id| st.doc.layer(id)).map(|l| l.name.as_str()), Some("Shape 1"), "the layer is the active one"); +} + +#[test] +fn undo_while_drawing_takes_back_anchors_then_the_layer() { + let mut app = app(); + let layers = app.session.active().unwrap().doc.layers.len(); + for (x, y) in [(500.0, 100.0), (700.0, 100.0), (700.0, 300.0)] { + click(&mut app, x, y); + } + menu(&mut app, "edit.undo"); + assert_eq!(draft_len(&app), Some(2), "the draft lost its last anchor"); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0], [700.0, 100.0]])], "and so did the layer"); + // Drawing carries on from the draft. + click(&mut app, 700.0, 400.0); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0], [700.0, 100.0], [700.0, 400.0]])]); + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.undo"); + assert_eq!(draft_len(&app), Some(1)); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0]])]); + menu(&mut app, "edit.undo"); + assert!(app.ui.pen.is_none(), "the draft goes with its layer"); + assert!(shapes(&app).is_empty()); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +#[test] +fn redo_while_drawing_brings_the_anchor_back_and_the_draft_follows() { + let mut app = app(); + for (x, y) in [(500.0, 100.0), (700.0, 100.0), (700.0, 300.0)] { + click(&mut app, x, y); + } + menu(&mut app, "edit.undo"); + assert_eq!(draft_len(&app), Some(2)); + menu(&mut app, "edit.redo"); + // The next frame, or the next click, reconciles the draft with the document. + crate::vector_ui::cancel_stale(&mut app); + assert_eq!(draft_len(&app), Some(3)); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0], [700.0, 100.0], [700.0, 300.0]])]); + // And it is a live draft again: the next anchor goes into the same layer. + click(&mut app, 500.0, 300.0); + assert_eq!(shapes(&app).len(), 1); + assert_eq!(subpaths(&shapes(&app)[0].1)[0].1.len(), 4); +} + +#[test] +fn another_history_state_drops_a_draft_whose_layer_is_gone() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + // Something else removes the layer (a History step back past it). + app.session.undo(); + app.session.undo(); + crate::vector_ui::cancel_stale(&mut app); + assert!(app.ui.pen.is_none()); + assert!(shapes(&app).is_empty()); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +#[test] +fn path_mode_other_operations_and_the_other_pens_make_no_layer_on_the_first_click() { + let mut app = app(); + let before = steps(&app); + // Path mode. + app.ui.tool_options.vector_mode = "path".into(); + click(&mut app, 500.0, 100.0); + assert!(shapes(&app).is_empty() && steps(&app) == before); + assert!(app.ui.pen.as_ref().is_some_and(|p| !p.live_layer)); + app.ui.pen = None; + // A Path Operation other than New Layer adds to a shape instead. + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.tool_options.pen_path_op = "combine".into(); + click(&mut app, 500.0, 100.0); + assert!(shapes(&app).is_empty() && steps(&app) == before); + app.ui.pen = None; + app.ui.tool_options.pen_path_op = "newLayer".into(); + // The Curvature Pen. + app.ui.tool = Tool::CurvaturePen; + crate::vector_ui::curvature_down(&mut app, 500.0, 100.0); + crate::vector_ui::curvature_up(&mut app); + assert!(shapes(&app).is_empty() && steps(&app) == before); + assert!(app.ui.pen.as_ref().is_some_and(|p| !p.live_layer)); +} + +#[test] +fn a_path_carried_on_from_its_endpoint_stays_one_step() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + pen_enter(&mut app); + let before = steps(&app); + click(&mut app, 700.0, 100.0); + assert!(app.ui.pen.as_ref().is_some_and(|p| p.resumes.is_some() && !p.live_layer), "a press on the endpoint carries the path on"); + click(&mut app, 700.0, 300.0); + pen_enter(&mut app); + assert_eq!(shapes(&app).len(), 1, "no new layer"); + assert_eq!(subpaths(&shapes(&app)[0].1)[0].1.len(), 3); + assert_eq!(steps(&app), before + 1); +} From c4f672d2f78b49b672fd1899d3ba349040b40806 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:32:03 +0100 Subject: [PATCH 202/385] test(compose): Blend If split fade measurements (#14855) --- .../compose/src/blend_if_split_fade_tests.rs | 98 +++++++++++++++++++ crates/compose/src/composite.rs | 4 + 2 files changed, 102 insertions(+) create mode 100644 crates/compose/src/blend_if_split_fade_tests.rs diff --git a/crates/compose/src/blend_if_split_fade_tests.rs b/crates/compose/src/blend_if_split_fade_tests.rs new file mode 100644 index 0000000000..1105867457 --- /dev/null +++ b/crates/compose/src/blend_if_split_fade_tests.rs @@ -0,0 +1,98 @@ +//! #14855: a split Blend If slider fades with both ends inclusive in 8-bit documents, measured in +//! the reference application on the test document of [`band_doc`]. + +use crate::render; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{BlendRange, Document, Layer}; +use photocraft_geom::{Rect, Size}; + +/// The issue's test document at `depth`: 400x300 px, a Background of 16 vertical grey bands of +/// 25 px (band `i` has the value 17·i), a blue Base rectangle from (0,150) to (400,300) and the +/// orange (255,128,0) Top rectangle from (50,50) to (350,250), which carries `this` (This Layer) +/// and `under` (Underlying Layer) as its Gray Blend If entry. +fn band_doc(depth: SampleType, this: BlendRange, under: BlendRange) -> Document { + let mut d = Document::new("t", Size::new(400, 300), ColorMode::Rgb, depth); + let fmt = d.pixel_format(); + let mut bg = Layer::raster("Background", fmt); + for i in 0..16 { + let v = (17 * i) as f32 / 255.0; + bg.surface_mut().unwrap().fill_rect(Rect::from_xywh(25 * i, 0, 25, 300), &[v, v, v, 1.0]); + } + let mut base = Layer::raster("Base", fmt); + base.surface_mut().unwrap().fill_rect(Rect::new(0, 150, 400, 300), &[0.0, 0.0, 1.0, 1.0]); + let mut top = Layer::raster("Top", fmt); + top.surface_mut().unwrap().fill_rect(Rect::new(50, 50, 350, 250), &[1.0, 128.0 / 255.0, 0.0, 1.0]); + top.blend_if.set(0, [this, under]); + d.layers.extend([bg, base, top]); + d +} + +/// The flattened pixel at (`x`, `y`) on the 0..=255 scale, rounded. +fn rgb8(d: &Document, x: i32, y: i32) -> [i32; 3] { + let p = render(d, Rect::from_xywh(x, y, 1, 1)).px[0]; + [0, 1, 2].map(|c| (p[c] * 255.0).round() as i32) +} + +/// Asserts every sample `(x, want)` on row y = 100 of `d` within ±`tol` levels. +fn assert_row(d: &Document, what: &str, samples: &[(i32, [i32; 3])], tol: i32) { + for &(x, want) in samples { + let got = rgb8(d, x, 100); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol), "{what} at ({x},100): {got:?}, want {want:?} ±{tol}"); + } +} + +/// A Blend If range with the black point `black` and the white point `white`, each (low, high). +fn range(black: [u8; 2], white: [u8; 2]) -> BlendRange { + BlendRange { black, white } +} + +#[test] +fn split_this_layer_white_point_fades_with_both_ends_inclusive() { + // Top's Gray is 152: alpha (160 − 152 + 1) / (160 − 140 + 1) = 9/21, not (160 − 152) / 20. + let d = band_doc(SampleType::U8, range([0, 0], [140, 160]), BlendRange::FULL); + assert_row(&d, "Current Layer Gray white 140/160", &[(62, [128, 74, 19]), (337, [236, 181, 127])], 1); +} + +#[test] +fn split_underlying_black_point_fades_from_its_low_level() { + // Over 68 (the low half itself) the layer already shows at 1/69; over 85 at 18/69. + let d = band_doc(SampleType::U8, BlendRange::FULL, range([68, 136], [255, 255])); + assert_row(&d, "Underlying Gray black 68/136", &[(112, [70, 69, 67]), (137, [129, 96, 63])], 1); +} + +#[test] +fn split_underlying_white_point_fades_to_its_high_level() { + // Over 153 the layer shows at 52/69; over 204 (the high half itself) at 1/69. + let d = band_doc(SampleType::U8, BlendRange::FULL, range([0, 0], [136, 204])); + assert_row(&d, "Underlying Gray white 136/204", &[(237, [230, 134, 38]), (312, [205, 203, 202])], 1); +} + +#[test] +fn unsplit_points_stay_hard_at_the_layers_own_level() { + let shown = [255, 128, 0]; + let hidden = [34, 34, 34]; + for (black, white, want) in [(152, 255, shown), (153, 255, hidden), (0, 152, shown), (0, 150, hidden), (0, 153, shown)] { + let d = band_doc(SampleType::U8, range([black, black], [white, white]), BlendRange::FULL); + assert_row(&d, &format!("This Layer Gray {black}/{white}"), &[(62, want)], 0); + } +} + +#[test] +fn split_points_in_deep_documents_keep_their_ramp() { + // Not measured at 16 or 32 bits: the ramp stays (v − low) / (high − low), so Top shows as at + // 40 % Opacity where 8 bits show 9/21, and not at all over the low half, where 8 bits show 1/69. + for depth in [SampleType::U16, SampleType::F32] { + for (this, under, x, alpha) in [ + (range([0, 0], [140, 160]), BlendRange::FULL, 62, 0.4), + (range([0, 0], [140, 160]), BlendRange::FULL, 337, 0.4), + (BlendRange::FULL, range([68, 136], [255, 255]), 112, 0.0), + ] { + let d = band_doc(depth, this, under); + let mut faded = band_doc(depth, BlendRange::FULL, BlendRange::FULL); + faded.layers[2].opacity = alpha; + let r = Rect::from_xywh(x, 100, 1, 1); + let (got, want) = (render(&d, r).px[0], render(&faded, r).px[0]); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-4), "{depth:?} {this:?}/{under:?} at ({x},100): {got:?}, want {want:?}"); + } + } +} diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 679a2298c0..a499f3015f 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -761,3 +761,7 @@ fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: B *b = blend::composite_gamma(mode, *b, s, opacity, gamma); } } + +#[cfg(test)] +#[path = "blend_if_split_fade_tests.rs"] +mod blend_if_split_fade_tests; From 9841d0f88606cc0e09cf7f2f2630620b9d6487c3 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:33:29 +0100 Subject: [PATCH 203/385] fix(compose): fade split Blend If points over both ends in 8-bit documents (#14855) A split Blend If slider faded as (v - low) / (high - low), so the fade started a level late and every value between the halves showed a little less of the layer than the reference application. 8-bit documents now fade as (v - low + 1) / (high - low + 1) on the black side and (high - v + 1) / (high - low + 1) on the white side, on the CPU (BlendRange::weight_8bit through blend_if_weight) and the GPU (bi_ramp, flagged per pass in p4.z). Unsplit points and 16/32-bit documents keep their behaviour. --- .../compose/src/blend_if_split_fade_tests.rs | 21 +++++++++++++++++++ crates/compose/src/composite.rs | 15 +++++++------ crates/compose/src/tests.rs | 7 ++++--- crates/doc/src/blend_if.rs | 19 +++++++++++++++-- crates/gpu/src/compose.wgsl | 6 ++++-- crates/gpu/src/plan/planner.rs | 4 +++- crates/gpu/src/plan/tests.rs | 17 +++++++++++++++ 7 files changed, 75 insertions(+), 14 deletions(-) diff --git a/crates/compose/src/blend_if_split_fade_tests.rs b/crates/compose/src/blend_if_split_fade_tests.rs index 1105867457..135f065b01 100644 --- a/crates/compose/src/blend_if_split_fade_tests.rs +++ b/crates/compose/src/blend_if_split_fade_tests.rs @@ -46,6 +46,27 @@ fn range(black: [u8; 2], white: [u8; 2]) -> BlendRange { BlendRange { black, white } } +#[test] +fn eight_bit_weight_counts_both_ends_of_a_split_point() { + // Black side (v − low + 1) / (high − low + 1): 0 only below the low half. + let black = range([68, 136], [255, 255]); + assert_eq!(black.weight_8bit(67.0), 0.0); + assert_eq!(black.weight_8bit(68.0), 1.0 / 69.0); + assert_eq!(black.weight_8bit(85.0), 18.0 / 69.0); + assert_eq!(black.weight_8bit(136.0), 1.0); + // White side (high − v + 1) / (high − low + 1): 0 only above the high half. + let white = range([0, 0], [140, 160]); + assert_eq!(white.weight_8bit(140.0), 1.0); + assert_eq!(white.weight_8bit(152.0), 9.0 / 21.0); + assert_eq!(white.weight_8bit(160.0), 1.0 / 21.0); + assert_eq!(white.weight_8bit(161.0), 0.0); + // Deep documents keep (v − low) / (high − low), and unsplit points are hard either way. + assert_eq!(white.weight(152.0), 0.4); + assert_eq!(black.weight(68.0), 0.0); + let hard = range([152, 152], [152, 152]); + assert_eq!([hard.weight_8bit(151.0), hard.weight_8bit(152.0), hard.weight_8bit(153.0)], [0.0, 1.0, 0.0]); +} + #[test] fn split_this_layer_white_point_fades_with_both_ends_inclusive() { // Top's Gray is 152: alpha (160 − 152 + 1) / (160 − 140 + 1) = 9/21, not (160 − 152) / 20. diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index a499f3015f..4d46f92d73 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -144,25 +144,28 @@ pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool /// How much of a pixel shows through `layer`'s Blend If ranges, given the layer's own colour /// (`this`, `None` where the layer has no content of its own there) and the colour beneath it /// (`under`, `None` where nothing is beneath). Every range multiplies in. -fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { +fn blend_if_weight(layer: &Layer, cx: &Ctx, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { use photocraft_color::ColorMode as M; let bi = &layer.blend_if; + // 8-bit documents fade split points over both ends (#14855); deeper ones keep the plain ramp. + let levels = cx.depth == photocraft_color::SampleType::U8; + let w = |r: photocraft_doc::BlendRange, v: f32| if levels { r.weight_8bit(v) } else { r.weight(v) }; let mut k = 1.0; for (side, px) in [this, under].into_iter().enumerate() { let Some(p) = px else { continue }; let v = |c: usize| blend_if_level(p[c]); - match mode { + match cx.mode { // Gray, then R, G, B. M::Rgb => { let gray = blend_if_gray(v(0), v(1), v(2)); - k *= bi.get(0)[side].weight(gray); + k *= w(bi.get(0)[side], gray); for c in 0..3 { - k *= bi.get(c + 1)[side].weight(v(c)); + k *= w(bi.get(c + 1)[side], v(c)); } } // One channel: the PSD spec marks the composite-gray entry irrelevant here, so the // channel's own entry carries the setting; both are honoured. - _ => k *= bi.get(0)[side].weight(v(0)) * bi.get(1)[side].weight(v(0)), + _ => k *= w(bi.get(0)[side], v(0)) * w(bi.get(1)[side], v(0)), } if k <= 0.0 { return 0.0; @@ -234,7 +237,7 @@ fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { None => Some(*p), }; let under = Some(*b).filter(|q| q[3] > 0.0); - let k = blend_if_weight(layer, cx.mode, this, under); + let k = blend_if_weight(layer, cx, this, under); if k >= 1.0 { continue; } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0018d22093..d21c946c77 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2906,15 +2906,16 @@ fn blend_if_gray_follows_photoshops_weights_and_rounding() { #[test] fn blend_if_split_point_fades_like_opacity() { - // A split black point (Alt-drag) at 50/150 shows a value-100 layer at half strength, which - // is exactly the layer at 50% opacity, also over a semi-transparent backdrop. + // A split black point (Alt-drag) at 50/150 shows a value-100 layer at (100 − 50 + 1) / + // (150 − 50 + 1) in an 8-bit document (#14855), which is exactly the layer at that opacity, + // also over a semi-transparent backdrop. let v = 100.0 / 255.0; let mut d = doc_white(4, 4); d.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.2, 1.0, 0.5]); let mut l = solid_layer("v", Rect::new(0, 0, 4, 4), [v, v, v, 1.0]); l.blend = BlendMode::Multiply; let mut half = l.clone(); - half.opacity = 0.5; + half.opacity = 51.0 / 101.0; l.blend_if.set(0, [range([50, 150], [255, 255]), FULL]); let mut d2 = d.clone(); d.layers.push(l); diff --git a/crates/doc/src/blend_if.rs b/crates/doc/src/blend_if.rs index 0c6ee40ba9..ce7c279e9f 100644 --- a/crates/doc/src/blend_if.rs +++ b/crates/doc/src/blend_if.rs @@ -45,10 +45,25 @@ impl BlendRange { /// a split point. An unsplit black point at `b` shows `v >= b`; an unsplit white point at `w` /// shows `v <= w`. pub fn weight(&self, v: f32) -> f32 { + self.weight_at(v, false) + } + + /// [`BlendRange::weight`] in an 8-bit document, where a split point counts both of its ends: + /// the black side shows `(v − low + 1) / (high − low + 1)` and the white side + /// `(high − v + 1) / (high − low + 1)`, as measured in the reference application (#14855): + /// Gray 152 under a white point at 140/160 shows at 9/21, a value on the black point's low half + /// already at 1 / (high − low + 1). Unsplit points stay hard. + pub fn weight_8bit(&self, v: f32) -> f32 { + self.weight_at(v, true) + } + + /// [`BlendRange::weight`], or [`BlendRange::weight_8bit`] when `levels`. + fn weight_at(&self, v: f32, levels: bool) -> f32 { let ramp = |lo: u8, hi: u8, x: f32| -> f32 { - // 0 at or below `lo`, 1 at or above `hi`. + // 0 at or below `lo` (below it on 8-bit levels), 1 at or above `hi`. let (lo, hi) = (f32::from(lo), f32::from(hi)); - if hi <= lo { if x >= lo { 1.0 } else { 0.0 } } else { ((x - lo) / (hi - lo)).clamp(0.0, 1.0) } + let lo_end = if levels { lo - 1.0 } else { lo }; + if hi <= lo { if x >= lo { 1.0 } else { 0.0 } } else { ((x - lo_end) / (hi - lo_end)).clamp(0.0, 1.0) } }; let lo = ramp(self.black[0], self.black[1], v); // Mirror for the white point: 1 at or below its low half, 0 above its high half. diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index e24605d9fd..4472a74cf5 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1059,12 +1059,14 @@ fn fs_lerp(in: VOut) -> @location(0) vec4 { // ---- Blend If (photocraft_doc::BlendRange, compose::blend_if_weight) --------------------------- -// 0 at or below `lo`, 1 at or above `hi`; a hard step at `lo` when unsplit. +// 0 at or below `lo`, 1 at or above `hi`; a hard step at `lo` when unsplit. In an 8-bit +// document (`p4.z`) a split ramp counts both ends, 0 only below `lo` (BlendRange::weight_8bit). fn bi_ramp(lo: f32, hi: f32, x: f32) -> f32 { if (hi <= lo) { return select(0.0, 1.0, x >= lo); } - return clamp((x - lo) / (hi - lo), 0.0, 1.0); + let lo_end = select(lo, lo - 1.0, op.p4.z > 0.5); + return clamp((x - lo_end) / (hi - lo_end), 0.0, 1.0); } // How much of value `v` (0..255) shows through range `e` (0 = Gray, then the channels) on side diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 3fe3cee6c9..2488f96e9f 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -320,7 +320,9 @@ impl<'a> Planner<'a> { p.flags = F_BLEND_IF; p.params = blend_if_params(&layer.blend_if); let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; - p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), 0.0, 0.0]; + // compose::blend_if_weight: split points fade over both ends in 8-bit documents (#14855). + let levels = self.cx.depth == photocraft_color::SampleType::U8; + p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), f32::from(u8::from(levels)), 0.0]; Ok(self.emit(p)) } diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index c563fb289f..2c0dc06d00 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -336,6 +336,23 @@ fn blend_if_plans_on_the_gpu() { assert_eq!(blend_if(&d), 0); } +/// #14855: the Blend If pass marks 8-bit documents in `p4.z`, where `compose.wgsl`'s `bi_ramp` +/// fades a split point over both ends as `BlendRange::weight_8bit` does; deeper documents keep the +/// plain ramp. +#[test] +fn blend_if_marks_eight_bit_documents_for_the_split_fade() { + for (depth, levels) in [(SampleType::U8, 1.0), (SampleType::U16, 0.0), (SampleType::F32, 0.0)] { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, depth, Color::WHITE); + let mut l = Layer::raster("bi", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 90], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); + d.layers.push(l); + let plan = plan(&d).unwrap(); + let pass = plan.passes.iter().find(|p| p.flags & F_BLEND_IF != 0).expect("a Blend If pass"); + assert_eq!(pass.extra[2], levels, "{depth:?}"); + } +} + #[test] fn blend_if_params_pack_every_range_exactly() { let mut bi = photocraft_doc::BlendIf::default(); 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 204/385] 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 0acff4c7f20e0e21ca6890019fdb2cfb932303e9 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:53:38 +0100 Subject: [PATCH 205/385] fix(compose): keep the plain Blend If ramp outside RGB documents Only 8-bit RGB was measured for #14855; Grayscale and Duotone keep today's split fade on the CPU and the GPU. --- crates/compose/src/blend_if_split_fade_tests.rs | 13 +++++++++++++ crates/compose/src/composite.rs | 5 +++-- crates/gpu/src/compose.wgsl | 2 +- crates/gpu/src/plan/planner.rs | 4 ++-- crates/gpu/src/plan/tests.rs | 17 +++++++++++------ 5 files changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/blend_if_split_fade_tests.rs b/crates/compose/src/blend_if_split_fade_tests.rs index 135f065b01..53f77de11b 100644 --- a/crates/compose/src/blend_if_split_fade_tests.rs +++ b/crates/compose/src/blend_if_split_fade_tests.rs @@ -117,3 +117,16 @@ fn split_points_in_deep_documents_keep_their_ramp() { } } } + +#[test] +fn split_points_in_grayscale_documents_keep_their_ramp() { + // Only RGB was measured: a Grayscale value of 128 under a split black point at 128/129 stays + // hidden, where an RGB document would show it at 1/2. + let mut d = Document::with_background("g", Size::new(1, 1), ColorMode::Grayscale, SampleType::U8, photocraft_color::Color::WHITE); + let mut l = Layer::raster("k", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[128.0 / 255.0, 1.0]); + l.blend_if.set(1, [range([128, 129], [255, 255]), BlendRange::FULL]); + d.layers.push(l); + let p = render(&d, Rect::from_xywh(0, 0, 1, 1)).px[0]; + assert!(p[..3].iter().all(|&c| c > 0.999), "{p:?}"); +} diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 4d46f92d73..257c9789ef 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -147,8 +147,9 @@ pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool fn blend_if_weight(layer: &Layer, cx: &Ctx, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { use photocraft_color::ColorMode as M; let bi = &layer.blend_if; - // 8-bit documents fade split points over both ends (#14855); deeper ones keep the plain ramp. - let levels = cx.depth == photocraft_color::SampleType::U8; + // 8-bit RGB documents fade split points over both ends (#14855); deeper documents and the + // one-channel modes (not measured) keep the plain ramp. + let levels = cx.depth == photocraft_color::SampleType::U8 && cx.mode == M::Rgb; let w = |r: photocraft_doc::BlendRange, v: f32| if levels { r.weight_8bit(v) } else { r.weight(v) }; let mut k = 1.0; for (side, px) in [this, under].into_iter().enumerate() { diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 4472a74cf5..6ceafe3940 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1060,7 +1060,7 @@ fn fs_lerp(in: VOut) -> @location(0) vec4 { // ---- Blend If (photocraft_doc::BlendRange, compose::blend_if_weight) --------------------------- // 0 at or below `lo`, 1 at or above `hi`; a hard step at `lo` when unsplit. In an 8-bit -// document (`p4.z`) a split ramp counts both ends, 0 only below `lo` (BlendRange::weight_8bit). +// RGB document (`p4.z`) a split ramp counts both ends, 0 only below `lo` (BlendRange::weight_8bit). fn bi_ramp(lo: f32, hi: f32, x: f32) -> f32 { if (hi <= lo) { return select(0.0, 1.0, x >= lo); diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 2488f96e9f..132cd3ecce 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -320,8 +320,8 @@ impl<'a> Planner<'a> { p.flags = F_BLEND_IF; p.params = blend_if_params(&layer.blend_if); let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; - // compose::blend_if_weight: split points fade over both ends in 8-bit documents (#14855). - let levels = self.cx.depth == photocraft_color::SampleType::U8; + // compose::blend_if_weight: split points fade over both ends in 8-bit RGB documents (#14855). + let levels = self.cx.depth == photocraft_color::SampleType::U8 && !one_channel; p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), f32::from(u8::from(levels)), 0.0]; Ok(self.emit(p)) } diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index 2c0dc06d00..4fcff58ded 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -336,20 +336,25 @@ fn blend_if_plans_on_the_gpu() { assert_eq!(blend_if(&d), 0); } -/// #14855: the Blend If pass marks 8-bit documents in `p4.z`, where `compose.wgsl`'s `bi_ramp` -/// fades a split point over both ends as `BlendRange::weight_8bit` does; deeper documents keep the -/// plain ramp. +/// #14855: the Blend If pass marks 8-bit RGB documents in `p4.z`, where `compose.wgsl`'s `bi_ramp` +/// fades a split point over both ends as `BlendRange::weight_8bit` does; deeper documents and +/// Grayscale keep the plain ramp. #[test] fn blend_if_marks_eight_bit_documents_for_the_split_fade() { - for (depth, levels) in [(SampleType::U8, 1.0), (SampleType::U16, 0.0), (SampleType::F32, 0.0)] { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, depth, Color::WHITE); + for (mode, depth, levels) in [ + (ColorMode::Rgb, SampleType::U8, 1.0), + (ColorMode::Rgb, SampleType::U16, 0.0), + (ColorMode::Rgb, SampleType::F32, 0.0), + (ColorMode::Grayscale, SampleType::U8, 0.0), + ] { + let mut d = Document::with_background("t", Size::new(8, 8), mode, depth, Color::WHITE); let mut l = Layer::raster("bi", d.pixel_format()); l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 90], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); d.layers.push(l); let plan = plan(&d).unwrap(); let pass = plan.passes.iter().find(|p| p.flags & F_BLEND_IF != 0).expect("a Blend If pass"); - assert_eq!(pass.extra[2], levels, "{depth:?}"); + assert_eq!(pass.extra[2], levels, "{mode:?} {depth:?}"); } } From afda36f2b5b294d71dd5b054659e820627a9defd Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 17 Nov 2026 15:26:44 +0530 Subject: [PATCH 206/385] Re-run CI: unrelated Windows timing failure in raster scratch_slow_folder From a156c153c601ff100e26797b8da9d69f933a1398 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Tue, 17 Nov 2026 15:27:32 +0530 Subject: [PATCH 207/385] Pen live shape layer: keep anchors the layer refused; keep a fill set by hand on close Undo with anchors the layer refused takes those back without undoing the last anchor it took. An edit elsewhere in the document keeps them in the draft. Closing a carried-on open shape replaces only a fill that is still the options bar's, not one set by hand. --- crates/ui-egui/src/tools/vector_ui/pen.rs | 43 ++++++++++-- .../vector_ui/pen_shape_first_click_tests.rs | 65 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/shapes.rs | 2 +- 3 files changed, 105 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index 36a57014b4..11b821d878 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -299,6 +299,12 @@ fn sync_live_layer_from_draft(app: &mut PhotocraftApp) { /// Edit › Undo while a live shape layer is being drawn takes back its last History step, which /// is its last anchor (or the layer itself with the first), and the draft follows (#12909). fn undo_live_step(app: &mut PhotocraftApp) -> bool { + // Anchors the layer refused are the draft's alone: Undo takes those back first, without + // undoing the last anchor the layer did take. + if live_anchors_pending(app) { + rebuild_live_draft(app); + return true; + } if let Err(e) = run_beside_draft(app, "edit.undo", json!({})) { app.ui.status = e; app.ui.status_error = true; @@ -307,8 +313,23 @@ fn undo_live_step(app: &mut PhotocraftApp) -> bool { true } +/// The layer's subpath a live draft carries, in the active document. +fn live_subpath<'a>(doc: &'a Document, pen: &PenPath) -> Option<&'a photocraft_doc::vector::Subpath> { + let r = pen.resumes.as_ref()?; + resumed_path(doc, r)?.subpaths.get(r.index) +} + +/// Does the live draft have anchors its layer has not taken (a refused `shape.edit`), while the +/// layer is still as the draft last left it? +fn live_anchors_pending(app: &PhotocraftApp) -> bool { + let (Some(pen), Some(st)) = (app.ui.pen.as_ref().filter(|p| p.live_layer), app.session.active()) else { return false }; + live_subpath(&st.doc, pen).is_some_and(|sub| pen.resumes.as_ref().is_some_and(|r| *sub == r.was) && !subpath_is(sub, &pen_to_json(pen, false))) +} + /// A live draft whose document moved on (Undo, Redo, the History panel…) is rebuilt from its -/// layer's open subpath, or dropped when the layer or the subpath is gone or closed (#12909). +/// layer's open subpath, or dropped when the layer or the subpath is gone or closed (#12909). When +/// the layer's subpath is as the draft last left it (an edit elsewhere in the document), the draft +/// keeps its anchors, including any the layer refused, and only follows the new document state. pub(super) fn sync_live_draft_from_layer(app: &mut PhotocraftApp) { let Some(pen) = app.ui.pen.as_ref().filter(|p| p.live_layer && !p.commit_failed) else { return }; let (Some(owner), Some(r)) = (pen.owner.as_ref(), pen.resumes.as_ref()) else { return }; @@ -316,6 +337,19 @@ pub(super) fn sync_live_draft_from_layer(app: &mut PhotocraftApp) { if st.doc.id != owner.document || owner.valid(app) { return; } + if live_subpath(&st.doc, pen).is_some_and(|sub| !sub.closed && *sub == r.was) { + follow_live_layer(app); + return; + } + rebuild_live_draft(app); +} + +/// Rebuild the live draft from its layer's open subpath, or drop it when the layer or the +/// subpath is gone, closed or empty. +fn rebuild_live_draft(app: &mut PhotocraftApp) { + let Some(pen) = app.ui.pen.as_ref().filter(|p| p.live_layer) else { return }; + let (Some(owner), Some(r)) = (pen.owner.as_ref(), pen.resumes.as_ref()) else { return }; + let Some(st) = app.session.active() else { return }; let sub = resumed_path(&st.doc, r).and_then(|p| p.subpaths.get(r.index)).filter(|s| !s.closed && !s.knots.is_empty()); let rebuilt = sub.map(|s| { let mut draft = resumed(r.doc, "layer".into(), r.layer, r.index, s, false); @@ -831,9 +865,10 @@ fn commit_resumed_on_layer(app: &mut PhotocraftApp, pen: &PenPath, path: &Value, } let mut params = json!({"layer": id, "path": p}); // Closing a shape made of open paths gives it the options bar's fill and stroke, as drawing it - // closed would have. A live layer has a fill already (#12909), so it counts by its draft and - // a shape made of open paths whatever its fill: the stroke was the open path's. - if closed && (pen.live_layer || sh.path.subpaths.iter().all(|s| !s.closed)) { + // closed would have. A Pen shape has its fill from the first click (#12909), so besides one + // with no fill this counts one whose fill is still the options bar's; a fill set by hand stays. + let pen_paint = sh.fill.is_none() || (app.ui.tool_options.shape_fill && sh.fill.as_ref() == Some(&super::shapes::tool_paint(app, false))); + if closed && (pen.live_layer || (pen_paint && sh.path.subpaths.iter().all(|s| !s.closed))) { params["fill"] = fill_param(app); params["stroke"] = stroke_param(app); } diff --git a/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs index bafade6965..2671c4a97f 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_shape_first_click_tests.rs @@ -237,3 +237,68 @@ fn a_path_carried_on_from_its_endpoint_stays_one_step() { assert_eq!(subpaths(&shapes(&app)[0].1)[0].1.len(), 3); assert_eq!(steps(&app), before + 1); } + +/// Refuse `shape.edit`, so the next anchor stays the draft's alone. +fn refuse_edits(app: &mut PhotocraftApp) { + app.session.authorize = Some(|id, _| if id == "shape.edit" { Err(photocraft_engine::EngineError::Other("refused edit fixture".into())) } else { Ok(()) }); +} + +#[test] +fn undo_takes_back_an_anchor_the_layer_refused_before_any_document_step() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + refuse_edits(&mut app); + click(&mut app, 700.0, 300.0); + assert_eq!(draft_len(&app), Some(3), "the refused anchor stays in the draft"); + app.session.authorize = None; + let before = steps(&app); + menu(&mut app, "edit.undo"); + assert_eq!(draft_len(&app), Some(2), "only the refused anchor is taken back"); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0], [700.0, 100.0]])], "the layer keeps the anchors it took"); + assert_eq!(steps(&app), before, "no document step is undone"); + menu(&mut app, "edit.undo"); + assert_eq!(draft_len(&app), Some(1)); + assert_eq!(subpaths(&shapes(&app)[0].1), [(false, vec![[500.0, 100.0]])]); +} + +#[test] +fn an_edit_elsewhere_keeps_the_anchors_the_layer_has_not_taken() { + let mut app = app(); + let below = app.session.active().unwrap().active_layer.unwrap().0; + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + refuse_edits(&mut app); + click(&mut app, 700.0, 300.0); + app.session.authorize = None; + app.run("layer.setProps", json!({"layer": below, "opacity": 0.5})).unwrap(); + crate::vector_ui::cancel_stale(&mut app); + assert_eq!(draft_len(&app), Some(3), "the pending anchor is kept"); + // The next anchor takes the pending one into the layer with it. + click(&mut app, 500.0, 300.0); + assert_eq!(subpaths(&shapes(&app)[0].1)[0].1.len(), 4); +} + +#[test] +fn closing_a_carried_on_open_shape_keeps_a_fill_set_by_hand() { + let mut app = app(); + click(&mut app, 500.0, 100.0); + click(&mut app, 700.0, 100.0); + click(&mut app, 700.0, 300.0); + pen_enter(&mut app); + let id = app.session.active().unwrap().active_layer.unwrap().0; + let options_fill = shapes(&app)[0].1.fill.clone(); + let mut path = None; + if let LayerContent::Shape(sh) = &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + path = Some(photocraft_engine::vector_cmds::path_json(&sh.path)); + } + app.run("shape.edit", json!({"layer": id, "path": path.unwrap(), "fill": [0.25, 0.5, 0.75, 1.0]})).unwrap(); + let own = shapes(&app)[0].1.fill.clone(); + assert!(own.is_some() && own != options_fill, "the layer has a fill of its own"); + click(&mut app, 700.0, 300.0); // its last anchor: carry on + click(&mut app, 500.0, 300.0); + click(&mut app, 500.0, 100.0); // its first anchor: close + let sh = &shapes(&app)[0].1; + assert!(sh.path.subpaths[0].closed); + assert_eq!(sh.fill, own, "a fill set by hand is not replaced by the options bar's"); +} diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 3e44cd5a10..a727ed4e01 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -42,7 +42,7 @@ pub(super) fn open_pen_stroke_param(app: &PhotocraftApp) -> Value { /// The paint the next shape's fill (`stroke` false) or stroke takes: the options bar's gradient, /// else the foreground / background colour. -fn tool_paint(app: &PhotocraftApp, stroke: bool) -> photocraft_doc::Fill { +pub(super) fn tool_paint(app: &PhotocraftApp, stroke: bool) -> photocraft_doc::Fill { let (gradient, color) = tool_paint_source(app, stroke); gradient.clone().unwrap_or_else(|| solid_paint(color)) } From e9796f05908c71542245f3ceaf1860bfeda64d92 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 17 Nov 2026 21:30:25 +0100 Subject: [PATCH 208/385] 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 209/385] 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 210/385] 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 211/385] 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 212/385] 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 213/385] 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 214/385] 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 215/385] 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 a1b0806ba69c41b241e0210d574c39fa6d9e3168 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:19:35 +0300 Subject: [PATCH 216/385] Check Spelling: enabled in any open document, also one without type layers (#14172) With no type layer, choosing it from the menu opens no dialog, shows no message and adds no history state; with no document open it stays greyed. --- crates/engine/src/cmd/type_spell_cmds.rs | 12 ++++-------- crates/ui-egui/src/panels/type_panels_ui.rs | 4 ++++ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs index dd2ff4e2d4..0796fc9068 100644 --- a/crates/engine/src/cmd/type_spell_cmds.rs +++ b/crates/engine/src/cmd/type_spell_cmds.rs @@ -59,11 +59,6 @@ fn type_layers(doc: &Document) -> Vec { doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect() } -fn has_type(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } -} - fn text(doc: &Document, id: LayerId) -> Option<&str> { match &doc.layer(id)?.content { LayerContent::Text(t) => Some(&t.text), @@ -284,7 +279,8 @@ pub fn specs() -> Vec { menu: &["Edit"], shortcut: None, params: r#"{"action":"list|change|changeAll|addToDictionary|removeFromDictionary|suggest"="list","allLayers":bool=true,"layer":id|name? (check one layer),"ignore":[word]? (Ignore All for this check),"suggestions":n=5; change: "layer"? (default: the active layer),"start","end" (chars),"word"? (verified),"replace"; changeAll: "word","replace"; addToDictionary/removeFromDictionary/suggest: "word"} → list: {"misspellings":[{"layer","start","end","word","suggestions"}],"count"} (an action records only a call without "action", as {"allLayers"} with its dialog on)"#, - enabled: has_type, + // Any open document, also one without type layers, where it lists nothing. + enabled: crate::commands::has_doc, journal: true, run: check_spelling, }, @@ -468,11 +464,11 @@ mod tests { } #[test] - fn disabled_without_type() { + fn enabled_only_with_a_document() { let mut s = Session::new(); assert!(!s.is_enabled("edit.checkSpelling")); s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - assert!(!s.is_enabled("edit.checkSpelling")); + assert!(s.is_enabled("edit.checkSpelling")); assert!(!s.is_enabled("type.insertText")); } diff --git a/crates/ui-egui/src/panels/type_panels_ui.rs b/crates/ui-egui/src/panels/type_panels_ui.rs index 4098f5719c..a09c24b085 100644 --- a/crates/ui-egui/src/panels/type_panels_ui.rs +++ b/crates/ui-egui/src/panels/type_panels_ui.rs @@ -47,6 +47,10 @@ pub struct TypePanelsUi { /// `panel_docking::command`. pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option> { if id == "edit.checkSpelling" && params.get("action").is_none() && params.get("ui").is_none_or(|u| u.as_bool() != Some(false)) { + // A document without any type layer opens no dialog and shows nothing, as in the reference (#14172). + if app.session.active().is_some_and(|st| !photocraft_engine::type_extra_cmds::has_type_layers(&st.doc)) { + return Some(app.session.execute("edit.checkSpelling", json!({"action": "list"})).map_err(|e| e.to_string())); + } return Some(open_spelling(app, params.get("allLayers").and_then(Value::as_bool).unwrap_or(true))); } let paragraph = match id { From ee791836d1e55bc53d1634cc9734ab0f39e4b2a5 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:19:35 +0300 Subject: [PATCH 217/385] Check Spelling: tests for its enabled state without type layers --- crates/engine/src/cmd/type_spell_cmds.rs | 4 ++ .../src/cmd/type_spell_enabled_tests.rs | 67 +++++++++++++++++++ crates/ui-egui/src/panels/type_panels_ui.rs | 4 ++ .../src/panels/type_spell_enabled_ui_tests.rs | 65 ++++++++++++++++++ 4 files changed, 140 insertions(+) create mode 100644 crates/engine/src/cmd/type_spell_enabled_tests.rs create mode 100644 crates/ui-egui/src/panels/type_spell_enabled_ui_tests.rs diff --git a/crates/engine/src/cmd/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs index 0796fc9068..e19e1a5de2 100644 --- a/crates/engine/src/cmd/type_spell_cmds.rs +++ b/crates/engine/src/cmd/type_spell_cmds.rs @@ -494,3 +494,7 @@ mod tests { assert_eq!(s.execute("type.caret", json!({"layer": id, "index": inserted["caret"]})).unwrap()["index"], inserted["caret"]); } } + +#[cfg(test)] +#[path = "type_spell_enabled_tests.rs"] +mod enabled_tests; diff --git a/crates/engine/src/cmd/type_spell_enabled_tests.rs b/crates/engine/src/cmd/type_spell_enabled_tests.rs new file mode 100644 index 0000000000..d1b5c15138 --- /dev/null +++ b/crates/engine/src/cmd/type_spell_enabled_tests.rs @@ -0,0 +1,67 @@ +//! #14172: Edit > Check Spelling is enabled in any open document, also one without type layers, +//! where it finds nothing and adds no history state; with no document open it stays greyed. +//! `type.insertText` keeps needing an active type layer. + +use serde_json::json; + +use crate::Session; + +pub(super) const CMD: &str = "edit.checkSpelling"; + +/// A white document with only its Background, as File > New makes one. +pub(super) fn blank() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 500, "background": "white"})).unwrap(); + s +} + +pub(super) fn history(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + +#[test] +fn greyed_without_a_document() { + let s = Session::new(); + assert!(!s.is_enabled(CMD)); + assert_eq!(s.disabled_reason(CMD).as_deref(), Some("no document open")); +} + +#[test] +fn enabled_in_a_document_without_type_layers() { + let mut s = blank(); + assert!(s.is_enabled(CMD), "{:?}", s.disabled_reason(CMD)); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + assert!(s.is_enabled(CMD), "an empty pixel layer on top keeps it enabled"); + assert!(!s.is_enabled("type.insertText"), "Insert Glyph still needs an active type layer"); +} + +#[test] +fn listing_a_document_without_type_layers_finds_nothing_and_adds_no_history() { + let mut s = blank(); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + let before = history(&s); + for params in [json!({"action": "list"}), json!({})] { + assert_eq!(s.execute(CMD, params.clone()).unwrap(), json!({"misspellings": [], "count": 0}), "{params}"); + } + assert_eq!(history(&s), before); +} + +#[test] +fn enabled_with_type_layers_as_before() { + let mut s = blank(); + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Teh end", "size": 12})).unwrap(); + assert!(s.is_enabled(CMD)); + assert!(s.is_enabled("type.insertText")); + assert_eq!(s.execute(CMD, json!({"action": "list"})).unwrap()["count"], 1); +} + +/// Lock All on the only type layer: greyed on main, now enabled, and it lists nothing since a +/// fully locked layer is not checked (its prompt is #14175). +#[test] +fn enabled_with_only_a_lock_all_type_layer_and_lists_nothing() { + let mut s = blank(); + let id = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Teh end", "size": 12})).unwrap()["layer"].clone(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + assert!(s.is_enabled(CMD), "{:?}", s.disabled_reason(CMD)); + assert_eq!(s.execute(CMD, json!({"action": "list"})).unwrap()["count"], 0); +} diff --git a/crates/ui-egui/src/panels/type_panels_ui.rs b/crates/ui-egui/src/panels/type_panels_ui.rs index a09c24b085..518c70ee7e 100644 --- a/crates/ui-egui/src/panels/type_panels_ui.rs +++ b/crates/ui-egui/src/panels/type_panels_ui.rs @@ -84,3 +84,7 @@ fn target(app: &PhotocraftApp) -> Value { } json!({}) } + +#[cfg(test)] +#[path = "type_spell_enabled_ui_tests.rs"] +mod spell_enabled_ui_tests; diff --git a/crates/ui-egui/src/panels/type_spell_enabled_ui_tests.rs b/crates/ui-egui/src/panels/type_spell_enabled_ui_tests.rs new file mode 100644 index 0000000000..0f52f18c52 --- /dev/null +++ b/crates/ui-egui/src/panels/type_spell_enabled_ui_tests.rs @@ -0,0 +1,65 @@ +//! #14172: Edit > Check Spelling... chosen from the menu in a document without type layers is +//! enabled and opens nothing: no dialog, no message, no history state. With no document open the +//! item is greyed. + +use craft::text::ui::spelling::CheckSpellingDialog; +use serde_json::json; + +use crate::PhotocraftApp; + +/// An app with `doc` open (or none): a white 800 x 500 document with an empty layer on top. +pub(super) fn app(doc: bool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + if doc { + app.run("file.new", json!({"width": 800, "height": 500, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Empty"})).unwrap(); + } + app.sync_views(); + app +} + +/// Whether Edit > Check Spelling... is enabled in the menu. +pub(super) fn enabled(app: &PhotocraftApp) -> bool { + crate::menus::is_enabled(app, "edit.checkSpelling") +} + +/// Chooses Edit > Check Spelling... as the menu does. +pub(super) fn choose(app: &mut PhotocraftApp) -> Result { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, "edit.checkSpelling", json!({})) +} + +fn history(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +#[test] +fn check_spelling_without_type_layers_is_enabled_and_opens_nothing() { + let mut app = app(true); + let before = history(&app); + assert!(enabled(&app), "Check Spelling... is enabled without type layers"); + choose(&mut app).unwrap(); + assert!(app.ui.type_panels.spell.is_none(), "no Check Spelling dialog"); + assert!(app.framework.dialogs.is_empty(), "no dialog at all"); + assert!(app.ui.status.is_empty() && !app.ui.status_error, "no message: {:?}", app.ui.status); + assert_eq!(history(&app), before, "no history state"); +} + +#[test] +fn check_spelling_is_greyed_without_a_document() { + assert!(!enabled(&app(false))); +} + +/// Lock All on the only type layer is not measured: the menu keeps today's dialog, which opens +/// with nothing listed (the hidden and locked layer prompts are #14175). +#[test] +fn check_spelling_with_only_a_lock_all_type_layer_opens_an_empty_dialog() { + let mut app = app(true); + let id = app.run("type.create", json!({"x": 10, "y": 60, "text": "Teh end"})).unwrap()["layer"].clone(); + app.run("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + assert!(enabled(&app), "Check Spelling... is enabled"); + choose(&mut app).unwrap(); + assert!(app.ui.type_panels.spell.is_some(), "the Check Spelling dialog opens"); + let dialog = app.framework.dialogs.get::().expect("the hosted dialog"); + assert!(dialog.items().is_empty(), "with nothing listed: {:?}", dialog.items()); +} From 3d16bfb6b175b4994b588d63feed16298861e043 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:36:44 +0300 Subject: [PATCH 218/385] Check Spelling: start at the active layer, go up the stack and wrap (#14174) With Check All Layers on, the type layers are checked from the active one upward, then from the bottom-most type layer up to just below it, instead of always from the top. A non-type active layer keeps the top-to-bottom order. The dialog passes the layer it was opened on as `from`, so a Change that refreshes the list keeps the same start after another layer became active. --- crates/engine/src/cmd/type_spell_cmds.rs | 29 ++++++++++++++----- .../src/panels/type_panels_ui/spelling.rs | 7 +++-- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs index e19e1a5de2..a2c591e1ff 100644 --- a/crates/engine/src/cmd/type_spell_cmds.rs +++ b/crates/engine/src/cmd/type_spell_cmds.rs @@ -54,9 +54,17 @@ fn char_offsets(text: &str, offsets: &[usize]) -> Vec { result } -/// Type layers top to bottom (Layers panel order), skipping fully locked ones. -fn type_layers(doc: &Document) -> Vec { - doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect() +/// Type layers in checking order, skipping fully locked ones: from the type layer `start` up the +/// stack, then from the bottom up to just below it, as the reference does (#14174). Without a +/// type layer to start at, top to bottom (Layers panel order). +fn type_layers(doc: &Document, start: Option) -> Vec { + let mut layers: Vec<(LayerId, bool)> = + doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(p, _, l)| (l.id, doc.locks_at(&p).all)).collect(); + match start.and_then(|id| layers.iter().position(|(l, _)| *l == id)) { + Some(i) => layers.rotate_left(i), + None => layers.reverse(), + } + layers.into_iter().filter(|(_, locked)| !locked).map(|(id, _)| id).collect() } fn text(doc: &Document, id: LayerId) -> Option<&str> { @@ -77,13 +85,18 @@ fn accepted(s: &Session, p: &Value) -> HashSet { fn layers_param(s: &Session, p: &Value) -> Result> { let st = s.active().ok_or(EngineError::NoDocument)?; - let all = type_layers(&st.doc); if p.get("allLayers").and_then(Value::as_bool) == Some(false) || p.get("layer").is_some() { let active = layer_param(s, p)?; - Ok(all.into_iter().filter(|id| *id == active).collect()) - } else { - Ok(all) + return Ok(type_layers(&st.doc, None).into_iter().filter(|id| *id == active).collect()); } + // The dialog passes the layer it was opened on (null without one), which stays the start when + // the active layer changes. + let start = match p.get("from") { + None => st.active_layer, + Some(Value::Null) => None, + Some(v) => Some(v.as_u64().map(LayerId).ok_or_else(|| bad("edit.checkSpelling", "`from` must be a layer id"))?), + }; + Ok(type_layers(&st.doc, start)) } fn list(s: &Session, p: &Value) -> Result { @@ -278,7 +291,7 @@ pub fn specs() -> Vec { label: "Check Spelling…", menu: &["Edit"], shortcut: None, - params: r#"{"action":"list|change|changeAll|addToDictionary|removeFromDictionary|suggest"="list","allLayers":bool=true,"layer":id|name? (check one layer),"ignore":[word]? (Ignore All for this check),"suggestions":n=5; change: "layer"? (default: the active layer),"start","end" (chars),"word"? (verified),"replace"; changeAll: "word","replace"; addToDictionary/removeFromDictionary/suggest: "word"} → list: {"misspellings":[{"layer","start","end","word","suggestions"}],"count"} (an action records only a call without "action", as {"allLayers"} with its dialog on)"#, + params: r#"{"action":"list|change|changeAll|addToDictionary|removeFromDictionary|suggest"="list","allLayers":bool=true,"layer":id|name? (check one layer),"from":id|null? (all layers: start at this type layer, go up and wrap; default: the active layer; null, or a `from` that is not a type layer: top to bottom),"ignore":[word]? (Ignore All for this check),"suggestions":n=5; change: "layer"? (default: the active layer),"start","end" (chars),"word"? (verified),"replace"; changeAll: "word","replace"; addToDictionary/removeFromDictionary/suggest: "word"} → list: {"misspellings":[{"layer","start","end","word","suggestions"}],"count"} (an action records only a call without "action", as {"allLayers"} with its dialog on)"#, // Any open document, also one without type layers, where it lists nothing. enabled: crate::commands::has_doc, journal: true, diff --git a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs index 93cfb0f8f7..d53a9af7fb 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs @@ -31,10 +31,13 @@ pub struct SpellDialog { } /// The engine's misspellings, as the raw JSON items of `edit.checkSpelling`. A single-layer check without a layer -/// lists nothing: an absent opening layer must not adopt the newly active one. +/// lists nothing: an absent opening layer must not adopt the newly active one. Check All Layers starts at the opening +/// layer, or top to bottom (null) without one (#14174). fn list(app: &mut PhotocraftApp, all_layers: bool, layer: Option, ignore: &[String]) -> Vec { let mut p = json!({ "action": "list", "allLayers": all_layers, "ignore": ignore, "suggestions": 8 }); - if !all_layers { + if all_layers { + p["from"] = json!(layer.map(|l| l.0)); + } else { let Some(layer) = layer else { return Vec::new() }; p["layer"] = json!(layer.0); } 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 219/385] 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 20969bbdb0eaa781462d6b06da9d7f1cf9a24609 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 10:31:21 -0800 Subject: [PATCH 220/385] test: apply bounded CI formatting repair for PR15101 --- .../src/color_replacement_digit_keys_tests.rs | 13 ++++++++++++- crates/ui-egui/src/lib.rs | 4 ++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs index b3c08bfd77..3f359c4392 100644 --- a/crates/ui-egui/src/color_replacement_digit_keys_tests.rs +++ b/crates/ui-egui/src/color_replacement_digit_keys_tests.rs @@ -19,7 +19,18 @@ fn press(app: &mut PhotocraftApp, digit: u8, shift: bool, now_ms: f64) { let commands = if shift { [D::SecondZero, D::SecondOne, D::SecondTwo, D::SecondThree, D::SecondFour, D::SecondFive, D::SecondSix, D::SecondSeven, D::SecondEight, D::SecondNine] } else { - [D::OpacityZero, D::OpacityOne, D::OpacityTwo, D::OpacityThree, D::OpacityFour, D::OpacityFive, D::OpacitySix, D::OpacitySeven, D::OpacityEight, D::OpacityNine] + [ + D::OpacityZero, + D::OpacityOne, + D::OpacityTwo, + D::OpacityThree, + D::OpacityFour, + D::OpacityFive, + D::OpacitySix, + D::OpacitySeven, + D::OpacityEight, + D::OpacityNine, + ] }; let mut fired = crate::blend_keys::test_fired(commands[usize::from(digit)].into()); fired.time = now_ms / 1000.0; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7edf198e78..e882c850ef 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -814,11 +814,11 @@ mod home_chrome_tests; #[cfg(test)] mod pen_variants_tests; -#[cfg(test)] -mod color_replacement_tests; #[cfg(test)] mod color_replacement_digit_keys_tests; #[cfg(test)] +mod color_replacement_tests; +#[cfg(test)] mod home_recent_gate_tests; #[cfg(test)] mod layers_panel_nodes; From 0a611fc735430da98d9e24e06bd932299d60a3f6 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 10:31:39 -0800 Subject: [PATCH 221/385] test: apply bounded CI formatting repair for PR15102 --- .../src/input/magic_eraser_digit_keys_tests.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs index bdf1620a1c..2f281aa5d3 100644 --- a/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs +++ b/crates/ui-egui/src/input/magic_eraser_digit_keys_tests.rs @@ -19,7 +19,18 @@ fn press(app: &mut PhotocraftApp, digit: u8, shift: bool, now_ms: f64) { let commands = if shift { [D::SecondZero, D::SecondOne, D::SecondTwo, D::SecondThree, D::SecondFour, D::SecondFive, D::SecondSix, D::SecondSeven, D::SecondEight, D::SecondNine] } else { - [D::OpacityZero, D::OpacityOne, D::OpacityTwo, D::OpacityThree, D::OpacityFour, D::OpacityFive, D::OpacitySix, D::OpacitySeven, D::OpacityEight, D::OpacityNine] + [ + D::OpacityZero, + D::OpacityOne, + D::OpacityTwo, + D::OpacityThree, + D::OpacityFour, + D::OpacityFive, + D::OpacitySix, + D::OpacitySeven, + D::OpacityEight, + D::OpacityNine, + ] }; let mut fired = crate::blend_keys::test_fired(commands[usize::from(digit)].into()); fired.time = now_ms / 1000.0; From ade1cd2c5449ac3fea886463919fd647cfc1e8f2 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 10:32:13 -0800 Subject: [PATCH 222/385] test: apply bounded CI formatting repair for PR12094 --- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/tools.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cde65aa045..3b0acb0615 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -259,7 +259,6 @@ use tools::cam_transform; pub use tools::cas_transform; pub use tools::crop_presets; pub use tools::crop_task_bar; -pub use tools::transform_task_bar; pub use tools::crop_ui; pub use tools::direct_select; pub use tools::eraser_ui; @@ -292,6 +291,7 @@ pub use tools::stroke_trail; pub use tools::symmetry_ui; use tools::tool_reset; pub use tools::transform_fx; +pub use tools::transform_task_bar; pub use tools::transform_tool; use tools::type_box_preview; use tools::type_font_preview; diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 80c3ef2d57..f864ae9295 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -11,7 +11,6 @@ pub(super) mod cam_transform; pub mod cas_transform; pub mod crop_presets; pub mod crop_task_bar; -pub mod transform_task_bar; pub mod crop_ui; pub mod direct_select; pub mod eraser_ui; @@ -44,6 +43,7 @@ pub mod stroke_trail; pub mod symmetry_ui; pub(super) mod tool_reset; pub mod transform_fx; +pub mod transform_task_bar; pub mod transform_tool; pub(super) mod type_box_preview; pub(super) mod type_font_preview; From 26ebb5c84052a68a092726297b1d839afaf7c4a0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 10:52:28 -0800 Subject: [PATCH 223/385] test(transform): match cargo fmt for migrated harness --- crates/ui-egui/src/control/inspect.rs | 3 +- .../ui-egui/src/transform_task_bar_tests.rs | 28 ++++++++++++------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 9508c86d40..1deba01290 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -89,8 +89,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { crate::layer_style::describe_params(app, &mut dialogs); // 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)) - .or_else(|| crate::transform_task_bar::shown_rect(app, app.ctx())); + let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)).or_else(|| crate::transform_task_bar::shown_rect(app, app.ctx())); // The one open canvas context menu, told apart by its kind. let menu = app.ui.canvas_tool_menu.as_ref(); let kind = menu.map(|menu| &menu.kind); diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 9efdf7dcfc..cfc37e6415 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -6,13 +6,13 @@ use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use crate::PhotocraftApp; -use crate::canvas::testing; use crate::app::framework::BuildApp as _; +use crate::canvas::testing; +use crate::control::{ControlRequest, Reply, handle}; +use crate::state::Tool; use craft::behavior::geometry::{BoxPart, CropBox}; use craft::behavior::kurbo::{Point, Rect as DocRect}; use std::cell::Cell; -use crate::control::{ControlRequest, Reply, handle}; -use crate::state::Tool; type AppHarness = Harness<'static, Box>; @@ -82,8 +82,6 @@ fn outside_box(app: &PhotocraftApp, at: egui::Pos2) -> BoxPart { app.ui.transform.as_ref().unwrap().session.state().part_at(v.to_doc(at), reach) } - - /// Settle the floating area's measured size before exercising its controls. fn open_box() -> AppHarness { let mut h = harness(); @@ -103,7 +101,9 @@ fn queue_control(h: &mut AppHarness, method: &str, params: Value) -> Value { fn control(h: &mut AppHarness, method: &str, params: Value) -> Value { let reply = queue_control(h, method, params); - if method == "ui.pointer" { h.run_steps(4); } + if method == "ui.pointer" { + h.run_steps(4); + } reply } @@ -292,8 +292,12 @@ fn transform_task_bar_inspection_keeps_crop_and_free_transform_rects_separate_be let mut h = open_box(); assert_eq!(bar(&mut h)["visible"], true); control(&mut h, "ui.set", json!({"tool": "crop"})); - queue_control(&mut h, "ui.pointer", json!({"tool": "crop", "events": [ - {"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]})); + queue_control( + &mut h, + "ui.pointer", + json!({"tool": "crop", "events": [ + {"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]}), + ); // Current ui.pointer is queued: before its real canvas pass neither bar can inherit the previous rect. assert!(!crate::transform_task_bar::eligible(h.state())); assert!(bar(&mut h)["rect"].is_null(), "Crop must wait for its own draw"); @@ -351,8 +355,12 @@ fn transform_task_bar_does_not_report_its_rect_as_crop_after_cancel() { assert!(crate::transform_task_bar::shown_rect(h.state(), &h.ctx).is_none()); control(&mut h, "ui.set", json!({"tool": "crop"})); - queue_control(&mut h, "ui.pointer", json!({"tool": "crop", "events": [ - {"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]})); + queue_control( + &mut h, + "ui.pointer", + json!({"tool": "crop", "events": [ + {"kind": "down", "x": 40, "y": 40}, {"kind": "move", "x": 230, "y": 170}, {"kind": "up", "x": 230, "y": 170}]}), + ); // No pass has consumed the queued Crop gesture: never expose the canceled Transform rectangle. let crop_bar = bar(&mut h); assert_eq!(crop_bar["visible"], false); From 2ffa8803a706d01c6db7ac7be504829cd6a1fa26 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:36:45 +0300 Subject: [PATCH 224/385] Check Spelling: tests for the order it checks the layers in --- crates/engine/src/cmd/type_spell_cmds.rs | 4 + .../engine/src/cmd/type_spell_order_tests.rs | 196 ++++++++++++++++++ .../src/panels/type_panels_ui/spelling.rs | 4 + .../src/panels/type_spell_order_ui_tests.rs | 78 +++++++ 4 files changed, 282 insertions(+) create mode 100644 crates/engine/src/cmd/type_spell_order_tests.rs create mode 100644 crates/ui-egui/src/panels/type_spell_order_ui_tests.rs diff --git a/crates/engine/src/cmd/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs index a2c591e1ff..a4db50c50e 100644 --- a/crates/engine/src/cmd/type_spell_cmds.rs +++ b/crates/engine/src/cmd/type_spell_cmds.rs @@ -511,3 +511,7 @@ mod tests { #[cfg(test)] #[path = "type_spell_enabled_tests.rs"] mod enabled_tests; + +#[cfg(test)] +#[path = "type_spell_order_tests.rs"] +mod order_tests; diff --git a/crates/engine/src/cmd/type_spell_order_tests.rs b/crates/engine/src/cmd/type_spell_order_tests.rs new file mode 100644 index 0000000000..242d3cf8b5 --- /dev/null +++ b/crates/engine/src/cmd/type_spell_order_tests.rs @@ -0,0 +1,196 @@ +//! #14174: with Check All Layers on, Check Spelling starts at the active layer, goes up the stack +//! and wraps to the bottom-most type layer, stopping just below the start; words within a layer +//! come left to right. Whether hidden and locked layers are checked is #14175, so the order is +//! checked on the layers listed, and the words on the visible unlocked ones. + +use serde_json::{Value, json}; + +use photocraft_doc::LayerId; + +use super::enabled_tests::{CMD, blank}; +use crate::Session; + +/// The issue's document, type layers bottom to top, then an empty pixel layer on top. The hidden +/// and locked layers' texts are not given there; they hold typos so that listing them shows. +const LAYERS: [(&str, &str); 10] = [ + ("T1 typos", "Teh quick brwn fox"), + ("T2 repeat", "the the end"), + ("T3 clean", "hello world"), + ("T4 hidden", "frist hidden"), + ("T5 locked", "lockd text"), + ("T6 para", "paragrph text here"), + ("T7 german", "Hallo Weltt"), + ("T8 repeat2", "brwn dog Teh"), + ("T9 hidden2", "secnd hidden"), + ("T10 locked2", "lockd again"), +]; + +const HIDDEN: [&str; 2] = ["T4 hidden", "T9 hidden2"]; + +fn document() -> Session { + let mut s = blank(); + for (i, (name, text)) in LAYERS.into_iter().enumerate() { + let y = 30.0 + 40.0 * i as f64; + let params = if name == "T6 para" { + json!({"box": [10, y - 20.0, 400, 36], "text": text, "size": 12, "name": name}) + } else { + json!({"x": 10, "y": y, "text": text, "size": 12, "name": name}) + }; + let id = s.execute("type.create", params).unwrap()["layer"].clone(); + if HIDDEN.contains(&name) { + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + } + if name.contains("locked") { + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + } + } + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + s +} + +fn name_of(s: &Session, id: &Value) -> String { + s.active().unwrap().doc.layer(LayerId(id.as_u64().unwrap())).unwrap().name.clone() +} + +/// (layer name, word) of each misspelling `{"action":"list"}` returns with `params` added. +fn listed(s: &mut Session, params: Value) -> Vec<(String, String)> { + let mut p = json!({"action": "list"}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + let r = s.execute(CMD, p).unwrap(); + r["misspellings"].as_array().unwrap().iter().map(|m| (name_of(s, &m["layer"]), m["word"].as_str().unwrap().to_string())).collect() +} + +/// The list with `start` active and Check All Layers on (the default). +fn check_from(s: &mut Session, start: &str) -> Vec<(String, String)> { + s.execute("layer.select", json!({"layer": start})).unwrap(); + listed(s, json!({})) +} + +/// The words of the visible unlocked layers, as "layer: word". T7's "Hallo" is left out: only the +/// English dictionary flags it, and checking T7 in German is #14189. +fn words(list: &[(String, String)]) -> Vec { + list.iter() + .filter(|(l, w)| !HIDDEN.contains(&l.as_str()) && !l.contains("locked") && !(l == "T7 german" && w == "Hallo")) + .map(|(l, w)| format!("{l}: {w}")) + .collect() +} + +/// Asserts the listed layers come in `order` (a layer not listed is passed over). +fn assert_layer_order(list: &[(String, String)], order: &[&str]) { + let mut visited: Vec<&str> = list.iter().map(|(l, _)| l.as_str()).collect(); + visited.dedup(); + let expected: Vec<&str> = order.iter().copied().filter(|l| visited.contains(l)).collect(); + assert_eq!(visited, expected, "layers visited out of order: {list:?}"); +} + +/// T1..T10 starting at `start` and wrapping. +fn rotation(start: usize) -> Vec<&'static str> { + LAYERS.iter().cycle().skip(start).take(LAYERS.len()).map(|(n, _)| *n).collect() +} + +#[test] +fn started_on_t3_goes_up_then_wraps_to_t1_and_t2() { + let mut s = document(); + let list = check_from(&mut s, "T3 clean"); + assert_eq!(words(&list), ["T6 para: paragrph", "T7 german: Weltt", "T8 repeat2: brwn", "T8 repeat2: Teh", "T1 typos: Teh", "T1 typos: brwn"]); + assert_layer_order(&list, &rotation(2)); +} + +#[test] +fn started_on_t6_checks_t6_t7_t8_then_t1() { + let mut s = document(); + let list = check_from(&mut s, "T6 para"); + assert_eq!(words(&list), ["T6 para: paragrph", "T7 german: Weltt", "T8 repeat2: brwn", "T8 repeat2: Teh", "T1 typos: Teh", "T1 typos: brwn"]); + assert_layer_order(&list, &rotation(5)); +} + +#[test] +fn started_on_t1_goes_bottom_up_with_words_left_to_right() { + let mut s = document(); + let list = check_from(&mut s, "T1 typos"); + assert_eq!(list.first().map(|(l, w)| (l.as_str(), w.as_str())), Some(("T1 typos", "Teh")), "main started at \"secnd\" in T9 hidden2"); + assert_eq!(words(&list), ["T1 typos: Teh", "T1 typos: brwn", "T6 para: paragrph", "T7 german: Weltt", "T8 repeat2: brwn", "T8 repeat2: Teh"]); + assert_layer_order(&list, &rotation(0)); +} + +/// The top type layer is T10 locked2: after it the check starts again at the bottom. +#[test] +fn started_on_the_top_type_layer_goes_on_from_the_bottom_up() { + let mut s = document(); + let list = check_from(&mut s, "T10 locked2"); + assert_eq!(list.first().map(|(l, w)| (l.as_str(), w.as_str())), Some(("T1 typos", "Teh"))); + assert_layer_order(&list, &rotation(9)); +} + +/// T8 is the top unlocked type layer: it comes first, then T1 upward. +#[test] +fn started_on_t8_checks_it_first_then_from_the_bottom() { + let mut s = document(); + let list = check_from(&mut s, "T8 repeat2"); + assert_eq!(words(&list), ["T8 repeat2: brwn", "T8 repeat2: Teh", "T1 typos: Teh", "T1 typos: brwn", "T6 para: paragrph", "T7 german: Weltt"]); + assert_layer_order(&list, &rotation(7)); +} + +/// `from` names the start for a caller whose active layer has moved on, as the dialog does. +#[test] +fn from_sets_the_start_whatever_layer_is_active() { + let mut s = document(); + s.execute("layer.select", json!({"layer": "T6 para"})).unwrap(); + let t6 = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.select", json!({"layer": "T1 typos"})).unwrap(); + let list = listed(&mut s, json!({"from": t6})); + assert_eq!(list.first().map(|(l, _)| l.as_str()), Some("T6 para")); + assert_layer_order(&list, &rotation(5)); + assert!(s.execute(CMD, json!({"action": "list", "from": "T6 para"})).is_err(), "`from` takes an id"); +} + +/// Not measured: an active layer that is not a type layer keeps today's top-to-bottom order. +#[test] +fn a_pixel_or_background_start_keeps_the_top_to_bottom_order() { + let mut s = document(); + let mut top_down: Vec<&str> = LAYERS.iter().map(|(n, _)| *n).collect(); + top_down.reverse(); + for start in ["Empty", "Background"] { + let list = check_from(&mut s, start); + assert_eq!(words(&list).first().map(String::as_str), Some("T8 repeat2: brwn"), "{start}"); + assert_layer_order(&list, &top_down); + } +} + +/// `from` null, an id that is no layer or a pixel layer's id: top to bottom, as without a type layer +/// to start at, whatever layer is active. +#[test] +fn a_null_unknown_or_pixel_from_checks_top_to_bottom() { + let mut s = document(); + let mut top_down: Vec<&str> = LAYERS.iter().map(|(n, _)| *n).collect(); + top_down.reverse(); + s.execute("layer.select", json!({"layer": "Empty"})).unwrap(); + let pixel = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.select", json!({"layer": "T1 typos"})).unwrap(); + for from in [json!(null), json!(999_999), json!(pixel)] { + let list = listed(&mut s, json!({"from": from})); + assert_eq!(words(&list).first().map(String::as_str), Some("T8 repeat2: brwn"), "from {from}"); + assert_layer_order(&list, &top_down); + } +} + +/// The issue's one measurement with several layers selected: T8 active with T1 also selected +/// starts at T8. (Here `add` makes the added layer active, so T1 is selected first.) +#[test] +fn with_t1_and_t8_selected_and_t8_active_the_check_starts_at_t8() { + let mut s = document(); + s.execute("layer.select", json!({"layer": "T1 typos"})).unwrap(); + s.execute("layer.select", json!({"layer": "T8 repeat2", "mode": "add"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers().len(), 2); + let list = listed(&mut s, json!({})); + assert_eq!(words(&list).first().map(String::as_str), Some("T8 repeat2: brwn")); + assert_layer_order(&list, &rotation(7)); +} + +/// Check All Layers off still checks the active layer alone. +#[test] +fn one_layer_check_lists_only_that_layer() { + let mut s = document(); + s.execute("layer.select", json!({"layer": "T8 repeat2"})).unwrap(); + assert_eq!(words(&listed(&mut s, json!({"allLayers": false}))), ["T8 repeat2: brwn", "T8 repeat2: Teh"]); +} diff --git a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs index d53a9af7fb..9b4a6e2d0f 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs @@ -298,3 +298,7 @@ mod tests { assert_eq!(action.dialogs.iter().copied().collect::>(), [0]); } } + +#[cfg(test)] +#[path = "../type_spell_order_ui_tests.rs"] +mod spell_order_ui_tests; diff --git a/crates/ui-egui/src/panels/type_spell_order_ui_tests.rs b/crates/ui-egui/src/panels/type_spell_order_ui_tests.rs new file mode 100644 index 0000000000..2d63dbaafa --- /dev/null +++ b/crates/ui-egui/src/panels/type_spell_order_ui_tests.rs @@ -0,0 +1,78 @@ +//! #14174: the Check Spelling dialog opened from the menu with Check All Layers on starts at the +//! active layer, goes up and wraps, and keeps that start when a Change refreshes the list after +//! another layer became active. + +use craft::text::ui::spelling::CheckSpellingDialog; +use craft::ui::dialog::StackDialog as _; +use serde_json::json; + +use super::super::spell_enabled_ui_tests::{app, choose}; +use super::*; + +fn dialog(app: &PhotocraftApp) -> &CheckSpellingDialog { + app.framework.dialogs.get::().expect("the Check Spelling dialog is open") +} + +/// The dialog's words, in its order. +fn words(app: &PhotocraftApp) -> Vec { + dialog(app).items().iter().map(|i| i.word.clone()).collect() +} + +/// The layers of the dialog's words, in its order. +fn layers(app: &PhotocraftApp) -> Vec { + dialog(app).items().iter().map(|i| i.object).collect() +} + +#[test] +fn dialog_starts_at_the_opening_layer_and_keeps_it_after_a_change() { + let mut app = app(true); + let bottom = app.run("type.create", json!({"x": 10, "y": 60, "text": "Teh quik one"})).unwrap()["layer"].as_u64().unwrap(); + app.run("type.create", json!({"x": 10, "y": 120, "text": "hello world"})).unwrap(); + let top = app.run("type.create", json!({"x": 10, "y": 180, "text": "brwn dog"})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + choose(&mut app).unwrap(); + assert_eq!(words(&app), ["Teh", "quik", "brwn"], "from the bottom layer up, not from the top"); + + // The host makes the top layer active while the dialog is open; Change refreshes the list. + app.run("layer.select", json!({"layer": top})).unwrap(); + let item = dialog(&app).items()[0].clone(); + change(&mut app, &item, "The"); + let items = relist(&mut app); + app.framework.dialogs.get_mut::().unwrap().set_items(items); + assert_eq!(words(&app), ["quik", "brwn"], "the start stays the layer the dialog was opened on"); + assert_eq!(text_of(&app, bottom), "The quik one", "Change replaced \"Teh\""); +} + +/// Bottom "Teh one" and top "brwn dog" over the empty layer; returns their ids. +fn two_layers() -> (Box, u64, u64) { + let mut app = app(true); + let bottom = app.run("type.create", json!({"x": 10, "y": 60, "text": "Teh one"})).unwrap()["layer"].as_u64().unwrap(); + let top = app.run("type.create", json!({"x": 10, "y": 120, "text": "brwn dog"})).unwrap()["layer"].as_u64().unwrap(); + (app, bottom, top) +} + +/// Opened with no layer active, Check All Layers goes top to bottom, and selecting a layer later +/// does not move the start there. +#[test] +fn dialog_opened_without_an_active_layer_keeps_the_top_to_bottom_order() { + let (mut app, bottom, top) = two_layers(); + app.run("select.deselectLayers", json!({})).unwrap(); + open_spelling(&mut app, true).unwrap(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + let first = relist(&mut app).first().map(|i| i.object); + assert_eq!(first, Some(top), "the top layer comes first"); +} + +/// Opened with Check All Layers off on the bottom layer, then turned on after the top layer became +/// active: the check starts at the opening layer. +#[test] +fn turning_check_all_layers_on_starts_at_the_opening_layer() { + let (mut app, bottom, top) = two_layers(); + let ctx = app.ctx().clone(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + open_spelling(&mut app, false).unwrap(); + app.run("layer.select", json!({"layer": top})).unwrap(); + app.framework.dialogs.get_mut::().unwrap().set_json_field(&ctx, "allLayers", json!(true)).unwrap(); + take(&mut app, &ctx); + assert_eq!(layers(&app), [bottom, top]); +} From 204301ab82551e5ae1390a72d6e2b9a36a0614a7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 11:10:54 -0800 Subject: [PATCH 225/385] Use the public canvas view type in transform tests --- crates/ui-egui/src/transform_task_bar_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index cfc37e6415..6b1c38585d 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -70,7 +70,7 @@ fn set_crop_frame(h: &mut AppHarness) { h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(100.0, 100.0, 200.0, 160.0), 0.0)); } -fn view(app: &PhotocraftApp) -> craft::ui::canvas::CanvasView { +fn view(app: &PhotocraftApp) -> craft::behavior::CanvasView { testing::view(app).expect("the primary canvas has shown its view") } From 4d576ced907488eb6e7f833b06be3dd99d1c1a25 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 11:21:18 -0800 Subject: [PATCH 226/385] 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 227/385] 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 1ed0f5ad7f061d73ef0549d87c04c61c4500be80 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:50:44 +0100 Subject: [PATCH 228/385] test(ui): carry sampler menu regression to the current analysis module Pre-resolve the upstream analysis_ui to analysis move. Preserve the complete current main sampler tests and add the document-switch menu assertion. The matching sync_views fix is retained in the companion update. --- .../src/tools/analysis/sampler_menu_tests.rs | 77 ++++++ .../tools/analysis_ui/sampler_menu_tests.rs | 224 ------------------ 2 files changed, 77 insertions(+), 224 deletions(-) create mode 100644 crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs delete mode 100644 crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs diff --git a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs new file mode 100644 index 0000000000..16c1bb2f03 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs @@ -0,0 +1,77 @@ +//! #11733: the Color Sampler's right-click menu cannot act on a sampler that is gone. + +use serde_json::json; + +use crate::canvas_tool_menu::SAMPLER_DELETE; +use crate::{PhotocraftApp, Tool}; + +/// A 200 x 100 document with the Color Sampler and samplers at (20, 20) and (120, 60). +fn app() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 20, "y": 20})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 120, "y": 60})).unwrap(); + app.ui.tool = Tool::ColorSampler; + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// A right-click at document point (x, y) through the window host, as a mouse sends it. +fn right_click(app: &mut PhotocraftApp, x: f64, y: f64) { + crate::canvas::testing::secondary_click(app, [x, y], egui::Modifiers::NONE); +} + +fn samplers(app: &PhotocraftApp) -> Vec<[f64; 2]> { + app.session.active().unwrap().color_samplers.clone() +} + +/// Delete never removes a different sampler when the list changes while the menu is open: one +/// deleted meanwhile, or another document with a sampler at the same index and spot. +#[test] +fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() { + let (mut app, ctx) = app(); + app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); + right_click(&mut app, 120.0, 60.0); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + // An agent deletes #1 while the menu is open: index 1 now names the old #3. + app.run("view.colorSamplers.delete", json!({"index": 0})).unwrap(); + crate::canvas_tool_menu::close_stale(&mut app); + assert!(app.ui.canvas_tool_menu.is_none(), "the menu's sampler moved, so the menu closes"); + crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); + assert_eq!(samplers(&app), [[120.5, 60.5], [180.5, 90.5]], "no other sampler is deleted"); + + // Another document with a sampler at the same index and spot: still not this menu's sampler. + right_click(&mut app, 180.0, 90.0); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + assert!(app.ui.canvas_tool_menu.is_none(), "switching documents closes the menu"); + for (x, y) in [(20, 20), (180, 90)] { + app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); + } + crate::canvas_tool_menu::close_stale(&mut app); + crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); + assert_eq!(samplers(&app).len(), 2, "another document's sampler is not deleted"); +} + +/// A stale index, a non-finite point, or no document at all: `sampler_at` answers `None`, and a +/// Delete then changes nothing and never panics. +#[test] +fn a_stale_sampler_or_odd_point_fails_gracefully() { + let (mut app, ctx) = app(); + app.run("view.colorSamplers.clear", json!({})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + assert_eq!(super::sampler_at(&app, [120.0, 60.0]), None, "the sampler at that spot is gone"); + for p in [[f64::NAN, 5.0], [f64::INFINITY, 5.0], [5.0, f64::NEG_INFINITY]] { + assert_eq!(super::sampler_at(&app, p), None, "{p:?}"); + } + crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); + assert_eq!(samplers(&app), [[5.5, 5.5]], "Delete with no open menu removes nothing"); + + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty.ui.tool = Tool::ColorSampler; + assert_eq!(super::sampler_at(&empty, [1.0, 1.0]), None); + if crate::canvas_tool_menu::open_at(&mut empty, Tool::ColorSampler, Default::default(), egui::pos2(10.0, 10.0), [1.0, 1.0], None) { + crate::canvas_tool_menu::choose(&mut empty, &ctx, SAMPLER_DELETE); + } + assert!(empty.session.active().is_none()); +} diff --git a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs deleted file mode 100644 index 2bb0e270b6..0000000000 --- a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs +++ /dev/null @@ -1,224 +0,0 @@ -//! #11733: the Color Sampler's right-click menu on the canvas. - -use egui::{Event, Modifiers, PointerButton, vec2}; -use egui_kittest::Harness; -use serde_json::{Value, json}; - -use crate::canvas_tool_menu::{SAMPLER_DELETE, SAMPLER_MENU}; -use crate::control::{ControlRequest, Outcome, handle}; -use crate::{PhotocraftApp, Tool}; - -/// A 200 x 100 document with the Color Sampler and samplers at (20, 20) and (120, 60). -fn app() -> (PhotocraftApp, egui::Context) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.run("view.colorSamplers.add", json!({"x": 20, "y": 20})).unwrap(); - app.run("view.colorSamplers.add", json!({"x": 120, "y": 60})).unwrap(); - app.ui.tool = Tool::ColorSampler; - (app, egui::Context::default()) -} - -fn control(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { - let (req, _rx) = ControlRequest::new(method, params); - let Outcome::Done(v) = handle(app, ctx, &req) else { panic!("{method} replies at once") }; - v -} - -/// An agent's right-click at document point (x, y), as `ui.pointer` sends it. -fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64) { - let r = control(app, ctx, "ui.pointer", json!({"button": "secondary", "events": [{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]})); - assert_eq!(r["ok"], json!(true), "{r}"); -} - -fn entries(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { - let r = control(app, ctx, "ui.inspect", json!({})); - r["result"]["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_else(|| panic!("no canvasToolMenu: {r}")) -} - -fn samplers(app: &PhotocraftApp) -> Vec<[f64; 2]> { - app.session.active().unwrap().color_samplers.clone() -} - -/// The reference application's rows, in order, with `|` for a separator. -const EXPECTED: &[&str] = &[ - "Delete", - "|", - "Actual Color", - "Proof Color", - "|", - "Grayscale", - "RGB Color", - "Web Color", - "HSB Color", - "HSL Color", - "CMYK Color", - "Lab Color", - "|", - "Grayscale 16 bit", - "RGB 16 bit", - "CMYK 16 bit", - "Lab 16 bit", - "|", - "Total Ink", -]; - -fn labels(entries: &[Value]) -> Vec { - entries.iter().map(|e| if e["separator"] == json!(true) { "|".to_string() } else { e["label"].as_str().unwrap().to_string() }).collect() -} - -#[test] -fn right_click_on_a_sampler_lists_the_menu_in_order_with_delete_enabled() { - let (mut app, ctx) = app(); - right_click(&mut app, &ctx, 20.5, 20.5); - let menu = app.ui.canvas_tool_menu.clone().expect("the Color Sampler menu opens"); - assert_eq!(menu.tool, Tool::ColorSampler); - assert_eq!(menu.sampler, Some(0)); - let entries = entries(&mut app, &ctx); - assert_eq!(labels(&entries), EXPECTED); - let enabled: Vec<&str> = entries.iter().filter(|e| e["enabled"] == json!(true)).filter_map(|e| e["id"].as_str()).collect(); - // The readout rows wait for per-sampler readout modes (#11735) and stay greyed until then. - assert_eq!(enabled, [SAMPLER_DELETE]); - for (_, id) in SAMPLER_MENU.iter().flatten() { - assert!(!crate::canvas_tool_menu::mode_checked(&app, &menu, id), "{id} shows no checkmark"); - } - assert_eq!(samplers(&app).len(), 2, "the right-click places no sampler"); -} - -#[test] -fn right_click_off_a_sampler_greys_every_row() { - let (mut app, ctx) = app(); - right_click(&mut app, &ctx, 70.0, 40.0); - let menu = app.ui.canvas_tool_menu.clone().expect("the menu opens off a sampler too"); - assert_eq!(menu.sampler, None); - let entries = entries(&mut app, &ctx); - assert_eq!(labels(&entries), EXPECTED); - assert!(entries.iter().all(|e| e["enabled"] != json!(true)), "every row greyed: {entries:?}"); - let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); - assert_eq!(r["ok"], json!(false), "a greyed Delete does nothing: {r}"); - assert_eq!(samplers(&app).len(), 2, "nothing deleted, no sampler placed"); -} - -/// The right-click menu's Delete removes the sampler under the pointer, closes the menu, and -/// the samplers after it move up a number. -#[test] -fn delete_removes_the_sampler_under_the_pointer_and_renumbers_the_rest() { - let (mut app, ctx) = app(); - app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); - right_click(&mut app, &ctx, 120.0, 60.0); - assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); - let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); - assert_eq!(r["ok"], json!(true), "{r}"); - assert_eq!(samplers(&app), [[20.5, 20.5], [180.5, 90.5]], "#3 became #2"); - assert!(app.ui.canvas_tool_menu.is_none(), "choosing closes the menu"); - let listed = app.run("view.colorSamplers.list", json!({})).unwrap(); - assert_eq!(listed["samplers"][1]["number"], json!(2)); -} - -/// Delete never removes a different sampler when the list changes while the menu is open: one -/// deleted or moved meanwhile, or another document with a sampler at the same index and spot. -#[test] -fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() { - let (mut app, ctx) = app(); - app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); - right_click(&mut app, &ctx, 120.0, 60.0); - assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); - // An agent deletes #1 while the menu is open: index 1 now names the old #3. - app.run("view.colorSamplers.delete", json!({"index": 0})).unwrap(); - let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); - assert_eq!(r["ok"], json!(false), "Delete greys out: {r}"); - assert_eq!(samplers(&app), [[120.5, 60.5], [180.5, 90.5]], "no other sampler is deleted"); - // The menu itself closes on the next frame. - right_click(&mut app, &ctx, 120.0, 60.0); - app.run("view.colorSamplers.move", json!({"index": 0, "x": 30, "y": 30})).unwrap(); - ctx.run_ui(Default::default(), |ui| crate::canvas_tool_menu::show(&mut app, ui.ctx())).textures_delta.clear(); - assert!(app.ui.canvas_tool_menu.is_none(), "a moved sampler closes the menu"); - // Another document with a sampler at the same index and spot: still not this menu's sampler. - right_click(&mut app, &ctx, 180.0, 90.0); - assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); - let menu = app.ui.canvas_tool_menu.clone().expect("the menu is open before switching documents"); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - assert!(app.ui.canvas_tool_menu.is_none(), "switching documents closes the menu"); - for (x, y) in [(20, 20), (180, 90)] { - app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); - } - assert!(!crate::canvas_tool_menu::entry_enabled(&app, &menu, SAMPLER_DELETE), "another document's sampler"); -} - -#[test] -fn readout_rows_do_nothing_until_samplers_have_readout_modes() { - let (mut app, ctx) = app(); - right_click(&mut app, &ctx, 20.0, 20.0); - let before = app.session.active().unwrap().revision; - let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": "colorSampler.readout.hsl"})); - assert_eq!(r["ok"], json!(false), "{r}"); - assert_eq!(app.session.active().unwrap().revision, before); - assert_eq!(samplers(&app).len(), 2); -} - -/// A sampler gone while the menu is open, a non-finite point, or no document at all: Delete -/// greys out and nothing panics. -#[test] -fn a_stale_sampler_or_odd_point_fails_gracefully() { - let (mut app, ctx) = app(); - right_click(&mut app, &ctx, 120.0, 60.0); - // The sampler went away while the menu was open: Delete greys out instead of removing another. - app.run("view.colorSamplers.clear", json!({})).unwrap(); - app.run("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(!crate::canvas_tool_menu::entry_enabled(&app, &menu, SAMPLER_DELETE)); - crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); - assert_eq!(samplers(&app), [[5.5, 5.5]]); - for p in [[f64::NAN, 5.0], [f64::INFINITY, 5.0], [5.0, f64::NEG_INFINITY]] { - assert_eq!(super::sampler_at(&app, p), None); - } - // No document: the menu opens greyed, nothing panics. - let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - empty.ui.tool = Tool::ColorSampler; - assert_eq!(super::sampler_at(&empty, [1.0, 1.0]), None); - if crate::canvas_tool_menu::open_at(&mut empty, &ctx, Tool::ColorSampler, [10.0, 10.0], Some([1.0, 1.0])) { - let menu = empty.ui.canvas_tool_menu.clone().unwrap(); - assert!(SAMPLER_MENU.iter().flatten().all(|(_, id)| !crate::canvas_tool_menu::entry_enabled(&empty, &menu, id))); - crate::canvas_tool_menu::choose(&mut empty, &ctx, SAMPLER_DELETE); - } -} - -#[test] -fn other_tools_keep_their_menus() { - let (mut app, ctx) = app(); - app.ui.tool = Tool::RectMarquee; - right_click(&mut app, &ctx, 20.0, 20.0); - let menu = app.ui.canvas_tool_menu.clone().expect("the selection menu"); - assert_eq!(crate::canvas_tool_menu::rows(&menu), crate::canvas_tool_menu::NO_SELECTION_MENU); - app.ui.canvas_tool_menu = None; - app.ui.tool = Tool::Pen; - right_click(&mut app, &ctx, 20.0, 20.0); - let menu = app.ui.canvas_tool_menu.clone().expect("the path menu"); - assert_eq!(crate::canvas_tool_menu::rows(&menu), crate::canvas_tool_menu::PEN_MENU); - app.ui.canvas_tool_menu = None; - // Outside the image the Color Sampler keeps the pasteboard menu. - app.ui.tool = Tool::ColorSampler; - right_click(&mut app, &ctx, 250.0, 40.0); - assert!(app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard)); -} - -/// A real right-click on the canvas over sampler #2 opens the menu on it. -#[test] -fn canvas_right_click_opens_the_menu_on_the_sampler() { - let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app().0 - }); - h.run_steps(5); - let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); - let at = xf.to_screen(120.5, 60.5); - h.event(Event::PointerMoved(at)); - h.run_steps(2); - for pressed in [true, false] { - h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(3); - let menu = h.state().ui.canvas_tool_menu.clone().expect("the Color Sampler menu opens"); - assert_eq!((menu.tool, menu.sampler), (Tool::ColorSampler, Some(1))); - assert_eq!(h.state().session.active().unwrap().color_samplers.len(), 2, "no sampler was placed or moved"); -} From 80344e35d7a6474d0d60dde5c8f18406e59b6026 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:51:38 +0100 Subject: [PATCH 229/385] fix(ui): retain document-bound canvas menus on current commands Pre-resolve commands.rs against the complete current main implementation, retaining the document identity check and canvas_tool_menu reset. Preserve upstream command refactors and CropFill changes. --- crates/ui-egui/src/app/commands.rs | 87 +++++++++--------------------- 1 file changed, 25 insertions(+), 62 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index f2fed52016..f5b296d7d3 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,6 +1,6 @@ use super::{ - DocId, PhotocraftApp, Tool, Value, actions, canvas, delete_layer_prompt, dock, gpu_canvas, jobs_ui, json, mask_trash_prompt, notices, panel_docking, - smart_svg_ui, state, transform_tool, type_transform, vector_ui, + DocId, PhotocraftApp, Value, actions, canvas, delete_layer_prompt, gpu_canvas, jobs_ui, json, mask_trash_prompt, notices, panel_docking, smart_svg_ui, + state, transform_tool, type_transform, vector_ui, }; impl PhotocraftApp { @@ -28,16 +28,8 @@ impl PhotocraftApp { if gate.is_some() { self.session.authorize = None; } - if let Ok(reply) = &result { - if library_change { - actions::library_selection_changed(self); - } else if id == "actions.load" { - actions::library_slots_changed(self); - } else if id == "actions.duplicate" - && let Some(slot) = reply["setSlot"].as_u64().and_then(|slot| usize::try_from(slot).ok()) - { - actions::library_slot_inserted(self, slot); - } + if library_change && result.is_ok() { + actions::library_changed(self); } // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: // ⌘2 after the mask was targeted goes back to the layer's pixels. @@ -112,15 +104,10 @@ impl PhotocraftApp { } // Document exports read committed pixels, not the pending Free Transform preview. // Check on execution (also dialog OK and automation), leaving Folder processing usable. - if id == "file.scripts.imageProcessor" - && self.ui.transform.is_some() - && match params.get("source").and_then(Value::as_str) { - Some("open") => true, - Some("current") => self.transform_preview.as_ref().is_none_or(|preview| self.session.active().is_some_and(|st| st.doc.id == preview.doc.id)), - _ => false, - } + if id == crate::dialogs::image_processor_ui::COMMAND + && crate::dialogs::image_processor_ui::waits_for_transform(self, params.get("source").and_then(Value::as_str)) { - return Err("Commit or cancel the transform first".into()); + return Err(tl!("Commit or cancel the transform first").into()); } if let Some(r) = transform_tool::intercept(self, id) { return r; @@ -204,7 +191,7 @@ impl PhotocraftApp { let r = if id == "actions.play" { actions::play(self, ¶ms) } else if photocraft_engine::actions_cmds::shell_view_command(id) { - actions::run_view(self, id, params) + actions::runner::run_view(self, id, params) } else { jobs_ui::run(self, id, params) }; @@ -243,12 +230,6 @@ impl PhotocraftApp { /// Keep one view per document, in tab order: a view and its windows stay with their document /// when tabs move (`document.move`) or close. - /// The tool pointer events go to: a held temporary tool when there is one (⌘ is the Move - /// tool, `hold_keys::cmd_moves`), else the selected tool. - pub fn active_tool(&self) -> state::Tool { - self.tool_override.unwrap_or(self.ui.tool) - } - /// Selects the newly attached type path on composite channel target so the path becomes immediately editable. fn select_attached_type_path(&mut self, command: &str, result: &Result) { if command != "type.attachToPath" { @@ -297,12 +278,7 @@ impl PhotocraftApp { if result.is_ok() && creates_adjustment_or_fill { // Properties comes to the front, shown and expanded, so the new layer's settings can // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. - if self.ui.docking.is_some() { - let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); - } else { - self.ui.dock_tabs.properties = 0; - dock::reveal(self, dock::Group::Properties); - } + let _ = panel_docking::show_panel(self, "properties", Some(true)); } // Making a new selection reveals its outline after View > Extras was hidden (#5597). // These interactive selection commands complete inline; a failed command, deselection, @@ -360,7 +336,6 @@ impl PhotocraftApp { /// Reconciles canvas view state with open documents in the session. pub fn sync_views(&mut self) { - crate::type_path_placement::cancel_stale(self); // The Paths panel selection and canvas context menu belong to the active document. // Ordinary edits replace the snapshot and advance its revision; a replaced snapshot // without a newer revision is a reopened document, even with the same ID. @@ -373,7 +348,7 @@ impl PhotocraftApp { && id != old_id && self.view_docs.contains(id) { - self.ui.tool_options.crop_content_aware = false; + self.ui.tool_options.crop.fill = craft::draw::ui::crop::CropFill::Background; } let same_document = match (&self.path_document, &document) { (Some((old_id, old_revision, old_source)), Some((id, revision, source))) => old_id == id && (revision > old_revision || old_source.ptr_eq(source)), @@ -385,25 +360,11 @@ impl PhotocraftApp { self.ui.canvas_tool_menu = None; } self.path_document = document; - // A shape box handle drag belongs to its document, revision and tool. - crate::shape_bounds_box::cancel_stale(self); vector_ui::cancel_stale_pen(self); crate::direct_select::cancel_stale(self); - canvas::cancel_stale_vector_drag(self); type_transform::cancel_stale(self); crate::cam_transform::cancel_stale(self); - crate::lasso_ui::cancel_stale(self); - crate::retouch_ui::cancel_stale(self); - // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. - if self.ui.tool != Tool::PolygonLasso { - self.ui.polygon.clear(); - self.ui.polygon_mode.clear(); - } - // ... and to the document it was started on. - crate::canvas::polygon_cancel_stale(self); - crate::crop_ui::cancel_stale(self); crate::distort_ui::cancel_stale(self); - crate::perspective_crop_ui::cancel_stale(self); // A pen path under construction belongs to the document it was started on too. vector_ui::cancel_stale(self); let ids: Vec = self.session.documents().iter().map(|d| d.doc.id).collect(); @@ -419,28 +380,30 @@ impl PhotocraftApp { } } self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect(); - self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some()); + canvas::document_windows::sync_documents(self, &ids); if !self.session.prefs().workspace.open_documents_as_tabs { - let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); - for &idx in &new_docs { - if !self.ui.windows.iter().any(|w| w.document == idx) { - crate::view_cmds::float_window(self, idx, idx, false); + let new_docs: Vec = ids.iter().filter(|id| !self.view_docs.contains(id)).copied().collect(); + let ctx = self.ctx().clone(); + for id in new_docs { + // A document already in a floating window keeps it. + if !crate::view_cmds::document_is_floating(self, id) { + crate::view_cmds::invoke(self, &ctx, "window.arrange.floatInWindow", &json!({"document": id.0})); } } } self.canvases.retain(|(doc, _), _| ids.contains(doc)); + self.raster_logs.retain(|(doc, _), _| ids.contains(doc)); self.navigator_textures.retain(|doc, _| ids.contains(doc)); - self.snapshot_thumbs.retain(|(doc, _), _| ids.contains(doc)); // Closing a document cancels its page work; its GPU pages go with `retain_gpu_documents`. self.streams.retain(|doc, _| ids.contains(doc)); - self.view_docs = ids; - self.prune_thumbs(); - self.sync_mask_targets(); - // Channel-view textures outlive a hidden view (cheap re-show), not their document. - if !self.channel_views.is_empty() { - let docs = self.session.documents(); - self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); + // A parameter dialog holds a target in a document that has left the session: it closes with it. + let closed: Vec = self.view_docs.iter().filter(|d| !ids.contains(d)).cloned().collect(); + if !closed.is_empty() { + let ctx = self.ctx().clone(); + crate::dialogs::cancel_for_closed(self, &ctx, &closed); } + self.view_docs = ids; + self.sync_mask_targets(); // With no document left, no canvas paints the Levels clipping display to drop its cache. if self.session.documents().is_empty() { self.levels_clipping = None; From 7de3fedcccc08f6052fdc74eff6ccf1a8b1d32da Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:56:00 +0100 Subject: [PATCH 230/385] test(ui): use the current canvas menu opening API Migrate the retained Hand and Zoom document-switch regressions from removed open_view to open_at, using the current modifier, screen point and document point types. Remove the obsolete test context. --- crates/ui-egui/src/view_sync_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/view_sync_tests.rs b/crates/ui-egui/src/view_sync_tests.rs index 91c6a8b1ca..b81388cc3e 100644 --- a/crates/ui-egui/src/view_sync_tests.rs +++ b/crates/ui-egui/src/view_sync_tests.rs @@ -51,8 +51,7 @@ fn switching_documents_closes_the_canvas_view_menu() { for tool in [crate::Tool::Zoom, crate::Tool::Hand] { let mut app = app_with_two_documents(); app.ui.tool = tool; - let ctx = egui::Context::default(); - assert!(crate::canvas_tool_menu::open_view(&mut app, &ctx, tool, [10.0, 10.0], [20.0, 20.0])); + assert!(crate::canvas_tool_menu::open_at(&mut app, tool, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); app.sync_views(); assert!(app.ui.canvas_tool_menu.is_some(), "ordinary sync keeps the menu"); app.run("layer.new.layer", json!({})).unwrap(); @@ -75,7 +74,7 @@ fn closing_a_tab_keeps_the_canvas_menu_only_for_its_own_document() { } app.ui.tool = crate::Tool::Hand; let document = app.session.active().unwrap().doc.id; - assert!(crate::canvas_tool_menu::open_view(&mut app, &egui::Context::default(), crate::Tool::Hand, [10.0, 10.0], [20.0, 20.0])); + assert!(crate::canvas_tool_menu::open_at(&mut app, crate::Tool::Hand, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); app.run("file.close", json!({"document": 0})).unwrap(); assert_eq!(app.session.active_index(), Some(0), "the survivor occupies the first slot"); assert_eq!(app.session.active().unwrap().doc.id == document, !close_menu_document); From 4b99d58df41fdc80b7ff12a3482239133863dec6 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 12:57:00 -0800 Subject: [PATCH 231/385] Keep transform fixtures on their intended input surfaces --- crates/ui-egui/src/transform_commit_click_tests.rs | 11 +++++++++++ crates/ui-egui/src/transform_task_bar_tests.rs | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/transform_commit_click_tests.rs b/crates/ui-egui/src/transform_commit_click_tests.rs index dd96824954..df7eb33857 100644 --- a/crates/ui-egui/src/transform_commit_click_tests.rs +++ b/crates/ui-egui/src/transform_commit_click_tests.rs @@ -59,6 +59,17 @@ fn a_click_outside_the_box_on_the_image_keeps_it_open() { fn a_click_on_the_pasteboard_commits_one_free_transform_step() { for p in [[-30.0, 100.0], [100.0, -30.0], [230.0, 100.0], [100.0, 230.0]] { let mut app = app(); + // This oracle addresses the canvas at these same four document points. + // The floating task bar can cover them; use the real Window command to + // expose the pasteboard without changing the click or bypassing its route. + let app_ctx = app.ctx().clone(); + crate::menus::invoke(&mut app, &app_ctx, "window.panel.contextualTaskBar", json!({"on": false})).unwrap(); + assert!(!app.ui.panels.context_task_bar); + crate::canvas::testing::shown(&mut app); + let view = crate::canvas::testing::view(&app).expect("the canvas shows the original click point"); + let point = crate::canvas::testing::to_screen(&app, p); + assert!(view.rect.contains(point), "the unchanged pasteboard point reaches the real canvas: {p:?}"); + assert!(crate::transform_task_bar::shown_rect(&app, &app_ctx).is_none(), "the bar cannot own this canvas click"); let before = steps(&app); click(&mut app, p); assert!(app.ui.transform.is_none(), "{p:?}"); diff --git a/crates/ui-egui/src/transform_task_bar_tests.rs b/crates/ui-egui/src/transform_task_bar_tests.rs index 6b1c38585d..86bee01fad 100644 --- a/crates/ui-egui/src/transform_task_bar_tests.rs +++ b/crates/ui-egui/src/transform_task_bar_tests.rs @@ -280,7 +280,7 @@ fn transform_task_bar_hides_while_a_shell_dialog_is_open() { assert_eq!(bar(&mut h)["visible"], false); h.run_steps(2); assert!(h.query_by_label("Rotate 90° Clockwise").is_none()); - control(&mut h, "ui.dialog.cancel", json!({})); + control(&mut h, "ui.dialog.cancel", json!({"dialog": "top"})); assert!(bar(&mut h)["rect"].is_null(), "the last pass did not draw the bar"); h.run_steps(4); assert_eq!(h.state().ui.transform.as_ref().unwrap().id, session); From b6428ed1043a17fa290cc0b15653feba922ab535 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:57:02 +0100 Subject: [PATCH 232/385] test(ui): assert document-switch fixtures open view menus Assert the current public right-click route opens MenuKind::View before checking document identity, ordinary edits and tab closure. This keeps future routing changes from weakening the retained regressions. --- crates/ui-egui/src/view_sync_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/view_sync_tests.rs b/crates/ui-egui/src/view_sync_tests.rs index b81388cc3e..be36297dd8 100644 --- a/crates/ui-egui/src/view_sync_tests.rs +++ b/crates/ui-egui/src/view_sync_tests.rs @@ -52,6 +52,7 @@ fn switching_documents_closes_the_canvas_view_menu() { let mut app = app_with_two_documents(); app.ui.tool = tool; assert!(crate::canvas_tool_menu::open_at(&mut app, tool, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); + assert!(matches!(app.ui.canvas_tool_menu.as_ref().map(|menu| &menu.kind), Some(crate::canvas_tool_menu::MenuKind::View))); app.sync_views(); assert!(app.ui.canvas_tool_menu.is_some(), "ordinary sync keeps the menu"); app.run("layer.new.layer", json!({})).unwrap(); @@ -75,6 +76,7 @@ fn closing_a_tab_keeps_the_canvas_menu_only_for_its_own_document() { app.ui.tool = crate::Tool::Hand; let document = app.session.active().unwrap().doc.id; assert!(crate::canvas_tool_menu::open_at(&mut app, crate::Tool::Hand, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); + assert!(matches!(app.ui.canvas_tool_menu.as_ref().map(|menu| &menu.kind), Some(crate::canvas_tool_menu::MenuKind::View))); app.run("file.close", json!({"document": 0})).unwrap(); assert_eq!(app.session.active_index(), Some(0), "the survivor occupies the first slot"); assert_eq!(app.session.active().unwrap().doc.id == document, !close_menu_document); From a419dad12103bed5998cb9b281c9e265b3f057a4 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:04:40 +0100 Subject: [PATCH 233/385] test(ui): retain the cross-document sampler Delete guard Capture the original sampler menu before switching documents, retain the immediate-dismissal assertion, and verify that its Delete action stays disabled after another document receives matching sampler indices and positions. Addresses the current CodeRabbit regression-coverage nitpick. --- crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs index 16c1bb2f03..2389fd03e4 100644 --- a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs @@ -43,11 +43,13 @@ fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() // Another document with a sampler at the same index and spot: still not this menu's sampler. right_click(&mut app, 180.0, 90.0); assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + let original_menu = app.ui.canvas_tool_menu.clone().unwrap(); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); assert!(app.ui.canvas_tool_menu.is_none(), "switching documents closes the menu"); for (x, y) in [(20, 20), (180, 90)] { app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); } + assert!(!crate::canvas_tool_menu::entry_enabled(&app, &original_menu, SAMPLER_DELETE), "the original menu cannot delete another document's sampler"); crate::canvas_tool_menu::close_stale(&mut app); crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); assert_eq!(samplers(&app).len(), 2, "another document's sampler is not deleted"); From 200e914d525018afece57c6f755ef6c6f97f3754 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Wed, 18 Nov 2026 23:14:05 +0100 Subject: [PATCH 234/385] fix(layer-style): keep imported Inner Shadow values on an untouched OK The hosted Inner Shadow page sends every field it models, so opening it over a PSD effect and clicking OK without touching anything pushed the file's values through the #14940 command clamps: Distance 40000 became 30000, Size 300 became 250 and Angle 200 became -160, in one history step. Size 300 to 250 moves pixels. effect_entry now drops the distance, size and angle keys while the field still holds what the snapshot carried, the way it already drops unedited bevel shading and gradient-stop keys; the snapshot keeps the file's value. A field the user did edit is still sent and still meets the page's ranges. The angle is only kept when the effect does not follow the shared light, because then the field shows the light's angle and not the effect's own - that case keeps writing it as before. Test: unedited_inner_shadow_keeps_imported_out_of_range_values, red before this hunk (stored 30000.0 where the file had 40000.0). --- crates/ui-egui/src/dialogs/layer_style.rs | 19 +++++++++++ .../ui-egui/src/dialogs/layer_style/tests.rs | 34 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 5d520e95e5..0f9fc9114a 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -650,6 +650,25 @@ fn effect_entry(fx: Option<&Value>, kind: &str, mut params: Value, initial_light } } } + if kind == "innerShadow" + && let Ok(original) = serde_json::from_value::(fx.clone()) + && let Some(edits) = params.as_object_mut() + { + let shown = values_of(&original, initial_light_angle.unwrap_or(120.0) as f32); + // A file can carry a Distance or Size outside the page's typed ranges (#14940) that + // the command clamps. An untouched field must not send it back through the clamp. + for key in ["distance", "size"] { + if edits.get(key) == shown.get(key) { + edits.remove(key); + } + } + // The Angle field shows the shared light while the effect is lit by it, so the + // effect's own angle is only what the field showed when the check is off; with it on, + // the light angle is written as before. + if shown.get("useGlobalLight") == Some(&Value::Bool(false)) && edits.get("angle") == shown.get("angle") { + edits.remove("angle"); + } + } if kind == "gradientOverlay" && let Ok(original) = serde_json::from_value::(fx.clone()) && let Some(edits) = params.as_object_mut() diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 48fa6fe94b..21cb99fd2d 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -539,6 +539,40 @@ fn unedited_bevel_shading_keeps_imported_precision() { } } +/// Pattern 5 (#14940): a PSD carries Inner Shadow values outside the page's typed ranges - +/// `parse_shadow` keeps Dstn, blur and lagl exactly as the file has them - and the hosted page's +/// OK re-sends every field it models. An untouched OK must not rewrite what the file imported +/// (Size 300 becoming 250 moves pixels); a field the user did edit still meets the page's clamps. +#[test] +fn unedited_inner_shadow_keeps_imported_out_of_range_values() { + for typed in [None, Some(40_001.0)] { + let mut s = session(); + s.execute("layer.layerStyle.innerShadow", json!({})).unwrap(); + s.edit("imported out-of-range values", |doc, active| { + let Effect::InnerShadow(sh) = &mut doc.layer_mut(active.unwrap()).unwrap().effects.items[0] else { panic!("inner shadow") }; + sh.distance = 40_000.0; + sh.size = 300.0; + sh.angle = 200.0; + sh.use_global_light = false; + Ok(()) + }) + .unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let mut d = LayerStyleDraft::new(drafted(&s)); + let shadow = d.style.instances(EffectKind::InnerShadow).next().unwrap(); + if let Some(distance) = typed { + d.set_param(shadow, "distance", StyleValue::Number(distance)); + } + apply(&d.style, id, None, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let Effect::InnerShadow(after) = &layer_effects(&s)[0] else { panic!("inner shadow") }; + // The typed distance is past the page's 30000, so an EDITED field is clamped; an untouched + // one keeps the imported value. + assert_eq!(f64::from(after.distance), typed.map_or(40_000.0, |d| d.min(30_000.0)), "distance {typed:?}"); + assert_eq!(f64::from(after.size), 300.0, "an untouched Size 300 keeps what the file imported"); + assert_eq!(f64::from(after.angle), 200.0, "an untouched Angle 200 keeps what the file imported"); + } +} + fn overlay_color(doc: &photocraft_doc::Document, layer: photocraft_doc::LayerId) -> photocraft_color::Color { match &doc.layer(layer).unwrap().effects.items[0] { Effect::ColorOverlay { color, .. } => *color, From 5d613280d37b2cdf4d35cc354e5c87716a2d9668 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Wed, 18 Nov 2026 23:14:50 +0100 Subject: [PATCH 235/385] docs(layer-style): say how a scripted Inner Shadow angle past a half turn lands The layer.layerStyle.innerShadow parameter doc now names the order the value goes through: clamped to the page's -360..360 first, then wrapped into -180..180, so a scripted 400 stores 0. The shared light angle of layer.layerStyle.globalLight wraps on its own, where 400 stores 40. --- crates/engine/src/layer_style.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 934c6a260d..89b14d1090 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -1163,7 +1163,7 @@ pub fn specs() -> Vec { style_cmd!( "innerShadow", "Inner Shadow…", - r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":-360..360 (stored wrapped into -180..180),"distance":0..30000,"choke":0..100,"size":0..250,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## + r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":-360..360 (clamped, then wrapped into -180..180: 400 -> 0; the shared light angle of layer.layerStyle.globalLight only wraps: 400 -> 40),"distance":0..30000,"choke":0..100,"size":0..250,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"## ), style_cmd!( "outerGlow", From 36d05ab93301495cb4b12a49f0d62447304360dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 23:26:31 +0100 Subject: [PATCH 236/385] 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 237/385] 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 52e46f83bcea34d67e175dcf20af58af3b23c155 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 00:05:50 +0100 Subject: [PATCH 238/385] test(layer-style): pin the lit side of the inner-shadow angle guard effect_entry only keeps an imported Inner Shadow Angle when the effect does not follow the shared light: while it does follow it, the page's Angle field shows the light's angle and not the effect's own, so an untouched OK keeps writing the light angle as before. This pins the other value of that condition, the way the unedited bevel-shading pin covers its own guard. Guard test: green before and after the fix hunk on purpose. With only crates/ui-egui/src/dialogs/layer_style.rs reverted to 9b2a5439e the filter run gave 3 passed and 1 failed, the failure being unedited_inner_shadow_keeps_imported_out_of_range_values (stored 30000.0 where the file carried 40000.0). --- .../ui-egui/src/dialogs/layer_style/tests.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 21cb99fd2d..54084c8b9d 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -573,6 +573,29 @@ fn unedited_inner_shadow_keeps_imported_out_of_range_values() { } } +/// The other side of the guard above: while the effect follows the shared light, the Angle field +/// shows that light and not the effect's own angle, so an untouched OK keeps writing the light's +/// angle as it did before this change - the imported angle was never what the field showed. +/// Guard test: it passes before and after the change on purpose. +#[test] +fn an_inner_shadow_lit_by_the_global_light_still_takes_the_shown_angle() { + let mut s = session(); + s.execute("layer.layerStyle.innerShadow", json!({})).unwrap(); + s.edit("imported angle while lit", |doc, active| { + let Effect::InnerShadow(sh) = &mut doc.layer_mut(active.unwrap()).unwrap().effects.items[0] else { panic!("inner shadow") }; + sh.angle = 200.0; + sh.use_global_light = true; + Ok(()) + }) + .unwrap(); + s.execute("layer.layerStyle.globalLight", json!({"angle": 45.0})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let d = LayerStyleDraft::new(drafted(&s)); + apply(&d.style, id, Some(45.0), |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let Effect::InnerShadow(after) = &layer_effects(&s)[0] else { panic!("inner shadow") }; + assert_eq!(f64::from(after.angle), 45.0, "the field showed the light's 45, so OK stores 45"); +} + fn overlay_color(doc: &photocraft_doc::Document, layer: photocraft_doc::LayerId) -> photocraft_color::Color { match &doc.layer(layer).unwrap().effects.items[0] { Effect::ColorOverlay { color, .. } => *color, From 2384a050ac7220dbaa1359ae2fd6f55bcd168cbb Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:07:24 +0100 Subject: [PATCH 239/385] Apply Data Set: buttons beside the body through button_place (craft-libs renamed side_buttons) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/apply_data_set_ui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/apply_data_set_ui.rs b/crates/ui-egui/src/panels/apply_data_set_ui.rs index 1e35efce7b..313579f4af 100644 --- a/crates/ui-egui/src/panels/apply_data_set_ui.rs +++ b/crates/ui-egui/src/panels/apply_data_set_ui.rs @@ -71,7 +71,7 @@ impl StackDialog for ApplyDataSetDialog { let ApplyDataSetDialog { names, selected } = self; let shown = FormDialog::new(label(tl!("Apply Data Set")), Bind::bound(selected)) .ok_label(label(tl!("Apply"))) - .side_buttons(true) + .button_place(craft::ui::dialog::ButtonPlace::Side) // Holding Alt keeps Cancel: the dialog has nothing to reset. .alt_resets(false) .show(ui, |ui, form, selected| { From 4aeb7e7c8da3141c67a8f13a40f7a4aaeeb033ad Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:14:05 +0100 Subject: [PATCH 240/385] 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 241/385] 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 242/385] 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 243/385] 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 244/385] 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 245/385] 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 246/385] 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 247/385] 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 248/385] 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 249/385] 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 2bbcdf5c65e7f4b01cb69c591c615201941b30e7 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 02:00:04 +0100 Subject: [PATCH 250/385] test(ui): pin Make Default with Use Global Light on Owner decision on #14887: the Reset to Default behaviour stands (Photoshop behaviour is the reference), and the Make-Default direction now gets a pin. make_default_keeps_the_typed_shared_angle clicks the Bevel page's Make Default with Angle 45 typed under the shared light: the stored defaults carry the shown 45 and useGlobalLight on, never the factory 120, and after retyping the light to 30 a Reset to Default follows the live shared angle, not the stored literal. Guard pin, no behaviour change; with the branch's reset seeding temporarily disabled the new test fails, so the pin bites. tests::harness becomes pub(super) for the button click. --- .../layer_style/bevel_reset_angle_tests.rs | 39 ++++++++++++++++++- .../ui-egui/src/dialogs/layer_style/tests.rs | 2 +- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs index 14bc3ae3c0..64ea112d65 100644 --- a/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/bevel_reset_angle_tests.rs @@ -4,10 +4,11 @@ //! disagreed. The reset now seeds the dialog's shared light angle into a globally lit effect, the //! way a new instance starts from it (`fresh_params`, and the draft's own `add_instance`). use craft::imaging::layer_style::{EffectId, EffectKind, LayerStyle, StyleParams, StyleValue}; +use egui_kittest::kittest::Queryable; use serde_json::json; use super::reset_to_default; -use super::tests::{app_with_layer, defaults, draft, edit, first_of, ok}; +use super::tests::{app_with_layer, defaults, draft, edit, first_of, harness, ok}; use super::{DialogId, open}; use crate::PhotocraftApp; @@ -101,3 +102,39 @@ fn reset_to_default_keeps_a_saved_defaults_own_angle_when_global_light_is_off() assert_eq!(num(style, bevel, "angle"), Some(77.0), "the saved default's own angle, not the shared light"); assert_eq!(num(style, bevel, "size"), Some(12.0), "the other fields are the saved default's too"); } + +/// Owner decision round (#14887, Photoshop behaviour as the reference): the Make-Default direction +/// of the same rule. Use Global Light on, Angle 45 typed: the Bevel page's Make Default button +/// sends its SHOWN values, and a globally lit Angle row shows the shared light angle, so the +/// stored default carries the typed 45 and `useGlobalLight` on, never the factory 120. Retyping +/// the shared light to 30 and resetting then takes the live angle, not the stored literal: the +/// stored default carries the shared-angle rule the way Reset to Default seeds it. +#[test] +fn make_default_keeps_the_typed_shared_angle() { + let mut app = app_with_layer(32); + app.run("layer.layerStyle.bevelEmboss", json!({})).unwrap(); + let id = open(&mut app, Some(EffectKind::BevelEmboss.key())).unwrap(); + let bevel = first_of(&app, id, EffectKind::BevelEmboss); + // What the Angle row does when 45 is typed, plus a Size to store as the new default. + edit(&mut app, id, |d| { + d.set_param(bevel, "angle", StyleValue::Number(45.0)); + d.set_param(bevel, "size", StyleValue::Number(9.0)); + }); + let mut h = harness(app); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Make Default").click(); + h.run_steps(3); + let stored = h.state_mut().run("layer.layerStyle.defaultFor", json!({"kind": "bevelEmboss"})).unwrap(); + assert_eq!(stored["params"]["angle"].as_f64(), Some(45.0), "Make Default stored the shown shared angle, not the factory 120"); + assert_eq!(stored["params"]["useGlobalLight"].as_bool(), Some(true), "the stored default carries the shared light rule"); + assert_eq!(stored["params"]["size"].as_f64(), Some(9.0), "the other shown fields are stored too"); + // Retype the shared light to 30, then Reset to Default: the live shared angle wins over the + // stored literal 45, and the other fields fall back to the stored Make-Default values. + edit(h.state_mut(), id, |d| d.set_param(bevel, "angle", StyleValue::Number(30.0))); + reset_to_default(h.state_mut(), id, bevel); + let style = &draft(h.state(), id).style; + assert_eq!(num(style, bevel, "angle"), Some(30.0), "the reset takes the live shared light, not the stored 45"); + assert_eq!(num(style, bevel, "size"), Some(9.0), "Size falls back to the stored default, not the factory one"); + assert_eq!(style.global_light, 30.0, "the reset does not move the shared light"); + ok(h.state_mut(), id); + assert_eq!(h.state().session.active().unwrap().doc.global_light.angle, 30.0, "OK sets the document's Global Light to 30"); +} diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 48fa6fe94b..f56002b426 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -128,7 +128,7 @@ fn row(setup: &[(&str, Value)]) -> (photocraft_engine::Session, LayerStyle) { (s, style) } -fn harness(app: Box) -> Harness<'static, Box> { +pub(super) fn harness(app: Box) -> Harness<'static, Box> { let mut h = Harness::builder().with_size(vec2(1500.0, 1000.0)).with_context(app.ctx().clone()).build_ui_state( |ui, app: &mut Box| { app.framework.dialogs.run(ui); From 90d9e35affabbf4aeacb1596590b4996820e683d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 02:37:11 +0100 Subject: [PATCH 251/385] 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 7752a5c07649f9f407a6fa1ff6be74b791c2be29 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 02:24:19 +0000 Subject: [PATCH 252/385] Composite 8/16-bit Grayscale Gradient Maps on the CPU The shader's Gradient Map LUT returns the stop colour unchanged, so the GPU compositor kept a coloured gradient in a Grayscale document while the CPU path now keeps the stop colour's CIE L* (#14698). The planner returns Unsupported for that case, as it does for CMYK/Lab channels, so the whole document falls back to the CPU compositor. --- crates/gpu/src/plan/planner.rs | 8 ++++++++ crates/gpu/src/plan/tests.rs | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 3fe3cee6c9..7ec3d5a8d1 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -790,6 +790,14 @@ impl<'a> Planner<'a> { if !adjustment_on_gpu(adj, self.cx.mode) { return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label()))); } + // An 8/16-bit Grayscale Gradient Map keeps each stop colour's CIE L* (compose::adjust:: + // gray_from_srgb_lightness); the shader's LUT lookup returns the stop colour itself. + if matches!(adj, Adjustment::GradientMap { .. }) + && self.cx.mode == photocraft_color::ColorMode::Grayscale + && self.cx.depth != photocraft_color::SampleType::F32 + { + return Err(Unsupported("Gradient Map in an 8/16-bit Grayscale document (evaluated on the CPU)".into())); + } if let Adjustment::GradientMap { stops, .. } = adj { check_gradient_stops(stops)?; } diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index c563fb289f..909658d141 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -25,6 +25,22 @@ fn stops_closer_than_one_lut_step_stay_on_the_cpu() { assert!(check_gradient_stops(&[(0.0_f32, ()), (1.0, ())]).is_ok()); } +#[test] +fn grayscale_gradient_map_at_8_and_16_bits_falls_back_to_the_cpu() { + let adj = Adjustment::GradientMap { stops: vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])], reverse: false, dither: false, source: None }; + for depth in [SampleType::U8, SampleType::U16] { + let mut doc = Document::new("gray", Size::new(4, 4), ColorMode::Grayscale, depth); + doc.layers.push(Layer::new("map", LayerContent::Adjustment(adj.clone()))); + assert!(plan(&doc).unwrap_err().0.contains("Grayscale"), "{depth:?}"); + // RGB and 32-bit Grayscale keep the shader's plain stop-colour LUT. + doc.mode = ColorMode::Rgb; + assert!(plan(&doc).is_ok(), "{depth:?} in RGB"); + doc.mode = ColorMode::Grayscale; + doc.depth = SampleType::F32; + assert!(plan(&doc).is_ok(), "32-bit Grayscale"); + } +} + #[test] fn lab_channel_adjustments_defer_to_the_cpu_in_lab_documents() { let lab_rules = [ From 5c7db90e2ac55cba51ebdfd3265d7f815adbedc9 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 02:46:32 +0000 Subject: [PATCH 253/385] fix(engine): start a new Find round when the search criteria change (#15007) Clear the remembered round origin together with the cursor when the find text or an option differs, and on a zero-hit Change All, so a new query cannot stop at the layer an earlier round started in. Adds changed_query_starts_a_new_round_and_reaches_the_old_origin. --- .../engine/src/cmd/edit_menu_cmds/find_replace.rs | 3 +++ .../edit_menu_cmds/find_replace_order_tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs index b705b696ab..55cb540344 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs @@ -88,6 +88,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { let count: usize = plan.iter().map(|(_, m)| m.len()).sum(); if count == 0 { s.edit_state.find_cursor = None; + s.edit_state.find_start = None; return Ok(json!({"count": 0, "layers": 0})); } s.edit("Replace All Text", |doc, _| { @@ -114,7 +115,9 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { .as_ref() .is_some_and(|c| c.find == find && c.case_sensitive == case && c.whole_word == whole && c.forward == forward && c.all_layers == all_layers); if !same_query { + // A new query starts a new round: forget both the cursor and the round origin. s.edit_state.find_cursor = None; + s.edit_state.find_start = None; } let cursor = s.edit_state.find_cursor.as_ref().map(|c| (c.layer, c.start, c.end)); let mut changed = None; diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs index b5dee10238..8bc8348e28 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace_order_tests.rs @@ -153,6 +153,21 @@ fn find_next_single_layer_and_change_all_preserved() { assert_eq!((r["count"].as_u64(), r["layers"].as_u64()), (Some(8), Some(4))); } +#[test] +fn changed_query_starts_a_new_round_and_reaches_the_old_origin() { + let (mut s, [t1, t2, ..], _) = make_order_doc(); + s.execute("layer.select", json!({"layer": t1.0})).unwrap(); + // The round starts at T1: four hits there, then the match in T2. + for _ in 0..4 { + assert_eq!(find_next(&mut s, true, true).map(|h| h.0), Some(t1)); + } + assert_eq!(find_next(&mut s, true, true), Some((t2, 4, 7, "cat".into()))); + + // A query that matches only in the old origin (T1) must be reachable from the cursor in T2. + let r = s.execute("edit.findAndReplaceText", json!({"find": "CAT", "action": "find", "forward": true, "allLayers": true, "caseSensitive": true})).unwrap(); + assert_eq!((r["found"]["layer"].as_u64(), r["found"]["text"].as_str()), (Some(t1.0), Some("CAT"))); +} + #[test] fn find_next_from_top_pixel_layer_wraps_to_bottom_type_layer() { let (mut s, [t1, ..], top_pixel) = make_order_doc(); From 13418925ca84db4bb03f4c05e0641352a0414b9d Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 04:00:48 +0100 Subject: [PATCH 254/385] 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 abb9f582b767a1e3e43af63a836d62e81ca237c9 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:06:12 +0100 Subject: [PATCH 255/385] Duplicate Layer: key the destination by document id, not tab index The Document choice stored a tab index, so reordering tabs or closing another document while the dialog was open sent the copy to whichever document took the chosen one's place. The choice now holds the document's id, resolved to its current index at OK; a destination closed meanwhile refuses OK with the reason and keeps the dialog open. --- .../dialogs/duplicate_layer_indexed_tests.rs | 21 +++-- .../ui-egui/src/dialogs/duplicate_layer_ui.rs | 93 ++++++++++++++++--- 2 files changed, 93 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs index 7802cf5069..96958d5d6a 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_indexed_tests.rs @@ -1,6 +1,6 @@ //! Duplicate Layer's Destination › Document list leaves out documents a layer can't be copied //! into, as Photoshop leaves out Indexed Color documents (#14612). The rest keep tab order and -//! their own document index on OK. +//! their own document on OK. use super::destinations; use crate::PhotocraftApp; use crate::new_layer_ui::testing::{set, top}; @@ -34,6 +34,11 @@ fn keys(app: &PhotocraftApp) -> Vec { destinations(app).into_iter().map(|(key, _)| key).collect() } +/// The keys the documents at these tab indices have: their ids. +fn ids(app: &PhotocraftApp, tabs: &[usize]) -> Vec { + tabs.iter().map(|&i| app.session.documents()[i].doc.id.0.to_string()).collect() +} + #[test] fn indexed_documents_are_left_out_and_the_other_modes_keep_tab_order() { let app = app_with(&[ @@ -49,7 +54,7 @@ fn indexed_documents_are_left_out_and_the_other_modes_keep_tab_order() { assert_eq!(modes[5], (ColorMode::Rgb, 16)); let names: Vec<_> = destinations(&app).into_iter().map(|(_, name)| name).collect(); assert_eq!(names, ["Poster", "Print", "Gray", "Lab", "Deep"]); - assert_eq!(keys(&app), ["0", "2", "3", "4", "5"], "each entry keeps its document's index"); + assert_eq!(keys(&app), ids(&app, &[0, 2, 3, 4, 5]), "each entry is keyed by its document"); } #[test] @@ -61,19 +66,21 @@ fn bitmap_and_multichannel_documents_are_left_out_too() { ]); assert_eq!(app.session.documents()[1].doc.mode, ColorMode::Bitmap); assert_eq!(app.session.documents()[2].doc.mode, ColorMode::Multichannel); - assert_eq!(keys(&app), ["0", "3"], "layer.copyToDocument refuses both modes"); + assert_eq!(keys(&app), ids(&app, &[0, 3]), "layer.copyToDocument refuses both modes"); } #[test] fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { let mut app = app_with(&[("Palette", "rgb", &[indexed()]), ("Card", "rgb", &[])]); - assert_eq!(keys(&app), ["0", "2"]); + assert_eq!(keys(&app), ids(&app, &[0, 2])); let ctx = app.ctx().clone(); crate::menus::invoke(&mut app, &ctx, "layer.duplicate", json!({})).unwrap(); let dialog = top(&app); let palette_layers = app.session.documents()[1].doc.layer_count(); - assert!(set(&mut app, dialog, "document", json!("1")).is_err(), "the Indexed document is not a choice"); - set(&mut app, dialog, "document", json!("2")).unwrap(); + let palette = ids(&app, &[1]).remove(0); + assert!(set(&mut app, dialog, "document", json!(palette)).is_err(), "the Indexed document is not a choice"); + let card = ids(&app, &[2]).remove(0); + set(&mut app, dialog, "document", json!(card)).unwrap(); crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap(); // The passes after OK deliver the held answer to the family that runs it. for _ in 0..2 { @@ -89,5 +96,5 @@ fn ok_on_the_document_after_an_indexed_one_copies_into_that_document() { fn the_source_stays_listed_whatever_its_mode() { let mut app = app_with(&[("Palette", "rgb", &[indexed()]), ("Card", "rgb", &[])]); app.session.set_active(1); - assert_eq!(keys(&app), ["0", "1", "2"], "duplicating within the source is a plain duplicate"); + assert_eq!(keys(&app), ids(&app, &[0, 1, 2]), "duplicating within the source is a plain duplicate"); } diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index c5d56672bc..59e6ace51c 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -27,23 +27,28 @@ enum Destination { } /// The destination the `document` field names; one rule for the held OK's check and for the run. +/// The field holds the document's id, looked up again here, so closing or reordering tabs while +/// the dialog is open never sends the copy to whichever document took the chosen one's place. fn destination(app: &PhotocraftApp, fields: &DialogFields) -> Result { match fields.text("document") { Some("new") => Ok(Destination::New), - Some(index) => index - .parse::() - .ok() - .filter(|i| *i < app.session.documents().len()) - .map(Destination::Document) - .ok_or_else(|| tl!("no destination document").to_string()), + Some(id) => { + let id = id.parse::().map_err(|_| tl!("no destination document").to_string())?; + app.session + .documents() + .iter() + .position(|d| d.doc.id.0 == id) + .map(Destination::Document) + .ok_or_else(|| tl!("The destination document is no longer open. Choose another one.").to_string()) + } None => Err(tl!("no destination document").to_string()), } } /// Opens the dialog on the selected layers. The document and the selection are captured for [`check`]. pub fn open(app: &mut PhotocraftApp) -> Result { - let index = app.session.active_index().ok_or("no document")?; let st = app.session.active().ok_or("no document")?; + let source = st.doc.id.0; let selected = st.selected_layers(); let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; let captured = json!({"document": st.doc.id.0, "selected": selected.iter().map(|id| id.0).collect::>()}); @@ -62,7 +67,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result { if let Some(name) = &name { rows.push(Param::new("name", tl!("As:"), ParamKind::text(name.clone()))); } - rows.push(Param::new("document", tl!("Document"), ParamKind::choice(options.clone(), Some(index.to_string())))); + rows.push(Param::new("document", tl!("Document"), ParamKind::choice(options.clone(), Some(source.to_string())))); // Photoshop's document `Name` starts empty; the engine defaults it when empty, and it is only there for a new document. rows.push(Param::new("documentName", tl!("Name:"), ParamKind::text("")).visible_when("document", "new")); ParamDialog::command(KEY, title, rows).values(Bind::bound(fields)) @@ -70,7 +75,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result { } /// The Destination › Document entries before New: the open documents in tab order, keyed by -/// their index, without those `layer.copyToDocument` refuses (Indexed Color and the other modes +/// their document id, without those `layer.copyToDocument` refuses (Indexed Color and the other modes /// outside `layered`), as Photoshop leaves them out (#14612). The source stays: copying within it /// is a plain duplicate. pub(crate) fn destinations(app: &PhotocraftApp) -> Vec<(String, String)> { @@ -80,7 +85,7 @@ pub(crate) fn destinations(app: &PhotocraftApp) -> Vec<(String, String)> { .iter() .enumerate() .filter(|(i, d)| Some(*i) == source || photocraft_engine::layer_copy_cmds::layered(d.doc.mode)) - .map(|(i, d)| (i.to_string(), d.doc.name.clone())) + .map(|(_, d)| (d.doc.id.0.to_string(), d.doc.name.clone())) .collect() } @@ -150,6 +155,19 @@ mod tests { fn names(app: &PhotocraftApp, i: usize) -> Vec { app.session.documents()[i].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() } + /// The Document choice's value for the document at tab `i`: its id. + fn key(app: &PhotocraftApp, i: usize) -> serde_json::Value { + json!(app.session.documents()[i].doc.id.0.to_string()) + } + /// Poster (active, with Ink), Card and Spare. + fn three_docs() -> Box { + let mut app = make_app(); + for name in ["Card", "Spare"] { + app.session.execute("file.new", json!({"width":8,"height":8,"name":name})).unwrap(); + } + app.session.set_active(0); + app + } #[test] fn the_menu_opens_the_dialog_and_ok_duplicates_under_the_typed_name() { @@ -170,7 +188,8 @@ mod tests { app.session.execute("file.new", json!({"width":8,"height":8,"name":"Card"})).unwrap(); app.session.set_active(0); let dialog = invoke(&mut app); - set(&mut app, dialog, "document", json!("1")).unwrap(); + let pick = key(&app, 1); + set(&mut app, dialog, "document", pick).unwrap(); confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(app.session.documents()[0].doc.layer_count(), 2); assert!(names(&app, 1).contains(&"Ink copy".to_string())); @@ -192,7 +211,7 @@ mod tests { } #[test] - fn a_new_destination_without_a_name_defaults_it_and_refuses_a_dead_index() { + fn a_new_destination_without_a_name_defaults_it_and_refuses_an_unknown_document() { let mut app = make_app(); let ctx = app.ctx().clone(); let dialog = invoke(&mut app); @@ -200,8 +219,8 @@ mod tests { confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(app.session.documents()[1].doc.name, "Poster copy"); let dialog = invoke(&mut app); - // Either the select refuses the index or the held OK does. - if set(&mut app, dialog, "document", json!("7")).is_ok() { + // Either the select refuses the id or the held OK does. + if set(&mut app, dialog, "document", json!(u64::MAX.to_string())).is_ok() { assert!(confirm(&mut app, &ctx, dialog).is_err()); } assert_eq!(app.session.documents().len(), 2); @@ -217,6 +236,52 @@ mod tests { assert!(app.framework.dialogs.stack().contains(dialog), "the dialog stays open"); assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "nothing was copied"); } + + /// The choice names a document, not a tab position: reordering tabs or closing another + /// document while the dialog is open still copies into the one picked. + #[test] + fn the_picked_document_receives_the_copy_after_tabs_move_or_close() { + for change in ["move", "close"] { + let mut app = three_docs(); + let ctx = app.ctx().clone(); + let dialog = invoke(&mut app); + let pick = key(&app, 2); + set(&mut app, dialog, "document", pick).unwrap(); + if change == "move" { + // Spare to the front: Card now sits where Spare was. + app.session.move_document(2, 0).unwrap(); + } else { + // Card closes: Spare moves up into its place. + app.session.close(1).unwrap(); + } + confirm(&mut app, &ctx, dialog).unwrap(); + let docs = app.session.documents(); + let spare = docs.iter().position(|d| d.doc.name == "Spare").unwrap(); + let spare_names: Vec<_> = docs[spare].doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect(); + assert!(spare_names.contains(&"Ink copy".to_string()), "{change}: Spare receives the copy: {spare_names:?}"); + if let Some(card) = docs.iter().position(|d| d.doc.name == "Card") { + assert_eq!(docs[card].doc.layer_count(), 1, "{change}: Card is untouched"); + } + let poster = docs.iter().position(|d| d.doc.name == "Poster").unwrap(); + assert_eq!(docs[poster].doc.layer_count(), 2, "{change}: the source is untouched"); + } + } + + /// Closing the picked document refuses OK with the reason and keeps the dialog open. + #[test] + fn a_closed_destination_refuses_and_keeps_the_dialog() { + let mut app = three_docs(); + let ctx = app.ctx().clone(); + let dialog = invoke(&mut app); + let pick = key(&app, 2); + set(&mut app, dialog, "document", pick).unwrap(); + app.session.close(2).unwrap(); + let err = confirm(&mut app, &ctx, dialog).unwrap_err(); + assert!(err.contains("no longer open"), "{err}"); + assert!(app.framework.dialogs.stack().contains(dialog), "the dialog stays open"); + assert_eq!(app.session.documents()[1].doc.layer_count(), 1, "Card, now in Spare's place, is untouched"); + assert_eq!(app.session.documents()[0].doc.layer_count(), 2, "nothing was copied"); + } } #[cfg(test)] From ec40c48cc2215b5f4e5ca9e899621eab981b490f Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 03:33:27 +0000 Subject: [PATCH 256/385] ci: build the tests once per OS and run the shards from a nextest archive --- .config/nextest.toml | 6 ++++ .github/workflows/ci.yml | 6 ++-- docs/development.md | 2 +- scripts/ci-gpu-lavapipe.py | 2 +- scripts/ci-test-shard.sh | 38 +++++++++------------- xtask/src/main.rs | 66 ++++++++++++++++++++++++++++++++------ 6 files changed, 85 insertions(+), 35 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index ce481be0f7..e50593dd52 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -33,6 +33,12 @@ test-group = 'gpu' fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" +# The gate's shards run the tests from a nextest archive (`cargo xtask ci archive`) and start them +# with the xtask binary the archive carries, so a shard builds nothing. Only one of the two exists. +archive.include = [ + { path = "debug/xtask", relative-to = "target", depth = 0, on-missing = "ignore" }, + { path = "debug/xtask.exe", relative-to = "target", depth = 0, on-missing = "ignore" }, +] # Keep phase timings for the remaining expensive Windows GPU regressions visible. This does # not relax their timeout, isolate failures differently or remove any test cases. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d8ece1fc4..70c2e6083e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,7 +155,7 @@ jobs: gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once with: # egui/winit/rfd. packages: >- @@ -184,6 +184,7 @@ jobs: # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' # own tests. lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint + archive-command: cargo xtask ci archive test-shards: 4 # The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs). shard-command: bash scripts/ci-test-shard.sh --gpu-shard @@ -201,7 +202,7 @@ jobs: needs: platforms if: needs.platforms.outputs.windows == 'true' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once with: os: '["windows-latest"]' # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with @@ -231,6 +232,7 @@ jobs: timeout-minutes: 100 warm-command: cargo xtask ci build lint-command: cargo xtask ci clippy + archive-command: cargo xtask ci archive test-shards: 6 shard-command: bash scripts/ci-test-shard.sh diff --git a/docs/development.md b/docs/development.md index 4297bd541b..fe51840cac 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate runs the tests in shards (`scripts/ci-test-shard.sh`, which calls `cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1` and run `python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu`. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index ab3d46d5a7..7ff41e10c7 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -2,7 +2,7 @@ """Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. The Linux gate runs nextest's `gpu` test group in a shard of its own through this script -(`ci-gpu-lavapipe.py cargo xtask ci tests --gpu`, scripts/ci-test-shard.sh): every wgpu +(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output is checked here for authored skips and for the parity tests' Vulkan backend line. diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh index c1c380de6f..40afc15146 100755 --- a/scripts/ci-test-shard.sh +++ b/scripts/ci-test-shard.sh @@ -1,41 +1,35 @@ #!/usr/bin/env bash -# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). Each shard -# restores the dependency cache, builds the tests (`cargo xtask ci build` builds the same on main's -# cache warm-up leg) and runs its share with `cargo xtask ci tests`. The gate sets GATE_SHARD (1..N), -# GATE_SHARDS (N) and NEXTEST_PARTITION (hash:GATE_SHARD/GATE_SHARDS). +# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's +# build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive +# carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps +# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, +# GATE_SHARDS and NEXTEST_PARTITION. # -# ci-test-shard.sh each shard runs its hash partition of every test; shard 1 also -# runs the doctests +# ci-test-shard.sh the shard runs its hash partition of every test # ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by -# scripts/ci-gpu-lavapipe.py; the other shards split the other tests, -# and shard 2 also runs the doctests +# scripts/ci-gpu-lavapipe.py; the other shards split the other tests set -euo pipefail +archive=target/nextest-archive +mkdir -p "$archive" +cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --extract-to "$archive" --extract-overwrite -E 'none()' --no-tests=pass +xtask=("$archive/target/debug/xtask" ci tests --from "$archive") +case "$(uname -s)" in MINGW* | MSYS* | CYGWIN*) xtask=("$archive/target/debug/xtask.exe" ci tests --from "$archive") ;; esac + case "${1:-}" in - "") - cargo xtask ci tests - doctests=1 - ;; + "") exec "${xtask[@]}" ;; --gpu-shard) if [ "$GATE_SHARDS" -lt 2 ]; then echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" exit 1 fi if [ "$GATE_SHARD" = 1 ]; then - # Build first, so only the test run goes through the lavapipe check. - cargo xtask ci build - python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu - else - NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" cargo xtask ci tests --no-gpu + exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu fi - doctests=2 + NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu ;; *) echo "usage: $0 [--gpu-shard]" >&2 exit 2 ;; esac - -if [ "$GATE_SHARD" = "$doctests" ]; then - cargo xtask ci doctest -fi diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 72abfd43dd..97ae021fd4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -35,11 +35,13 @@ commands: wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call, plus one per optional web feature) test workspace tests (cargo nextest when installed, else cargo test), then doctests - ci [lint | build | tests [--gpu | --no-gpu] | ] + ci [lint | archive | build | tests [--from ] [--gpu | --no-gpu] | ] the CI gate: fmt --check, egui-fork, clippy -D warnings, layers, panel-commands, scorecard --check, tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the - steps that need no test build; `tests` runs the tests and panic_hunt on the partition in + steps that need no test build; `archive` builds the tests into the nextest archive at + $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that archive + extracted to (without --from it builds them); `tests` runs the tests and panic_hunt on the partition in $NEXTEST_PARTITION (`--gpu`: all of nextest's gpu test group, whatever the partition, each test's output shown; `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` @@ -284,6 +286,10 @@ struct CiOptions { build_only: bool, /// The nextest partition the test steps run ($NEXTEST_PARTITION with `ci tests`). partition: Option, + /// `ci archive`: build the tests into this nextest archive instead of running them. + archive: Option, + /// `ci tests --from `: run the tests from a nextest archive extracted to this directory. + from: Option, selection: Selection, /// Workspace packages left out of the test build and the doctests ($PHOTOCRAFT_CI_EXCLUDE). exclude: Vec, @@ -388,7 +394,22 @@ fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>) -> Vec Result<(), String> { /// warm-up's entry covers each shard's build. fn build_tests(o: &CiOptions) -> Result<(), String> { let mut c = cargo(); - c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); + match &o.archive { + Some(file) => { + c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file); + } + None => { + c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); + } + } let what = shown(&c); run(c, &what) } @@ -465,18 +493,23 @@ fn ci_exclude() -> Vec { /// The steps `cargo xtask ci ` runs, and how: no argument runs every step; a part (`lint`, /// `build`, `tests`) runs the steps of one gate job; a step's name runs that step. fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOptions), String> { - let mut options = CiOptions { build_only: false, partition: None, selection: Selection::All, exclude }; + let mut options = CiOptions { build_only: false, partition: None, archive: None, from: None, selection: Selection::All, exclude }; let mut what = None; - for &arg in args { + let mut it = args.iter(); + while let Some(&arg) = it.next() { match arg { + "--from" => { + let dir = it.next().ok_or("--from needs the directory the archive was extracted to")?; + options.from = Some(std::path::absolute(dir).map_err(|e| format!("--from {dir}: {e}"))?); + } "--gpu" => options.selection = Selection::Gpu, "--no-gpu" => options.selection = Selection::NoGpu, _ if what.is_none() && !arg.starts_with('-') => what = Some(arg), _ => return Err(format!("ci: unexpected argument `{arg}`")), } } - if options.selection != Selection::All && what != Some("tests") { - return Err("ci: --gpu and --no-gpu go with `ci tests`".into()); + if (options.selection != Selection::All || options.from.is_some()) && what != Some("tests") { + return Err("ci: --from, --gpu and --no-gpu go with `ci tests`".into()); } let parts: &[Part] = match what { None => &[Part::Lint, Part::Test, Part::Doc], @@ -485,6 +518,14 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOption options.build_only = true; &[Part::Test] } + // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE (which also + // carries this xtask, .config/nextest.toml), and the doctests, which need the rlibs. + Some("archive") => { + let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; + options.archive = Some(file.into()); + options.build_only = true; + &[Part::Test, Part::Doc] + } Some("tests") => { options.partition = tests_partition(options.selection, std::env::var("NEXTEST_PARTITION").ok()); &[Part::Test] @@ -574,7 +615,14 @@ mod ci_tests { #[test] fn a_shard_builds_what_the_warm_up_builds_and_runs_its_partition() { - let options = CiOptions { build_only: false, partition: Some("hash:2/3".into()), selection: Selection::NoGpu, exclude: vec!["photocraft-web".into()] }; + let options = CiOptions { + build_only: false, + archive: None, + from: None, + partition: Some("hash:2/3".into()), + selection: Selection::NoGpu, + exclude: vec!["photocraft-web".into()], + }; let build = "--workspace --locked --features heif --exclude photocraft-web --lib --bins --tests"; let args = nextest_args(&options, false, Some("package(g)")).join(" "); assert_eq!(args, format!("nextest run --profile ci {build} --partition hash:2/3 -E not (package(g))")); From c353bd027454adb8796cd927c0644fc98921cb45 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 04:47:18 +0000 Subject: [PATCH 257/385] windows_delay_loads: read the exe path at run time, so a run from a nextest archive finds it --- apps/photocraft/tests/windows_delay_loads.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index f7b7504ced..a060f05871 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -10,7 +10,10 @@ const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; /// The built exe names each print-only DLL in its delay-load table, never its import table. #[test] fn print_only_system_dlls_are_delay_loaded() { - let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); + // The run-time variable first: a run from a nextest archive points it at the extracted exe, + // while the compile-time path names the directory the archive was built in. + let path = std::env::var("CARGO_BIN_EXE_photocraft").unwrap_or_else(|_| env!("CARGO_BIN_EXE_photocraft").to_string()); + let exe = std::fs::read(path).unwrap(); let pe = Pe::parse(&exe); let imports = pe.dll_names(1, 20, 12); let delayed = pe.dll_names(13, 32, 4); From 4e949fa450dfe594d2d0f238935f9413104426a0 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 07:57:34 +0100 Subject: [PATCH 258/385] Track engine change signals --- crates/engine/src/lib.rs | 1 + crates/engine/src/prefs/store.rs | 62 +++++++++++++++++++++++++- crates/engine/src/session/documents.rs | 30 +++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d75e2a645d..4dbb442134 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -201,6 +201,7 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do #[derive(Default)] pub struct Session { docs: Vec, + documents_generation: u64, /// Override Open belongs only to one Batch scratch session, never to caller preferences. pub(crate) batch_open: Option, /// Import diagnostics retained by a Batch scratch that suppresses only profile prompts. diff --git a/crates/engine/src/prefs/store.rs b/crates/engine/src/prefs/store.rs index 07f0d8260f..10194488c8 100644 --- a/crates/engine/src/prefs/store.rs +++ b/crates/engine/src/prefs/store.rs @@ -8,6 +8,8 @@ use super::{Deserialize, Map, Preferences, Serialize, Value}; pub struct PrefsStore { values: Preferences, rev: u64, + catalog_rev: u64, + section_revs: std::collections::BTreeMap, } impl PrefsStore { @@ -16,8 +18,29 @@ impl PrefsStore { } /// Change preferences; bumps the revision. pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + let before = (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar); + let before = (before.0.clone(), before.1.clone(), before.2.clone()); + let sections = self.values.sections.clone(); self.rev += 1; - f(&mut self.values) + let result = f(&mut self.values); + if (&before.0, &before.1, &before.2) != (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar) { + self.catalog_rev = self.catalog_rev.wrapping_add(1); + } + for key in sections.keys().chain(self.values.sections.keys()).collect::>() { + if sections.get(key) != self.values.sections.get(key) { + let revision = self.section_revs.entry(key.clone()).or_default(); + *revision = revision.wrapping_add(1); + } + } + result + } + /// Revision of catalog-affecting preferences. + pub fn catalog_rev(&self) -> u64 { + self.catalog_rev + } + /// Revision of a framework preference section. + pub fn section_rev(&self, key: &str) -> u64 { + self.section_revs.get(key).copied().unwrap_or_default() } pub fn rev(&self) -> u64 { self.rev @@ -131,3 +154,40 @@ fn lay_over( fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() } + +#[cfg(test)] +mod revision_tests { + use super::PrefsStore; + use serde_json::json; + + #[test] + fn unrelated_preference_edits_do_not_invalidate_the_catalog() { + let mut prefs = PrefsStore::default(); + let before = prefs.catalog_rev(); + prefs.edit(|p| p.selected_tool = json!("brush")); + assert_eq!(prefs.catalog_rev(), before); + prefs.edit(|p| { + p.shortcuts.insert("example".into(), "A".into()); + }); + assert_eq!(prefs.catalog_rev(), before.wrapping_add(1)); + } + + #[test] + fn section_revisions_change_independently() { + let mut prefs = PrefsStore::default(); + prefs.edit(|p| { + p.sections.insert("one".into(), json!({"value": 1})); + }); + let one = prefs.section_rev("one"); + let two = prefs.section_rev("two"); + prefs.edit(|p| { + p.sections.insert("two".into(), json!({"value": 2})); + }); + assert_eq!(prefs.section_rev("one"), one); + assert_eq!(prefs.section_rev("two"), two.wrapping_add(1)); + prefs.edit(|p| { + p.sections.remove("one"); + }); + assert_eq!(prefs.section_rev("one"), one.wrapping_add(1)); + } +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index fc3b1708aa..72ca474fe1 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,11 @@ impl Session { &self.docs } + /// Changes whenever a document is opened or closed. + pub fn documents_generation(&self) -> u64 { + self.documents_generation + } + pub fn active_index(&self) -> Option { self.active } @@ -182,6 +187,7 @@ impl Session { st.snapshots.clear(); } self.docs.push(st); + self.documents_generation = self.documents_generation.wrapping_add(1); let i = self.docs.len() - 1; self.active = Some(i); self.note_active_change(); @@ -222,6 +228,7 @@ impl Session { self.link_scan = None; } let d = self.docs.remove(index); + self.documents_generation = self.documents_generation.wrapping_add(1); self.open_document_order.retain(|&id| id != d.doc.id); self.active = if self.docs.is_empty() { None @@ -244,3 +251,26 @@ pub(super) fn fix_active(st: &mut DocState) { fix_selection(st); channel_cmds::fix_view(st); } + +#[cfg(test)] +mod document_generation_tests { + use super::Session; + use photocraft_color::SampleType; + use photocraft_doc::{ColorMode, Document}; + use photocraft_geom::Size; + + #[test] + fn document_generation_tracks_open_and_close_but_not_selection() { + let mut session = Session::new(); + let before = session.documents_generation(); + session.add_document(Document::new("test", Size::new(2, 2), ColorMode::Rgb, SampleType::U8), None); + let opened = session.documents_generation(); + assert_eq!(opened, before.wrapping_add(1)); + session.set_active(0); + assert_eq!(session.documents_generation(), opened); + session.close(0); + assert_eq!(session.documents_generation(), opened.wrapping_add(1)); + session.close(0); + assert_eq!(session.documents_generation(), opened.wrapping_add(1)); + } +} From e681044bf52c6fc6840ede6fd3dfc94f330a95bf Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 07:58:27 +0100 Subject: [PATCH 259/385] Reduce slow algorithm test fixtures --- crates/algo/src/inpaint/tests.rs | 4 ++-- crates/algo/src/panorama/parallel_tests.rs | 2 +- crates/algo/src/render.rs | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs index 747e9c36cd..8db4da3828 100644 --- a/crates/algo/src/inpaint/tests.rs +++ b/crates/algo/src/inpaint/tests.rs @@ -186,10 +186,10 @@ fn a_hole_is_as_thick_as_it_is_through_not_along() { #[test] #[cfg(not(target_arch = "wasm32"))] fn thin_holes_are_filled_the_same_on_any_number_of_threads() { - let (w, h) = (300, 200); + let (w, h) = (150, 100); let img = busy(w, h, 3, 5); // A wavy line 6 px thick across the image. - let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); + let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 15.0 + 50.0 - (i / w) as f32).abs() < 3.0).collect(); let px = roles(w, h, &hole); let run = |threads: usize| { let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs index 54f6f54edb..2bfa239fd5 100644 --- a/crates/algo/src/panorama/parallel_tests.rs +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -367,7 +367,7 @@ fn multiband_matches_the_serial_code() { /// none and everything, pass through every split the images can have (#15652; it swept 47 budgets). #[test] fn multiband_batches_match_the_serial_code() { - for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { + for (n, &(w, h)) in [(40usize, 30usize), (97, 61)].iter().enumerate() { for ch in [1usize, 3] { let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); for levels in [1usize, 3, 5] { diff --git a/crates/algo/src/render.rs b/crates/algo/src/render.rs index 6bce0bfa59..4df30a76a1 100644 --- a/crates/algo/src/render.rs +++ b/crates/algo/src/render.rs @@ -273,6 +273,10 @@ mod tests { let fmt = PixelFormat::new(mode, depth, true); for (w, h) in [(512, 512), (900, 240), (2400, 1200)] { for seed in [0, 3, 7, 18916] { + // One seed exercises the large canvas; all seeds still run at both smaller sizes. + if w == 2400 && seed != 0 { + continue; + } let px = render(fmt, w, h, seed, (BLACK, WHITE), None); let v: Vec = px.chunks_exact(fmt.channels()).map(|p| p[0]).collect(); let n = v.len() as f32; From 236bc84a5e7d67aa75976f401df9af5a51e78f35 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:01:25 +0100 Subject: [PATCH 260/385] Give scratch tests a deterministic volume capacity --- crates/automation/tests/it/scratch_save.rs | 1 + crates/compose/tests/it/scratch_retry.rs | 1 + .../engine/tests/global_state/scratch_disk.rs | 1 + .../tests/global_state/scratch_pause.rs | 1 + crates/format/tests/it/scratch_retry.rs | 1 + crates/raster/src/spill.rs | 40 ++++++++++++++++--- crates/raster/tests/it/main.rs | 4 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/tests/it/gpu_device_loss.rs | 2 + .../tests/it/gpu_tests/live_stroke_canvas.rs | 2 + .../ui-egui/tests/it/variables_data_sets.rs | 4 ++ 11 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/automation/tests/it/scratch_save.rs b/crates/automation/tests/it/scratch_save.rs index 140b916e31..e6f4eaa860 100644 --- a/crates/automation/tests/it/scratch_save.rs +++ b/crates/automation/tests/it/scratch_save.rs @@ -34,6 +34,7 @@ impl BandRenderer for QueuedDiagnosticsRenderer { #[test] fn native_save_refuses_previews_rendered_from_unreadable_scratch() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-automation-scratch-save-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Scratch", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); diff --git a/crates/compose/tests/it/scratch_retry.rs b/crates/compose/tests/it/scratch_retry.rs index 70fdc41225..625bb30e7f 100644 --- a/crates/compose/tests/it/scratch_retry.rs +++ b/crates/compose/tests/it/scratch_retry.rs @@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write}; #[test] fn failed_effect_build_is_not_reused_after_original_pixels_recover() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-compose-scratch-retry-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Shadow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); diff --git a/crates/engine/tests/global_state/scratch_disk.rs b/crates/engine/tests/global_state/scratch_disk.rs index 888fa4551c..21122fced2 100644 --- a/crates/engine/tests/global_state/scratch_disk.rs +++ b/crates/engine/tests/global_state/scratch_disk.rs @@ -9,6 +9,7 @@ use std::sync::Arc; #[test] fn scratch_pixels_history_and_failed_save_are_transactional() { + photocraft_raster::spill::use_test_volume_space(); let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id())); let mut session = Session::new(); diff --git a/crates/engine/tests/global_state/scratch_pause.rs b/crates/engine/tests/global_state/scratch_pause.rs index 309e69fd39..30c81f2903 100644 --- a/crates/engine/tests/global_state/scratch_pause.rs +++ b/crates/engine/tests/global_state/scratch_pause.rs @@ -9,6 +9,7 @@ use serde_json::json; #[test] fn paused_scratch_disk_restores_the_history_limit() { + photocraft_raster::spill::use_test_volume_space(); let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id())); let mut session = Session::new(); diff --git a/crates/format/tests/it/scratch_retry.rs b/crates/format/tests/it/scratch_retry.rs index 3d8a32f540..ea26de5a88 100644 --- a/crates/format/tests/it/scratch_retry.rs +++ b/crates/format/tests/it/scratch_retry.rs @@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write}; #[test] fn retry_after_failed_hashing_never_reuses_placeholder_hashes() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-format-scratch-retry-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Retry", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 2fc5707fa7..9b5245dea9 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -256,6 +256,7 @@ struct Registry { } struct Config { + query_space: fn(&Path) -> Option<(u64, u64)>, dir: Option, /// Opened at configuration time; startup also reaps abandoned Unix files. file: Option>, @@ -341,7 +342,17 @@ static M: Manager = Manager { recovering: AtomicBool::new(false), space_unmeasured: AtomicBool::new(false), registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), - config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None, room: None }), + config: Mutex::new(Config { + query_space: free_space, + dir: None, + file: None, + last_error: None, + budget: 0, + paused: None, + backoff: RETRY_FIRST, + size_cap: None, + room: None, + }), evictions: AtomicU64::new(0), reloads: AtomicU64::new(0), written: AtomicU64::new(0), @@ -609,11 +620,15 @@ impl Manager { /// Record a volume's answer (`None` = it didn't say) and derive the growth limit from it. fn apply_space(c: &mut Config, used: u64, space: Option<(u64, u64)>) { M.space_unmeasured.store(space.is_none(), Ordering::Relaxed); - c.room = space.map(|(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20)))); + c.room = space.map(|(available, total)| growth_limit(used, available, total)); store_limit(c); M.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed); } +fn growth_limit(used: u64, available: u64, total: u64) -> u64 { + used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20))) +} + /// Publish the scratch size the volume and the size limit allow. fn store_limit(c: &Config) { let room = c.room.unwrap_or(u64::MAX); @@ -664,13 +679,13 @@ fn run_query(dir: PathBuf, prepare: bool, done: Arc) { } // Before measuring: writes made during the query come off the free space and must not be // counted again on top of it. Another folder's file says nothing about this one. - let (open, used) = { + let (open, used, query_space) = { let c = M.config(); let current = c.file.as_ref().filter(|_| c.dir.as_deref() == Some(dir.as_path())); - (prepare && current.is_none(), current.map_or(0, |f| f.used())) + (prepare && current.is_none(), current.map_or(0, |f| f.used()), c.query_space) }; let file = open.then(|| std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir))); - let space = free_space(&dir); + let space = query_space(&dir); // Forget it first: a caller that joined it can rely on the answer, and a later caller asks anew. QUERIES.lock().unwrap_or_else(PoisonError::into_inner).retain(|q| !Arc::ptr_eq(&q.done, &done)); M.settle(&dir, prepare, file, used, space, &done); @@ -1122,6 +1137,12 @@ pub fn scratch_handle_for_tests() -> Option { M.config().file.as_ref().and_then(|f| f.duplicate_handle().ok()) } +/// Use a volume with ample space for scratch tests. Missing folders still report unknown space. +#[doc(hidden)] +pub fn use_test_volume_space() { + M.config().query_space = |dir| dir.is_dir().then_some((32 << 30, 64 << 30)); +} + /// Runs at the start of every folder query, off every lock: tests stall it to simulate a dead mount. #[doc(hidden)] pub fn set_query_hook_for_tests(hook: Option) { @@ -1156,6 +1177,15 @@ fn log_error(msg: &str) { mod tests { use super::*; + #[test] + fn scratch_growth_preserves_the_larger_of_one_gib_or_five_percent() { + const GIB: u64 = 1 << 30; + let used = 3 * GIB; + assert_eq!(growth_limit(used, 2 * GIB, 10 * GIB), used + GIB); + assert_eq!(growth_limit(used, 7 * GIB, 100 * GIB), used + 2 * GIB); + assert_eq!(growth_limit(used, 3 * GIB, 100 * GIB), used); + } + #[cfg(windows)] #[test] fn free_space_keeps_a_trailing_dot_folder() { diff --git a/crates/raster/tests/it/main.rs b/crates/raster/tests/it/main.rs index cda56fa4c1..9a6b14ffce 100644 --- a/crates/raster/tests/it/main.rs +++ b/crates/raster/tests/it/main.rs @@ -14,5 +14,7 @@ pub(crate) static SCRATCH: Mutex<()> = Mutex::new(()); /// Takes one of the locks above; a failed test that held it does not fail the next. pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { - lock.lock().unwrap_or_else(PoisonError::into_inner) + let guard = lock.lock().unwrap_or_else(PoisonError::into_inner); + photocraft_raster::spill::use_test_volume_space(); + guard } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f65417fd5c..47e02244e3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -228,6 +228,8 @@ impl PhotocraftApp { #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] live_tokens: theme::live::LiveTokens::from_env(), }; + #[cfg(all(test, not(target_arch = "wasm32")))] + photocraft_raster::spill::use_test_volume_space(); // Saved preferences are in place before the first frame; recovery starts in upkeep. prefs_ui::load(&mut app); // The workspace set reads the loaded preferences (and moves the earlier saves into it). diff --git a/crates/ui-egui/tests/it/gpu_device_loss.rs b/crates/ui-egui/tests/it/gpu_device_loss.rs index a3aa0bdca3..94d0bce1d3 100644 --- a/crates/ui-egui/tests/it/gpu_device_loss.rs +++ b/crates/ui-egui/tests/it/gpu_device_loss.rs @@ -142,6 +142,8 @@ mod gpu_tests { fn app_switches_to_the_cpu_canvas_and_keeps_the_documents() { let _gpu = gpu_lock(); let Some(rs) = render_state() else { return }; + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.set_wgpu(rs); app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs index fba4fef7a9..1556fb0e04 100644 --- a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs @@ -76,6 +76,8 @@ fn harness() -> 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(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if let Some(rs) = cc.wgpu_render_state.as_ref() { app.set_wgpu(rs.clone()); diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index 3fb254e664..6625378806 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -83,6 +83,8 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, H, String) { let png = photocraft_io::export(&source.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; std::fs::write(dir.path().join(name), png).unwrap(); } + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); let layer = app.session.active().unwrap().active_layer.unwrap(); @@ -103,6 +105,8 @@ fn save_draft_and_open_apply_menu(h: &mut H, id: &str) -> String { #[test] fn apply_menu_ok_requires_a_row_but_not_variable_definitions() { for (rows, expected) in [(json!([]), None), (json!([{"name": "Empty", "values": []}]), Some(0))] { + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); app.run("image.variables.dataSets", json!({"dataSets": rows})).unwrap(); From 3ee723a5259160df3e5136c6e7b7de951455268d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:01:29 +0100 Subject: [PATCH 261/385] Reduce slow engine test fixtures --- crates/engine/src/cmd/image_cmds/tests.rs | 10 ++++++---- crates/engine/src/cmd/retouch_cmds/tests.rs | 8 +++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 5acec8b8ba..88da8f65c1 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -798,16 +798,18 @@ fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { #[test] fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { use photocraft_color::PixelFormat; - let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); for depth in [8, 16, 32] { for angle in [3.0, -7.5, 33.0, 181.0] { + let (w, h) = if depth == 8 && angle == 33.0 { (700, 500) } else { (140, 100) }; + let scale = w / 140; + let pixels = || (0..h).flat_map(|y| (0..w).map(move |x| (x, y))); let mut sessions = [true, false].map(|delete| { let mut s = Session::new(); - s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); s.edit("paint", |doc, active| { let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; - let all = Rect::new(0, 0, 700, 500); + let all = Rect::new(0, 0, w, h); let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); let l = doc.layer_mut(active.unwrap()).unwrap(); @@ -824,7 +826,7 @@ fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { Ok(()) }) .unwrap(); - let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); + let p = json!({"x": 30 * scale, "y": 24 * scale, "width": 66 * scale, "height": 58 * scale, "angle": angle, "deleteCroppedPixels": delete}); s.execute("image.crop", p).unwrap(); s }); diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 49eaaaa52f..999575cf69 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -1650,10 +1650,11 @@ fn large_move(depth: u64) -> Session { } #[test] -fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths() { +fn content_aware_move_previews_large_selections_coarse_then_exact() { use crate::jobs::JobCtx; let p = json!({"offset": [250, 60]}); - for depth in DEPTHS { + // The small move test covers all depths; the preview sequence needs one. + for depth in [8] { let mut s = large_move(depth); let before = s.active().unwrap().revision; let job = content_aware_move_preview(&s, &p).unwrap(); @@ -1684,9 +1685,6 @@ fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths( let fine = job.refine().unwrap(); assert!(!fine.is_coarse() && fine.refine().is_none()); assert!(matches!(fine.run(&ctx), Err(EngineError::Cancelled)), "depth {depth}"); - if depth != 8 { - continue; - } // The refined preview is the command's result, bit for bit. let (exact, _) = fine.run(&JobCtx::new()).unwrap(); assert_eq!(s.active().unwrap().revision, before); From cb019d6cc6d294148d4bee4d53a0555c26d65145 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:10:56 +0100 Subject: [PATCH 262/385] Initialize the measurement callback in the isolated spill manager --- crates/raster/src/spill.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 9b5245dea9..9caf545c5e 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -1359,6 +1359,7 @@ mod tests { space_unmeasured: AtomicBool::new(false), registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), config: Mutex::new(Config { + query_space: free_space, dir: Some(base.join("growth")), file: None, last_error: None, From 63ac4be5a2c27af19920a9ff1df2ccfcba32ee3d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:17:10 +0100 Subject: [PATCH 263/385] Reduce redundant pixelate fixture combinations --- crates/algo/src/pixelate/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs index ac432283a5..59a3936e43 100644 --- a/crates/algo/src/pixelate/tests.rs +++ b/crates/algo/src/pixelate/tests.rs @@ -127,9 +127,13 @@ fn halftone_unusual_coordinates_and_params_keep_direct_semantics() { fn tiled_filters_match_scalar_at_all_depths_with_soft_selection() { use crate::{FilterParams, apply_tiled}; let bounds = Rect::new(-17, -9, 26, 24); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [false, true] { + // Every mode/depth pair and both alpha values for each mode and depth. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (di, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { + if (mi + di) % 2 != ai { + continue; + } let ctx = Ctx { bounds, mode, alpha }; let src = fixture(bounds, &ctx, 2); let mut surface = Surface::new(PixelFormat::new(mode, depth, alpha)); From 35219ec6a1c2a7b64c754628ee91da4a0f8b2d12 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:27:27 +0100 Subject: [PATCH 264/385] Track surface pixel generations --- crates/raster/src/lib.rs | 40 ++++++++++++++++++++++++++++++++++++-- crates/raster/src/shift.rs | 10 ++++++++-- crates/raster/src/tests.rs | 21 ++++++++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 1c1b74d992..8255122bb8 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -311,6 +311,7 @@ impl PruneCursor { #[derive(Clone, Debug)] pub struct Surface { + generation: u64, format: PixelFormat, default_pixel: Box<[u8]>, tiles: BTreeMap>, @@ -585,7 +586,23 @@ fn decode_tile_row_rgba(fmt: &PixelFormat, t: &[u8], base: usize, dst: &mut [[f3 } } +// Tokens identify a particular pixel state across surfaces and copy-on-write clones. +static NEXT_SURFACE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +fn fresh_surface_generation() -> u64 { + NEXT_SURFACE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + impl Surface { + /// Equal generations identify the same pixel state, including across clones. + pub fn generation(&self) -> u64 { + self.generation + } + + fn note_mutation(&mut self) { + self.generation = fresh_surface_generation(); + } + /// Reads a region into a newly allocated buffer, returning an error instead of aborting if /// the requested pixel buffer cannot be represented or reserved. pub fn try_read_region(&self, r: Rect) -> Result, AllocationError> { @@ -647,7 +664,7 @@ impl Surface { /// Transparent/zero surface. pub fn new(format: PixelFormat) -> Self { - Self { format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } + Self { generation: fresh_surface_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). @@ -687,6 +704,7 @@ impl Surface { /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { + self.note_mutation(); let fmt = self.format; let dp = &self.default_pixel; let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); @@ -696,6 +714,7 @@ impl Surface { /// Fallible counterpart to [`Surface::tile_mut`]. Pixel storage is reserved before changing /// the surface, and a shared tile is copied only after its replacement has been allocated. pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { + self.note_mutation(); if let Some(tile) = self.tiles.get(&c) { drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?); } @@ -723,6 +742,7 @@ impl Surface { /// Writes a region using fallible pixel-tile allocations. Callers that need transactional /// document updates should perform this on their staged document copy and commit on success. pub fn try_write_region(&mut self, r: Rect, data: &[f32]) -> Result<(), AllocationError> { + self.note_mutation(); let n = self.channels(); let sample = self.format.sample; let expected = (r.width() as usize).checked_mul(r.height() as usize).and_then(|v| v.checked_mul(n)).ok_or(AllocationError::SizeOverflow)?; @@ -804,6 +824,7 @@ impl Surface { /// large it is, and across every surface that shares `interner`. Tiles are copy-on-write, so /// editing one splits it off again. Returns the bytes no longer held by this surface alone. pub fn share_uniform_tiles(&mut self, interner: &mut TileInterner) -> usize { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let mut saved = 0; for t in self.tiles.values_mut() { @@ -826,6 +847,7 @@ impl Surface { /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { + self.note_mutation(); let dp = self.default_pixel.as_ref(); let bpp = dp.len(); self.tiles.retain(|_, t| t.bytes().chunks_exact(bpp).any(|px| px != dp)); @@ -844,6 +866,7 @@ impl Surface { /// before the last visited coordinate is not visited, one inserted after it is (and dropped /// when it holds only the default pixel, which reads the same as an absent tile). pub fn prune_batch(&mut self, cursor: &mut PruneCursor, max: usize) -> bool { + self.note_mutation(); if cursor.done { return true; } @@ -902,6 +925,7 @@ impl Surface { } pub fn write_pixel(&mut self, x: i32, y: i32, px: &[f32]) { + self.note_mutation(); let (c, base) = self.locate(x, y); let n = self.channels(); let sample = self.format.sample; @@ -1099,6 +1123,7 @@ impl Surface { /// section that must not run another Rayon job on its stack. [`Surface::write_region_par`] /// writes the same bytes on all cores. pub fn write_region(&mut self, r: Rect, data: &[f32]) { + self.note_mutation(); let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); @@ -1114,6 +1139,7 @@ impl Surface { /// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must /// not do that use [`Surface::write_region`]. pub fn write_region_par(&mut self, r: Rect, data: &[f32]) { + self.note_mutation(); let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); @@ -1130,6 +1156,7 @@ impl Surface { /// pixel), so they can be edited elsewhere, e.g. in parallel: `Arc::unwrap_or_clone` copies a /// tile only if an undo snapshot still shares it. Give them back with [`Surface::put_tiles`]. pub fn take_tiles(&mut self, r: Rect) -> Vec<(TileCoord, Arc)> { + self.note_mutation(); let fmt = self.format; let mut blank: Option> = None; r.tiles() @@ -1143,6 +1170,7 @@ impl Surface { /// Fallible counterpart to [`Surface::take_tiles`]. Reserves the complete result and any /// default tile before removing a tile, so a reservation failure leaves the surface intact. pub fn try_take_tiles(&mut self, r: Rect) -> Result)>, AllocationError> { + self.note_mutation(); // Counted in u64 and checked before narrowing: on 32-bit targets the grid of a sparse // surface's bounds can pass `usize` (and visiting it to count it takes just as long). let count = usize::try_from(r.tile_count()).map_err(|_| AllocationError::SizeOverflow)?; @@ -1162,6 +1190,7 @@ impl Surface { /// Put tiles back (see [`Surface::take_tiles`]); each replaces the tile at its coordinate. pub fn put_tiles(&mut self, tiles: impl IntoIterator)>) { + self.note_mutation(); for (c, t) in tiles { self.tiles.insert(c, t); } @@ -1187,6 +1216,7 @@ impl Surface { /// Fill a rectangle with one pixel value. pub fn fill_rect(&mut self, r: Rect, px: &[f32]) { + self.note_mutation(); let n = self.channels(); let mut enc = vec![0u8; self.format.bytes_per_pixel()]; encode_pixel(&self.format, &px[..n], &mut enc); @@ -1224,6 +1254,7 @@ impl Surface { /// Write interleaved encoded bytes (same format as the surface) into `r`. pub fn write_interleaved(&mut self, r: Rect, bytes: &[u8]) { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let w = r.width() as usize; assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch"); @@ -1246,6 +1277,7 @@ impl Surface { /// /// This enters Rayon, as [`Surface::write_region_par`] does. pub fn try_write_interleaved(&mut self, r: Rect, bytes: &[u8]) -> Result<(), AllocationError> { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let w = r.width() as usize; let expected = w.checked_mul(r.height() as usize).and_then(|v| v.checked_mul(bpp)).ok_or(AllocationError::SizeOverflow)?; @@ -1273,6 +1305,7 @@ impl Surface { where F: Fn(i32, i32, &mut [u8]) + Sync, { + self.note_mutation(); self.try_prepare_rows(r, |tiles, format, default_pixel| fill_tiles(tiles, r, format, default_pixel, &fill, &|| Ok(()))) } @@ -1282,6 +1315,7 @@ impl Surface { where F: Fn(i32, i32, &mut [u8]) + Sync, { + self.note_mutation(); self.try_prepare_rows(r, |tiles, format, default_pixel| { fill_tiles(tiles, r, format, default_pixel, &fill, &|| ctl.check().map_err(RowWriteError::Cancelled)) }) @@ -1347,7 +1381,8 @@ 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 { format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; + let mut out = + Surface { generation: fresh_surface_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); @@ -1375,6 +1410,7 @@ impl Surface { /// Applies `f` to every colour sample (not alpha), including the default pixel: a tone-curve /// change such as linearising when a document becomes 32-bit. pub fn map_color(&mut self, f: impl Fn(f32) -> f32) { + self.note_mutation(); let format = self.format; let color = format.mode.color_channels(); let n = format.channels(); diff --git a/crates/raster/src/shift.rs b/crates/raster/src/shift.rs index 6c3a49ffab..c75ebf3401 100644 --- a/crates/raster/src/shift.rs +++ b/crates/raster/src/shift.rs @@ -221,7 +221,8 @@ impl TranslateSteps { let builder = ShiftBuilder::new(&src, dx, dy, content); 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 { format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; + let out = + Surface { generation: super::fresh_surface_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; Self { sources: tiles.len(), scan: tiles.into_iter(), @@ -274,7 +275,12 @@ impl TranslateSteps { } else { return Some(std::mem::replace( &mut self.out, - Surface { format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default() }, + Surface { + generation: super::fresh_surface_generation(), + format: self.src.format, + default_pixel: self.src.default_pixel.clone(), + tiles: Default::default(), + }, )); } if !more() { diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index 6c9427d963..db6a3ca0ff 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -1341,3 +1341,24 @@ fn benchmark_u16_rgba_reads() { } } } + +#[test] +fn generations_follow_mutations_and_remain_shared_by_unmodified_clones() { + let mut original = Surface::new(PixelFormat::RGBA8); + let initial = original.generation(); + let copy = original.clone(); + assert_eq!(copy.generation(), initial); + let region = Rect::new(0, 0, 1, 1); + let _ = original.read_region(region); + assert_eq!(original.generation(), initial); + original.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]); + assert_ne!(original.generation(), initial); + assert_eq!(copy.generation(), initial); + assert_ne!(original.read_region(region), copy.read_region(region)); + let changed = original.generation(); + original.map_color(|v| v * 0.5); + assert_ne!(original.generation(), changed); + let mapped = original.generation(); + original.prune(); + assert_ne!(original.generation(), mapped); +} From 5e6b4c0945d12fbb4aa2f8605cd2eb30e7ab0b30 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:35:06 +0100 Subject: [PATCH 265/385] Use typed blend modes in Layers menu --- crates/color/src/blend.rs | 61 ++++++++++++++++++++++++ crates/ui-egui/src/panels/layers_tree.rs | 18 +++---- 2 files changed, 71 insertions(+), 8 deletions(-) diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index d6149feafb..196a0dcafd 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -47,6 +47,52 @@ pub enum BlendMode { } impl BlendMode { + /// Stable key used by the Layers panel. + pub fn key(self) -> &'static str { + match self { + Self::PassThrough => "passthrough", + Self::Normal => "normal", + Self::Dissolve => "dissolve", + Self::Darken => "darken", + Self::Multiply => "multiply", + Self::ColorBurn => "colorburn", + Self::LinearBurn => "linearburn", + Self::DarkerColor => "darkercolor", + Self::Lighten => "lighten", + Self::Screen => "screen", + Self::ColorDodge => "colordodge", + Self::LinearDodge => "lineardodgeadd", + Self::LighterColor => "lightercolor", + Self::Overlay => "overlay", + Self::SoftLight => "softlight", + Self::HardLight => "hardlight", + Self::VividLight => "vividlight", + Self::LinearLight => "linearlight", + Self::PinLight => "pinlight", + Self::HardMix => "hardmix", + Self::Difference => "difference", + Self::Exclusion => "exclusion", + Self::Subtract => "subtract", + Self::Divide => "divide", + Self::Hue => "hue", + Self::Saturation => "saturation", + Self::Color => "color", + Self::Luminosity => "luminosity", + Self::Reflect => "reflect", + Self::Glow => "glow", + Self::Negation => "negation", + Self::Xor => "xor", + Self::PaintNetColorBurn => "colorburnpaint.net", + Self::PaintNetColorDodge => "colordodgepaint.net", + } + } + + /// Resolve a canonical Layers panel key. + pub fn from_key(key: &str) -> Option { + static MODES: std::sync::OnceLock> = std::sync::OnceLock::new(); + MODES.get_or_init(|| std::iter::once(Self::PassThrough).chain(Self::layer_modes()).map(|mode| (mode.key(), mode)).collect()).get(key).copied() + } + /// Paint.NET modes without an exact Photoshop equivalent. pub const PAINT_NET_MODES: [BlendMode; 6] = [Self::Reflect, Self::Glow, Self::Negation, Self::Xor, Self::PaintNetColorBurn, Self::PaintNetColorDodge]; @@ -623,3 +669,18 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa #[cfg(test)] mod tests; + +#[cfg(test)] +mod key_tests { + use super::BlendMode; + + #[test] + fn canonical_keys_match_legacy_panel_names_and_round_trip() { + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + let old = mode.label().to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + assert_eq!(mode.key(), old); + assert_eq!(BlendMode::from_key(&old), Some(mode)); + } + assert_eq!(BlendMode::from_key("no-such-mode"), None); + } +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index adb8c24cf9..8a9643c3c7 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -28,7 +28,7 @@ use crate::PhotocraftApp; /// The key the panel and the filter use for a blend mode: its label folded as the engine's /// `blend_from_str` reads it ("normal", "lineardodgeadd"). pub(crate) fn blend_key(m: BlendMode) -> String { - m.label().to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "") + m.key().to_string() } /// The blend mode a panel key names. @@ -382,13 +382,15 @@ impl LayerTree for PhotoLayers<'_> { } fn blend_modes(&self, group: bool, current: &str) -> Vec> { - let current = blend_of(current).unwrap_or(BlendMode::Normal); - let modes: Vec> = - super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(blend_key(m), m)).collect(); - blend_entries(&modes, |e| { - let label = blend_of(&e.key).map_or(e.key.as_str(), |m| tl!(m.label())); - Label::from(label.to_string()) - }) + let current = BlendMode::from_key(current).or_else(|| blend_of(current)).unwrap_or(BlendMode::Normal); + let modes: Vec> = super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(m, m)).collect(); + blend_entries(&modes, |mode| Label::from(tl!(mode.key.label()).to_string())) + .into_iter() + .map(|entry| match entry.value() { + Some(mode) => Entry::new(mode.key().to_string(), entry.label().clone()), + None => Entry::separator(), + }) + .collect() } fn footer(&self) -> LayersFooterState { From 567b88610abffc52bf83098803c637296d207670 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:36:47 +0100 Subject: [PATCH 266/385] Pair tone target test flags --- crates/engine/tests/it/tone_target_picker.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/tone_target_picker.rs b/crates/engine/tests/it/tone_target_picker.rs index 16b4ee9cec..9f34868798 100644 --- a/crates/engine/tests/it/tone_target_picker.rs +++ b/crates/engine/tests/it/tone_target_picker.rs @@ -237,9 +237,13 @@ fn gray_tone_records_do_not_leak_from_rgb_channels() { for (target, panel) in [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] { - for style in ["levels", "points", "pencil"] { - for sampled in [false, true] { - for explicit in [false, true] { + // Each style sees both flags; all four flag pairs occur across the styles. + for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { + for (ai, sampled) in [false, true].into_iter().enumerate() { + for (ei, explicit) in [false, true].into_iter().enumerate() { + if (si + ai) % 2 != ei { + continue; + } let mut clean = session(mode, depth); clean.active_mut().unwrap().channel_view.target = panel; clean From 8b68407a61c7c83f9a2a0481552741a8089ee0b5 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:36:50 +0100 Subject: [PATCH 267/385] Reduce blur and selection test fixtures --- crates/algo/src/blur/tests.rs | 6 +++++- crates/algo/src/gallery/tests.rs | 10 +++++++--- crates/algo/src/segment/workflow_tests.rs | 15 ++++++++------- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs index fd2917cd32..41018d91ae 100644 --- a/crates/algo/src/blur/tests.rs +++ b/crates/algo/src/blur/tests.rs @@ -255,7 +255,11 @@ fn layer_box_blurs_match_direct_convolution_at_any_radius() { SampleType::U16 => 1.0 / 65535.0, _ => 0.0, } + 2e-5; - for p in ¶ms { + // Each format sees both blur modes; each radius is covered across formats. + for (pi, p) in params.iter().enumerate() { + if pi % 2 != i % 2 { + continue; + } let boxes = box_widths(p).expect("a box-pass blur"); let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); let area = crate::output_area(p, s.content_bounds(), canvas, None); diff --git a/crates/algo/src/gallery/tests.rs b/crates/algo/src/gallery/tests.rs index e822d7a938..0e1967b89c 100644 --- a/crates/algo/src/gallery/tests.rs +++ b/crates/algo/src/gallery/tests.rs @@ -149,9 +149,13 @@ fn iris_depths_models_selection_tiles_and_cancellation() { let mut selection = Surface::new(PixelFormat::GRAY8); selection.fill_rect(bounds, &[0.4]); selection.fill_rect(Rect::new(3, 19, 35, 44), &[1.0]); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [false, true] { + // Cover every mode/sample pair and both alpha values for each mode and sample. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { + if (mi + si) % 2 != ai { + continue; + } let fmt = PixelFormat::new(mode, sample, alpha); let mut surface = Surface::new(fmt); surface.write_region(bounds, &image(bounds, fmt.channels()).data); diff --git a/crates/algo/src/segment/workflow_tests.rs b/crates/algo/src/segment/workflow_tests.rs index 96c6caeb8f..3ab7d5ea83 100644 --- a/crates/algo/src/segment/workflow_tests.rs +++ b/crates/algo/src/segment/workflow_tests.rs @@ -82,16 +82,16 @@ fn quick_selection_workflow_release_comparison() { #[test] fn quick_selection_preserves_textures_low_contrast_and_thin_features() { - let (w, h) = (360usize, 280usize); + let (w, h) = (180usize, 140usize); let canvas = Rect::new(0, 0, w as i32, h as i32); for kind in 0..6 { let img = RgbImage::from_fn(w, h, |x, y| { let inside = if kind == 2 { - (x as f32 - 180.0).hypot(y as f32 - 140.0) < 72.0 + (x as f32 - 90.0).hypot(y as f32 - 70.0) < 36.0 } else if kind == 3 { - y > 130 && y < 145 + y > 65 && y < 73 } else { - x > 60 && x < 300 && y > 60 && y < 220 + x > 30 && x < 150 && y > 30 && y < 110 }; let t = ((x * 23 + y * 19) % 101) as f32 / 100.0; match kind { @@ -102,7 +102,7 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() { [0.4, 0.3 + t * 0.1, 0.2] } } - 1 => [0.4 + x as f32 / 1800.0, 0.3 + y as f32 / 1400.0, t * 0.02], + 1 => [0.4 + x as f32 / 900.0, 0.3 + y as f32 / 700.0, t * 0.02], 4 => [t, ((x * 7 + y * 31) % 79) as f32 / 78.0, 0.4], 5 => [0.4; 3], _ => { @@ -115,8 +115,9 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() { } }); let sampler = ImageSampler { img: &img, origin: (0, 0) }; - for (points, brush) in [(vec![(180.0, 140.0)], 12.0), (vec![(90.0, 140.0), (270.0, 140.0)], 40.0), (vec![(1.0, 1.0), (160.0, 130.0)], 64.0)] { - for direct_px in [10_000, 300_000] { + for (points, brush) in [(vec![(90.0, 70.0)], 6.0), (vec![(45.0, 70.0), (135.0, 70.0)], 20.0), (vec![(1.0, 1.0), (80.0, 65.0)], 32.0)] { + // Scale the coarse-cut threshold with the canvas area; the second case stays direct. + for direct_px in [2_500, 300_000] { let tune = quick::Tuning { direct_px, ..quick::Tuning::default() }; let old = quick::quick_select_using::(&sampler, canvas, &points, brush, &tune); let new = quick::quick_select_using::(&sampler, canvas, &points, brush, &tune); From 6b207c5b55e9af7426e26c8e9017b46ce4bed00a Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:41:16 +0100 Subject: [PATCH 268/385] 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 a0dd01679354dbf501296b3a24a18e7656938e45 Mon Sep 17 00:00:00 2001 From: Bobderto <230258561+Bobderto@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:47:37 +0000 Subject: [PATCH 269/385] Label Ellipse tool creation steps in History --- crates/engine/src/cmd/vector_cmds.rs | 3 + .../ellipse_tool_history_name_tests.rs | 80 +++++++++++++++++++ .../line_tool_history_name_tests.rs | 2 +- crates/engine/src/cmd/vector_cmds/paths.rs | 9 +-- crates/engine/src/cmd/vector_cmds/shape.rs | 3 +- .../triangle_history_names_tests.rs | 2 +- crates/ui-egui/src/tools/vector_ui/shapes.rs | 4 +- 7 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/cmd/vector_cmds/ellipse_tool_history_name_tests.rs diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 9c91142e26..2cc34afd23 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -381,3 +381,6 @@ mod triangle_history_names_tests; #[cfg(test)] mod line_arrowhead_history_names_tests; + +#[cfg(test)] +mod ellipse_tool_history_name_tests; diff --git a/crates/engine/src/cmd/vector_cmds/ellipse_tool_history_name_tests.rs b/crates/engine/src/cmd/vector_cmds/ellipse_tool_history_name_tests.rs new file mode 100644 index 0000000000..10c5af2a8d --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/ellipse_tool_history_name_tests.rs @@ -0,0 +1,80 @@ +use photocraft_doc::LiveShape; +use serde_json::json; + +use crate::Session; + +const LABEL: &str = "Ellipse Tool"; + +fn document() -> Session { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 160, "height": 120})).unwrap(); + session +} + +#[test] +fn ellipse_shape_records_one_undoable_tool_step() { + let mut session = document(); + let before = session.active().unwrap().doc.clone(); + let steps = session.active().unwrap().history.past_len(); + session.execute("shape.create", json!({"kind": "ellipse", "rect": [15, 20, 45, 35], "historyName": LABEL})).unwrap(); + let state = session.active().unwrap(); + assert_eq!(state.history.past_len(), steps + 1); + assert_eq!(state.history.undo_label(), Some(LABEL)); + assert_eq!(state.doc.layers.last().unwrap().name, "Ellipse 1"); + let with_ellipse = state.doc.clone(); + assert!(session.undo()); + assert_eq!(session.active().unwrap().doc, before); + assert!(session.redo()); + assert_eq!(session.active().unwrap().doc, with_ellipse); +} + +#[test] +fn each_ellipse_work_path_edit_records_an_independent_tool_step() { + let mut session = document(); + let state = session.active().unwrap(); + let steps = state.history.past_len(); + let layers = state.doc.layers.len(); + let mut outline = photocraft_doc::vector::Path::default(); + for (i, x) in [15.0, 80.0].into_iter().enumerate() { + let ellipse = photocraft_vector::shapes::live_path(&LiveShape::Ellipse { rect: [x, 20.0, 45.0, 35.0] }); + outline.subpaths.extend(ellipse.subpaths); + session.execute("path.set", json!({"name": "work", "path": super::path_json(&outline), "historyName": LABEL})).unwrap(); + let state = session.active().unwrap(); + assert_eq!(state.history.past_len(), steps + i + 1); + assert_eq!(state.history.undo_label(), Some(LABEL)); + assert_eq!(state.doc.work_path.as_ref().unwrap().subpaths.len(), i + 1); + assert_eq!(state.doc.layers.len(), layers); + } + assert!(session.undo()); + assert_eq!(session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths.len(), 1); + assert!(session.undo()); + assert!(session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn scripting_defaults_and_shape_additions_keep_their_labels() { + let mut session = document(); + let response = session.execute("shape.create", json!({"kind": "ellipse", "rect": [15, 20, 45, 35]})).unwrap(); + let layer = &response["layer"]; + assert_eq!(session.active().unwrap().history.undo_label(), Some("New Shape Layer")); + session.execute("shape.create", json!({"kind": "ellipse", "rect": [30, 30, 40, 40], "addTo": layer, "historyName": LABEL})).unwrap(); + assert_eq!(session.active().unwrap().history.undo_label(), Some("Add Shape")); + + let ellipse = photocraft_vector::shapes::live_path(&LiveShape::Ellipse { rect: [15.0, 20.0, 45.0, 35.0] }); + session.execute("path.set", json!({"name": "work", "path": super::path_json(&ellipse)})).unwrap(); + assert_eq!(session.active().unwrap().history.undo_label(), Some("Work Path")); +} + +#[test] +fn invalid_history_labels_leave_the_document_and_history_intact() { + let mut session = document(); + let before = session.active().unwrap().doc.clone(); + let steps = session.active().unwrap().history.past_len(); + let ellipse = photocraft_vector::shapes::live_path(&LiveShape::Ellipse { rect: [15.0, 20.0, 45.0, 35.0] }); + for invalid in [json!("Wrong Tool"), json!(42), json!("Ellipse tool")] { + assert!(session.execute("shape.create", json!({"kind": "ellipse", "rect": [15, 20, 45, 35], "historyName": invalid})).is_err()); + assert!(session.execute("path.set", json!({"name": "work", "path": super::path_json(&ellipse), "historyName": invalid})).is_err()); + } + assert_eq!(session.active().unwrap().doc, before); + assert_eq!(session.active().unwrap().history.past_len(), steps); +} diff --git a/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs index 2cf94ff571..7bb8af9d2a 100644 --- a/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs +++ b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs @@ -61,7 +61,7 @@ fn without_the_tool_the_commands_keep_their_own_names() { fn an_unknown_history_name_is_refused_without_a_step() { let mut s = session(); let n = steps(&s); - assert!(s.execute("shape.create", line(Some("Ellipse Tool"))).is_err()); + assert!(s.execute("shape.create", line(Some("Unknown Tool"))).is_err()); assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err()); assert_eq!(steps(&s), n); } diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index df8d922b45..975415ded8 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -74,8 +74,8 @@ pub(super) fn paths_list(s: &Session) -> Result { } /// The tools that override these shared commands' normal History labels with their own name: -/// Freeform Pen (#12829), the Line tool (#13244) and the Triangle tool (#13354). -const TOOL_HISTORY_NAMES: [&str; 3] = ["Freeform Pen", "Line Tool", "Triangle Tool"]; +/// Freeform Pen (#12829), Line (#13244), Triangle (#13354), and Ellipse (#13223). +const TOOL_HISTORY_NAMES: [&str; 4] = ["Freeform Pen", "Line Tool", "Triangle Tool", "Ellipse Tool"]; /// Validate before editing so malformed automation input cannot change the document. pub(super) fn pen_history_name<'a>(p: &Value, cmd: &str, default: &'a str) -> Result<&'a str> { @@ -84,13 +84,12 @@ pub(super) fn pen_history_name<'a>(p: &Value, cmd: &str, default: &'a str) -> Re Some(v) => TOOL_HISTORY_NAMES .into_iter() .find(|&n| v.as_str() == Some(n)) - .ok_or_else(|| bad(cmd, "`historyName` must be \"Freeform Pen\", \"Line Tool\" or \"Triangle Tool\"")), + .ok_or_else(|| bad(cmd, "`historyName` must be \"Freeform Pen\", \"Line Tool\", \"Triangle Tool\" or \"Ellipse Tool\"")), } } /// Replaces the Work Path or a saved path, or appends subpaths with the requested operation. -/// The optional Freeform Pen or Line Tool history label overrides the normal Work Path or Save -/// Path label. +/// An optional tool history label overrides the normal Work Path or Save Path label. pub(super) fn path_set(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.set"; let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?; diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index b14dd410c7..9a4be259a3 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -436,8 +436,7 @@ fn default_name(kind: &str) -> &'static str { } /// Creates a shape layer, or adds path components to the shape identified by `addTo`. -/// The Freeform Pen or Line Tool history override labels new layers; additions retain the Add -/// Shape label. +/// A tool history override labels new layers. Additions use the Add Shape label. pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { const CMD: &str = "shape.create"; let label = super::paths::pen_history_name(p, CMD, "New Shape Layer")?; diff --git a/crates/engine/src/cmd/vector_cmds/triangle_history_names_tests.rs b/crates/engine/src/cmd/vector_cmds/triangle_history_names_tests.rs index d63d2c786b..a2159545d4 100644 --- a/crates/engine/src/cmd/vector_cmds/triangle_history_names_tests.rs +++ b/crates/engine/src/cmd/vector_cmds/triangle_history_names_tests.rs @@ -97,7 +97,7 @@ fn without_the_tool_the_commands_keep_their_own_names() { fn an_unknown_history_name_is_refused_without_a_step() { let mut s = session(); let n = steps(&s); - assert!(s.execute("shape.create", triangle(Some("Ellipse Tool"))).is_err()); + assert!(s.execute("shape.create", triangle(Some("Unknown Tool"))).is_err()); assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err()); assert_eq!(steps(&s), n); } diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 3c5a9e793c..a8cc6ca86c 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -321,12 +321,12 @@ fn path_op_of(op: &str) -> photocraft_doc::vector::PathOp { } } -/// A Line tool drag is one History step named after the tool, as in Photoshop (#13244); the -/// other Shape tools keep the commands' own names. +/// The tool's History label for a new shape layer or a Work Path edit, when defined. pub(crate) fn tool_history_name(kind: ShapeKind) -> Option<&'static str> { match kind { ShapeKind::Line => Some("Line Tool"), ShapeKind::Triangle => Some("Triangle Tool"), + ShapeKind::Ellipse => Some("Ellipse Tool"), _ => None, } } From 878d5fa717f4058e250a688c2b4719d5b2f4adfb Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:52:11 +0100 Subject: [PATCH 270/385] Pair scalar cell filter cases --- crates/algo/src/pixelate/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs index 59a3936e43..a97a9d6f88 100644 --- a/crates/algo/src/pixelate/tests.rs +++ b/crates/algo/src/pixelate/tests.rs @@ -202,14 +202,18 @@ fn cell_filters_match_scalar_models_edges_and_fractional_cells() { // The cell filters see the mode only as a channel count, CMYK's ink direction (`subtractive`) and the native // background, so Lab adds nothing to RGB; cells of 100 and 300 are both past every `out`, and the seed has no // branch (0 and u32::MAX keep the wrapping ends) (#15652). - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel] { - for alpha in [false, true] { + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { let ctx = Ctx { bounds, mode, alpha }; for pattern in 0..5 { for halo in [0, 7] { let src = fixture(bounds.inflate(halo), &ctx, pattern); for out in [bounds, Rect::new(-23, -15, 37, 31), Rect::new(-7, 2, 18, 13)] { - for cell in [2.0, 3.75, 10.0, 300.0] { + // Retain every mode/alpha pair and all four cell sizes for each mode. + for (ci, cell) in [2.0, 3.75, 10.0, 300.0].into_iter().enumerate() { + if ci % 2 != (mi + ai) % 2 { + continue; + } for seed in [0, u32::MAX] { let got = cells::crystallize(&src, out, &ctx, cell, seed).unwrap(); assert_bits(&got, &crystallize_direct(&src, out, &ctx, cell, seed)); From b3f4721c29a8743008437c12b32f5426a09ccc75 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:52:12 +0100 Subject: [PATCH 271/385] Reduce bitmap and color move fixtures --- crates/engine/src/cmd/mode_cmds.rs | 7 ++++++- crates/engine/src/cmd/mode_cmds/tests.rs | 8 ++++---- .../cmd/retouch_cmds/content_aware_move_color_tests.rs | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index fb8b40f152..20b9aede70 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -600,6 +600,11 @@ fn custom_pattern_map(s: &Session, cmd: &str, p: &Value) -> Result<(Vec, us } fn bitmap(s: &mut Session, p: &Value) -> Result { + bitmap_in_bands(s, p, 0) +} + +/// Convert with the requested compositor band height (zero chooses its normal budget). +fn bitmap_in_bands(s: &mut Session, p: &Value, band_rows: i32) -> Result { const CMD: &str = "image.mode.bitmap"; let d = s.active().ok_or(EngineError::NoDocument)?; let input = f64::from(d.doc.resolution_dpi.max(1.0)); @@ -674,7 +679,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result { let n = fmt.channels(); let mut out = Surface::new(fmt); let (mut gray, mut data) = (Vec::new(), Vec::new()); - let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> std::result::Result<(), std::convert::Infallible> { + let _ = photocraft_compose::render_bands(doc, doc.bounds(), band_rows, |band| -> std::result::Result<(), std::convert::Infallible> { gray.clear(); gray.extend(band.px.iter().map(|q| { // Over white, as the flattened image. diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 8164ea3aac..c64e38b09b 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -860,10 +860,10 @@ fn bitmap_pixels(d: &Document) -> Vec { #[test] fn bitmap_in_bands_matches_one_full_canvas_conversion() { - // #8477: the composite is converted in bands (32768 px wide: 256 rows each, so 300 rows are - // two). Diffusion carries its error across the band edge, and pattern, halftone and custom + // #8477: 300 rows cross a 256-row compositor band. Diffusion carries its error across the + // band edge, and pattern, halftone and custom // pattern stay anchored to the image's rows: the result equals one full-canvas conversion. - let (w, h) = (32_768u32, 300u32); + let (w, h) = (64u32, 300u32); let mut s = session(w, h, 8, "grayscale"); paint(&mut s, |x, y| { let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); @@ -888,7 +888,7 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { if method == "customPattern" { p["pattern"] = json!("Cells"); } - s.execute("image.mode.bitmap", p.clone()).unwrap(); + bitmap_in_bands(&mut s, &p, 256).unwrap(); let want = match method { "halftone" => { let cell = (before.resolution_dpi / 53.0).max(2.0); diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs index 57e99d3898..8375889a98 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -43,9 +43,9 @@ fn checker(x: i32, y: i32) -> Option { } } -/// 800×600. Left half grey, right half green, with the 80×80 checker at (100, 100). +/// 640×460. Grey to the left of x=400, green to the right, with an 80×80 checker at (100, 100). fn green_doc() -> Session { - let mut s = session(800, 600); + let mut s = session(640, 460); paint(&mut s, |x, y| { if let Some(v) = checker(x, y) { [v, v, v] From 0ef7ab1450e941383ee93e417746f2d8fac65801 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 08:52:41 +0100 Subject: [PATCH 272/385] 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 273/385] 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 eb67d8f066309da3b7c4b82dc3de9bbeeb5028af Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:54:07 +0100 Subject: [PATCH 274/385] Cover surface tile mutation generations --- crates/raster/src/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index db6a3ca0ff..68d9870b0e 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -1361,4 +1361,10 @@ fn generations_follow_mutations_and_remain_shared_by_unmodified_clones() { let mapped = original.generation(); original.prune(); assert_ne!(original.generation(), mapped); + let before_tile = original.generation(); + let old_copy = original.clone(); + original.tile_mut(TileCoord { tx: 0, ty: 0 }).bytes_mut()[0] ^= 0xff; + assert_ne!(original.generation(), before_tile); + assert_eq!(old_copy.generation(), before_tile); + assert_ne!(original.read_region(region), old_copy.read_region(region)); } From 475dcbcad17006c1a74a78f5e178cb4a7feac7cb Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:58:53 +0100 Subject: [PATCH 275/385] Reduce redundant smart blur offsets --- crates/algo/src/blur2/smart_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/blur2/smart_tests.rs b/crates/algo/src/blur2/smart_tests.rs index 9114ee8505..d2db9cb077 100644 --- a/crates/algo/src/blur2/smart_tests.rs +++ b/crates/algo/src/blur2/smart_tests.rs @@ -110,12 +110,14 @@ fn offset_fast_path_matches_the_per_channel_oracle() { for (mode, n, alpha) in layouts { let src = image(win, n, alpha); let ctx = Ctx { bounds: win, mode, alpha }; - for radius in [0.1f32, 1.0, 3.0, 12.0, 17.5] { + // Centre only, unit stride, and a coarse stride for both qualities. At 13 the inner + // rectangle still has pixels, so coarse offsets exercise the fast path too. + for radius in [0.1f32, 3.0, 13.0] { let ri = f32::ceil(radius) as i32; // The usual tile (the window less the halo), the whole window, and one sticking out of it. let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri); for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] { - // Quality only sets the offset stride: Low a coarse one, High every offset at these radii (#15652). + // Quality selects the offset stride; both paths are compared to the oracle. for quality in [BlurQuality::Low, BlurQuality::High] { for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] { for threshold in [8.0, 60.0] { From 213cd3470b0eebdeb41907a0f2f094d224d09406 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 09:00:55 +0100 Subject: [PATCH 276/385] fix(ui): Rotate Canvas keeps its Interpolation pick out of remembered values The Arbitrary rotation dialog fills its interpolation row from Preferences > General > Image Interpolation on every opening, but the row was an ordinary choice row, so the framework remembered a confirmed pick and applied it over the opening values on the next opening: a one-time Bilinear choice silently resampled later rotations, and a changed preference never reached the dialog again. The row now opts out of remembering, like the rows beside it that the open document supplies (angle, direction) and like Lens Blur's depth map. The dropdown itself goes away with #14462. Red before green: the new ui-egui test arbitrary_rotation_interpolation_reopens_at_the_preference failed on the head without the fix (left bilinear, right bicubic) and passes with it. --- crates/ui-egui/src/dialogs/filter_dialog.rs | 6 ++++ .../src/dialogs/filter_dialog/tests.rs | 30 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 9a661d2551..10785249b4 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -328,6 +328,12 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if document_derived(command, &p.key) { p = p.not_remembered(); } + // #14465: the row opens from Preferences › General › Image Interpolation on every + // opening, so a pick there applies to that opening only; the row stays out of the + // remembered values, as the rows above do. + if command == "image.rotation.arbitrary" && p.key == "interpolation" { + p = p.not_remembered(); + } // Global Light's Altitude takes whole degrees, as its Angle does (#14980). if command == "layer.layerStyle.globalLight" && p.key == "altitude" { p = p.decimals(0); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index d6686353b2..0d816616e6 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -218,6 +218,36 @@ fn remembering_dialogs_never_persists_paths_or_document_indices() { assert_ne!(f.int("mapDocument"), Some(0), "a document index is never remembered"); } +/// #14465 review: the Rotate Canvas dialog fills Interpolation from Preferences › General › +/// Image Interpolation on every opening, so a dropdown pick applies to that opening only and +/// never carries into the next one. The reference application has no Interpolation row at all: +/// the preference decides. The other rows of the dialog keep opening from the document +/// (angle and direction are the ruler's, #12035). +#[test] +fn arbitrary_rotation_interpolation_reopens_at_the_preference() { + const CMD: &str = "image.rotation.arbitrary"; + let mut app = new_app(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + + // 1. The preference's default (Bicubic Automatic) opens the row at bicubic. + let id = open(&mut app, CMD).unwrap(); + assert_eq!(field_json(&app, id, "interpolation"), json!("bicubic"), "the row opens at the preference"); + set(&mut app, id, "angle", json!(30.0)); + set(&mut app, id, "interpolation", json!("bilinear")); + assert!(ok(&mut app, id), "OK rotates and files its values"); + + // 2. A later opening starts from the preference again, not from the confirmed Bilinear pick. + let id = open(&mut app, CMD).unwrap(); + assert_eq!(field_json(&app, id, "interpolation"), json!("bicubic"), "a one-time Bilinear pick does not carry into the next opening"); + cancel(&mut app, id); + + // 3. A changed preference reaches the next opening. + app.session.edit_prefs(|p| p.general.image_interpolation = photocraft_engine::prefs::Interpolation::Nearest); + let id = open(&mut app, CMD).unwrap(); + assert_eq!(field_json(&app, id, "interpolation"), json!("nearest"), "Nearest Neighbor shows nearest"); + cancel(&mut app, id); +} + /// A layer-id param has no number field: the Auto-Align dialog used to write `reference: 0` /// back, which the engine rejects as not a selected layer (#674). #[test] From c9746558d7628ce3f3888ec4fe5bbabe527b989a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 08:06:05 +0000 Subject: [PATCH 277/385] ci: build the tests once per OS, keep compiled workspace crates, balance the shards - Both gate calls build the tests once into a nextest archive (cargo xtask ci archive); the shards run it, and the build job runs the doctests after the upload. - The Linux gate keeps the compiled workspace crates in a rolling cache entry (cache-workspace-crates). A nightly cold build is its safety net; gate-cache-prune keeps the newest entry. test (without heif) restores that entry. - The shards split the tests with nextest's slice partition, which spreads the slow modules: on one main run's times the non-GPU shards go from 728/493/523 s (hash) to about 602/506/625 s. Fixes #15702 --- .github/workflows/ci.yml | 111 ++++++++++++++++++++++++++----------- docs/development.md | 2 +- scripts/ci-gpu-lavapipe.py | 2 +- scripts/ci-test-shard.sh | 15 +++-- xtask/src/main.rs | 12 ++-- 5 files changed, 96 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70c2e6083e..8a0af37391 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,10 +2,14 @@ name: CI # Quality gates for every push to main and every pull request. The Linux and Windows tests run # through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the -# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. +# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. Every night +# the Linux gate alone runs a cold build: the safety net for the workspace crates it keeps between +# runs (`cache-workspace-crates`), and a fresh start for that cache entry. on: push: branches: [main] + schedule: + - cron: "11 3 * * *" pull_request: # `labeled` so that adding `full-ci` to an open PR starts a run with Windows in it. types: [opened, synchronize, reopened, labeled] @@ -70,7 +74,7 @@ concurrency: jobs: # Git dependencies come from github.com/storytold, and Cargo.lock is complete and up to date. git-sources: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main @@ -86,7 +90,7 @@ jobs: # `windows_skip`: the platform-neutral packages whose Windows tests a pull request skips because nothing it # changes reaches them (same script); empty on main and `full-ci`. platforms: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 10 name: select platforms runs-on: ubuntu-latest @@ -145,17 +149,20 @@ jobs: fi # The Linux gate (craft-common-actions gate.yml). Its `lint` leg runs the checks that need no test - # build; four test shards each build the tests from the restored cache and run their share - # (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and fails on - # a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other tests, and - # shard 2 runs the doctests. The `gpu` group is ~2400 test-seconds on 4 slots (~12 min with its - # slowest test, ~8 once the five slow UI tests are fixed); the other ~5900 test-seconds over 3 - # shards are ~8 min each, so a fifth shard would not shorten the gate. Its rust-cache entry is - # the one `test (without heif)` restores. + # build. The `build` job builds the tests once into a nextest archive (`cargo xtask ci archive`), + # uploads it and then runs the doctests; four test shards download the archive and run their + # share (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and + # fails on a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other + # tests. The `gpu` group is ~840 test-seconds on 4 slots (~3.5 min); the other ~6900 + # test-seconds over 3 shards are ~8.5-10.5 min each. + # The build keeps the compiled workspace crates between runs (`cache-workspace-crates`), so a + # pull request rebuilds only the crates its changes reach. Each main run's build job saves a + # rolling entry of its own, which `test (without heif)` restores too; `gate-cache-prune` keeps + # the newest one. gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@ci-build-once-test with: # egui/winit/rfd. packages: >- @@ -175,34 +182,32 @@ jobs: LPDEST=photocraft-no-such-printer CARGO_PROFILE_TEST_STRIP=symbols timeout-minutes: 100 - # On main, a `cache warm` leg builds xtask and the tests, as each shard does, and saves the - # dependency cache as soon as the build succeeds; the shards then only restore, so a failing - # test cannot keep the entry from being saved (craft-common-actions#270). The lint leg keeps - # its own entry. - warm-command: cargo xtask ci build + cache-workspace-crates: true + cold-build: ${{ github.event_name == 'schedule' }} # fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' # own tests. lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint archive-command: cargo xtask ci archive + after-archive-command: cargo xtask ci doctest test-shards: 4 # The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs). shard-command: bash scripts/ci-test-shard.sh --gpu-shard # The Windows tests and Clippy on the same gate, when `platforms` says the run needs them: a - # `lint` leg runs Clippy, and six shards each build the tests and run their hash partition; - # shard 1 also runs the doctests. Windows runs the tests ~1.75x slower than Linux: ~55 min on - # one runner, ~9 min per shard. A seventh shard would not shorten the slowest one while its - # slowest test alone takes ~9.6 min (the shortcut-dispatch UI test). The browser apps are wasm - # targets, so their native tests are left out; - # pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they change - # reaches (`windows_gpu`, `windows_skip`). The `cache warm` leg (main only) builds what main's - # build job builds. + # `lint` leg runs Clippy, the `build` job builds the tests once into a nextest archive and then + # runs the doctests, and six shards run their slice of the tests from the archive. Windows runs + # the tests ~1.75x slower than Linux: ~55 min on one runner, ~9 min per shard. A seventh shard + # would not shorten the slowest one while its slowest test alone takes ~9.6 min (the + # shortcut-dispatch UI test). The browser apps are wasm targets, so their native tests are left + # out; pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they + # change reaches (`windows_gpu`, `windows_skip`). Windows keeps a dependency-only cache entry: + # its workspace crates would not fit the repository's cache budget beside Linux's. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@ci-build-once-test with: os: '["windows-latest"]' # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with @@ -230,18 +235,57 @@ jobs: CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE PHOTOCRAFT_CI_EXCLUDE=photocraft-web photocraft-web-boot ${{ needs.platforms.outputs.windows_gpu == 'false' && 'photocraft-gpu' || '' }} ${{ needs.platforms.outputs.windows_skip }} timeout-minutes: 100 - warm-command: cargo xtask ci build lint-command: cargo xtask ci clippy archive-command: cargo xtask ci archive + after-archive-command: cargo xtask ci doctest test-shards: 6 shard-command: bash scripts/ci-test-shard.sh + # The Linux gate's build job saves a rolling cache entry of its own on every main and nightly run + # (`cache-workspace-crates`), about 3.8 GB, and every run restores only the newest. This deletes + # the older ones at once instead of leaving them to the 10 GB budget's eviction, which would + # evict other entries too. + gate-cache-prune: + needs: gate + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + timeout-minutes: 5 + runs-on: ubuntu-24.04 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Delete all but the newest rolling entry of each job and runner + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + # `-rust---crates-----...`, newest first. + gh cache list --repo "$REPO" --limit 100 --sort created_at --order desc --json id,key \ + --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" + declare -A kept + while read -r id key; do + [[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue + entry=${BASH_REMATCH[1]} + if [ -n "${kept[$entry]:-}" ]; then + echo "delete $key" + gh cache delete "$id" --repo "$REPO" + else + kept[$entry]=1 + echo "keep $key" + fi + done < "$RUNNER_TEMP/caches" + # The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error - # for distributors who leave it out. Runs beside the gate and restores the gate's dependency - # cache without saving one: the dependencies are the same, and the 10 GB cache budget is tight - # (#2688). + # for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling + # cache entry without saving one: the dependencies are the same, and the 10 GB cache budget is + # tight (#2688). Its sources keep their checkout mtimes, so the workspace crates it builds are + # rebuilt. test-without-heif: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 60 name: test (without heif) # The gate's runner: its cache entry is keyed on the OS. @@ -279,11 +323,12 @@ jobs: # The gate's own key (the shared action computes it), restore only. The toolchain action # exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of - # the key. - - uses: storytold/craft-common-actions/actions/rust-cache@main + # the cache paths. + - uses: aiongg/craft-common-actions/actions/rust-cache@ci-build-once-test with: cache-version: v2 job: gate + cache-workspace-crates: "true" align-environment: "true" - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 @@ -294,7 +339,7 @@ jobs: run: cargo nextest run -p photocraft-io --locked --profile ci corpus: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 30 # Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are # pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache diff --git a/docs/development.md b/docs/development.md index fe51840cac..bd62ca10e1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as `scripts/ci-test-shard.sh` does. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index 7ff41e10c7..8d89c1a17f 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -2,7 +2,7 @@ """Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. The Linux gate runs nextest's `gpu` test group in a shard of its own through this script -(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu +(`ci-gpu-lavapipe.py ci tests --from --gpu`, scripts/ci-test-shard.sh): every wgpu device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output is checked here for authored skips and for the parity tests' Vulkan backend line. diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh index 40afc15146..298c672b2f 100755 --- a/scripts/ci-test-shard.sh +++ b/scripts/ci-test-shard.sh @@ -2,10 +2,15 @@ # One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's # build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive # carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps -# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, -# GATE_SHARDS and NEXTEST_PARTITION. +# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD +# and GATE_SHARDS. # -# ci-test-shard.sh the shard runs its hash partition of every test +# The shards split the tests with nextest's `slice` partition (round-robin over every test of every +# binary). Test times are heavy-tailed and cluster in a few modules: on the times of a main run +# (#15702), a three-way `hash` split of the non-GPU tests ran 728, 493 and 523 s, and `slice` +# would run them in about 602, 506 and 625 s. +# +# ci-test-shard.sh the shard runs its slice of every test # ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by # scripts/ci-gpu-lavapipe.py; the other shards split the other tests set -euo pipefail @@ -17,7 +22,7 @@ xtask=("$archive/target/debug/xtask" ci tests --from "$archive") case "$(uname -s)" in MINGW* | MSYS* | CYGWIN*) xtask=("$archive/target/debug/xtask.exe" ci tests --from "$archive") ;; esac case "${1:-}" in - "") exec "${xtask[@]}" ;; + "") NEXTEST_PARTITION="slice:$GATE_SHARD/$GATE_SHARDS" exec "${xtask[@]}" ;; --gpu-shard) if [ "$GATE_SHARDS" -lt 2 ]; then echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" @@ -26,7 +31,7 @@ case "${1:-}" in if [ "$GATE_SHARD" = 1 ]; then exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu fi - NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu + NEXTEST_PARTITION="slice:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu ;; *) echo "usage: $0 [--gpu-shard]" >&2 diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 97ae021fd4..4fdf22d635 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -40,12 +40,12 @@ commands: tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the steps that need no test build; `archive` builds the tests into the nextest archive at - $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that archive + $NEXTEST_ARCHIVE_FILE (the gate's build job, which then runs `doctest`); `tests --from ` runs the tests from that archive extracted to (without --from it builds them); `tests` runs the tests and panic_hunt on the partition in $NEXTEST_PARTITION (`--gpu`: all of nextest's gpu test group, whatever the partition, each test's output shown; `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` - builds (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves + builds. $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves packages out of the test build and the doctests corpus [--all | --pngsuite | --psd | --psd-tools | --pixls | --atn | --photoshop | --gimp] [--local] [--update-manifest] show where test corpora live and their pins (xtask/src/corpus_pins.rs), or fetch @@ -265,7 +265,7 @@ enum Part { Lint, /// The tests, which the gate splits over its shards (`ci tests`). Test, - /// The doctests, which the gate runs in one shard (`ci doctest`). + /// The doctests, which the gate's build job runs once the archive is uploaded (`ci doctest`). Doc, } @@ -518,13 +518,13 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOption options.build_only = true; &[Part::Test] } - // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE (which also - // carries this xtask, .config/nextest.toml), and the doctests, which need the rlibs. + // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE, which also + // carries this xtask (.config/nextest.toml). Some("archive") => { let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; options.archive = Some(file.into()); options.build_only = true; - &[Part::Test, Part::Doc] + &[Part::Test] } Some("tests") => { options.partition = tests_partition(options.selection, std::env::var("NEXTEST_PARTITION").ok()); From 17e6b13052a2f262d4d8a795f910d6eeb40c02cc Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:21:52 +0100 Subject: [PATCH 278/385] Reduce preview and pattern boundary fixtures --- crates/engine/src/cmd/mode_cmds/tests.rs | 5 +++- crates/engine/src/cmd/pattern_cmds.rs | 24 ++++++++++++------- crates/engine/src/cmd/retouch_cmds.rs | 4 +++- .../cmd/retouch_cmds/content_aware_move.rs | 8 ++++++- crates/engine/src/cmd/retouch_cmds/tests.rs | 20 ++++++++++------ crates/engine/src/color_channels/tone.rs | 10 +++++--- 6 files changed, 50 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index c64e38b09b..7e49ee5f8f 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -866,7 +866,7 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { let (w, h) = (64u32, 300u32); let mut s = session(w, h, 8, "grayscale"); paint(&mut s, |x, y| { - let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); + let v = ((x % 61) as f32 / 61.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); [v, v, v, 1.0] }); add_pattern(&mut s, "Cells", 3, 2, &[10, 200, 90, 250, 150, 40]); @@ -902,6 +902,9 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { }; // Grayscale stores 0/1 the way `from_rgba` turns the old RGBA output into gray. let want: Vec = want.iter().map(|g| photocraft_raster::from_rgba(&storage_format(ColorMode::Bitmap), [*g, *g, *g, 1.0])[0]).collect(); + if method == "threshold" { + assert!(want.contains(&0.0) && want.contains(&1.0), "the gradient crosses the threshold"); + } let got = bitmap_pixels(doc(&s)); let diff = got.iter().zip(&want).filter(|(a, b)| (**a - **b).abs() > 1e-6).count(); assert_eq!(diff, 0, "{method}: {diff} of {} pixels differ", got.len()); diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index d1a93b42d4..c113b69dba 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -325,6 +325,12 @@ pub fn default_name(s: &Session) -> String { const MAX_DEFINE_EDGE: u32 = 8000; fn define(s: &mut Session, p: &Value) -> Result { + let sample = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format().sample; + define_with_max_pixels(s, p, photocraft_doc::pattern::max_paint_pixels(sample)) +} + +/// Define a pattern with a bound on its pixel count. +fn define_with_max_pixels(s: &mut Session, p: &Value, max_px: u64) -> Result { let cmd = "edit.definePattern"; let st = s.active().ok_or(EngineError::NoDocument)?; let doc = &st.doc; @@ -345,7 +351,6 @@ fn define(s: &mut Session, p: &Value) -> Result { // A pattern the compositor could not hold would define but paint nothing: 8 bits go to the // edge limit, 16-bit documents to 33,554,432 px in all, float to 16,777,216 (4096 × 4096). let sample = doc.pixel_format().sample; - let max_px = photocraft_doc::pattern::max_paint_pixels(sample); if u64::from(r.width()) * u64::from(r.height()) > max_px { return Err(bad(cmd, format!("patterns in a {}-bit document are limited to {max_px} px in all", sample.bytes() * 8))); } @@ -762,17 +767,20 @@ mod tests { assert!(e.contains("16-bit") && e.contains("33554432"), "{e}"); } - /// A pattern of the largest area Define Pattern accepts at 8 bits is paintable: held at 4 - /// bytes a pixel, 256 MB, as the compositor's cap allows, and it renders. + /// A pattern at the area limit is paintable and renders; production permits 8000×8000 at 8 bits. #[test] - fn an_8000_by_8000_pattern_is_defined_and_paints() { + fn a_pattern_at_the_area_limit_is_defined_and_paints() { let mut s = Session::new(); - s.execute("file.new", json!({"width": 8000, "height": 8000, "depth": 8})).unwrap(); + assert_eq!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8), 8000 * 8000); + assert_eq!(photocraft_doc::pattern::working_bytes_for(8000 * 8000, SampleType::U8), 8000 * 8000 * 4); + let (side, max_px) = (80, 80 * 80); + s.execute("file.new", json!({"width": side, "height": side, "depth": 8})).unwrap(); s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); - s.execute("edit.definePattern", json!({"name": "Largest"})).unwrap(); + assert!(define_with_max_pixels(&mut s, &json!({"name": "Too large"}), max_px - 1).is_err()); + define_with_max_pixels(&mut s, &json!({"name": "Largest"}), max_px).unwrap(); let p = s.patterns.items.iter().find(|p| p.name == "Largest").unwrap(); - assert_eq!((p.width, p.height), (8000, 8000)); - assert!(p.is_paintable() && p.working_bytes() == 256_000_000); + assert_eq!((p.width, p.height), (side, side)); + assert!(p.is_paintable() && p.working_bytes() == max_px * 4); s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap(); s.execute("layer.newFillLayer.pattern", json!({"pattern": "Largest"})).unwrap(); let [r, g, b, a] = pixel(&s, 5, 5); diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 95cbe7ca99..00631c91b3 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -35,7 +35,9 @@ pub use pattern_stamp::{ }; mod periodic; mod remove; -pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; +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 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 fb1e8a703d..89eca9973a 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -696,12 +696,18 @@ impl ContentAwarePreview { /// Prepare the preview of `paint.contentAwareMove` with params `p` on the active document. Errors /// as the command does (bad params, nothing to move, a selection larger than the command takes). pub fn preview(s: &Session, p: &Value) -> Result { + preview_with_pixel_budget(s, p, PREVIEW_MAX_PIXELS) +} + +/// 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 { let captured = crate::channel_cmds::inject_target(s, CMD, p.clone()); let p = &captured; let plan = plan(s, p, PREVIEW_MARGIN)?; let px = |r: Rect| u64::from(r.width()) * u64::from(r.height()); let pixels = px(plan.area).max(px(plan.dest)); - let scale = if pixels > PREVIEW_MAX_PIXELS { (PREVIEW_MAX_PIXELS as f64 / pixels as f64).sqrt() } else { 1.0 }; + let max_pixels = max_pixels.max(1); + let scale = if pixels > max_pixels { (max_pixels as f64 / pixels as f64).sqrt() } else { 1.0 }; let d = s.active().ok_or(EngineError::NoDocument)?; Ok(ContentAwarePreview { colors: crate::color_channels::target(s, p)?, doc: d.doc.clone(), plan, params: p.clone(), scale }) } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 999575cf69..c1096a7135 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -1698,15 +1698,21 @@ fn content_aware_move_previews_large_selections_coarse_then_exact() { #[test] fn content_aware_move_coarse_preview_handles_transform_extend_and_limits() { use crate::jobs::JobCtx; - let s = large_move(8); + let mut s = session(128, 64, 8, "rgb"); + paint_layer(&mut s, with_object(20, 26)); + s.execute("select.rect", json!({"x": 16, "y": 22, "width": 20, "height": 20})).unwrap(); let px = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y); - // Transform On Drop: turned 90° about the selection's centre (210, 160), then moved; the - // object sits at the centre, so it lands at (460, 220) either way. - let (turned, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "rotate": 90})).unwrap().run(&JobCtx::new()).unwrap(); - assert!(is_object(px(&turned, 460, 220)) && !is_object(px(&turned, 210, 160))); + // A 400-pixel selection is just over the preview budget. It turns about its centre and moves. + let preview = |p: &Value| content_aware_move::preview_with_pixel_budget(&s, p, 399); + let job = preview(&json!({"offset": [70, 0], "rotate": 90})).unwrap(); + assert!(job.is_coarse()); + let (turned, _) = job.run(&JobCtx::new()).unwrap(); + assert!(is_object(px(&turned, 96, 32)) && !is_object(px(&turned, 26, 32))); // Extend keeps the original. - let (extended, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "mode": "extend"})).unwrap().run(&JobCtx::new()).unwrap(); - assert!(is_object(px(&extended, 460, 220)) && is_object(px(&extended, 210, 160))); + let job = preview(&json!({"offset": [70, 0], "mode": "extend"})).unwrap(); + assert!(job.is_coarse()); + let (extended, _) = job.run(&JobCtx::new()).unwrap(); + assert!(is_object(px(&extended, 96, 32)) && is_object(px(&extended, 26, 32))); // Off the canvas, or past the command's own limit, is still an error. assert!(content_aware_move_preview(&s, &json!({"offset": [400, 0]})).is_err()); let mut big = session(5000, 4000, 8, "rgb"); diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index b7db453e09..584e28953c 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -263,8 +263,8 @@ mod tests { space: ToneSpace::Lab, }, ]; - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] { - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (mi, mode) in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652). @@ -281,7 +281,11 @@ mod tests { let mut holes = Surface::with_default(mask.format(), &[0.63]); holes.fill_rect(Rect::from_xywh(2, 8, 7, 5), &[0.0]); let colors = ColorChannels::from_indices([0, mode.color_channels() - 1], mode.color_channels()).unwrap(); - for selection in [None, Some(&mask), Some(&holes)] { + // Every mode/sample, mode/selection and sample/selection pair remains. + for (ti, selection) in [None, Some(&mask), Some(&holes)].into_iter().enumerate() { + if ti != (mi + si) % 3 { + continue; + } for adjustment in &adjustments { let mut expected = source.clone(); let mut actual = source.clone(); From bd0671f017d7baf964e787b6eea7ddab5b50087e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:21:52 +0100 Subject: [PATCH 279/385] Exercise relight bands with a smaller budget --- crates/algo/src/relight.rs | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/crates/algo/src/relight.rs b/crates/algo/src/relight.rs index 679c9b7f51..d36454d238 100644 --- a/crates/algo/src/relight.rs +++ b/crates/algo/src/relight.rs @@ -150,6 +150,11 @@ fn read_rgba(src: &Image, ctx: &Ctx, x: i32, y: i32) -> [f32; 4] { /// Relight `out` of `src`. Identity when `intensity` is 0 (or not finite). pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec { + relight_with_luma_budget(src, out, ctx, p, MAX_LUMA_PIXELS) +} + +/// Relight with a bound on the luma field allocated by each band. +fn relight_with_luma_budget(src: &Image, out: Rect, ctx: &Ctx, p: Params, max_luma_pixels: usize) -> Vec { let n = src.ch; if out.is_empty() || n == 0 { return src.crop(out); @@ -160,14 +165,14 @@ pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec let sig = sigma(p.softness, ctx.bounds); let step = step_for_sigma(sig); let reach = read_radius(sig); - if let Some(band_h) = luma_band_rows(out, reach) { + if let Some(band_h) = luma_band_rows(out, reach, max_luma_pixels) { return relight_bands(src, out, ctx, p, sig, step, band_h); } relight_rect(src, out, ctx, p, sig, step) } /// Horizontal strip height so the inflated luma field stays within [`MAX_LUMA_PIXELS`]. -fn luma_band_rows(out: Rect, reach: i32) -> Option { +fn luma_band_rows(out: Rect, reach: i32, max_luma_pixels: usize) -> Option { let margin = 2usize.saturating_mul(reach.max(0) as usize); let yw = (out.width() as usize).saturating_add(margin); let yh = (out.height() as usize).saturating_add(margin); @@ -179,10 +184,10 @@ fn luma_band_rows(out: Rect, reach: i32) -> Option { Some(_) => return None, None => usize::MAX, }; - if n <= MAX_LUMA_PIXELS { + if n <= max_luma_pixels { return None; } - let max_yh = (MAX_LUMA_PIXELS / yw).max(1); + let max_yh = (max_luma_pixels / yw).max(1); let inner = max_yh.saturating_sub(margin).max(1).min(i32::MAX as usize) as i32; if inner >= out.height() as i32 { None } else { Some(inner.max(1)) } } @@ -534,10 +539,9 @@ mod tests { } #[test] - fn layers_above_8mp_are_relit() { - // 4096×2048 = 8.39 MP. A single full-frame kernel call inflates past 8 MP of luma, - // which used to return the input unchanged. Force one tile so that path is taken. - let (w, h) = (4096, 2048); + fn layers_above_the_luma_budget_are_relit() { + // A small budget exercises the same banding path as an 8 MP luma field. + let (w, h) = (256, 128); let bounds = Rect::new(0, 0, w, h); let mut s = Surface::new(PixelFormat::RGBA8); let bytes: Vec = (0..h) @@ -550,15 +554,19 @@ mod tests { }) .collect(); s.write_interleaved(bounds, &bytes); - let p = relight_p(180.0, 30.0, 90.0, 12.0, 0.0, 25.0); - let area = output_area(&p, s.content_bounds(), bounds, None); + let p = Params { angle: 180.0, elevation: 30.0, intensity: 90.0, ambient: 12.0, warmth: 0.0, softness: 25.0 }; + let reach = read_radius(sigma(p.softness, bounds)); + assert!(luma_band_rows(bounds, reach, 20_000).is_some()); + let src = Image::read_clamped(&s, bounds.inflate(reach), bounds); + let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true }; let before = s.pixel(w / 2, h / 2); - let out = apply_tiled(&s, &p, area, bounds, None, 8192, None); - let after = out.pixel(w / 2, h / 2); + let out = relight_with_luma_budget(&src, bounds, &ctx, p, 20_000); + let pixel = |x: i32, y: i32| &out[((y * w + x) * 4) as usize..][..4]; + let after = pixel(w / 2, h / 2); assert!(after.iter().all(|c| c.is_finite()), "{after:?}"); - let d = max_diff(&before, &after); - assert!(d > 1e-4, "8 MP+ layer was left unchanged (max diff {d})"); - assert!(max_diff(&s.pixel(8, 8), &out.pixel(8, 8)) > 1e-4); + let d = max_diff(&before, after); + assert!(d > 1e-4, "over-budget layer was left unchanged (max diff {d})"); + assert!(max_diff(&s.pixel(8, 8), pixel(8, 8)) > 1e-4); } #[test] From cb368d32e96aa4ef16993ab99e06e1ec48c134db Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:29:51 +0100 Subject: [PATCH 280/385] Correct pattern budget assertions --- crates/engine/src/cmd/pattern_cmds.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index c113b69dba..1271ea0591 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -771,7 +771,8 @@ mod tests { #[test] fn a_pattern_at_the_area_limit_is_defined_and_paints() { let mut s = Session::new(); - assert_eq!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8), 8000 * 8000); + assert_eq!(MAX_DEFINE_EDGE, 8000); + assert!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8) >= 8000 * 8000); assert_eq!(photocraft_doc::pattern::working_bytes_for(8000 * 8000, SampleType::U8), 8000 * 8000 * 4); let (side, max_px) = (80, 80 * 80); s.execute("file.new", json!({"width": side, "height": side, "depth": 8})).unwrap(); @@ -780,7 +781,8 @@ mod tests { define_with_max_pixels(&mut s, &json!({"name": "Largest"}), max_px).unwrap(); let p = s.patterns.items.iter().find(|p| p.name == "Largest").unwrap(); assert_eq!((p.width, p.height), (side, side)); - assert!(p.is_paintable() && p.working_bytes() == max_px * 4); + // A small pattern uses the expanded float representation, unlike the largest 8-bit one. + assert!(p.is_paintable() && p.working_bytes() == max_px * 16); s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap(); s.execute("layer.newFillLayer.pattern", json!({"pattern": "Largest"})).unwrap(); let [r, g, b, a] = pixel(&s, 5, 5); From 16935087ab25952cca3a74eb18ac4a713ad3aa5e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:30:24 +0100 Subject: [PATCH 281/385] 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 de5725af2fc532aa42141334cc993dfb2a375664 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:40:39 +0100 Subject: [PATCH 282/385] Use strips for Camera Raw parity tests --- crates/gpu/tests/it/camera_raw.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index 836c1d42a1..d85a2fac52 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -170,10 +170,6 @@ fn image(w: usize, h: usize, depth: Depth) -> Vec<[f32; 4]> { } /// Develops `p` both ways and returns the largest channel difference. -fn compare(g: &mut Gpu, p: &Case, depth: Depth) -> f32 { - compare_at(g, p, depth, (171, 113)) -} - fn compare_at(g: &mut Gpu, p: &Case, depth: Depth, (w, h): (usize, usize)) -> f32 { compare_image(g, p, depth, &image(w, h, depth), (w, h)) } @@ -207,10 +203,14 @@ fn compare_image(g: &mut Gpu, p: &Case, depth: Depth, src: &[[f32; 4]], (w, h): } fn check(name: &str, sets: &[Case]) { + check_at(name, sets, (171, 113)); +} + +fn check_at(name: &str, sets: &[Case], size: (usize, usize)) { let Some(mut g) = gpu() else { return }; for p in sets { for depth in DEPTHS { - let d = compare(&mut g, p, depth); + let d = compare_at(&mut g, p, depth, size); eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}"); } } @@ -424,7 +424,8 @@ fn shadows_and_highlights() { cr! { shadows: 35.0, highlights: -45.0, encoding_gamma: 1.8}, ]; assert_moves(&sets); - check("shadows/highlights", &sets); + // The long side preserves the spatial filter scale; 48 rows keep several pyramid levels. + check_at("shadows/highlights", &sets, (171, 48)); } #[test] @@ -476,7 +477,7 @@ fn shadows_and_highlights_with_per_pixel_stages() { vignette_amount: -30.0, grain_amount: 20.0, pixel_scale: 0.2}; - check( + check_at( "shadows/highlights + per pixel", &[ all.clone(), @@ -485,10 +486,11 @@ fn shadows_and_highlights_with_per_pixel_stages() { cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4}, cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8}, ], + (171, 48), ); // At the dialog's proxy width, at one depth: the depth only changes how the input is // quantized (8 and 16 bits both develop with `float = false`), and every depth already ran - // above at 171×113. The long side is what matters here (subsampled pyramid levels); the short + // above at 171×48. The long side is what matters here (subsampled pyramid levels); the short // one only needs to keep several levels, so the frame is a strip. let Some(mut g) = gpu() else { return }; let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120)); @@ -499,9 +501,9 @@ fn shadows_and_highlights_with_per_pixel_stages() { /// with the CPU can't pass trivially. fn assert_moves(sets: &[Case]) { for p in sets { - let src = image(171, 113, Depth::Sixteen); + let src = image(171, 48, Depth::Sixteen); let mut out = src.clone(); - develop(&mut out, 171, 113, p, false); + develop(&mut out, 171, 48, p, false); let moved = out.iter().zip(&src).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); assert!(moved > 0.02, "{p:?} moves pixels by at most {moved}"); } @@ -523,7 +525,8 @@ fn clarity_texture_and_dehaze() { cr! { dehaze: -30.0, clarity: -25.0, texture: 60.0, encoding_gamma: 1.8}, ]; assert_moves(&sets); - check("clarity/texture/dehaze", &sets); + // Match the movement check while retaining several pyramid levels. + check_at("clarity/texture/dehaze", &sets, (171, 48)); } #[test] @@ -563,11 +566,11 @@ fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() { cr! { clarity: 50.0, whites: -50.0, blacks: 45.0, exposure: -0.3}, cr! { texture: -60.0, whites: 30.0, blacks: -60.0}, ]; - check("clarity/texture/dehaze + shadows/highlights + per pixel", &sets); + check_at("clarity/texture/dehaze + shadows/highlights + per pixel", &sets, (171, 48)); let Some(mut g) = gpu() else { return }; // At the dialog's proxy width (Dehaze and Clarity on a copy subsampled twice), and wider (three // times). One depth per size: the depth only changes how the input is quantized (8 and 16 - // bits both develop with `float = false`), and every depth already ran above at 171×113. The + // bits both develop with `float = false`), and every depth already ran above at 171×48. The // long side sets the subsampling; the short one only needs to keep several pyramid levels, so // the frames are strips. for (size, depth) in [((858, 120), Depth::Eight), ((1600, 120), Depth::Float)] { From 83f391c3c9db253e84b39a6f97e8efa810e9781d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:46:01 +0100 Subject: [PATCH 283/385] Reduce sparse resampling fixture --- crates/algo/src/resample/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index f4406da0d2..0f4c9547ac 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -297,23 +297,23 @@ fn canvas_edges_repeat_instead_of_fading() { } } -/// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but +/// Two tiles in opposite corners of a 20096 px square: the content bounds are huge but /// almost nothing is stored. Shrinking it to one pixel must neither allocate a window /// proportional to the scale (#713) nor read the empty middle. #[test] fn tiny_target_of_a_huge_sparse_source() { let mut s = Surface::new(PixelFormat::RGBA32F); s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); - s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); - let k = 1.0 / 100_096.0; + s.fill_rect(Rect::new(19_840, 19_840, 20_096, 20_096), &[1.0, 1.0, 1.0, 1.0]); + let k = 1.0 / 20_096.0; let o = resize_surface(&s, k, k, Resample::Bicubic); assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); let p = o.pixel(0, 0); - // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. + // Two 256² tiles out of 20096²: nearly transparent, and white where it isn't. assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); // Squashed to one row but kept wide: the whole height feeds one band of output rows, // which must not hold a full-height intermediate. - let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); + let o = resize_surface(&s, 1000.0 / 20_096.0, k, Resample::Bicubic); let b = o.content_bounds(); assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); From b43ffa380f185169056b251861867bf649874b0b Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:48:31 +0100 Subject: [PATCH 284/385] 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 b0c0abee5490cc6be608cbc4fbc197778afa695e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:56:44 +0100 Subject: [PATCH 285/385] Pair sharpen tile and format cases --- crates/algo/src/sharpen/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs index aef62259a3..f491c14f18 100644 --- a/crates/algo/src/sharpen/tests.rs +++ b/crates/algo/src/sharpen/tests.rs @@ -183,13 +183,17 @@ fn exact_tiled_selected_outputs_and_cancellation() { let mut sel = Surface::new(PixelFormat::GRAY8); sel.fill_rect(area, &[0.4]); sel.fill_rect(Rect::new(250, 250, 270, 265), &[1.0]); - for depth in SampleType::ALL { + for (di, depth) in SampleType::ALL.into_iter().enumerate() { let surface = source(bounds, PixelFormat::new(ColorMode::Rgb, depth, true)); - for radius in [0.6, 3.0, 10.0] { + for (ri, radius) in [0.6, 3.0, 10.0].into_iter().enumerate() { let p = crate::FilterParams::UnsharpMask { amount: 150.0, radius, threshold: 8.0 }; for extent in [None, Some(bounds)] { let expected = apply_reference(&surface, &p, area, bounds, Some(&sel), extent, 256); - for tile in [63, 256, 512] { + // Keep every depth/radius, depth/tile and radius/tile pair, with both extents. + for (ti, tile) in [63, 256, 512].into_iter().enumerate() { + if ti != (di + ri) % 3 { + continue; + } let actual = crate::apply_tiled(&surface, &p, area, bounds, Some(&sel), tile, extent); assert_eq!(expected.to_interleaved(bounds), actual.to_interleaved(bounds)); } From 378fda83b0bc9f28a5000949abee59bfcb1d1a93 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:02:15 +0100 Subject: [PATCH 286/385] Pair extrude sweep fixture axes --- crates/algo/src/stylize2/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/stylize2/tests.rs b/crates/algo/src/stylize2/tests.rs index 4751511e62..17c70df860 100644 --- a/crates/algo/src/stylize2/tests.rs +++ b/crates/algo/src/stylize2/tests.rs @@ -44,8 +44,11 @@ fn swept_blocks_match_the_pixel_search_part(part: u64) { let repeat = !seen.insert((n, alpha, mode == ColorMode::Cmyk)); for kind in 0..5 { let src = image(bounds.inflate(20), n, kind); - for (size, depth) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)] { - for flags in (0..8).filter(|f| !repeat || f & 1 != 0) { + for (si, (size, depth)) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)].into_iter().enumerate() { + // For distinct channel layouts each kind and size sees every flag + // combination. Repeated layouts keep one level-based case per pair. + let first = (kind + si) % 8; + for flags in (0..8).filter(|f| (!repeat || f & 1 != 0) && (*f == first || *f == (first + 3) % 8)) { case += 1; if !sweep.includes(case) { continue; From 52a5293663e66f4df212729cfa3892a1a2ddc8d4 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:08:25 +0100 Subject: [PATCH 287/385] Reuse content-aware crop scenes --- .../engine/tests/it/crop_content_aware_layers.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/crop_content_aware_layers.rs b/crates/engine/tests/it/crop_content_aware_layers.rs index 24f407ee3a..df7bf506b9 100644 --- a/crates/engine/tests/it/crop_content_aware_layers.rs +++ b/crates/engine/tests/it/crop_content_aware_layers.rs @@ -134,8 +134,8 @@ fn undo_redo(s: &mut Session, before: &Document) { /// Matches the three measured rows: bounds and sample points, at half the measured size. #[test] fn measured_straight_rows_fill_background_and_only_the_active_raster() { + let (mut s, ids) = scene(); for row in 0..3 { - let (mut s, ids) = scene(); let active = if row == 1 { ids.edge } else { ids.quads }; if row == 2 { s.edit("Layer 0", |d, _| { @@ -172,6 +172,8 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() { unchanged(d, &plain, &untouched); named_one_step(&s, past, "Content-aware Crop"); undo_redo(&mut s, &before); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &before); } } @@ -179,8 +181,9 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() { #[test] fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() { let (x, y) = extension_sample(); + let (mut s, ids) = scene(); + let original = doc(&s).clone(); for row in 0..3 { - let (mut s, ids) = scene(); // Uniform donors isolate target selection from the existing turned-fill sampling policy. s.edit("Uniform Quads", |d, _| { let fmt = d.pixel_format(); @@ -213,15 +216,20 @@ fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() { unchanged(d, &plain, &untouched); named_one_step(&s, past, "Content-aware Crop"); undo_redo(&mut s, &before); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &before); + s.execute("edit.undo", json!({})).unwrap(); // Restore the scene before the uniform edit. + assert_eq!(doc(&s), &original); } } /// Selecting the Background leaves each other layer identical to its plain crop. #[test] fn background_active_is_not_a_second_target() { + let (mut s, ids) = scene(); + let original = doc(&s).clone(); for turned in [false, true] { let (x, y) = extension_sample(); - let (mut s, ids) = scene(); select(&mut s, ids.background); let p = frame(turned); let plain = plain_control(&mut s, &p); @@ -230,6 +238,8 @@ fn background_active_is_not_a_second_target() { pixel(doc(&s), ids.background, x, y, WHITE); unchanged(doc(&s), &plain, &[ids.quads, ids.small, ids.edge, ids.hidden, ids.text]); named_one_step(&s, past, "Content-aware Crop"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &original); } } From 931ec750c010f821aabca63b374cca90f68fda02 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:27:10 +0100 Subject: [PATCH 288/385] Keep color move reference fixture --- .../src/cmd/retouch_cmds/content_aware_move_color_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs index 8375889a98..57e99d3898 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -43,9 +43,9 @@ fn checker(x: i32, y: i32) -> Option { } } -/// 640×460. Grey to the left of x=400, green to the right, with an 80×80 checker at (100, 100). +/// 800×600. Left half grey, right half green, with the 80×80 checker at (100, 100). fn green_doc() -> Session { - let mut s = session(640, 460); + let mut s = session(800, 600); paint(&mut s, |x, y| { if let Some(v) = checker(x, y) { [v, v, v] From 8ff1a1862e53062a3c1f353a78e484dbed728588 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 09:30:58 +0000 Subject: [PATCH 289/385] ci: the cache prune lists main's entries only --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a0af37391..9cffda4e94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -264,7 +264,7 @@ jobs: run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do From 378c31c92b363bb579859a9d0fa96fd717a30ca3 Mon Sep 17 00:00:00 2001 From: haranishi <223786623+haranishi@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:38:36 +0900 Subject: [PATCH 290/385] fix(compose): render Size 1 Softer Inner Glow at edges --- crates/compose/src/effects.rs | 3 + .../src/effects/inner_glow_size_one_tests.rs | 94 +++++++++++++++++++ crates/compose/src/effects/paint.rs | 7 ++ crates/gpu/src/fx/builders.rs | 4 + 4 files changed, 108 insertions(+) create mode 100644 crates/compose/src/effects/inner_glow_size_one_tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 57a836fc1e..d2dbc0f51f 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -251,3 +251,6 @@ mod tests; #[cfg(test)] mod satin_size_one_tests; + +#[cfg(test)] +mod inner_glow_size_one_tests; diff --git a/crates/compose/src/effects/inner_glow_size_one_tests.rs b/crates/compose/src/effects/inner_glow_size_one_tests.rs new file mode 100644 index 0000000000..fe143fba84 --- /dev/null +++ b/crates/compose/src/effects/inner_glow_size_one_tests.rs @@ -0,0 +1,94 @@ +use super::{Contour, Effect, FxPaint, Glow, GlowSource, GlowTechnique}; +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, FxCommon, Layer}; +use photocraft_geom::{Rect, Size}; + +fn inner_glow(size: f32) -> Glow { + Glow { + common: FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(Color::BLACK), + technique: GlowTechnique::Softer, + spread: 0.0, + size, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + } +} + +fn fixture(mode: ColorMode, depth: SampleType, background: Color, fill: &[f32], glow: Glow) -> Document { + let mut doc = Document::with_background("Inner glow", Size::new(400, 300), mode, depth, background); + let mut layer = Layer::raster("Rectangle", doc.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(100, 75, 300, 225), fill); + layer.effects.items.push(Effect::InnerGlow(glow)); + doc.layers.push(layer); + doc +} + +fn orange(glow: Glow) -> crate::Buffer { + crate::flatten(&fixture(ColorMode::Rgb, SampleType::U8, Color::WHITE, &[1.0, 128.0 / 255.0, 0.0, 1.0], glow)) +} + +fn green(image: &crate::Buffer, x: i32, y: i32) -> u8 { + (image.get(x, y)[1] * 255.0).round() as u8 +} + +#[test] +fn size_one_draws_the_measured_pixel_on_all_four_edges() { + let image = orange(inner_glow(1.0)); + for ((x, y), (nx, ny)) in [((200, 75), (200, 76)), ((200, 224), (200, 223)), ((100, 150), (101, 150)), ((299, 150), (298, 150))] { + let edge = green(&image, x, y); + assert!(edge.abs_diff(64) <= 2, "edge ({x}, {y}): expected green 64, got {edge}"); + assert_eq!(green(&image, nx, ny), 128, "the glow stops after the first pixel"); + } + assert_eq!(green(&image, 200, 150), 128); + assert_eq!(green(&image, 200, 74), 255, "the glow stays inside the layer"); +} + +#[test] +fn other_sizes_keep_their_profiles() { + for (size, profile) in [(0.0, &[128][..]), (3.0, &[43, 100, 128]), (10.0, &[13, 36, 57, 74, 90, 102, 113, 120, 125, 128]), (20.0, &[6])] { + let image = orange(inner_glow(size)); + for (offset, &expected) in profile.iter().enumerate() { + let actual = green(&image, 200, 75 + offset as i32); + assert!(actual.abs_diff(expected) <= 2, "size {size}, offset {offset}: expected green {expected}, got {actual}"); + } + assert_eq!(green(&image, 200, 75 + size as i32), 128); + } +} + +#[test] +fn other_size_one_settings_keep_their_profiles() { + let precise = orange(Glow { technique: GlowTechnique::Precise, ..inner_glow(1.0) }); + assert_eq!(green(&precise, 200, 75), 64); + assert_eq!(green(&precise, 200, 76), 128); + + let center = orange(Glow { source: GlowSource::Center, ..inner_glow(1.0) }); + assert_eq!(green(¢er, 200, 75), 0); + assert_eq!(green(¢er, 200, 150), 0); + + let choke = orange(Glow { spread: 0.25, ..inner_glow(1.0) }); + assert_eq!(green(&choke, 200, 75), 128); +} + +#[test] +fn size_one_uses_the_document_color_and_depth() { + let gray = + fixture(ColorMode::Grayscale, SampleType::U16, Color::gray(1.0), &[0.5, 1.0], Glow { paint: FxPaint::Color(Color::gray(0.0)), ..inner_glow(1.0) }); + let gray = crate::flatten_to_surface(&gray, gray.pixel_format(), None); + assert!((gray.sample_channel(200, 75, 0) - 0.25).abs() < 0.0001); + assert!((gray.sample_channel(200, 76, 0) - 0.5).abs() < 0.0001); + + let ink = |k| Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, k], alpha: 1.0 }; + let cmyk = fixture(ColorMode::Cmyk, SampleType::U16, ink(0.0), &[0.0, 0.0, 0.0, 0.25, 1.0], Glow { paint: FxPaint::Color(ink(1.0)), ..inner_glow(1.0) }); + assert!(crate::cmyk::split::supports(&cmyk)); + let cmyk = crate::flatten_to_surface(&cmyk, cmyk.pixel_format(), None); + assert!((cmyk.sample_channel(200, 75, 3) - 0.625).abs() < 0.0001); + assert!((cmyk.sample_channel(200, 76, 3) - 0.25).abs() < 0.0001); + for ch in 0..3 { + assert_eq!(cmyk.sample_channel(200, 75, ch), 0.0); + } +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index cce928d737..03689cf426 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -399,6 +399,13 @@ pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) - // 1 − the edge glow, for both techniques). let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; let mut m = match g.technique { + GlowTechnique::Softer if inner && g.source == GlowSource::Edge && g.size == 1.0 && g.spread == 0.0 => { + // A width-one box blur leaves no coverage inside the edge. The Size 1 taps + // put quarter coverage on the first pixel, which Range 50% doubles (#14924). + let mut m = src; + super::blur::size_one_blur(&mut m); + m + } GlowTechnique::Precise => { // Coverage falls linearly from 0.5 at the edge to 0 at `size + 1` px (centre to // centre), solid within the spread / choke: after the default 50 % Range that is diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index a3a2311201..e11aa1d75c 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -46,6 +46,10 @@ impl B { // glow_map let center = inner && g.source == GlowSource::Center; let m = match g.technique { + GlowTechnique::Softer if inner && g.source == GlowSource::Edge && g.size == 1.0 && g.spread == 0.0 => { + let src = self.shift(In::Shape, 0.0, 0.0, 0.0, true); + self.conv(src, fx::size_one_kernel()) + } GlowTechnique::Precise => { let d = self.field(if inner { FieldKind::Inside } else { FieldKind::Outside }, g.size); let solid = g.size * g.spread; From a8f95bd16d9917cf658a36f36f3bd0c9564c2ade Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 10:07:19 +0000 Subject: [PATCH 291/385] Document layer index and index-ordered selection (#15704) Document.layers is a LayerTree that builds an id index on first lookup and drops it on any mutable access. Layer lookups and selected_layers use the index instead of walking the document. --- crates/compose/src/cmyk/tests.rs | 3 +- crates/compose/src/stroke_tests.rs | 4 +- crates/compose/src/tests.rs | 10 +- crates/doc/src/layer_tree.rs | 227 ++++++++++++++++++ crates/doc/src/lib.rs | 49 ++-- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/adjust_cmds.rs | 2 +- crates/engine/src/cmd/artboard_cmds.rs | 2 +- crates/engine/src/cmd/background_cmds.rs | 2 +- crates/engine/src/cmd/channel_cmds/spot.rs | 2 +- crates/engine/src/cmd/channel_cmds/tests.rs | 2 +- crates/engine/src/cmd/color_cmds.rs | 2 +- crates/engine/src/cmd/edit_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/export.rs | 2 +- crates/engine/src/cmd/file_cmds/processing.rs | 8 +- crates/engine/src/cmd/file_cmds/save.rs | 2 +- crates/engine/src/cmd/history_cmds.rs | 6 +- crates/engine/src/cmd/image_cmds.rs | 2 +- .../engine/src/cmd/layer_label_cmds/tests.rs | 2 +- crates/engine/src/cmd/layer_menu_cmds.rs | 4 +- .../engine/src/cmd/layer_menu_cmds/tests.rs | 2 +- crates/engine/src/cmd/layer_xmp_cmds/tests.rs | 2 +- crates/engine/src/cmd/mode_cmds.rs | 2 +- crates/engine/src/cmd/multichannel_cmds.rs | 2 +- crates/engine/src/cmd/ops.rs | 2 +- crates/engine/src/cmd/rasterize_style_cmds.rs | 2 +- crates/engine/src/cmd/sample_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/placing.rs | 2 +- crates/engine/src/cmd/smart_cmds/source.rs | 2 +- .../src/cmd/smart_cmds/tests/selection.rs | 14 +- .../cmd/smart_cmds/tests/source_flatten.rs | 4 +- .../src/cmd/smart_cmds/tests/svg_profile.rs | 2 +- crates/engine/src/cmd/smart_cmds/unpack.rs | 2 +- crates/engine/src/cmd/stamp_cmds.rs | 2 +- crates/engine/src/cmd/vector_clipboard.rs | 4 +- crates/engine/src/cmd/web_cmds/tests.rs | 4 +- crates/engine/src/doc_state.rs | 66 ++++- crates/engine/src/inspect.rs | 2 +- crates/engine/src/layer_place.rs | 2 +- crates/engine/src/pixels.rs | 2 +- crates/engine/tests/it/atn_newer_events.rs | 2 +- crates/engine/tests/it/atn_stack_modes.rs | 2 +- .../tests/it/convert_profile_options.rs | 2 +- .../engine/tests/it/export_shape_strokes.rs | 2 +- .../tests/it/image_size_scale_styles.rs | 2 +- crates/format/src/convert.rs | 2 +- crates/format/tests/it/roundtrip.rs | 4 +- crates/gpu/src/plan/tests.rs | 2 +- crates/gpu/src/prefix.rs | 2 +- crates/gpu/tests/it/parity.rs | 10 +- crates/io/src/affinity.rs | 2 +- crates/io/src/exr_parts.rs | 2 +- crates/io/src/flat.rs | 18 +- crates/io/src/kra.rs | 2 +- crates/io/src/ora.rs | 2 +- crates/io/src/ora/tests.rs | 4 +- crates/io/src/pdf/tests.rs | 8 +- crates/io/src/psd_import.rs | 2 +- crates/io/src/psd_import/tests.rs | 4 +- crates/io/src/svg.rs | 2 +- crates/io/src/xcf.rs | 2 +- crates/io/tests/it/artboard_guide_order.rs | 2 +- crates/io/tests/it/comps_artboards.rs | 2 +- crates/io/tests/it/roundtrip.rs | 14 +- crates/ui-egui/examples/interactive_bench.rs | 4 +- .../ui-egui/src/tools/transform_tool/tests.rs | 2 +- crates/ui-egui/tests/support/layout_doc.rs | 2 +- 67 files changed, 432 insertions(+), 129 deletions(-) create mode 100644 crates/doc/src/layer_tree.rs diff --git a/crates/compose/src/cmyk/tests.rs b/crates/compose/src/cmyk/tests.rs index eee79ac0d9..2e8292f8c0 100644 --- a/crates/compose/src/cmyk/tests.rs +++ b/crates/compose/src/cmyk/tests.rs @@ -1704,7 +1704,8 @@ fn normal_onto_nothing_is_exact() { }; let mut d = doc(4, 6); d.layers = - vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })]; + vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })] + .into(); assert_matches_reference(&d); assert_eq!(render1(&d, 0, 0)[..4], [0.0; 4]); } diff --git a/crates/compose/src/stroke_tests.rs b/crates/compose/src/stroke_tests.rs index 3608327628..3800441d1e 100644 --- a/crates/compose/src/stroke_tests.rs +++ b/crates/compose/src/stroke_tests.rs @@ -170,10 +170,10 @@ fn a_stroked_shapes_mask_applies_to_fill_and_stroke_together() { assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}"); // With effects too. l.effects.items = vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 1.0, 1.0) }]; - d.layers = vec![l.clone()]; + d.layers = vec![l.clone()].into(); let p = px(&d, 12, 20); assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "without clipped layers: {p:?}"); - d.layers = vec![l, clip]; + d.layers = vec![l, clip].into(); let p = px(&d, 12, 20); assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}"); } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e281204b00..b7375afa8e 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -404,7 +404,7 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() { let mut top = Layer::raster("t", PixelFormat::RGBA32F); top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 2), &source); top.blend = mode; - d.layers = vec![bottom, top]; + d.layers = vec![bottom, top].into(); let got = px(&d, 0, 0); // A 32-bit document: Add / Divide don't clip at 1 (Divide gives 0.6 / 0.2 = 3 in red). psblend::HDR.with(|h| h.set(true)); @@ -434,7 +434,7 @@ fn full_coverage_adjustment_keeps_its_result_over_huge_hdr_values() { dither: false, source: None, }; - d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))]; + d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))].into(); let got = px(&d, 0, 0); for c in &got[..3] { assert!((c - 0.5).abs() < 1e-6, "{v}: {got:?}"); @@ -479,7 +479,7 @@ fn blend_px(depth: SampleType, mode: BlendMode, bottom: [f32; 3], top: [f32; 3]) let mut t = Layer::raster("t", fmt); t.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [top[0], top[1], top[2], 1.0])); t.blend = mode; - d.layers = vec![b, t]; + d.layers = vec![b, t].into(); px(&d, 0, 0) } @@ -3294,7 +3294,7 @@ fn exposure_scales_32_bit_samples_as_stored() { let mut d = Document::new("e", Size::new(1, 1), ColorMode::Rgb, depth); let mut l = Layer::raster("px", fmt); l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[0.2, 0.2, 0.2, 1.0]); - d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))]; + d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))].into(); let got = px(&d, 0, 0)[0]; assert!((got - want).abs() < 2e-3, "{depth:?}: {got}"); } @@ -3384,7 +3384,7 @@ fn float_adjustments_preserve_hdr_range() { let mut d = Document::new("HDR", Size::new(1, 1), ColorMode::Rgb, SampleType::F32); let mut l = Layer::raster("pixels", PixelFormat::RGBA32F); l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[4.0, 2.0, 0.5, 0.75]); - d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))]; + d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))].into(); let got = px(&d, 0, 0); for (a, b) in got[..3].iter().zip(want) { assert!((a - b).abs() < 1e-5, "{adj:?}: {got:?} vs {want:?}"); diff --git a/crates/doc/src/layer_tree.rs b/crates/doc/src/layer_tree.rs new file mode 100644 index 0000000000..ce7549738c --- /dev/null +++ b/crates/doc/src/layer_tree.rs @@ -0,0 +1,227 @@ +//! The document's layer stack with a lazily built id index. + +use std::collections::HashMap; +use std::ops::{Deref, DerefMut}; +use std::sync::OnceLock; + +use crate::{Layer, LayerId, LayerPath}; + +/// Where a layer sits in the stack. +#[derive(Clone, Debug)] +struct Entry { + path: LayerPath, + parent: Option, +} + +/// Id to position for every layer, nested ones included. +#[derive(Debug, Default)] +pub struct LayerIndex { + entries: HashMap, + serial: u64, +} + +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +impl LayerIndex { + fn build(layers: &[Layer]) -> Self { + fn rec(layers: &[Layer], parent: Option, path: &mut LayerPath, out: &mut HashMap) { + for (i, l) in layers.iter().enumerate() { + path.push(i); + out.entry(l.id).or_insert_with(|| Entry { path: path.clone(), parent }); + if let Some(ch) = l.children() { + rec(ch, Some(l.id), path, out); + } + path.pop(); + } + } + let mut entries = HashMap::with_capacity(layers.len()); + rec(layers, None, &mut Vec::new(), &mut entries); + Self { entries, serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } + } + + /// The layer's path from the root. Paths order layers bottom-to-top as the depth-first walk does. + pub fn path(&self, id: LayerId) -> Option<&[usize]> { + self.entries.get(&id).map(|e| e.path.as_slice()) + } + + /// The group holding the layer; `None` at the root or for an unknown id. + pub fn parent(&self, id: LayerId) -> Option { + self.entries.get(&id)?.parent + } + + /// Nesting depth: 0 at the root. + pub fn depth(&self, id: LayerId) -> Option { + self.entries.get(&id).map(|e| e.path.len() - 1) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// A number unique to this build: it differs between two builds, so equal serials mean the + /// same index (tests count rebuilds with it). + pub fn serial(&self) -> u64 { + self.serial + } +} + +/// The layer stack, bottom-to-top, with an index from layer id to position built on the first +/// lookup. +/// +/// The stack is a public vector that code edits in place, nested groups included, so no mutator +/// method can be the place that drops the index. Every route to a `&mut Layer` or `&mut Vec` +/// goes through `DerefMut`, so the reset lives there: any write drops the index, and the next +/// lookup rebuilds it once. `Clone` starts without an index. +#[derive(Default)] +pub struct LayerTree { + layers: Vec, + index: OnceLock, +} + +impl LayerTree { + /// The id index, built on first use after the last write. + pub fn index(&self) -> &LayerIndex { + self.index.get_or_init(|| LayerIndex::build(&self.layers)) + } +} + +/// `Vec` methods that callers pass `&document` into (`doc.layers.push(make(&doc))`): as methods +/// on the tree the receiver borrow is two-phase, which it is not through `DerefMut`. +impl LayerTree { + pub fn push(&mut self, layer: Layer) { + self.deref_mut().push(layer); + } + + pub fn insert(&mut self, at: usize, layer: Layer) { + self.deref_mut().insert(at, layer); + } +} + +impl Deref for LayerTree { + type Target = Vec; + fn deref(&self) -> &Vec { + &self.layers + } +} + +impl DerefMut for LayerTree { + fn deref_mut(&mut self) -> &mut Vec { + self.index = OnceLock::new(); + &mut self.layers + } +} + +impl Clone for LayerTree { + fn clone(&self) -> Self { + Self { layers: self.layers.clone(), index: OnceLock::new() } + } +} + +impl PartialEq for LayerTree { + fn eq(&self, other: &Self) -> bool { + self.layers == other.layers + } +} + +impl std::fmt::Debug for LayerTree { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.layers.fmt(f) + } +} + +impl From> for LayerTree { + fn from(layers: Vec) -> Self { + Self { layers, index: OnceLock::new() } + } +} + +impl<'a> IntoIterator for &'a LayerTree { + type Item = &'a Layer; + type IntoIter = std::slice::Iter<'a, Layer>; + fn into_iter(self) -> Self::IntoIter { + self.layers.iter() + } +} + +impl<'a> IntoIterator for &'a mut LayerTree { + type Item = &'a mut Layer; + type IntoIter = std::slice::IterMut<'a, Layer>; + fn into_iter(self) -> Self::IntoIter { + self.deref_mut().iter_mut() + } +} + +impl FromIterator for LayerTree { + fn from_iter>(iter: I) -> Self { + iter.into_iter().collect::>().into() + } +} + +impl IntoIterator for LayerTree { + type Item = Layer; + type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.layers.into_iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PixelFormat; + + fn layers(n: usize) -> LayerTree { + (0..n).map(|i| Layer::raster(format!("l{i}"), PixelFormat::RGBA8)).collect() + } + + #[test] + fn index_builds_once_per_edit() { + let mut t = layers(200); + let id = t[150].id; + let first = t.index().serial(); + for _ in 0..100 { + assert_eq!(t.index().path(id), Some(&[150][..])); + } + assert_eq!(t.index().serial(), first, "lookups reuse the index"); + t.push(Layer::raster("new", PixelFormat::RGBA8)); + let second = t.index().serial(); + assert_ne!(second, first, "an edit rebuilds it"); + assert_eq!(t.index().serial(), second); + let _ = &mut t[3]; + assert_ne!(t.index().serial(), second, "any mutable access drops it"); + } + + #[test] + fn clone_after_edit_does_not_reuse_the_index() { + let mut t = layers(5); + let old = t.index().serial(); + let new_id = { + t.insert(0, Layer::raster("below", PixelFormat::RGBA8)); + t[0].id + }; + let c = t.clone(); + assert_ne!(c.index().serial(), old); + assert_eq!(c.index().path(new_id), Some(&[0][..])); + assert_eq!(t.index().path(new_id), Some(&[0][..])); + } + + #[test] + fn nested_edits_reset_and_paths_follow_walk_order() { + let inner = Layer::raster("in", PixelFormat::RGBA8); + let inner_id = inner.id; + let group = Layer::group("g", vec![inner]); + let group_id = group.id; + let mut t: LayerTree = vec![Layer::raster("a", PixelFormat::RGBA8), group].into(); + assert_eq!(t.index().path(inner_id), Some(&[1, 0][..])); + assert_eq!(t.index().parent(inner_id), Some(group_id)); + assert_eq!(t.index().depth(inner_id), Some(1)); + let before = t.index().serial(); + t[1].children_mut().unwrap().insert(0, Layer::raster("x", PixelFormat::RGBA8)); + assert_eq!(t.index().path(inner_id), Some(&[1, 1][..])); + assert_ne!(t.index().serial(), before); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d7a87ff756..523bdc16fa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ pub mod comps; pub mod effects; pub mod frame; pub mod import_conversion; +pub mod layer_tree; pub mod mode; pub mod pattern; pub mod slices; @@ -901,7 +902,7 @@ pub struct Document { pub depth: SampleType, pub icc_profile: Option>>, /// Bottom-to-top. - pub layers: Vec, + pub layers: layer_tree::LayerTree, pub channels: Vec, pub guides: Guides, /// The rulers' zero point in document pixels (`[x, y]`), dragged from the ruler corner. The @@ -1004,7 +1005,7 @@ impl Document { mode, depth, icc_profile: None, - layers: Vec::new(), + layers: Default::default(), channels: Vec::new(), guides: Guides::default(), ruler_origin: [0.0, 0.0], @@ -1161,18 +1162,7 @@ impl Document { } pub fn path_of(&self, id: LayerId) -> Option { - fn rec(layers: &[Layer], id: LayerId, path: &mut LayerPath) -> bool { - for (i, l) in layers.iter().enumerate() { - path.push(i); - if l.id == id || l.children().is_some_and(|ch| rec(ch, id, path)) { - return true; - } - path.pop(); - } - false - } - let mut path = Vec::new(); - rec(&self.layers, id, &mut path).then_some(path) + self.layers.index().path(id).map(<[usize]>::to_vec) } /// The locks in force on the layer at `path`: its own and those of every group around it, @@ -1211,10 +1201,7 @@ impl Document { } pub fn layer(&self, id: LayerId) -> Option<&Layer> { - fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> { - layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) }) - } - rec(&self.layers, id) + self.layer_at(self.layers.index().path(id)?) } pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> { @@ -1394,6 +1381,32 @@ mod tests { assert_eq!(d.unused_link_group(), Some(3)); } + /// Id lookups share one index per document state: 100 lookups on 200 layers build it once, + /// an edit builds it once more, and a clone built after the edit has its own. + #[test] + fn layer_lookups_share_one_index_per_state() { + let mut d = doc(); + for i in 0..199 { + d.layers.push(Layer::raster(format!("l{i}"), PixelFormat::RGBA8)); + } + let ids: Vec = d.layers.iter().map(|l| l.id).collect(); + let first = d.layers.index().serial(); + for i in 0..100 { + let id = ids[i * 2]; + assert_eq!(d.layer(id).unwrap().id, id); + assert_eq!(d.path_of(id), Some(vec![i * 2])); + } + assert_eq!(d.layers.index().serial(), first); + assert!(d.shift(ids[10], 1)); + assert_eq!(d.path_of(ids[10]), Some(vec![11])); + let second = d.layers.index().serial(); + assert_ne!(second, first); + d.layer_mut(ids[3]).unwrap().name = "x".into(); + let copy = d.clone(); + assert_ne!(copy.layers.index().serial(), d.layers.index().serial()); + assert_eq!(copy.layer(ids[3]).unwrap().name, "x"); + } + #[test] fn new_document_has_locked_background() { let d = doc(); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c2d10acae7..3f3ee0c378 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -894,7 +894,7 @@ fn build() -> Vec { 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]; + doc.layers = vec![bg].into(); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 6c97430d50..f7dd8925bd 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -652,7 +652,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result { bg.locks.position = true; crate::pixels_mut(&mut bg)?.write_region(doc.bounds(), &data); *active = Some(bg.id); - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.selection = None; Ok(()) })?; diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 55966ce97a..af62d62696 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -643,7 +643,7 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result let mut one = doc.clone(); one.name = l.name.clone(); one.size = Size::new(r.width(), r.height()); - one.layers = vec![group]; + one.layers = vec![group].into(); one.channels.clear(); one.selection = None; one.quick_mask = None; diff --git a/crates/engine/src/cmd/background_cmds.rs b/crates/engine/src/cmd/background_cmds.rs index 0c067b3842..f5d2ffbf3d 100644 --- a/crates/engine/src/cmd/background_cmds.rs +++ b/crates/engine/src/cmd/background_cmds.rs @@ -69,7 +69,7 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { only.clipped = false; let visible = l.visible; let fmt = doc.pixel_format(); - let rest = std::mem::replace(&mut doc.layers, vec![only]); + let rest = std::mem::replace(&mut doc.layers, vec![only].into()); let pixels = photocraft_compose::flatten_to_surface(doc, fmt, Some([bg[0], bg[1], bg[2]])); doc.layers = rest; let mut out = Layer::raster("Background", fmt); diff --git a/crates/engine/src/cmd/channel_cmds/spot.rs b/crates/engine/src/cmd/channel_cmds/spot.rs index 74b227d8d4..23ae600c79 100644 --- a/crates/engine/src/cmd/channel_cmds/spot.rs +++ b/crates/engine/src/cmd/channel_cmds/spot.rs @@ -43,7 +43,7 @@ pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result { sf.prune(); } let id = bg.id; - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.channels.remove(i); *active = Some(id); Ok(()) diff --git a/crates/engine/src/cmd/channel_cmds/tests.rs b/crates/engine/src/cmd/channel_cmds/tests.rs index f198fccde6..65ee637059 100644 --- a/crates/engine/src/cmd/channel_cmds/tests.rs +++ b/crates/engine/src/cmd/channel_cmds/tests.rs @@ -1259,7 +1259,7 @@ fn split_refuses_an_image_with_more_than_one_layer() { assert_eq!(s.execute("channel.split", json!({})).unwrap()["documents"].as_array().unwrap().len(), 3); // A lone group is a layer the split would lose. let mut s = session(); - std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])]; + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])].into(); assert!(!s.is_enabled("channel.split")); assert!(s.execute("channel.split", json!({})).is_err()); assert_eq!(s.documents().len(), 1); diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index 96fe367ea4..ce069c131c 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -1116,7 +1116,7 @@ fn flatten_for_profile(doc: &mut Document, active: &mut Option Result { out.push(l); } } - doc.layers = out; + doc.layers = out.into(); *active = Some(mid); Ok(()) })?; diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index b1cdbe0f62..abb4425033 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -77,7 +77,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let mut only = l.clone(); only.visible = true; only.clipped = false; - one.layers = vec![only]; + one.layers = vec![only].into(); if trim { let mut bounds = Rect::EMPTY; let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5e0d6b2ddb..5438a52a73 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -304,9 +304,9 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready // for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the // contents, with no wrapper group. - let layers = std::mem::take(&mut stack.layers); + let layers = std::mem::take(&mut *stack.layers); let smart = crate::smart_cmds::layers_to_smart(&stack, &smart_name, layers)?; - stack.layers = vec![smart]; + stack.layers = vec![smart].into(); } let i = s.add_document(stack, None); if align { @@ -314,10 +314,10 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; if smart { s.edit("Convert to Smart Object", |doc, active| { - let layers = std::mem::take(&mut doc.layers); + let layers = std::mem::take(&mut *doc.layers); let smart = crate::smart_cmds::layers_to_smart(doc, &smart_name, layers)?; *active = Some(smart.id); - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); Ok(()) })?; if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index eba2b9502d..4b8eef165f 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -312,7 +312,7 @@ pub(super) fn save_a_copy(s: &mut Session, p: &Value) -> Result { // "Layers" unchecked in Save a Copy: write the flattened image. let fmt = doc.pixel_format(); let px = flattened_checked(&doc, fmt, "file.saveACopy")?; - doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))]; + doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))].into(); } let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?; Ok(json!({"path": path, "warnings": warnings})) diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index 2717465db5..30d8528545 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -145,7 +145,7 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { let one_layer = |doc: &Document, layer: Layer| { let mut doc = doc.clone(); let id = layer.id; - doc.layers = vec![layer]; + doc.layers = vec![layer].into(); (Arc::new(doc), LayerTarget { active: Some(id), selected: vec![id] }) }; let (doc, layers) = match from { @@ -525,7 +525,7 @@ mod tests { assert_eq!(st.memory_bytes(), base + flat); // Room for the document's tiles and four fill tiles. let cur = tile_bytes(&st.doc); - let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec(), ..(*st.doc).clone() }); + let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); assert!(flat <= fill, "the flattened tile is no bigger than a fill's"); let budget = cur + 4 * fill; for s in [&mut with, &mut without] { @@ -549,7 +549,7 @@ mod tests { s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); // The snapshot's green layer tile, now only in it and the last state. - let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec(), ..(*st.doc).clone() }); + let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); let all = st.history.unique_bytes(&st.doc); let r = s.execute("edit.purge.histories", json!({})).unwrap(); assert_eq!(r["bytes"], json!(all - shared), "the green tile stays with the snapshot"); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 571f4754ac..55b45e9707 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1213,7 +1213,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { let mut merged = Layer::new(if has_background { "Background" } else { "Layer 1" }, LayerContent::Raster(surf)); merged.locks.transparency = has_background; merged.locks.position = has_background; - doc.layers = vec![merged]; + doc.layers = vec![merged].into(); // A merged-only copy has no original layers for saved comps to restore. // Don't carry dangling comp state into a single-layer flattened document. doc.layer_comps.clear(); diff --git a/crates/engine/src/cmd/layer_label_cmds/tests.rs b/crates/engine/src/cmd/layer_label_cmds/tests.rs index 3288c5aebf..b7cb432286 100644 --- a/crates/engine/src/cmd/layer_label_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_label_cmds/tests.rs @@ -21,7 +21,7 @@ fn fixture(depth: u8) -> (Session, [LayerId; 4]) { let outer_id = outer.id; let other = Layer::raster("Other", doc.pixel_format()); let other_id = other.id; - doc.layers = vec![outer, other]; + doc.layers = vec![outer, other].into(); Ok([outer_id, inner_id, leaf_id, other_id]) }) .unwrap(); diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 944b6755c6..252c41930f 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -876,7 +876,7 @@ fn create_layer(s: &mut Session, p: &Value) -> Result { let mut tmp = Document::new("fx", doc.size, doc.mode, doc.depth); tmp.global_light = light; tmp.patterns = doc.patterns.clone(); - tmp.layers = vec![alone]; + tmp.layers = vec![alone].into(); let buf = photocraft_compose::render(&tmp, area); let mut surf = Surface::new(fmt); let data: Vec = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); @@ -952,7 +952,7 @@ pub fn layer_document(doc: &Document, id: LayerId) -> Result { alone.blend = if alone.is_group() { BlendMode::PassThrough } else { BlendMode::Normal }; alone.clipped = false; let mut tmp = doc.clone(); - tmp.layers = vec![alone]; + tmp.layers = vec![alone].into(); tmp.selection = None; let area = doc.bounds(); let buf = photocraft_compose::render(&tmp, area); diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index 0dcd7c2333..8efe428398 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -548,7 +548,7 @@ fn stack_modes_render_from_the_nested_layers() { let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None, frame_stroke: None })); let smart = crate::smart_cmds::layer_to_smart(doc, &g)?; let id = smart.id; - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); *active = Some(id); Ok(()) }) diff --git a/crates/engine/src/cmd/layer_xmp_cmds/tests.rs b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs index 5fb67ad13c..cacad97308 100644 --- a/crates/engine/src/cmd/layer_xmp_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs @@ -11,7 +11,7 @@ fn fixture(depth: u8) -> (Session, LayerId, LayerId) { let a = Layer::raster("A", doc.pixel_format()); let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]); let ids = (a.id, b.id); - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); Ok(ids) }) .unwrap(); diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index fb8b40f152..45d47f0ca1 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -241,7 +241,7 @@ fn single_layer_surface(doc: &mut Document, active: &mut Option, mode: *surf = pixels; } *active = Some(l.id); - doc.layers = vec![l]; + doc.layers = vec![l].into(); for ch in doc.channels.iter_mut() { let f = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false); ch.surface = ch.surface.convert(PixelFormat { alpha: ch.surface.format().alpha, ..f }); diff --git a/crates/engine/src/cmd/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs index 91570fc245..77846d17c5 100644 --- a/crates/engine/src/cmd/multichannel_cmds.rs +++ b/crates/engine/src/cmd/multichannel_cmds.rs @@ -246,7 +246,7 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resu bg.locks.transparency = true; bg.locks.position = true; *active = Some(bg.id); - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.channels = others; Ok(if reinterpret { "channels" } else { "appearance" }) })?; diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index 5a7373f843..7073b45184 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -246,7 +246,7 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { solo.blend = photocraft_doc::BlendMode::Normal; solo.clipped = false; let mut tmp = doc.clone(); - tmp.layers = vec![solo]; + tmp.layers = vec![solo].into(); let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); merged.id = group.id; merged.opacity = group.opacity; diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 5c8210852b..5ef5c9860c 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -64,7 +64,7 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { if !area.is_empty() { // Render the layer on its own with the document's settings (mode, depth, global // light, patterns), then put the real stack back. - let stack = std::mem::replace(&mut doc.layers, vec![alone]); + let stack = std::mem::replace(&mut doc.layers, vec![alone].into()); let buf = photocraft_compose::render(doc, area); doc.layers = stack; let n = fmt.channels(); diff --git a/crates/engine/src/cmd/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs index 5baa7f14f2..5b676eb575 100644 --- a/crates/engine/src/cmd/sample_cmds.rs +++ b/crates/engine/src/cmd/sample_cmds.rs @@ -158,7 +158,7 @@ fn sampled_document(doc: &Document, active: Option, which: SampleLayers layer.fill_opacity = 1.0; layer.blend = photocraft_color::BlendMode::Normal; let mut solo = doc.clone(); - solo.layers = vec![layer]; + solo.layers = vec![layer].into(); return Some(Cow::Owned(solo)); } _ => {} diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs index f107df8fd3..fa0f9cf459 100644 --- a/crates/engine/src/cmd/smart_cmds/placing.rs +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -236,7 +236,7 @@ pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec) -> Result } let has_fx = layers.iter().any(|l| any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty())); let region = layers.iter().map(|l| subtree_bounds(l, canvas)).fold(canvas, |a, b| a.union(&b)).inflate(if has_fx { 256 } else { 0 }); - sub.layers = layers; + sub.layers = layers.into(); let buf = photocraft_compose::render(&sub, region); let w = region.width() as usize; diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index 52b6b5820a..3a4d65e0a4 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -285,7 +285,7 @@ fn convert_source(src: &Document, fmt: PixelFormat, raster: impl FnOnce(PixelFor } let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth); doc.icc_profile = src.icc_profile.clone(); - doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))]; + doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))].into(); if gray { let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale); crate::color_cmds::convert_document(&mut doc, &gray_profile, craft_cms::Intent::RelativeColorimetric, true)?; diff --git a/crates/engine/src/cmd/smart_cmds/tests/selection.rs b/crates/engine/src/cmd/smart_cmds/tests/selection.rs index a4f94029fa..793499f6f4 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/selection.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/selection.rs @@ -45,7 +45,7 @@ fn selected_pixels_become_one_editable_smart_object_in_every_mode_and_depth() { let mut hidden = pixel(&doc, "Hidden", Rect::new(50, 40, 58, 44), [0.2, 0.9, 0.3, 1.0]); hidden.visible = false; let ids = [a.id, b.id, hidden.id]; - doc.layers = vec![a, b, hidden]; + doc.layers = vec![a, b, hidden].into(); let mut selection = Surface::new(PixelFormat::GRAY8); selection.fill_rect(Rect::new(0, 0, 12, 12), &[0.5]); doc.selection = Some(selection); @@ -99,7 +99,7 @@ fn selected_group_and_descendant_are_embedded_once() { let group_id = group.id; let b = pixel(&doc, "Outside", Rect::new(16, 0, 32, 16), [0.0, 0.0, 1.0, 1.0]); let b_id = b.id; - doc.layers = vec![group, b]; + doc.layers = vec![group, b].into(); let mut s = selected_session(doc, &[group_id, a_id, b_id]); convert(&mut s); assert_eq!(s.active().unwrap().doc.layers.len(), 1); @@ -120,7 +120,7 @@ fn mixed_parent_selection_keeps_unselected_siblings_and_uses_the_top_selected_pa let lower = Layer::group("Lower parent", vec![a, keep_a.clone()]); let upper = Layer::group("Upper parent", vec![b, keep_b.clone()]); let (lower_id, upper_id) = (lower.id, upper.id); - doc.layers = vec![lower, upper]; + doc.layers = vec![lower, upper].into(); let original = doc.clone(); let mut s = selected_session(doc, &[b_id, a_id]); let before = flat(&s); @@ -144,7 +144,7 @@ fn explicit_layer_converts_only_that_layer_despite_multi_selection() { let a = pixel(&doc, "A", Rect::new(0, 0, 8, 8), [1.0, 0.0, 0.0, 1.0]); let b = pixel(&doc, "B", Rect::new(8, 0, 16, 8), [0.0, 0.0, 1.0, 1.0]); let (a_id, b_id) = (a.id, b.id); - doc.layers = vec![a, b.clone()]; + doc.layers = vec![a, b.clone()].into(); let mut s = selected_session(doc, &[a_id, b_id]); s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": a_id.0})).unwrap(); assert_eq!(s.active().unwrap().doc.layers.len(), 2); @@ -160,7 +160,7 @@ fn combined_contents_survive_native_and_psd_save_open() { let a = pixel(&doc, "Bottom", Rect::new(-2, 4, 20, 20), [1.0, 0.0, 0.0, 1.0]); let b = pixel(&doc, "Top", Rect::new(10, 8, 24, 24), [0.0, 0.0, 1.0, 1.0]); let ids = [a.id, b.id]; - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); let mut s = selected_session(doc, &ids); let id = LayerId(convert(&mut s)); let original = s.active().unwrap().doc.clone(); @@ -189,7 +189,7 @@ fn selected_ancestor_in_another_parent_cannot_remove_the_new_smart_object() { let lower = Layer::group("Selected parent", vec![a]); let upper = Layer::group("Unselected parent", vec![b, keep]); let (lower_id, upper_id) = (lower.id, upper.id); - doc.layers = vec![lower, upper]; + doc.layers = vec![lower, upper].into(); let mut s = selected_session(doc, &[lower_id, a_id, b_id]); let so = LayerId(convert(&mut s)); let outer = &s.active().unwrap().doc; @@ -210,7 +210,7 @@ fn an_all_hidden_selection_is_rejected_without_changing_document_selection_or_hi a.visible = false; b.visible = false; let ids = [a.id, b.id]; - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); let original = doc.clone(); let mut s = selected_session(doc, &ids); let err = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap_err(); diff --git a/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs b/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs index 6d3f3a9e23..e97e3d32d0 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs @@ -4,7 +4,7 @@ use crate::cmd::smart_cmds::source::{flattened_source, source_surface_from_buffe /// A source document of `mode`/`depth` with a textured, partly transparent block on a layer. fn source(mode: ColorMode, depth: SampleType) -> Document { let mut doc = Document::new("source", Size::new(W as u32, H as u32), mode, depth); - doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))]; + doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))].into(); doc } @@ -127,7 +127,7 @@ fn effects_across_block_edges_match() { let mut mask = LayerMask::reveal_all(); mask.surface.fill_rect(Rect::new(0, 240, width as i32, 270), &[0.3]); base.mask = Some(mask); - doc.layers = vec![base]; + doc.layers = vec![base].into(); same(&format!("blocks {width} {depth:?}"), &doc, fmt); } } diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index 0a5c635d97..6a824011ef 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -173,7 +173,7 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() { assert!(warnings.is_empty()); assert_eq!(reported.unwrap(), warped, "warning-bearing warp parity"); assert!((warped.pixel(10, 8)[0] - corrected.pixel(3, 3)[0]).abs() < 0.01, "warp must keep corrected colours"); - linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))]; + linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))].into(); let saved = encode_source(&linear).unwrap(); let reopened = decode_source("saved.pcraft", &saved).unwrap(); let LayerContent::Smart(restored) = &reopened.layers[0].content else { panic!("smart object lost on save") }; diff --git a/crates/engine/src/cmd/smart_cmds/unpack.rs b/crates/engine/src/cmd/smart_cmds/unpack.rs index a7d1eb9030..d821e1fedd 100644 --- a/crates/engine/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine/src/cmd/smart_cmds/unpack.rs @@ -33,7 +33,7 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc: crate::image_cmds::convert_layers_depth(&mut src.layers, doc.depth); } let background_id = src.background().map(|l| l.id); - let mut layers = std::mem::take(&mut src.layers); + let mut layers = std::mem::take(&mut *src.layers); for l in &mut layers { if Some(l.id) == background_id { l.name = "Layer 0".into(); diff --git a/crates/engine/src/cmd/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs index 1f96831f7e..06785cd53a 100644 --- a/crates/engine/src/cmd/stamp_cmds.rs +++ b/crates/engine/src/cmd/stamp_cmds.rs @@ -130,7 +130,7 @@ fn stamp_down(s: &mut Session, p: &Value) -> Result { let mut tmp = doc.clone(); let mut base = lower.clone(); base.visible = true; - tmp.layers = vec![base, upper]; + tmp.layers = vec![base, upper].into(); let fmt = doc.pixel_format(); let fmt = if lower.locks.transparency { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) }; let surf = photocraft_compose::flatten_to_surface(&tmp, fmt, None); diff --git a/crates/engine/src/cmd/vector_clipboard.rs b/crates/engine/src/cmd/vector_clipboard.rs index 0ad426d3b4..fde0d7763b 100644 --- a/crates/engine/src/cmd/vector_clipboard.rs +++ b/crates/engine/src/cmd/vector_clipboard.rs @@ -217,11 +217,11 @@ pub(super) fn paste(s: &mut Session, p: &Value, mode: Mode) -> Result { copies.layers = if mode == Mode::Shape { let layer = shape(&copies)?; shape_budget(layer, &destination, dx, dy)?; - vec![layer.duplicate()] + vec![layer.duplicate()].into() } else { let image = crate::smart_cmds::svg_source_image(&bytes, PixelFormat::new(ColorMode::Rgb, SampleType::F32, true), 1.0)?; copies.depth = SampleType::F32; - vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))] + vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))].into() }; crate::layer_copy_cmds::adapt_copies(s, &mut copies, &destination)?; crate::layer_copy_cmds::translate_copies(&mut copies, &destination, dx, dy); diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index bc1d154e07..ee4abbd846 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -881,7 +881,7 @@ fn image_assets_keep_full_artboards() { let board = photocraft_doc::Artboard { rect: Rect::new(4, 6, 44, 36), background: photocraft_doc::ArtboardBackground::Transparent, preset: String::new() }; let group = photocraft_doc::Group { children: vec![logo], expanded: true, artboard: Some(board), frame_stroke: None }; - doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))]; + doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))].into(); Ok(()) }) .unwrap(); @@ -920,7 +920,7 @@ fn image_assets_refuse_empty_artboards() { }; let empty = photocraft_doc::Group { children: vec![], expanded: true, artboard: Some(board(0)), frame_stroke: None }; let off = photocraft_doc::Group { children: vec![outside], expanded: true, artboard: Some(board(24)), frame_stroke: None }; - doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))]; + doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))].into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 17ac800c97..7dcacd3561 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -322,9 +322,71 @@ pub struct CopiedStyle { pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; /// The selected layers of `doc` whose active layer is `active` and whose selection set is `selected`, in bottom-to-top -/// order ([`DocState::selected_layers`]), for a reader that holds the document without its editing state. +/// order ([`DocState::selected_layers`]), taken from the document's layer index rather than a walk, for a reader that holds the document without its editing state. pub fn selected_in(doc: &Document, active: Option, selected: &[LayerId]) -> Vec { let Some(active) = active else { return Vec::new() }; let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) }; - doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + // Paths from the document's layer index order layers as the walk does (depth-first, bottom-to-top). + let index = doc.layers.index(); + let mut ids: Vec = set.iter().copied().filter(|id| index.path(*id).is_some()).collect(); + ids.sort_unstable_by(|a, b| index.path(*a).cmp(&index.path(*b))); + ids.dedup(); + ids +} + +#[cfg(test)] +mod selected_tests { + use super::selected_in; + use photocraft_doc::{ColorMode, Document, Layer, LayerId, PixelFormat, SampleType, Size}; + + fn raster(name: &str) -> Layer { + Layer::raster(name, PixelFormat::RGBA8) + } + + /// The answer before the layer index: filter the depth-first walk by the selection set. + fn by_walk(doc: &Document, active: Option, selected: &[LayerId]) -> Vec { + let Some(active) = active else { return Vec::new() }; + let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) }; + doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + } + + /// `a`, group `g` (`b`, group `h` (`c`), `d`), `e`: nested groups mixed with root layers. + fn mixed() -> (Document, Vec) { + let mut doc = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + let (a, b, c, d, e) = (raster("a"), raster("b"), raster("c"), raster("d"), raster("e")); + let h = Layer::group("h", vec![c.clone()]); + let g = Layer::group("g", vec![b.clone(), h.clone(), d.clone()]); + let ids = [&a, &g, &b, &h, &c, &d, &e].map(|l| l.id).to_vec(); + doc.layers = vec![a, g, e].into(); + (doc, ids) + } + + #[test] + fn selection_order_matches_the_walk_through_edits() { + let (mut doc, ids) = mixed(); + let stale = LayerId::fresh(); + let sets: Vec> = + vec![vec![ids[6], ids[4], ids[0]], vec![ids[5], ids[2], ids[1], ids[3]], vec![ids[4], ids[4], ids[0], stale], vec![ids[0]], vec![]]; + let check = |doc: &Document| { + let first = doc.layers.index().serial(); + for set in &sets { + for active in [None, Some(ids[0]), Some(ids[4]), Some(ids[6]), Some(stale)] { + assert_eq!(selected_in(doc, active, set), by_walk(doc, active, set)); + } + } + assert_eq!(doc.layers.index().serial(), first, "no rebuild while the document is unchanged"); + }; + check(&doc); + // Reorder: move `e` to the bottom, then a layer inside a group. + doc.shift(ids[6], -2); + check(&doc); + doc.shift(ids[5], -1); + check(&doc); + // Add and delete. + doc.insert_above(Some(ids[4]), raster("new")); + check(&doc); + doc.remove(ids[3]); + check(&doc); + assert_eq!(selected_in(&doc, Some(ids[0]), &[ids[0], ids[3], ids[4]]), vec![ids[0]], "deleted layers are skipped"); + } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 722e8b5c6d..1c6643f083 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -344,7 +344,7 @@ mod tests { roots.push(Layer::group("Outer", vec![group])); session .edit("Mask fixtures", |doc, _| { - doc.layers = roots; + doc.layers = roots.into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs index 53d8f836b8..6e0589f123 100644 --- a/crates/engine/src/layer_place.rs +++ b/crates/engine/src/layer_place.rs @@ -64,7 +64,7 @@ pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, p pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, place: Place) -> LayerId { let id = layer.id; let (parent, index) = insertion_point(doc, anchor, &layer, place); - let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; + let sib = if parent.is_empty() { Some(&mut *doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; if let Some(sib) = sib { let mut index = index.min(sib.len()); if layer.artboard().is_some() { diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index bb5f6924a5..ae27445174 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -558,7 +558,7 @@ pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer { let mut tmp = Document::new("merge", doc.size, format.mode, format.sample); // The pair is read (and a CMYK one separated again) through the document's own profile. tmp.icc_profile = doc.icc_profile.clone(); - tmp.layers = stack; + tmp.layers = stack.into(); // A Background stays canvas-sized; any other layer keeps the pixels outside the canvas (#5067). let s = if doc.is_background(lower.id) { composite_layers(&tmp, format, None) } else { composite_layers_uncropped(&tmp, format) }; let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s)); diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 77ecad13ef..16440ba1bf 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -468,7 +468,7 @@ fn artboard_fixture() -> Session { } let group = Layer::group("Group", vec![child]); let id = group.id; - doc.layers = vec![group]; + doc.layers = vec![group].into(); s.restore_layer_selection(Some(id), &[id], Some(id)).unwrap(); s } diff --git a/crates/engine/tests/it/atn_stack_modes.rs b/crates/engine/tests/it/atn_stack_modes.rs index d70fe99a41..1085f83cba 100644 --- a/crates/engine/tests/it/atn_stack_modes.rs +++ b/crates/engine/tests/it/atn_stack_modes.rs @@ -134,7 +134,7 @@ fn stack(depth: u32) -> Session { let group = Layer::new("Stack", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); let smart = photocraft_engine::smart_cmds::layer_to_smart(doc, &group)?; *active = Some(smart.id); - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/tests/it/convert_profile_options.rs b/crates/engine/tests/it/convert_profile_options.rs index ad28e2d2d5..b7cc909e1f 100644 --- a/crates/engine/tests/it/convert_profile_options.rs +++ b/crates/engine/tests/it/convert_profile_options.rs @@ -196,7 +196,7 @@ fn smart_scene(children: Vec) -> Session { doc.icc_profile = Some(Builtin::Srgb.profile().to_bytes()); let ordinary = Layer::raster("Ordinary", PixelFormat::RGBA32F); let active = ordinary.id; - doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary]; + doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary].into(); from_document(doc, Some(active)) } diff --git a/crates/engine/tests/it/export_shape_strokes.rs b/crates/engine/tests/it/export_shape_strokes.rs index 0875f4bfc0..a9c23d47e3 100644 --- a/crates/engine/tests/it/export_shape_strokes.rs +++ b/crates/engine/tests/it/export_shape_strokes.rs @@ -66,7 +66,7 @@ fn image_size_scales_strokes_once_and_undo_restores_them() { fn grouped_strokes_scale_up_and_unchanged_size_is_a_noop() { let (mut s, id) = shape_session(8); s.edit("Group", |doc, _| { - let children = std::mem::take(&mut doc.layers); + let children = std::mem::take(&mut *doc.layers); doc.layers.push(photocraft_doc::Layer::group("Outer", vec![photocraft_doc::Layer::group("Inner", children)])); Ok(()) }) diff --git a/crates/engine/tests/it/image_size_scale_styles.rs b/crates/engine/tests/it/image_size_scale_styles.rs index 4ae6cbabd2..5bde492676 100644 --- a/crates/engine/tests/it/image_size_scale_styles.rs +++ b/crates/engine/tests/it/image_size_scale_styles.rs @@ -28,7 +28,7 @@ fn styled_shape(depth: u32) -> (Session, LayerId) { ..Default::default() }; doc.layer_mut(id).unwrap().effects = effects.clone(); - let children = std::mem::take(&mut doc.layers); + let children = std::mem::take(&mut *doc.layers); let mut outer = Layer::group("Outer", vec![Layer::group("Inner", children)]); outer.effects = effects; doc.layers.push(outer); diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index cc255ab818..cd76c4c542 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -698,7 +698,7 @@ impl Loader<'_> { mode: m.mode, depth: m.depth, icc_profile: self.opt_blob(&m.icc_profile)?, - layers, + layers: layers.into(), channels, guides: m.guides.clone(), ruler_origin: m.ruler_origin, diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 79850cb26a..3e9f340c1e 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -461,11 +461,11 @@ fn group_depth(layers: &[Layer]) -> usize { /// [`rich_doc`] with its layers wrapped in groups until they are nested `levels` deep. fn nested_doc(levels: usize, depth: SampleType) -> Document { let mut doc = rich_doc(ColorMode::Rgb, depth); - let mut layers = std::mem::take(&mut doc.layers); + let mut layers = std::mem::take(&mut *doc.layers); for i in group_depth(&layers)..levels { layers = vec![Layer::group(format!("Level {i}"), layers)]; } - doc.layers = layers; + doc.layers = layers.into(); assert_eq!(group_depth(&doc.layers), levels); doc } diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index c563fb289f..39b0f64e6a 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -12,7 +12,7 @@ fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially( layers = vec![group, clipped]; } let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - doc.layers = layers; + doc.layers = layers.into(); let started = std::time::Instant::now(); let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; assert!(error.0.contains("too many nested layers"), "{}", error.0); diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rs index 31406c6449..6c45acb096 100644 --- a/crates/gpu/src/prefix.rs +++ b/crates/gpu/src/prefix.rs @@ -114,7 +114,7 @@ impl Prefix { // Keeping every non-layer field makes new document inputs invalidate automatically. // Tile data is Arc-shared; shared Tile equality does not scan its pixel bytes. let mut context = doc.clone(); - let layers = std::mem::take(&mut context.layers); + let layers = std::mem::take(&mut *context.layers); let same_context = self.context.as_ref() == Some(&context); // The lowest root layer this render changes since the last one (a layer added or removed // at the top changes from there on). diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 46154fb3f5..e12030fe52 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -78,7 +78,7 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() { let mut d = Document::new("HDR adjustments", Size::new(3, 1), ColorMode::Rgb, SampleType::F32); let mut layer = Layer::raster("pixels", PixelFormat::RGBA32F); layer.surface_mut().unwrap().write_region(Rect::new(0, 0, 3, 1), &[4.0, 2.0, 0.5, 1.0, -0.1, 3.0, 0.25, 0.75, 0.0, 0.0, 0.0, 1.0]); - d.layers = vec![layer, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))]; + d.layers = vec![layer, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))].into(); let cpu = photocraft_compose::flatten(&d); assert!(cpu.px[0][0] > 1.0, "HDR reference unexpectedly clipped: {adj:?}"); check(&mut g, &d, &format!("HDR {adj:?}")); @@ -1011,7 +1011,7 @@ fn hard_stop_fill_fallback_respects_caches_and_visibility() { assert_gradient_fallback(&d); let mut clipped = Layer::new("clipped", LayerContent::Fill(fill)); clipped.clipped = true; - d.layers = vec![Layer::new("base", LayerContent::Fill(Fill::Solid(Color::WHITE))), clipped]; + d.layers = vec![Layer::new("base", LayerContent::Fill(Fill::Solid(Color::WHITE))), clipped].into(); assert_gradient_fallback(&d); d.layers.push(Layer::new("cover", LayerContent::Fill(Fill::Solid(Color::WHITE)))); assert!(photocraft_gpu::plan(&d).is_ok(), "occluded gradients are not sampled"); @@ -3040,7 +3040,7 @@ fn lab_documents_mix_in_lab() { a.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); let mut b = Layer::raster("b", fmt); b.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 0.0, 0.5])); - d.layers = vec![a, b]; + d.layers = vec![a, b].into(); let p = photocraft_compose::flatten(&d).px[0]; assert!((p[0] - 0.5).abs() > 0.05 || (p[2] - 0.5).abs() > 0.05, "{p:?}"); } @@ -3545,7 +3545,7 @@ fn integration_adjustment_fill_opacity_masks_and_hdr_match_cpu() { &[coverage], ); layer.mask = Some(mask); - d.layers = vec![base, layer]; + d.layers = vec![base, layer].into(); check(&mut g, &d, &format!("combined {mode:?} fill={fill} opacity={opacity} mask={coverage} clipped={clipped}")); } } @@ -3565,7 +3565,7 @@ fn integration_adjustment_fill_opacity_masks_and_hdr_match_cpu() { dither: false, source: None, }; - d.layers = vec![base, Layer::new("lookup", LayerContent::Adjustment(look))]; + d.layers = vec![base, Layer::new("lookup", LayerContent::Adjustment(look))].into(); check(&mut g, &d, "HDR full coverage with bounded result"); } diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 8e925bf8b4..f4625caf71 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -201,7 +201,7 @@ impl Builder<'_> { l.locks.position = true; layers.insert(0, l); } - self.doc.layers = layers; + self.doc.layers = layers.into(); Ok(()) } diff --git a/crates/io/src/exr_parts.rs b/crates/io/src/exr_parts.rs index 7ebac8eae2..4b815787d8 100644 --- a/crates/io/src/exr_parts.rs +++ b/crates/io/src/exr_parts.rs @@ -270,7 +270,7 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result) -> Result) -> Result 0.0 && xres < 1.0e6 { diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index e4f5868717..e073b01908 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -42,7 +42,7 @@ fn doc(depth: SampleType) -> Document { through_child.blend = BlendMode::LinearLight; through_child.locks.all = true; let through = Layer::group("Pass <&> \"through\"", vec![through_child]); - d.layers = vec![base, off, hidden, group, through]; + d.layers = vec![base, off, hidden, group, through].into(); d } @@ -93,7 +93,7 @@ fn float_documents_save_as_16_bit() { let mut d = doc(SampleType::U16); d.depth = SampleType::F32; let fmt = PixelFormat::RGBA32F; - d.layers = vec![block("Float", fmt, 0, 0, 10, 10, 9)]; + d.layers = vec![block("Float", fmt, 0, 0, 10, 10, 9)].into(); let (back, warnings, _) = round_trip(&d); assert!(warnings.iter().any(|w| w.contains("16-bit")), "{warnings:?}"); assert_eq!(back.depth, SampleType::U16); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 3dd6322c88..b3844d993e 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -28,7 +28,7 @@ fn doc(mode: ColorMode) -> Document { let fmt = PixelFormat::new(mode, SampleType::F32, true); let bg = paper(mode); let mut d = Document::new("t.pdf", Size { width: 4, height: 2 }, mode, SampleType::F32); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 4, 2, &bg)))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 4, 2, &bg)))].into(); d } @@ -187,7 +187,7 @@ fn the_page_measures_at_the_document_resolution() { let mut d = doc(ColorMode::Rgb); d.size = Size { width: 300, height: 150 }; let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))].into(); d.resolution_dpi = 300.0; let out = export(&d, true, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch"); @@ -495,7 +495,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() { d.size = Size { width: 128, height: 48 }; let fmt = d.pixel_format(); // Synthetic photo-like backdrop; no personal image or third-party asset. - d.layers = vec![Layer::new("Photo", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[0.2, 0.4, 0.6, 1.0])))]; + d.layers = vec![Layer::new("Photo", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[0.2, 0.4, 0.6, 1.0])))].into(); let text = "café Ω 😀"; d.layers.push(Layer::new( "Text", @@ -599,7 +599,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() { let mut d = doc(ColorMode::Rgb); d.size = Size { width: 128, height: 48 }; let fmt = d.pixel_format(); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[1.0, 1.0, 1.0, 1.0])))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[1.0, 1.0, 1.0, 1.0])))].into(); // A box too short for its paragraph: the layout hides the overflow, so `prepare` accepts // the layer (its checks only see placed clusters) while emission refuses it, because the // hidden, unpainted source text would otherwise show up in the selection plane. diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 7884cef7c2..706802ee26 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1451,7 +1451,7 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ let cc = fmt.mode.color_channels(); let tree = file.layer_tree_max_depth(photocraft_doc::MAX_GROUP_DEPTH); let space = photocraft_compose::cmyk_space(doc); - doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); + doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)).into(); mark_background(file, &mut doc.layers); if let Some(Ok(craft_psd::resources::ResourceData::LayerGroupInfo(groups))) = file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(craft_psd::resources::ImageResource::parsed) diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index 2cef2ad229..8a0825c881 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -319,7 +319,7 @@ fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { let transparent = |names: &[&str]| { let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())].into(); doc.channels.retain(|c| names.contains(&c.name.as_str())); doc }; @@ -350,7 +350,7 @@ fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { #[test] fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())].into(); let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); let file = PsdFile::from_bytes(&bytes).unwrap(); assert!(file.merged_has_alpha()); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 5830316088..2905cca741 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1047,7 +1047,7 @@ fn import_parsed_with_limits( } } } else { - doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform()); + doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform()).into(); } if doc.layers.is_empty() && !conv.noted.contains(&"raster-panic") { conv.warnings.push("SVG: nothing to draw (an empty drawing)".to_string()); diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 9ae250ee11..2f9706d43d 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -297,7 +297,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result 0.0 && *x < 1.0e6) { diff --git a/crates/io/tests/it/artboard_guide_order.rs b/crates/io/tests/it/artboard_guide_order.rs index 514c7e0b56..de53f9d407 100644 --- a/crates/io/tests/it/artboard_guide_order.rs +++ b/crates/io/tests/it/artboard_guide_order.rs @@ -33,7 +33,7 @@ fn doc_with_board(rect: Rect) -> Document { if let LayerContent::Group(g) = &mut g1.content { g.artboard = Some(Artboard { rect, background: ArtboardBackground::White, preset: String::new() }); } - d.layers = vec![g1]; + d.layers = vec![g1].into(); d.guides = Guides { horizontal: vec![90.0], vertical: vec![20.0], ..Default::default() }; d } diff --git a/crates/io/tests/it/comps_artboards.rs b/crates/io/tests/it/comps_artboards.rs index 3476560d1c..27500a9d55 100644 --- a/crates/io/tests/it/comps_artboards.rs +++ b/crates/io/tests/it/comps_artboards.rs @@ -134,7 +134,7 @@ fn synthetic(depth: SampleType) -> Document { g.artboard = Some(Artboard { rect: Rect::new(40, 0, 80, 40), background: ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)), preset: String::new() }); } - d.layers = vec![g1, g2]; + d.layers = vec![g1, g2].into(); let states = capture_states(&d); d.layer_comps.push(LayerComp { id: 11, diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index 6402329d9d..af72cd1e1c 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -417,7 +417,7 @@ fn link_groups_and_effects_reference_round_trip() { let mut inner = Layer::raster("inner", fmt); inner.link_group = Some(3); let g = Layer::group("g", vec![inner]); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let back = roundtrip(&d); assert_eq!(back.layers[0].link_group, Some(7)); assert_eq!(back.layers[1].link_group, Some(7)); @@ -459,7 +459,7 @@ fn channel_restrictions_round_trip_as_brst() { a.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); a.excluded_channels = 0b110; let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b]; + d.layers = vec![a, b].into(); let f = document_to_psd(&d).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "a").unwrap(); assert_eq!(rec.block(b"brst").unwrap().data, vec![0, 0, 0, 1, 0, 0, 0, 2]); @@ -497,7 +497,7 @@ fn advanced_blending_round_trips_as_tagged_blocks() { g.advanced.knockout = Knockout::Shallow; g.fill_opacity = 128.0 / 255.0; let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let f = document_to_psd(&d).unwrap(); let rec = |name: &str| f.layers().iter().find(|r| r.name() == name).unwrap().clone(); let ra = rec("a"); @@ -539,7 +539,7 @@ fn blend_if_round_trips_as_blending_ranges() { let mut g = Layer::group("g", vec![Layer::raster("c", d.pixel_format())]); g.blend_if.set(1, [BlendRange { black: [1, 2], white: [3, 4] }, BlendRange::FULL]); let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let f = document_to_psd(&d).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "a").unwrap(); let full = [0u8, 0, 255, 255, 0, 0, 255, 255]; @@ -630,7 +630,7 @@ fn frame_children_keep_their_links() { let b = Layer::raster("b", fmt); let mut outside = Layer::raster("outside", fmt); outside.link_group = Some(5); - d.layers = vec![framed(vec![a, b], Some(photocraft_doc::ShapeStroke::default())), outside]; + d.layers = vec![framed(vec![a, b], Some(photocraft_doc::ShapeStroke::default())), outside].into(); let back = roundtrip(&d); let LayerContent::Group(g) = &back.layers[0].content else { panic!("frame is not a group") }; let names: Vec<_> = g.children.iter().map(|l| (l.name.as_str(), l.link_group)).collect(); @@ -645,7 +645,7 @@ fn frame_stroke_exports_its_pixels() { let mut d = Document::new("s", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); let fmt = d.pixel_format(); let stroke = photocraft_doc::ShapeStroke { width: 2.0, ..Default::default() }; - d.layers = vec![framed(vec![Layer::raster("a", fmt)], Some(stroke))]; + d.layers = vec![framed(vec![Layer::raster("a", fmt)], Some(stroke))].into(); let r = export(&d, "x.psd", &ExportOptions::default()).unwrap(); let f = PsdFile::from_bytes(&r.bytes).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "Frame Stroke").expect("stroke record"); @@ -659,7 +659,7 @@ fn an_invalidated_frame_stays_removed_after_psd_roundtrip() { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { let mut doc = Document::new("frame", Size::new(8, 8), ColorMode::Rgb, depth); - doc.layers = vec![framed(vec![Layer::raster("image", doc.pixel_format())], None)]; + doc.layers = vec![framed(vec![Layer::raster("image", doc.pixel_format())], None)].into(); let mut imported = roundtrip(&doc); let frame = &mut imported.layers[0]; assert!(frame.frame.is_some(), "{depth:?}: the frame must first survive import"); diff --git a/crates/ui-egui/examples/interactive_bench.rs b/crates/ui-egui/examples/interactive_bench.rs index d4c555df47..090aad88b4 100644 --- a/crates/ui-egui/examples/interactive_bench.rs +++ b/crates/ui-egui/examples/interactive_bench.rs @@ -294,7 +294,7 @@ fn clipped_document(w: u32, h: u32, styled: bool) -> (Document, LayerId) { } above.clipped = true; above.opacity = 0.6; - doc.layers = vec![base, below, target, above]; + doc.layers = vec![base, below, target, above].into(); (doc, id) } @@ -746,7 +746,7 @@ mod reporting_tests { if let Some(s) = photo.surface_mut() { s.fill_rect(doc.bounds(), &[0.4, 0.5, 0.6, 1.0]); } - doc.layers = vec![photo]; + doc.layers = vec![photo].into(); let psd = photocraft_io::export(&doc, "x.psd", &Default::default()).expect("export psd").bytes; let no_free_memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; photocraft_io::memory::with_mock_memory(no_free_memory, || { diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index e73a495756..cdaaf74c93 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1251,7 +1251,7 @@ fn artboard_preview_app(background: photocraft_doc::ArtboardBackground) -> (Box< ab.background = background; g.artboard = Some(ab); } - doc.layers = vec![board]; + doc.layers = vec![board].into(); (app, board_id, red_id) } diff --git a/crates/ui-egui/tests/support/layout_doc.rs b/crates/ui-egui/tests/support/layout_doc.rs index a36acfc604..249f22e18d 100644 --- a/crates/ui-egui/tests/support/layout_doc.rs +++ b/crates/ui-egui/tests/support/layout_doc.rs @@ -344,7 +344,7 @@ pub fn build(spec: Spec) -> (Document, Handles) { let lv = t(levels); let background = doc.layers.remove(0); assert!(doc.layers.is_empty(), "unassembled layers: {:?}", doc.layers.iter().map(|l| &l.name).collect::>()); - doc.layers = vec![background, gallery, products, hero, header, footer, lv]; + doc.layers = vec![background, gallery, products, hero, header, footer, lv].into(); handles.closed_group = hero_id; (doc, handles) } From 587f5e5dab4eaea4dc745565b89e2d39d4eb0e0b Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 10:09:05 +0000 Subject: [PATCH 292/385] 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 36066eae8f855250300e3f6f92dcbc7ecb3fa6ef Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 19 Nov 2026 12:38:27 +0100 Subject: [PATCH 293/385] fix(algo): retry today's patch radius when 11x11 leaves no donor Round 2 review on #15284: with the measured option set the fill asked for 11x11 patches even where no such donor window exists, so the completion found nothing to copy and the fill answered with the smooth membrane where today's 7x7 patch still copies pieces. Two distinct causes, both measured at b2764ca1c on stripe buffers with the measured options and the Rectangular area: - a buffer narrower than the patch: at 9x9 (1 px border hole) the radius-3 completion fills the hole with 96 channel values differing from the membrane, radius 5 has no donor at all and the fill returned the membrane in all 243 channel values; at 10x10 that is 108 of 300. - a hole that uses up every window of a big enough buffer: at 18x18 with an 8x8 centre hole there are 11x11 windows (centres x and y 5 to 12) but the hole is in each of them, while 7x7 windows remain; radius 5 gives no donor and the fill returned the membrane, 192 of 972 channel values away from today's radius-3 completion. (The review's 18x18 with a 2x2 centre hole is not one of these: there the fill still completed with radius 5, 178 channel values from today's answer.) Change: fill_cow now hands the completion today's default radius when the measured radius finds nothing to copy, before the membrane fallback. A measured fill keeps its pixels borrowed and rebuilds the attempt (the mosaic gap follows the radius); every other option set still gets exactly one attempt, in place as before, so the not-measured pins are untouched. `fill_cow` also gives way to named parts: variant_specs, mosaic_variants, mosaic_pixels, window_roles, fill_attempt and fill_retry. New tests in the file #14191 names, red before the fix (2 failed), green after: measured_fill_on_a_small_image_keeps_todays_patch_radius, measured_fill_falls_back_to_todays_radius_when_the_hole_leaves_no_room_for_the_patch; guards pinning what did not change: measured_fill_uses_the_11x11_patch_when_a_window_fits, measured_fill_without_room_for_todays_patch_still_falls_back_to_the_membrane. --- crates/algo/src/content_aware.rs | 318 +++++++++++++----- .../content_aware/structure_continue_tests.rs | 122 +++++++ 2 files changed, 352 insertions(+), 88 deletions(-) diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 51cdfd436e..f9d84bd713 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -266,6 +266,186 @@ fn rectangular_area(hole: &[bool], source: &[bool]) -> bool { hole.iter().zip(source).all(|(h, s)| *h || *s) } +/// The variant specs of `opts`: mirror, the rotation set, the scaled pair. +fn variant_specs(opts: &FillOptions) -> Vec<(f32, f32, bool)> { + let mut specs: Vec<(f32, f32, bool)> = Vec::new(); + if opts.mirror { + specs.push((0.0, 1.0, true)); + } + for ° in &opts.rotations { + specs.push((deg, 1.0, false)); + } + if opts.scale { + specs.push((0.0, 0.8, false)); + specs.push((0.0, 1.25, false)); + } + specs +} + +/// The variants of `src` for `specs`, or none when none are asked for or their mosaic would not fit +/// in the budget. The mosaic gap follows `params`, so they are built again for every attempt. +fn mosaic_variants(src: Src, specs: &[(f32, f32, bool)], params: &CompleteParams, ctl: &Interrupt) -> Result, Cancelled> { + if specs.is_empty() { + return Ok(Vec::new()); + } + let gap = 2 * params.patch_radius + 2; + let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(src.w, src.h, deg, scale)).collect(); + if mosaic_size(src.w, src.h, gap, &dims).is_none() { + return Ok(Vec::new()); + } + let mut extra = Vec::new(); + for &(deg, scale, mirror) in specs { + extra.push(variant(src, deg, scale, mirror, ctl)?); + } + Ok(extra) +} + +/// The roles of the window's pixels: the hole, what may be copied from, and the rest of the image. +fn window_roles(hole: &[bool], ok: &[bool]) -> Vec { + par::map(hole.len(), true, |s| { + if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + } + }) +} + +/// The mosaic of the window and its variants: identity at the left, the variants in a column to its +/// right, gaps that are no image. `None` when the mosaic spans more than the budget (the variants +/// then go unused, as they did before they were built). +#[allow(clippy::too_many_arguments)] +fn mosaic_pixels( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + extra: &[Variant], + params: &CompleteParams, +) -> Option<(usize, usize, Vec, Vec)> { + let gap = 2 * params.patch_radius + 2; + if extra.is_empty() { + return None; + } + let (mw, mh) = mosaic_size(w, h, gap, &extra.iter().map(|v| (v.w, v.h)).collect::>())?; + let mut mimg = vec![0.0f32; mw * mh * ch]; + let mut roles = vec![Px::Void; mw * mh]; + for y in 0..h { + for x in 0..w { + let (s, d) = (y * w + x, y * mw + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); + roles[d] = if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + }; + } + } + let mut oy = 0; + for v in extra { + for y in 0..v.h { + for x in 0..v.w { + let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); + if v.ok[s] { + roles[d] = Px::Source; + } + } + } + oy += v.h + gap; + } + Some((mw, mh, mimg, roles)) +} + +/// One completion attempt: the variant mosaic to run it on, or the plain window when no variant was +/// asked for or the mosaic would not fit the budget. +struct Attempt { + /// The mosaic's dimensions (the window's own when there is no mosaic). + mw: usize, + mh: usize, + /// The mosaic pixels; empty when the attempt runs on the window itself. + mosaic: Vec, + /// The roles of the attempt's pixels (the window's own when there is no mosaic). + roles: Vec, +} + +/// Build one attempt: variants first (their pixels are expensive, so the mosaic budget is settled +/// on their dimensions before any variant is built), then the mosaic or the plain window's roles. +/// The mosaic gap follows `params`, so an attempt is built for every patch radius. +#[allow(clippy::too_many_arguments)] +fn fill_attempt( + w: usize, + h: usize, + ch: usize, + pixels: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &CompleteParams, + ctl: &Interrupt, +) -> Result { + let src = Src { w, h, ch, img: pixels, ok }; + let extra = mosaic_variants(src, specs, params, ctl)?; + ctl.check()?; + match mosaic_pixels(w, h, ch, pixels, hole, ok, &extra, params) { + Some((mw, mh, mosaic, roles)) => Ok(Attempt { mw, mh, mosaic, roles }), + // No variant was asked for, or its mosaic would not fit the budget: complete the window. + None => Ok(Attempt { mw: w, mh: h, mosaic: Vec::new(), roles: window_roles(hole, ok) }), + } +} + +/// The window's own pixels out of a finished mosaic (its left region, the variants and the gaps +/// beside it are no answer). +fn window_from_mosaic(w: usize, h: usize, ch: usize, mw: usize, mosaic: &[f32]) -> Vec { + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + for x in 0..w { + let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); + out[d..d + ch].copy_from_slice(&mosaic[s..s + ch]); + } + } + out +} + +/// The measured fill of #14191, asked again with today's radius when the 11x11 patch leaves no +/// donor: an 11x11 window needs room inside the buffer, and a hole can also use up every window of +/// a bigger one. Without that second attempt the fill would answer with the smooth membrane where +/// today's 7x7 patch still copies pieces; #14191 measures a 600x400 document and keeps every other +/// case on today's behaviour. +#[allow(clippy::too_many_arguments)] +fn fill_retry( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &Interrupt, +) -> Result>, Cancelled> { + let measured = params.patch_radius; + for radius in [measured, CompleteParams::default().patch_radius] { + params.patch_radius = radius; + let attempt = fill_attempt(w, h, ch, img, hole, ok, specs, params, ctl)?; + if attempt.mosaic.is_empty() { + if let Some(f) = complete_masked(w, h, ch, img, &attempt.roles, params, inner)? { + return Ok(Some(f)); + } + } else if let Some(f) = complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, params, inner)? { + return Ok(Some(window_from_mosaic(w, h, ch, attempt.mw, &f))); + } + } + Ok(None) +} + #[allow(clippy::too_many_arguments)] fn fill_cow( w: usize, @@ -287,110 +467,72 @@ fn fill_cow( if structure_measured(opts) && rectangular_area(hole, source) { params.patch_radius = MEASURED_STRUCTURE_PATCH_RADIUS; } - let gap = 2 * params.patch_radius + 2; let ok: Vec = par::map(w * h, true, |i| !hole[i] && source[i]); - let src = Src { w, h, ch, img: &img, ok: &ok }; - // Variants: the identity (which holds the hole) first, then the adaptations. Their pixels are - // expensive, so the mosaic budget is settled on their dimensions before any variant is built; - // when the variants would not fit, the image itself is completed without them. - let mut specs: Vec<(f32, f32, bool)> = Vec::new(); - if opts.mirror { - specs.push((0.0, 1.0, true)); - } - for ° in &opts.rotations { - specs.push((deg, 1.0, false)); - } - if opts.scale { - specs.push((0.0, 0.8, false)); - specs.push((0.0, 1.25, false)); - } - let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(w, h, deg, scale)).collect(); - let size = if specs.is_empty() { None } else { mosaic_size(w, h, gap, &dims) }; - let mut extra: Vec = Vec::new(); - if size.is_some() { - for &(deg, scale, mirror) in &specs { - extra.push(variant(src, deg, scale, mirror, ctl)?); - } - } - let role = |s: usize| { - if hole[s] { - Px::Hole - } else if ok[s] { - Px::Source - } else { - Px::Known - } - }; - // Mosaic: identity at the left, variants in a column to its right, gaps that are no image. - // Without variants it is the image itself; so it is when the variants would not fit - // (`size` above is then None and `extra` is empty). - let (mw, mh, mosaic, roles): (usize, usize, Option>, Vec) = if let Some((mw, mh)) = size { - let mut mimg = vec![0.0f32; mw * mh * ch]; - let mut roles = vec![Px::Void; mw * mh]; - for y in 0..h { - for x in 0..w { - let (s, d) = (y * w + x, y * mw + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); - roles[d] = role(s); - } - } - let mut oy = 0; - for v in &extra { - ctl.check()?; - for y in 0..v.h { - for x in 0..v.w { - let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); - if v.ok[s] { - roles[d] = Px::Source; - } - } - } - oy += v.h + gap; - } - (mw, mh, Some(mimg), roles) - } else { - (w, h, None, par::map(w * h, true, role)) - }; - drop((extra, ok)); - ctl.check()?; + let specs = variant_specs(opts); // The completion is nearly all the work. let cancel = || ctl.cancelled(); let progress = |f: f32| ctl.progress(f * 0.99); let inner = photocraft_raster::Interrupt::new(&cancel, &progress); - let out = match mosaic { - // Without variants the image itself is completed (it changes only in the hole). - None => { - let filled: Result, Cow<[f32]>> = match img { - Cow::Owned(v) => complete_masked_owned(w, h, ch, v, &roles, ¶ms, &inner)?.map_err(Cow::Owned), - Cow::Borrowed(b) => complete_masked(w, h, ch, b, &roles, ¶ms, &inner)?.ok_or(Cow::Borrowed(b)), - }; - match filled { + // One completion for every option set but the measured one: it fills the caller's buffer in + // place when it owns one. The measured set may be asked a second time (see `fill_retry`). + if params.patch_radius != MEASURED_STRUCTURE_PATCH_RADIUS { + let mut pixels = img.into_owned(); + let attempt = fill_attempt(w, h, ch, &pixels, hole, &ok, &specs, ¶ms, ctl)?; + ctl.check()?; + let out = if attempt.mosaic.is_empty() { + match complete_masked_owned(w, h, ch, pixels, &attempt.roles, ¶ms, &inner)? { Ok(f) => f, - Err(img) => membrane_fill_with(w, h, ch, &img, hole, ctl)?, + // Nothing to copy from: the membrane, as today. + Err(v) => membrane_fill_with(w, h, ch, &v, hole, ctl)?, } - } - Some(mimg) => match complete_masked(mw, mh, ch, &mimg, &roles, ¶ms, &inner)? { - Some(f) => { - let mut out = img.into_owned(); - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); - out[d..d + ch].copy_from_slice(&f[s..s + ch]); + } else { + match complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, ¶ms, &inner)? { + Some(f) => { + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + let (s, d) = ((y * attempt.mw + x) * ch, (y * w + x) * ch); + pixels[d..d + ch].copy_from_slice(&f[s..s + ch]); + } } } + pixels } - out + None => membrane_fill_with(w, h, ch, &pixels, hole, ctl)?, } - None => membrane_fill_with(w, h, ch, &img, hole, ctl)?, - }, - }; + }; + ctl.check()?; + ctl.progress(1.0); + return Ok(out); + } + let out = fill_cow_measured(w, h, ch, img.as_ref(), hole, &ok, &specs, &mut params, &inner, ctl)?; ctl.check()?; ctl.progress(1.0); Ok(out) } +/// The measured fill (#14191): the window is read where it stands, so both attempts see the same +/// pixels; the answer is a new buffer, as in [`fill_with`] (measured fills come from the command's +/// own copy of the sampling window). +#[allow(clippy::too_many_arguments)] +fn fill_cow_measured( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &photocraft_raster::Interrupt, +) -> Result, Cancelled> { + match fill_retry(w, h, ch, img, hole, ok, specs, params, inner, ctl)? { + Some(f) => Ok(f), + // Nothing to copy from at either radius: the membrane, as today. + None => membrane_fill_with(w, h, ch, img, hole, ctl), + } +} /// Box mean of radius `r` over a `w × h` plane (edge-clamped), by summed areas. fn box_mean(w: usize, h: usize, v: &[f32], r: usize) -> Vec { let w1 = w + 1; diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 30ff8111ae..895e9f5d02 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -348,3 +348,125 @@ fn auto_fill_whose_area_differs_from_rectangular_keeps_todays_patch_radius() { let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); assert_eq!(moved, 0, "{moved} channel values differ from today's radius-3 fill"); } + +/// A small buffer that carries the measured option set and the Rectangular area, so the patch +/// radius is the only thing under test: vertical stripes (period 4) in two far-apart colours, with +/// the hole the 1 px border of the buffer. An off-centre 2 x 2 hole leaves no 7 x 7 donor either on +/// a buffer this small (every 7 x 7 window takes a hole pixel), so it proves nothing here. +fn small_stripes(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = (0..n * n).map(|i| (i % n).min(i / n) < 1 || (i % n).max(i / n) > n - 2).collect(); + (img, hole) +} + +/// The completion of the same roles with a given patch radius: `None` when that radius leaves no +/// donor to copy from, which is what sends the fill to the membrane. +fn completion(n: usize, img: &[f32], hole: &[bool], params: &CompleteParams) -> Option> { + let roles: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); + complete_masked(n, n, 3, img, &roles, params, &Interrupt::NONE).unwrap() +} + +/// The smallest side that still holds a fully interior 11 x 11 donor window. +const PATCH_SIDE: usize = MEASURED_STRUCTURE_PATCH_RADIUS * 2 + 1; + +/// Review round 2, real: on a buffer narrower than the 11 x 11 patch there is no window centre for +/// radius 5 at all, so the measured fill found no donor and answered with the smooth membrane where +/// today's radius 3 still copies pieces (#14191 measures 600 x 400 and keeps every other case on +/// today's behaviour, and its "no regression" bullet covers this). Measured at b2764ca1c: on the +/// 9 x 9 buffer the radius-3 completion fills the border hole with 96 channel values differing from +/// the membrane; the radius-5 completion has no donor, so the fill returned the membrane in all 243 +/// channel values of that buffer. The fill now gets today's radius-3 answer there again. +#[test] +fn measured_fill_on_a_small_image_keeps_todays_patch_radius() { + for n in [PATCH_SIDE - 2, PATCH_SIDE - 1] { + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "n {n}: the measured configuration"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "n {n}: today's radius"); + let today = completion(n, &img, &hole, ¶ms).unwrap_or_else(|| panic!("n {n}: today's radius-3 fill has no donor either")); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let like_membrane = out.iter().zip(&membrane).filter(|(a, b)| *a == *b).count(); + assert_eq!( + moved, + 0, + "n {n}: {moved} of {} channel values differ from today's radius-3 fill; {like_membrane} of them equal the membrane fill", + img.len() + ); + } +} + +/// The other side of that border: when an 11 x 11 donor window does exist, the measured fill uses +/// it, also on a small buffer (18 x 18 with a 1 px border hole: 178 channel values differ from +/// today's radius-3 completion there). Guard test, passes before and after the change. +#[test] +fn measured_fill_uses_the_11x11_patch_when_a_window_fits() { + let n = 18; + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + let with_patch = completion(n, &img, &hole, &wide).expect("n 18: an 11 x 11 donor window must exist beside a 1 px border hole"); + let today = completion(n, &img, &hole, &CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }) + .expect("n 18: today's fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let from_patch = out.iter().zip(&with_patch).filter(|(a, b)| a != b).count(); + let from_today = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(from_patch, 0, "the measured fill is not the 11 x 11 completion ({from_patch} channel values differ)"); + assert_ne!(from_today, 0, "the 11 x 11 completion is the same as today's ({from_today} differ): the patch was never used"); +} + +/// The membrane fallback stays where it already is today: a buffer with no room even for the +/// default 7 x 7 patch has no donor at either radius, so the new radius never reaches it. +/// Guard test, passes before and after the change. +#[test] +fn measured_fill_without_room_for_todays_patch_still_falls_back_to_the_membrane() { + for n in 4..7 { + let (img, hole) = small_stripes(n); + let opts = FillOptions { color_adaptation: Adapt::NONE, ..FillOptions::default() }; + let source: Vec = hole.iter().map(|h| !h).collect(); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, ¶ms).is_none(), "n {n}: no donor at today's radius either"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let moved = out.iter().zip(&membrane).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "n {n}: {moved} channel values differ from the membrane fill"); + } +} + +/// The same buffer as [`small_stripes`] with an 8 x 8 hole in the middle instead of the border: at +/// 18 x 18 there are 11 x 11 windows (their centres are x and y 5 to 12), but the hole covers every +/// one of them, while a 7 x 7 window still fits in the 8-wide strips left and right of it. +fn stripes_hole_blocking_the_wide_windows(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = + (0..n * n).map(|i| matches!(i % n, x if x >= n / 2 - 1 && x <= n / 2 + 6) && matches!(i / n, y if y >= n / 2 - 1 && y <= n / 2 + 6)).collect(); + (img, hole) +} + +/// The other way radius 5 can leave no donor: a buffer with room for 11 x 11 windows, and a hole +/// that uses up all of them. #14191 measured a hole four patches across in a 400 x 400 window, so a +/// fill that completes today with the default radius has to complete the same way here, before the +/// membrane fallback. +#[test] +fn measured_fill_falls_back_to_todays_radius_when_the_hole_leaves_no_room_for_the_patch() { + let n = 18; + let (img, hole) = stripes_hole_blocking_the_wide_windows(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "the measured configuration"); + assert_eq!(hole.iter().filter(|h| **h).count(), 64, "an 8 x 8 hole"); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, &wide).is_none(), "radius 5 must leave no donor here, that is the case under test"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "today's radius"); + let today = completion(n, &img, &hole, ¶ms).expect("today's radius-3 fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "{moved} of {} channel values differ from today's radius-3 fill", img.len()); +} From 0d2ed110e8b4580dc5c4f25c8e88d42010682065 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:53:45 +0100 Subject: [PATCH 294/385] Keep transient surface generations out of content diagnostics --- crates/raster/src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 8255122bb8..8bb7d13a77 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -309,7 +309,7 @@ impl PruneCursor { } } -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct Surface { generation: u64, format: PixelFormat, @@ -317,6 +317,14 @@ pub struct Surface { tiles: BTreeMap>, } +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 + // document should retain the same content representation. + f.debug_struct("Surface").field("format", &self.format).field("default_pixel", &self.default_pixel).field("tiles", &self.tiles).finish() + } +} + /// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer. fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { if let Some(samples) = stack.get_mut(..channels) { From 47e4c5543ed062dda647ce652faebd0af904ffa5 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Thu, 19 Nov 2026 11:57:36 +0000 Subject: [PATCH 295/385] Scale Effects: title "Scale Layer Effects" and a popup-slider percent field (#14996) The dialog now reads "Scale Layer Effects" and its Scale row is a whole-percent field whose arrow opens a linear 1..1000 slider, instead of the schema row's always-shown logarithmic slider. Other wide-range rows keep their slider. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/filter_dialog.rs | 38 +++++++++- .../src/dialogs/scale_effects_layout_tests.rs | 71 +++++++++++++++++++ 3 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/scale_effects_layout_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4b7963e120..678e976ac7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -745,6 +745,8 @@ mod paths_export_document_bounds_tests; pub(crate) mod pattern_fill_ui; pub mod preset_group_prompt; pub mod rasterize_prompt; +#[cfg(test)] +mod scale_effects_layout_tests; pub mod screen_picker; pub mod select_mask_ui; pub mod shape_dialog; diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 4fad587bf0..d5ed89ae47 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -10,12 +10,14 @@ use std::sync::Arc; +use craft::behavior::NumberCodec; use craft::host::{PickRequest, Picked}; -use craft::ui::contract::Bind; +use craft::ui::contract::{Bind, Show as _}; use craft::ui::dialog::{DialogId, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult}; -use craft::ui::runtime::env::{Label, UnitKind}; +use craft::ui::runtime::env::{Env, Label, UnitKind}; use craft::ui::runtime::requests::PathKind; +use craft::ui::text::NumberField; use photocraft_doc::Document; use photocraft_engine::color_cmds::ColorSettings; use serde_json::{Map, Value, json}; @@ -26,6 +28,7 @@ mod rows; pub(crate) use rows::{REPLACE_COLOR, replace_color_sample}; const MATCH_COLOR: &str = "image.adjustments.matchColor"; +const SCALE_EFFECTS: &str = "layer.layerStyle.scaleEffects"; #[cfg(test)] pub(crate) const MATCH_COLOR_DESTINATION: &str = "__matchColorDestination"; @@ -302,6 +305,9 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< let kind = if command == "layer.layerStyle.globalLight" { ParamKind::angle_in(min, max, default, 0) } else { ParamKind::angle(default) }; p = Param::new(p.key, p.label, kind); } + if command == SCALE_EFFECTS && p.key == "scale" { + return scale_effects_row(p); + } if let ParamKind::Range { max, .. } = p.kind { if is_pixel_param_of(command, &p.key) { p = p.unit(UnitKind::Pixels); @@ -363,6 +369,30 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< list } +/// Scale Layer Effects' row, as in Photoshop (#14996): a whole-percent field whose arrow opens a linear slider over +/// the range, where the schema's range row would draw an always-shown logarithmic slider for 1..1000. +fn scale_effects_row(p: Param) -> Param { + let ParamKind::Range { min, max, default, .. } = p.kind else { return p }; + let label = p.label; + Param::custom("scale", label.clone(), move |ui, fields, _| { + let value = fields.number("scale").unwrap_or(default); + let codec = NumberCodec::new(Env::of(ui).units().reader(None), 0); + let shown = NumberField::new(label.clone(), Bind::given(Some(value))) + .codec(codec) + .range(min..=max) + .step(1.0) + .commit_decimals(0) + .unit("%") + .popup_slider(min..=max) + .show(ui); + if let Some(v) = shown.edit.value().copied().flatten() { + fields.set("scale", v.round()); + } + shown.edit.response + }) + .opens_with(default) +} + /// The values `command`'s dialog opens with before the remembered ones: the open document's, the /// session's and the captured editing target. Each is the dialog's own opening state, so the Alt /// reset restores them too (through [`reset_values`]). @@ -531,7 +561,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result let fields = fields(app, command, ¶ms); let captured = if command == MATCH_COLOR { json!(app.session.active().map(|st| (st.doc.id, st.active_layer))) } else { Value::Null }; let reset = reset_values(¶ms, &fields); - let build = builder(app, command, title_of(spec.label), params, reset); + // Photoshop titles the Scale Effects… dialog with the longer name (#14996). + let title = if command == SCALE_EFFECTS { Label::from(tl!("Scale Layer Effects")) } else { title_of(spec.label) }; + let build = builder(app, command, title, params, reset); let id = crate::dialogs::params::open_param(app, command, fields, captured, build); if command == MATCH_COLOR { reconcile_match_color(app); diff --git a/crates/ui-egui/src/dialogs/scale_effects_layout_tests.rs b/crates/ui-egui/src/dialogs/scale_effects_layout_tests.rs new file mode 100644 index 0000000000..a76502fad6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/scale_effects_layout_tests.rs @@ -0,0 +1,71 @@ +//! #14996: Scale Layer Effects is titled as in Photoshop and its one row is a whole-percent field whose arrow opens a +//! linear slider, instead of the schema dialog's always-shown logarithmic slider for 1..1000. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::{PhotocraftApp, Services}; + +const SCALE_EFFECTS: &str = "layer.layerStyle.scaleEffects"; + +/// The app with a document open and `command`'s dialog shown through `dialogs::run`. +fn dialog(command: &str) -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + super::filter_dialog::open(&mut app, command).unwrap(); + let mut h = Harness::builder() + .with_context(app.ctx().clone()) + .with_size(egui::vec2(900.0, 700.0)) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run(); + h +} + +fn sliders(h: &Harness<'_, Box>) -> usize { + h.query_all_by_role(Role::Slider).count() +} + +fn scale(h: &Harness<'_, Box>) -> f64 { + h.get_by_role_and_label(Role::SpinButton, "Scale").accesskit_node().numeric_value().expect("the Scale field has a number") +} + +#[test] +fn the_dialog_is_titled_scale_layer_effects() { + let h = dialog(SCALE_EFFECTS); + assert!(h.query_by_role_and_label(Role::Dialog, "Scale Layer Effects").is_some()); + assert!(h.query_by_role_and_label(Role::Dialog, "Scale Effects").is_none()); +} + +#[test] +fn the_scale_row_is_a_field_with_a_popup_slider_and_no_drawn_slider() { + let h = dialog(SCALE_EFFECTS); + assert_eq!(scale(&h), 100.0); + assert_eq!(sliders(&h), 0, "no slider is drawn under the field"); + assert!(h.query_by_role_and_label(Role::Button, "Slider").is_some(), "the field has the popup-slider arrow"); +} + +#[test] +fn the_popup_slider_runs_linearly_over_1_to_1000_and_sets_the_field() { + let mut h = dialog(SCALE_EFFECTS); + h.get_by_role_and_label(Role::Button, "Slider").click(); + h.run(); + let track = h.get_by_role(Role::Slider).rect(); + let middle = track.center(); + h.hover_at(middle); + h.drag_at(middle); + h.run(); + h.drop_at(middle); + h.run(); + let value = scale(&h); + assert!((450.0..=550.0).contains(&value), "the middle of a linear 1..1000 slider is about 500, got {value}"); + assert_eq!(value.fract(), 0.0, "whole percents"); +} + +#[test] +fn other_wide_range_rows_keep_their_drawn_slider() { + let h = dialog("filter.blur.gaussianBlur"); + assert_eq!(sliders(&h), 1, "Gaussian Blur's 0.1..1000 radius keeps today's slider"); +} From b1368133d11748af832419d6834216cad120a1c1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:05:19 +0100 Subject: [PATCH 296/385] Advance the surface generation once per serial write --- crates/raster/src/lib.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 8bb7d13a77..9ccf9e67e7 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -713,6 +713,11 @@ impl Surface { /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { self.note_mutation(); + self.tile_for_write(c) + } + + // Region writers already advanced the generation before entering their tile loop. + fn tile_for_write(&mut self, c: TileCoord) -> &mut Tile { let fmt = self.format; let dp = &self.default_pixel; let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); @@ -723,6 +728,10 @@ impl Surface { /// the surface, and a shared tile is copied only after its replacement has been allocated. pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { self.note_mutation(); + self.try_tile_for_write(c) + } + + fn try_tile_for_write(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { if let Some(tile) = self.tiles.get(&c) { drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?); } @@ -759,7 +768,7 @@ impl Surface { } for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let t = self.try_tile_mut(tc)?; + let t = self.try_tile_for_write(tc)?; let mut target = t.bytes_mut(); let span = tr.width() as usize * n; for y in tr.y0..tr.y1 { @@ -933,7 +942,6 @@ impl Surface { } pub fn write_pixel(&mut self, x: i32, y: i32, px: &[f32]) { - self.note_mutation(); let (c, base) = self.locate(x, y); let n = self.channels(); let sample = self.format.sample; @@ -1137,7 +1145,7 @@ impl Surface { assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); let sample = self.format.sample; for tc in r.tiles() { - write_tile(self.tile_mut(tc), tc, r, data, w, n, sample); + write_tile(self.tile_for_write(tc), tc, r, data, w, n, sample); } } @@ -1240,7 +1248,7 @@ impl Surface { self.tiles.insert(tc, t.clone()); continue; } - let mut t = self.tile_mut(tc).bytes_mut(); + let mut t = self.tile_for_write(tc).bytes_mut(); for y in tr.y0..tr.y1 { let ly = (y - tc.ty * TILE_SIZE) as usize; let lx0 = (tr.x0 - tc.tx * TILE_SIZE) as usize; @@ -1268,7 +1276,7 @@ impl Surface { assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch"); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let mut t = self.tile_mut(tc).bytes_mut(); + let mut t = self.tile_for_write(tc).bytes_mut(); let span = tr.width() as usize * bpp; for y in tr.y0..tr.y1 { let src = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp; From 19641af17110694e4280afcc8d97df35ff6e8db2 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:06:09 +0100 Subject: [PATCH 297/385] Cache legacy blend mode parsing --- crates/color/src/blend.rs | 36 +++++++++++++++++++ crates/engine/src/cmd.rs | 8 ++--- crates/engine/src/cmd/adjust_params.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_make.rs | 2 +- crates/engine/src/cmd/atn_cmds/tables.rs | 2 +- crates/engine/src/cmd/brush_cmds.rs | 2 +- crates/engine/src/cmd/channel_cmds/refs.rs | 2 +- crates/engine/src/cmd/edit_menu_cmds.rs | 2 +- crates/engine/src/cmd/edit_menu_cmds/fade.rs | 4 +-- crates/engine/src/cmd/extra_cmds.rs | 2 +- crates/engine/src/cmd/fill_cmds.rs | 4 +-- crates/engine/src/cmd/gradient_fill_cmds.rs | 4 +-- crates/engine/src/cmd/layer_menu_cmds.rs | 2 +- crates/engine/src/cmd/layer_params.rs | 8 +---- crates/engine/src/cmd/paint_cmds.rs | 6 ++-- crates/engine/src/cmd/retouch_cmds.rs | 2 +- crates/engine/src/cmd/retouch_cmds/clone.rs | 4 +-- crates/engine/src/cmd/retouch_cmds/dab.rs | 6 ++-- crates/engine/src/cmd/smart_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/filters.rs | 6 ++-- crates/engine/src/cmd/vector_cmds.rs | 2 +- crates/engine/src/cmd/vector_cmds/paths.rs | 4 +-- crates/engine/src/group_options.rs | 4 +-- crates/engine/src/layer_style.rs | 8 ++--- crates/engine/src/new_layer.rs | 2 +- crates/engine/src/presets/styles.rs | 2 +- crates/ui-egui/src/control/dialogs.rs | 8 ++--- crates/ui-egui/src/control/dispatch.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/blend_options.rs | 12 +++---- .../src/dialogs/fade_mode_list_tests.rs | 7 ++-- crates/ui-egui/src/dialogs/fade_modes.rs | 3 +- crates/ui-egui/src/dialogs/fill_ui.rs | 3 +- .../ui-egui/src/dialogs/new_group_ui/tests.rs | 2 +- crates/ui-egui/src/dialogs/new_layer_ui.rs | 5 ++- .../src/dialogs/smart_filter_dialog.rs | 5 ++- .../src/dialogs/smart_filter_dialog/tests.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 5 +-- crates/ui-egui/src/panels/blend_rows_tests.rs | 3 +- crates/ui-egui/src/panels/layer_filter_ui.rs | 4 +-- .../src/panels/layer_filter_ui/tests.rs | 4 +-- crates/ui-egui/src/panels/layers_tree.rs | 12 ++----- 42 files changed, 108 insertions(+), 99 deletions(-) diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 196a0dcafd..7b26f06a4f 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -46,6 +46,23 @@ pub enum BlendMode { PaintNetColorDodge, } +/// Parse legacy command names and labels, retaining their case and punctuation tolerance. +pub fn parse_blend(s: &str) -> Option { + fn normalize(value: &str) -> String { + value.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "") + } + static ALIASES: std::sync::OnceLock> = std::sync::OnceLock::new(); + let aliases = ALIASES.get_or_init(|| { + let mut aliases = std::collections::HashMap::new(); + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + aliases.entry(normalize(mode.label())).or_insert(mode); + aliases.entry(normalize(&format!("{mode:?}"))).or_insert(mode); + } + aliases + }); + aliases.get(&normalize(s)).copied() +} + impl BlendMode { /// Stable key used by the Layers panel. pub fn key(self) -> &'static str { @@ -674,6 +691,25 @@ mod tests; mod key_tests { use super::BlendMode; + #[test] + fn parser_preserves_legacy_names_and_normalization() { + let normalize = |s: &str| s.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + let legacy = |s: &str| { + let wanted = normalize(s); + std::iter::once(BlendMode::PassThrough) + .chain(BlendMode::layer_modes()) + .find(|mode| normalize(mode.label()) == wanted || normalize(&format!("{mode:?}")) == wanted) + }; + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + for name in [mode.label().to_owned(), format!("{mode:?}"), mode.label().to_ascii_uppercase().replace(' ', "_-")] { + assert_eq!(super::parse_blend(&name), legacy(&name), "{name}"); + } + } + for name in ["", "not a mode", "color.burn", "é"] { + assert_eq!(super::parse_blend(name), legacy(name), "{name}"); + } + } + #[test] fn canonical_keys_match_legacy_panel_names_and_round_trip() { for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c2d10acae7..809fd05d96 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,6 +1,6 @@ //! The command registry. Ids follow Photoshop's menu structure (see the parity checklist). -use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size}; use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::Surface; @@ -189,13 +189,13 @@ use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment}; pub use adjust_params::{adjustment_from_params, adjustment_kind}; pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_or_channel, has_selection}; -pub use layer_params::blend_from_str; pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; pub(crate) use layer_references::{recorded_drop, recorded_layer}; use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer, translate_layer_wrapped}; use params::{bad, set_clipped}; pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; +pub use photocraft_color::blend::parse_blend; pub fn command_specs() -> &'static [CommandSpec] { ®istry().specs @@ -726,7 +726,7 @@ fn build() -> Vec { // 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); + let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).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); @@ -745,7 +745,7 @@ fn build() -> Vec { 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}`")))?; + let b = parse_blend(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))); diff --git a/crates/engine/src/cmd/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs index 416016c8d3..fa078383e2 100644 --- a/crates/engine/src/cmd/adjust_params.rs +++ b/crates/engine/src/cmd/adjust_params.rs @@ -24,7 +24,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: & None | Some(Value::Null) => BlendMode::Normal, Some(v) => { let m = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name".into()))?; - crate::commands::blend_from_str(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))? + crate::commands::parse_blend(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))? } }; let clip = match p.get("clipToPrevious") { diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 0e16f09c8f..995a7120e5 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -892,7 +892,7 @@ fn adjustment_layer_to(id: &str, p: &Value) -> Option { None | Some(Value::Null) => None, Some(v) => { let label = v.as_str()?; - if crate::commands::blend_from_str(label)? == photocraft_doc::BlendMode::PassThrough { + if crate::commands::parse_blend(label)? == photocraft_doc::BlendMode::PassThrough { return None; } Some(blend_ps(label)?) diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs index 0a6a07abee..6751291997 100644 --- a/crates/engine/src/cmd/atn_cmds/tables.rs +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -56,7 +56,7 @@ pub(super) fn blend_label(ps: &str) -> Option<&'static str> { } pub(super) fn blend_ps(label: &str) -> Option<&'static str> { - crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) + crate::commands::parse_blend(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::parse_blend(v) == Some(m))).map(|(k, _)| *k) } /// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index f17b5b28b4..afd521e942 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -448,7 +448,7 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings { } else if p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("behind")) { b.mode = photocraft_color::BlendMode::Normal; b.behind = true; - } else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) { + } else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::parse_blend) { b.mode = m; b.behind = false; } diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index 39a56e1928..eace867c12 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -314,7 +314,7 @@ impl Blending { match name.to_ascii_lowercase().as_str() { "add" => Ok(Blending::Add { scale, offset }), "subtract" => Ok(Blending::Subtract { scale, offset }), - other => match crate::commands::blend_from_str(other) { + other => match crate::commands::parse_blend(other) { Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)), _ => Err(format!("unsupported blending `{other}`")), }, diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index fab273a9a6..a78e39e49b 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::channel_cmds::Target; -use crate::commands::{CommandSpec, blend_from_str, int, layer_param}; +use crate::commands::{CommandSpec, int, layer_param, parse_blend}; use crate::{EngineError, Result, Session}; // ------------------------------------------------------------------ state diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs index e8c797b212..59f15057e3 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/fade.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -1,5 +1,5 @@ use super::{ - BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, + BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, f32_or, from_rgba_into, json, parse_blend, str_or, surface_of, surface_of_mut, to_rgba, }; @@ -103,7 +103,7 @@ fn fade_job(s: &Session, p: &Value) -> Result { let cmd = "edit.fade"; let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; - let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; + let mode = parse_blend(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; let st = s.active().ok_or(EngineError::NoDocument)?; let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?; let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 505048f6ae..7e09659db9 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -147,7 +147,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result { let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]); let mode = match p.get("mode") { None | Some(Value::Null) => photocraft_color::BlendMode::Normal, - Some(Value::String(m)) => crate::commands::blend_from_str(m) + Some(Value::String(m)) => crate::commands::parse_blend(m) .filter(|m| *m != photocraft_color::BlendMode::PassThrough) .ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("unknown blend mode `{m}`") })?, Some(v) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("mode must be a blend mode name, not {v}") }), diff --git a/crates/engine/src/cmd/fill_cmds.rs b/crates/engine/src/cmd/fill_cmds.rs index 988a5b4aad..2d16adb077 100644 --- a/crates/engine/src/cmd/fill_cmds.rs +++ b/crates/engine/src/cmd/fill_cmds.rs @@ -11,7 +11,7 @@ use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; -use crate::commands::{blend_from_str, color_param, layer_param}; +use crate::commands::{color_param, layer_param, parse_blend}; use crate::{EngineError, Result, Session}; const CMD: &str = "edit.fill"; @@ -66,7 +66,7 @@ fn contents(p: &Value) -> Result<&str> { fn mode(p: &Value) -> Result { match p.get("mode") { None | Some(Value::Null) => Ok(BlendMode::Normal), - Some(Value::String(m)) => blend_from_str(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), + Some(Value::String(m)) => parse_blend(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), Some(v) => Err(bad(format!("`mode` must be a blend mode name, not {v}"))), } } diff --git a/crates/engine/src/cmd/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs index 39a61de8f4..7a4e036409 100644 --- a/crates/engine/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine/src/cmd/gradient_fill_cmds.rs @@ -17,7 +17,7 @@ use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId use photocraft_geom::Rect; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str, check_pixels_unlocked, layer_param}; +use crate::commands::{CommandSpec, check_pixels_unlocked, layer_param, parse_blend}; use crate::presets::gradients::{GradientPreset, transparency_param}; use crate::{EngineError, Result, Session}; @@ -300,7 +300,7 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result { let opacity = num(p, "opacity").unwrap_or(100.0).clamp(0.0, 100.0) / 100.0; let blend = match p.get("mode").and_then(Value::as_str) { None | Some("") => photocraft_color::BlendMode::Normal, - Some(m) => blend_from_str(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?, + Some(m) => parse_blend(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?, }; let canvas = doc.bounds(); if canvas.is_empty() { diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 944b6755c6..448b047067 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -525,7 +525,7 @@ fn blending_options(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.blendingOptions"; let id = layer_param(s, p)?; let blend = match p.get("blend").and_then(Value::as_str) { - Some(b) => Some(crate::commands::blend_from_str(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), + Some(b) => Some(crate::commands::parse_blend(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), None => None, }; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); diff --git a/crates/engine/src/cmd/layer_params.rs b/crates/engine/src/cmd/layer_params.rs index 82726f8369..1f15afea2e 100644 --- a/crates/engine/src/cmd/layer_params.rs +++ b/crates/engine/src/cmd/layer_params.rs @@ -1,5 +1,5 @@ use super::params::bad; -use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; +use super::{Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; /// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that /// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays @@ -72,12 +72,6 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { } } -pub fn blend_from_str(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); - let want = norm(s); - std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) -} - /// The active selection as the mask of a layer being created, or None without a selection. /// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on /// the selected area only (#1250). [`mask_new_layer`] then drops the selection (#8801). diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index e4e0c2265a..ffe6720b56 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -3,7 +3,7 @@ use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient}; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::presets::gradients; use crate::{EngineError, Result, Session}; @@ -47,7 +47,7 @@ fn fill_mode(p: &Value) -> Result { match p.get("mode") { None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)), Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear), - Some(Value::String(m)) => blend_from_str(m) + Some(Value::String(m)) => parse_blend(m) .filter(|m| *m != photocraft_color::BlendMode::PassThrough) .map(FillMode::Blend) .ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), @@ -186,7 +186,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result { }; let reverse = b(p, "reverse", false); let opacity = opacity(p, "paint.gradient")?; - let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal); + let blend = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(photocraft_color::BlendMode::Normal); let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) }; s.edit("Gradient", |doc, _| { diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 95cbe7ca99..868a5428ba 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -22,7 +22,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::{EngineError, Result, Session}; mod art_history; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index ada043ade4..59c39ab183 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -3,7 +3,7 @@ use super::heal::history_source; use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, - alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, + alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point, reject_huge_stroke, run_stroke, to_rgba, }; @@ -212,7 +212,7 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { match p.get("mode").and_then(Value::as_str) { None => Ok(BlendMode::Normal), - Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), + Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), } } diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 564df7512d..7c17ecf9e5 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -1,8 +1,8 @@ use super::sampling::{AllLayers, sample_all_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect, - Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, blend_from_str, damage_json, - dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, + Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, + from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba, }; // --------------------------------------------------------------------------------------------- @@ -206,7 +206,7 @@ pub(super) enum DabTool { fn smudge_mode(p: &Value, cmd: &str) -> Result { use BlendMode::{Color, Darken, Hue, Lighten, Luminosity, Normal, Saturation}; let Some(v) = p.get("mode") else { return Ok(Normal) }; - let named = v.as_str().and_then(blend_from_str).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity)); + let named = v.as_str().and_then(parse_blend).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity)); named.ok_or_else(|| { let given = v.as_str().map_or_else(|| v.to_string(), str::to_owned); bad(cmd, format!("unknown mode `{given}` (normal|darken|lighten|hue|saturation|color|luminosity)")) diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index ada909f54b..ffb172cf88 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -34,7 +34,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use stack_cache::{Stage, StageKey}; -use crate::commands::{CommandSpec, blend_from_str, layer_param}; +use crate::commands::{CommandSpec, layer_param, parse_blend}; use crate::jobs::JobCtx; use crate::{EngineError, Result, Session}; diff --git a/crates/engine/src/cmd/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs index c37c17a6f2..46a5ccba39 100644 --- a/crates/engine/src/cmd/smart_cmds/filters.rs +++ b/crates/engine/src/cmd/smart_cmds/filters.rs @@ -1,8 +1,8 @@ use super::rendering::{refresh_or_fail, refresh_or_fail_in}; use super::source::source_bytes; use super::{ - BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json, - layer_param, other, + BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, json, layer_param, other, + parse_blend, }; pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { @@ -241,7 +241,7 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result { pub(super) fn blending_options(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.smartFilter.blendingOptions"; let blend = match p.get("blend").and_then(Value::as_str) { - Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), + Some(b) => Some(parse_blend(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), None => None, }; let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32); diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 9c91142e26..aa9e9a33ce 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -26,7 +26,7 @@ use photocraft_geom::{Affine, Point, Rect}; use photocraft_vector as vector; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::{EngineError, Result, Session}; /// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized. diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index df8d922b45..5fdda419f9 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -2,7 +2,7 @@ use super::params::{color, f64p, layer_id, op_from, parse_path, path_json}; use super::shape::{map_path, map_shape, transform_shape, with_shape}; use super::{ Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad, - blend_from_str, json, sel, vector, + json, parse_blend, sel, vector, }; // --------------------------------------------------------------------------- @@ -444,7 +444,7 @@ pub(super) fn path_fill(s: &mut Session, p: &Value) -> Result { let rgb = c.to_rgb(); let src = [rgb[0], rgb[1], rgb[2], c.alpha]; let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32; - let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal); + let mode = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(BlendMode::Normal); let feather = f64p(p, "feather").unwrap_or(0.0) as f32; let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); let id = layer_id(s, p)?; diff --git a/crates/engine/src/group_options.rs b/crates/engine/src/group_options.rs index dd2ddee02f..a2a50f027b 100644 --- a/crates/engine/src/group_options.rs +++ b/crates/engine/src/group_options.rs @@ -37,9 +37,7 @@ impl GroupOptions { let blend = match get("mode") { None => None, Some(v) => Some( - v.as_str() - .and_then(crate::commands::blend_from_str) - .ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, + v.as_str().and_then(crate::commands::parse_blend).ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, ), }; let opacity = match get("opacity") { diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 9f7c2c7873..6a4e683fa7 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -9,7 +9,7 @@ use photocraft_doc::{ }; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::presets::{always, bad}; use crate::{EngineError, Result, Session}; @@ -714,7 +714,7 @@ fn overlay_common(c: &mut FxCommon, p: &Value) { if let Some(x) = b_of(p, "enabled") { c.enabled = x; } - if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(parse_blend) { c.blend = x; } if let Some(x) = f_of(p, "opacity") { @@ -883,10 +883,10 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) { } overlay_contour(p, "glossContour", &mut bv.gloss_contour); overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias); - if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(parse_blend) { bv.highlight.blend = blend; } - if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(parse_blend) { bv.shadow.blend = blend; } overlay_color(p, "highlightColor", &mut bv.highlight_color); diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs index b102907ccc..ed05e24c8e 100644 --- a/crates/engine/src/new_layer.rs +++ b/crates/engine/src/new_layer.rs @@ -74,7 +74,7 @@ pub(crate) fn parse(p: &Value) -> Result { None | Some(Value::Null) => BlendMode::Normal, Some(v) => { let name = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name"))?; - crate::commands::blend_from_str(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))? + crate::commands::parse_blend(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))? } }; let opacity = match p.get("opacity") { diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index cac8fb158a..241cea036f 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -280,7 +280,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { } } }, - blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::blend_from_str).or_else(|| with_blend.then_some(l.blend)), + blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::parse_blend).or_else(|| with_blend.then_some(l.blend)), fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)), opacity: p.get("opacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.opacity)), }; diff --git a/crates/ui-egui/src/control/dialogs.rs b/crates/ui-egui/src/control/dialogs.rs index 3e40a1788a..f7423d0441 100644 --- a/crates/ui-egui/src/control/dialogs.rs +++ b/crates/ui-egui/src/control/dialogs.rs @@ -199,14 +199,10 @@ fn dont_save_all(_: &Value, _: &Value) -> Vec<(String, Value)> { vec![pair("applyToAll", json!(true)), pair("choice", json!("dontSave"))] } -/// A blend label such as "Multiply" to the Blend row's id; a string `blend_from_str` refuses passes through so the +/// A blend label such as "Multiply" to the Blend row's id; a string `parse_blend` refuses passes through so the /// row refuses it. fn blend_id(value: &Value) -> Value { - value - .as_str() - .and_then(photocraft_engine::commands::blend_from_str) - .map(|mode| json!(crate::panels::layers_tree::blend_key(mode).to_string())) - .unwrap_or_else(|| value.clone()) + value.as_str().and_then(photocraft_engine::commands::parse_blend).map(|mode| json!(mode.key().to_string())).unwrap_or_else(|| value.clone()) } // PLAN: the framework field ids `mode` (Fill, Stroke) and `blend` (Smart Filter) are assumed (dialogs-w22 by request). diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index ea4a202f17..52f5bb000c 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -615,7 +615,7 @@ fn marquee_params(app: &PhotocraftApp, p: &Value) -> std::result::Result<(Option fn gradient_blend_param(p: &Value) -> std::result::Result, String> { let Some(value) = p.get("gradientBlendMode") else { return Ok(None) }; let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) }; - photocraft_engine::commands::blend_from_str(name) + photocraft_engine::commands::parse_blend(name) .filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) .map(Some) .ok_or_else(|| format!("unknown gradient blend mode `{name}`")) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4b7963e120..30b71c92b4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -660,7 +660,7 @@ fn convert_blend_mode(key: &str, value: &mut Value) { } let Some(mode) = value.get_mut("mode") else { return }; if let Some(blend) = mode.as_str().and_then(crate::panels::layers_tree::blend_of) { - *mode = Value::String(crate::panels::layers_tree::blend_key(blend)); + *mode = Value::String(blend.key().to_string()); } } diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index c0a99dce95..6d48c6ec82 100644 --- a/crates/ui-egui/src/dialogs/blend_options.rs +++ b/crates/ui-egui/src/dialogs/blend_options.rs @@ -6,18 +6,18 @@ use craft::ui::runtime::env::Label; use photocraft_color::BlendMode; use serde_json::{Map, Value, json}; -use crate::panels::layers_tree::blend_key; - /// A blend-mode row `key` over the Layers panel's mode list (`group` adds Pass Through), opening on `current`. pub(crate) fn blend_param(key: &str, label: impl Into