From af15d2769973a1200f851df7405c323589f2ff31 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 16:14:38 +0100 Subject: [PATCH 1/6] 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 00000000000..a7cf9a7f966 --- /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 9c1d0ea6b84..510c5262376 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 e5ce74d868644dd175eb6934ff3c43b13f5554b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 17:42:42 +0100 Subject: [PATCH 2/6] 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 5fe3b4fd191..d2c098cd2e9 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 00000000000..6888bb7a70a --- /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 9c1d0ea6b84..23de66e2a95 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 4aeb7e7c8da3141c67a8f13a40f7a4aaeeb033ad Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 00:14:05 +0100 Subject: [PATCH 3/6] 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 4/6] 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 472b385157e..0128245ffd3 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 5/6] 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 0128245ffd3..77163189e0d 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 5ed4a3769c6bf6b7a7b3426d0f336dbf0458cb19 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Fri, 20 Nov 2026 01:06:03 +0800 Subject: [PATCH 6/6] Use shared PSD channel restriction helpers (#15779) --- crates/io/src/blocks.rs | 8 ++--- crates/io/src/psd_export.rs | 2 +- crates/io/src/psd_import.rs | 2 +- crates/io/tests/it/roundtrip.rs | 52 +++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 24cfba224a8..5fa2056888e 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -9,14 +9,10 @@ use photocraft_geom::Affine; /// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of /// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored). -pub fn parse_brst(data: &[u8]) -> u32 { - data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i) -} +pub use craft_psd::tagged::channel_restrictions as parse_brst; /// Inverse of [`parse_brst`]; `None` when every channel blends (no block). -pub fn brst_data(mask: u32) -> Option> { - (mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect()) -} +pub use craft_psd::tagged::channel_restrictions_data as brst_data; /// The Advanced Blending blocks, as (key, value for `a`, Photoshop's default value): `knko` /// (0 none, 1 shallow, 2 deep), `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`. Each is stored as one diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 6ab2dc4134e..7b0fd16d0a9 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -609,7 +609,7 @@ impl Ex<'_> { None => raw.retain(|(k, _)| k != b"fxrp"), } // Advanced Blending channel restrictions: written from the field (in place). - match crate::blocks::brst_data(l.excluded_channels) { + match craft_psd::tagged::channel_restrictions_data(l.excluded_channels) { Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") { Some(e) => e.1 = data, None => raw.push((*b"brst", data)), diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 706802ee26f..e5c3e593301 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -479,7 +479,7 @@ impl Ctx<'_> { // Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out); // also kept in `psd_blocks`, where export rewrites it from the field. if let Some(b) = rec.block(b"brst") { - l.excluded_channels = crate::blocks::parse_brst(&b.data); + l.excluded_channels = craft_psd::tagged::channel_restrictions(&b.data); } // Advanced Blending (`knko`, `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`); the blocks stay in // `psd_blocks`, where export rewrites them from the field in place. diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index af72cd1e1c9..076fbc75536 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -474,6 +474,58 @@ fn channel_restrictions_round_trip_as_brst() { assert!(f.layers().iter().find(|r| r.name() == "a").unwrap().block(b"brst").is_none()); } +fn channel_restrictions_psd(payload: Vec) -> Vec { + use craft_psd::{LayerSpec, PixelData, PsdBuilder, TaggedBlock}; + let mut layer = LayerSpec::new("restricted", 0, 0, 1, 1, PixelData::Rgba8(vec![80, 120, 160, 255])); + layer.extra_blocks = vec![TaggedBlock::new(*b"zBef", vec![1, 2, 3, 4]), TaggedBlock::new(*b"brst", payload), TaggedBlock::new(*b"zAft", vec![5, 6, 7, 8])]; + let mut builder = PsdBuilder::new(1, 1); + builder.push_layer(layer); + builder.composite(PixelData::Rgba8(vec![80, 120, 160, 255])); + builder.to_bytes().unwrap() +} + +#[test] +fn channel_restrictions_partial_records_preserve_valid_indices_and_neighboring_blocks() { + for trailing in [vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc]] { + // The complete indices are 31, 32, 0, 31: 32 is ignored and 31 is a duplicate. + let mut payload = vec![0, 0, 0, 31, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 31]; + payload.extend(trailing); + let bytes = channel_restrictions_psd(payload.clone()); + let document = import("restrictions.psd", &bytes).unwrap().document; + let layer = document.layers.iter().find(|layer| layer.name == "restricted").unwrap(); + assert_eq!(layer.excluded_channels, 0x8000_0001); + assert!(layer.psd_blocks.iter().any(|(key, data)| key == b"brst" && data.as_slice() == payload)); + + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + let preserved: Vec<_> = record.blocks.iter().filter(|block| [*b"zBef", *b"brst", *b"zAft"].contains(&block.key)).collect(); + assert_eq!(preserved.iter().map(|block| block.key).collect::>(), vec![*b"zBef", *b"brst", *b"zAft"]); + assert_eq!(preserved[0].data, vec![1, 2, 3, 4]); + assert_eq!(preserved[1].data, vec![0, 0, 0, 0, 0, 0, 0, 31]); + assert_eq!(preserved[2].data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0x8000_0001); + } +} + +#[test] +fn channel_restrictions_without_valid_records_are_omitted() { + for payload in [vec![], vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc], vec![0, 0, 0, 32, 255, 255, 255, 255]] { + let bytes = channel_restrictions_psd(payload); + let document = import("restrictions.psd", &bytes).unwrap().document; + assert_eq!(document.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes; + let file = PsdFile::from_bytes(&saved).unwrap(); + let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap(); + assert!(record.block(b"brst").is_none()); + assert_eq!(record.block(b"zBef").unwrap().data, vec![1, 2, 3, 4]); + assert_eq!(record.block(b"zAft").unwrap().data, vec![5, 6, 7, 8]); + let reopened = import("restrictions.psd", &saved).unwrap().document; + assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0); + } +} + /// Advanced Blending maps to `knko` / `infx` / `clbl` / `tsly` / `lmgm` / `vmgm` (one byte + /// three of padding), at every depth: non-default values are written, default layers gain no /// blocks, and imported blocks are rewritten in place.