From 2b5f0f598489bbabdcf198ef9d9b2d56f919902b Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:20:04 +0400 Subject: [PATCH 01/43] Levels: Alt turns Cancel into Reset (#3328) Holding Alt in the Image > Adjustments > Levels dialog turns Cancel into Reset, as in Color Balance: every channel's input, gamma and output levels go back to the values the dialog opened with (RGB, Gray, CMYK inks or Lab), the Channel popup returns to the composite, and the dialog stays open. Other kinds keep Cancel under Alt. --- crates/ui-egui/src/adjust_dialog.rs | 86 +++++++++++++++++++++++++--- crates/ui-egui/src/adjust_editors.rs | 16 +++++- 2 files changed, 93 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index a4b831ed2f..2c2175154d 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -131,20 +131,23 @@ fn dialog_mem(kind: &str) -> egui::Id { egui::Id::new(("adjust-dialog", kind)) } -/// Whether holding Alt turns the dialog's Cancel into Reset. Measured in Photoshop 25.4 for Color -/// Balance; other kinds keep Cancel until checked against Photoshop. +/// Whether holding Alt turns the dialog's Cancel into Reset, as in Photoshop's Color Balance +/// (measured in 25.4) and Levels dialogs; other kinds keep Cancel until checked against Photoshop. pub fn resets(fields: &Map) -> bool { - fields.get("__adjust").and_then(Value::as_str) == Some("colorBalance") + matches!(fields.get("__adjust").and_then(Value::as_str), Some("colorBalance" | "levels")) } /// Alt+Cancel (Reset): back to the defaults Photoshop's Reset restores, dialog stays open. pub fn reset(ctx: &egui::Context, fields: &mut Map) { - if !resets(fields) { - return; - } let mut values = crate::filter_dialog::params_of(fields); - adjust_editors::reset_color_balance(ctx, dialog_mem("colorBalance"), &mut values); + match fields.get("__adjust").and_then(Value::as_str) { + Some("colorBalance") => adjust_editors::reset_color_balance(ctx, dialog_mem("colorBalance"), &mut values), + Some("levels") => adjust_editors::reset_levels(ctx, dialog_mem("levels"), &mut values), + _ => return, + } if let Value::Object(v) = values { + // Replace the parameter keys, keep the private ones (as `body` does). + fields.retain(|k, _| k.starts_with("__")); fields.extend(v); } } @@ -393,12 +396,79 @@ mod tests { use egui_kittest::kittest::Queryable; let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "image.adjustments.levels").unwrap(); + open(h.state_mut(), "image.adjustments.curves").unwrap(); h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); h.run_steps(3); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); } + /// #3328: holding Alt turns the Levels dialog's Cancel into Reset, as in Photoshop: every + /// channel's levels back to neutral and the Channel choice back to the composite, with the + /// dialog still open and the document untouched. + #[test] + fn levels_dialog_alt_cancel_resets_every_channel() { + use egui_kittest::kittest::Queryable; + let mut h = Harness::builder() + .with_size(egui::vec2(1200.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let original = h.state().session.active().unwrap().doc.clone(); + let id = open(h.state_mut(), "image.adjustments.levels").unwrap(); + let defaults = crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(id).unwrap().fields); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("inBlack".into(), json!(30)); + d.fields.insert("red".into(), json!({"inBlack": 0, "gamma": 1.0, "inWhite": 200, "outBlack": 0, "outWhite": 255})); + d.fields.insert("green".into(), json!({"inBlack": 0, "gamma": 1.4, "inWhite": 255, "outBlack": 0, "outWhite": 255})); + d.fields.insert("blue".into(), json!({"inBlack": 0, "gamma": 1.0, "inWhite": 255, "outBlack": 20, "outWhite": 255})); + let channel = egui::Id::new(("adjust-dialog", "levels")).with("levels-ch"); + h.ctx.data_mut(|d| d.insert_temp(channel, 2usize)); + h.run_steps(3); + assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(2); + let reset = h.get_by_label("Reset").rect(); + assert!(h.query_by_label("Cancel").is_none()); + let click = + |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); + let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.clone()).expect("Reset keeps the dialog open"); + assert_eq!(crate::filter_dialog::params_of(&fields), defaults, "every channel back to neutral"); + assert_eq!(fields.get("__preview"), Some(&json!(true)), "Reset keeps Preview"); + assert_eq!(h.ctx.data(|d| d.get_temp::(channel)), Some(0), "Reset shows the composite channel"); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original), "Reset leaves the document alone"); + // Without Alt it is Cancel again, and it closes. + let cancel = h.get_by_label("Cancel").rect(); + let click = + |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); + } + + /// Levels' Reset writes the parameter set the dialog opened with in every colour mode (RGB + /// channels, Gray's composite, CMYK's inks, Lab's lightness/a/b), dropping stray keys. + #[test] + fn levels_reset_restores_the_opening_parameters_in_every_mode() { + let ctx = egui::Context::default(); + for mode in ["rgb", "gray", "cmyk", "lab"] { + let mut app = app_in_mode(mode); + let id = open(&mut app, "image.adjustments.levels").unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + let defaults = crate::filter_dialog::params_of(fields); + fields.insert("inBlack".into(), json!(40)); + fields.insert("gray".into(), json!({"inWhite": 100})); + for key in ["red", "cyan", "a"] { + if fields.contains_key(key) { + fields.insert(key.into(), json!({"inBlack": 10, "gamma": 2.0, "inWhite": 180, "outBlack": 5, "outWhite": 250})); + } + } + reset(&ctx, fields); + assert_eq!(crate::filter_dialog::params_of(fields), defaults, "{mode}"); + assert_eq!(fields.get("__adjust"), Some(&json!("levels")), "{mode}: private keys kept"); + } + } + fn sample_params(kind: &str) -> Value { match kind { "brightnessContrast" => json!({"brightness": 40}), diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 53964d8939..d72fb90f06 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -526,13 +526,27 @@ fn nearest(xs: &[f32], x: f32) -> Option { xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8) } +fn levels_channel_id(mem: egui::Id) -> egui::Id { + mem.with("levels-ch") +} + +/// Levels reset to defaults (Alt+Cancel in the dialog): every channel's input, gamma and output +/// levels back to neutral in the values' channel space, and the Channel choice back to the +/// composite, as the dialog opens. +pub fn reset_levels(ctx: &egui::Context, mem: egui::Id, v: &mut Value) { + let neutral = photocraft_doc::adjust::LevelsChannel::default(); + let space = space_of(v); + *v = adjust_params::to_params(&Adjustment::Levels { master: neutral.clone(), per_channel: Default::default(), space, black: neutral }); + ctx.data_mut(|d| d.insert_temp(levels_channel_id(mem), 0usize)); +} + fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let t = Tokens::get(ui.ctx()); let chans = tone_channels(space_of(v), cx.gray); let mut ch = 0; let mut auto = false; ui.horizontal(|ui| { - ch = channel_picker(ui, cx.mem.with("levels-ch"), chans, tl!("Channel:")); + ch = channel_picker(ui, levels_channel_id(cx.mem), chans, tl!("Channel:")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { auto = widgets::secondary_button(ui, tl!("Auto"), 0.0).clicked(); }); From 69147701adb485e0aa3654fa7dc56e38421aa13d Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Sun, 11 Oct 2026 21:50:14 +0400 Subject: [PATCH 02/43] Levels: Alt-drag clipping display on the Input sliders (#3328) Alt-dragging the Levels dialog's black or white Input slider shows Photoshop's threshold display on the canvas: white with the channels the input levels clip to black at 0, or black with those clipped to white at 255. Clipping is tested at the input-range clamp, so gamma and Output Levels can't hide it; agents set the __clipping field. --- crates/ui-egui/src/adjust_dialog.rs | 1 + crates/ui-egui/src/adjust_editors.rs | 14 +- crates/ui-egui/src/adjust_preview.rs | 13 +- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/levels_clipping.rs | 378 +++++++++++++++++ crates/ui-egui/src/levels_clipping_tests.rs | 448 ++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 + docs/control-protocol.md | 1 + 8 files changed, 858 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/levels_clipping.rs create mode 100644 crates/ui-egui/src/levels_clipping_tests.rs diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index 2c2175154d..d235afa357 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -206,6 +206,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map egui::Id { mem.with("levels-ch") } +fn levels_drag_id(mem: egui::Id) -> egui::Id { + mem.with("levels-drag") +} + +/// The Levels Input slider handle being dragged in the editor rooted at `mem` (0 black, 1 gamma, +/// 2 white), as of its last frame. +pub(crate) fn levels_drag(ctx: &egui::Context, mem: egui::Id) -> Option { + ctx.data(|d| d.get_temp::>(levels_drag_id(mem))).flatten() +} + /// Levels reset to defaults (Alt+Cancel in the dialog): every channel's input, gamma and output /// levels back to neutral in the values' channel space, and the Channel choice back to the /// composite, as the dialog opens. @@ -578,7 +588,9 @@ fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let track = sr.shrink2(vec2(6.0, 0.0)); let xpos = |val: f32| track.left() + val / 255.0 * track.width(); let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0); - let drag_id = cx.mem.with("levels-drag"); + // Where 0 and 255 sit (tests press the handles there). + ui.data_mut(|d| d.insert_temp(cx.mem.with("levels-slider"), track)); + let drag_id = levels_drag_id(cx.mem); let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); let ctx = ui.ctx().clone(); let pressed = |r: &egui::Response| r.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()); diff --git a/crates/ui-egui/src/adjust_preview.rs b/crates/ui-egui/src/adjust_preview.rs index d94d58bff6..cb0ca04510 100644 --- a/crates/ui-egui/src/adjust_preview.rs +++ b/crates/ui-egui/src/adjust_preview.rs @@ -191,6 +191,15 @@ fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> { Some((kind, crate::filter_dialog::params_of(&d.fields), preview)) } +/// Whether Image › Adjustments `kind` on document `idx` would edit a channel (the Channels panel's +/// target or the Quick Mask) or the active layer's mask instead of the layer's pixels. +pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str) -> bool { + let Some(st) = app.session.documents().get(idx) else { return false }; + st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite + || st.doc.quick_mask.is_some() + || !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null() +} + /// FNV-1a over `parts`, never 0. fn hash(parts: &[&[u8]]) -> u64 { parts.iter().flat_map(|p| p.iter()).fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) | 1 @@ -221,9 +230,7 @@ fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> { let (doc_id, revision, target) = (st.doc.id, st.revision, st.active_layer?); // Commands that target a channel (Channels panel / Quick Mask) or a layer mask keep the proxy // preview. - let channel_target = st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite - || st.doc.quick_mask.is_some() - || !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null(); + let channel_target = targets_channel(app, idx, &kind); let session = hash(&[&doc_id.0.to_le_bytes(), &revision.to_le_bytes(), &target.0.to_le_bytes(), &[u8::from(channel_target)]]); let h = hash(&[kind.as_bytes(), params.to_string().as_bytes(), &[u8::from(preview)]]); if let Some(p) = &app.adjust_preview diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ac5eacbe6a..ee0eb2d83a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1537,7 +1537,7 @@ pub(crate) fn committed_filter_preview(app: &mut PhotocraftApp, idx: usize) -> O /// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners /// so a rotated camera still covers the visible tiles. -fn visible_doc_rect(xf: &ViewXform) -> DRect { +pub(crate) fn visible_doc_rect(xf: &ViewXform) -> DRect { let r = xf.rect; let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; let mut x0 = docs[0][0]; @@ -2605,6 +2605,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: painter.image(tex, img_rect, uv, Color32::WHITE); } } + // Image › Adjustments › Levels: Alt-drag on the black / white Input slider (levels_clipping.rs). + crate::levels_clipping::paint(app, &ctx, &painter, &xf, idx); crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). if doc.has_artboards() { diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs new file mode 100644 index 0000000000..5c3ceaefd0 --- /dev/null +++ b/crates/ui-egui/src/levels_clipping.rs @@ -0,0 +1,378 @@ +//! Photoshop's Levels clipping display (#3328). While Alt is held and the black or white Input +//! slider of the Image › Adjustments › Levels dialog is dragged, the canvas shows what the input +//! levels clip instead of the preview: +//! - black slider: the image turns white; a channel the input levels clip to black drops to 0, so +//! pixels clipped in every channel are black and pixels clipped in red alone are cyan; +//! - white slider: the image turns black; a channel clipped to white rises to 255, so red alone is +//! red and all three are white. +//! +//! Releasing Alt or the mouse shows the preview again; the document is never touched. Grayscale +//! documents show black and white only. CMYK and Lab documents, and commands that edit a channel, +//! a layer mask or a non-pixel layer, keep the normal preview. +//! +//! The display is an opaque texture over the visible part of the image, at about the screen's +//! resolution: one texel per block of `factor`×`factor` document pixels. A block shows a channel +//! clipped when any pixel in it is, so a lone clipped highlight stays visible zoomed out. Clipping +//! is a threshold on each channel's sample (the input stretch is monotone), so the target's +//! per-block minimum and maximum are scanned once per view and a slider move only compares them +//! with the new thresholds. +//! +//! State is the dialog field `__clipping` (`"shadows"` / `"highlights"`): [`sync`] sets it when an +//! Alt-drag starts and clears it when the drag ends, and automation can set it with +//! `ui.dialog.set`. OK never sees it (`filter_dialog::params_of` drops `__` keys). + +use egui::{Color32, Mesh, TextureOptions, pos2}; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_compose::adjust::{levels_float, levels_q}; +use photocraft_doc::adjust::{LevelsChannel, ToneSpace}; +use photocraft_doc::{Adjustment, DocId, LayerContent, LayerId}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; + +/// The dialog field that turns the display on. +pub const FIELD: &str = "__clipping"; + +/// A pixel counts where the selection covers at least this much (the command blends the rest). +const SELECTED: f32 = 0.5; + +/// Which input slider's clipping is shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ClipEnd { + /// The black slider: what the input levels clip to black. + Shadows, + /// The white slider: what they clip to white. + Highlights, +} + +impl ClipEnd { + fn name(self) -> &'static str { + match self { + ClipEnd::Shadows => "shadows", + ClipEnd::Highlights => "highlights", + } + } + + /// The display a `__clipping` field value asks for (anything else: off). + pub fn parse(v: Option<&Value>) -> Option { + match v.and_then(Value::as_str) { + Some("shadows") => Some(ClipEnd::Shadows), + Some("highlights") => Some(ClipEnd::Highlights), + _ => None, + } + } +} + +/// Mirror an Alt-drag on the Levels dialog's black or white Input slider (editor state under +/// `mem`) into the dialog's [`FIELD`]. Only changes are written, so a display turned on through +/// automation stays until it is cleared or a drag ends. +pub fn sync(ctx: &egui::Context, mem: egui::Id, fields: &mut Map) { + if fields.get("__adjust").and_then(Value::as_str) != Some("levels") { + return; + } + let held = ctx.input(|i| i.modifiers.alt && i.pointer.primary_down()); + let live = match crate::adjust_editors::levels_drag(ctx, mem) { + Some(0) if held => Some(ClipEnd::Shadows), + Some(2) if held => Some(ClipEnd::Highlights), + _ => None, + }; + let last_id = mem.with("levels-clipping"); + let last: Option = ctx.data(|d| d.get_temp(last_id)).flatten(); + if live == last { + return; + } + ctx.data_mut(|d| d.insert_temp(last_id, live)); + match live { + Some(end) => { + fields.insert(FIELD.into(), json!(end.name())); + } + None => { + fields.remove(FIELD); + } + } + // The canvas paints before the dialogs: show the change on the next frame. + ctx.request_repaint(); +} + +/// Which ends the Levels input levels clip a sample `v` (0..1) of one channel to, as +/// (black, white): the channel's own input range or, after it, the composite's. `quantum` is the +/// document's (whole levels, as the compositor rounds them; None: 32-bit float, unclamped). Gamma +/// and the output levels don't matter: what reaches an end of an input range is flattened there, +/// wherever the output levels then put it. +pub fn classify(master: &LevelsChannel, channel: &LevelsChannel, v: f32, quantum: Option) -> (bool, bool) { + let eval = |ch: &LevelsChannel, v: f32| if quantum.is_some() { levels_q(ch, v, quantum) } else { levels_float(ch, v) }; + let full = |ch: &LevelsChannel| LevelsChannel { out_black: 0.0, out_white: 1.0, ..ch.clone() }; + let stretch = |ch: &LevelsChannel| LevelsChannel { gamma: 1.0, ..full(ch) }; + let own = eval(&stretch(channel), v); + let composite = eval(&stretch(master), eval(&full(channel), v)); + (own <= 0.0 || composite <= 0.0, own >= 1.0 || composite >= 1.0) +} + +/// A sample as a 16-bit key: exact for 8- and 16-bit documents (their samples are on this grid), +/// 32-bit samples clamped to 0..1 (beyond is clipped either way). Non-finite: None. +fn key(v: f32) -> Option { + v.is_finite().then(|| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16) +} + +/// Per channel (R, G, B): the highest key clipped to black and the lowest clipped to white (None: +/// no key clips that way). +pub type Thresholds = [(Option, Option); 3]; + +/// The [`Thresholds`] of the Levels `adj` in a document of `depth`. None for anything but Levels +/// in the RGB channel space (which Grayscale documents use too). +pub fn thresholds(adj: &Adjustment, depth: SampleType) -> Option { + let Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } = adj else { return None }; + let quantum = photocraft_compose::adjustment_quantum(depth); + let at = |ch: &LevelsChannel, k: u16| classify(master, ch, f32::from(k) / 65535.0, quantum); + Some(std::array::from_fn(|c| { + let ch = &per_channel[c]; + // Black clipping holds below a key and white clipping above one (the stretch is monotone). + let black = (at(ch, 0).0).then(|| last_true(|k| at(ch, k).0)); + let white = (at(ch, u16::MAX).1).then(|| first_true(|k| at(ch, k).1)); + (black, white) + })) +} + +/// The largest key where `f` holds, given it holds at 0 and stops holding at most once. +fn last_true(f: impl Fn(u16) -> bool) -> u16 { + let (mut lo, mut hi) = (0u32, u32::from(u16::MAX) + 1); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if f(mid as u16) { + lo = mid; + } else { + hi = mid; + } + } + lo as u16 +} + +/// The smallest key where `f` holds, given it holds at `u16::MAX` and starts holding at most once. +fn first_true(f: impl Fn(u16) -> bool) -> u16 { + let (mut lo, mut hi) = (-1i32, i32::from(u16::MAX)); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if f(mid as u16) { + hi = mid; + } else { + lo = mid; + } + } + hi as u16 +} + +/// Per block of the scanned area: each channel's minimum (0..3) and maximum (3..6) key over the +/// pixels that count. A block with none has min > max. +type Extremes = [u16; 6]; +const NONE: Extremes = [u16::MAX, u16::MAX, u16::MAX, 0, 0, 0]; + +/// The target's per-block extremes over `rect` (document pixels, `factor`×`factor` blocks). +pub struct Stats { + rect: Rect, + factor: u32, + size: [usize; 2], + blocks: Vec, +} + +/// Scan `surface` (a layer's pixels) over `rect` in `factor`×`factor` blocks. Pixels count when +/// visible (alpha > 0, finite) and, with a `selection`, at least half selected. +pub fn scan(surface: &Surface, selection: Option<&Surface>, rect: Rect, factor: u32) -> Stats { + let factor = factor.max(1); + let f = factor as usize; + let size = [rect.width().div_ceil(factor) as usize, rect.height().div_ceil(factor) as usize]; + let mut blocks = vec![NONE; size[0] * size[1]]; + let row = |by: usize, out: &mut [Extremes]| { + let y0 = rect.y0.saturating_add((by * f) as i32); + let band = Rect::new(rect.x0, y0, rect.x1, y0.saturating_add(factor as i32).min(rect.y1)); + let width = band.width() as usize; + let mut px = vec![[0.0f32; 4]; width * band.height() as usize]; + surface.read_rgba_into(band, &mut px); + let mut coverage = Vec::new(); + let stride = selection.map_or(1, |s| s.channels().max(1)); + if let Some(s) = selection { + s.read_region_into(band, &mut coverage); + } + for (i, p) in px.iter().enumerate() { + let visible = p[3] > 0.0; + let selected = selection.is_none() || coverage.get(i * stride).is_some_and(|k| *k >= SELECTED); + if !visible || !selected { + continue; + } + let (Some(r), Some(g), Some(b)) = (key(p[0]), key(p[1]), key(p[2])) else { continue }; + let Some(e) = out.get_mut((i % width.max(1)) / f) else { continue }; + for (c, k) in [r, g, b].into_iter().enumerate() { + e[c] = e[c].min(k); + e[c + 3] = e[c + 3].max(k); + } + } + }; + if size[0] > 0 { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + blocks.par_chunks_mut(size[0]).enumerate().for_each(|(by, out)| row(by, out)); + } + #[cfg(target_arch = "wasm32")] + for (by, out) in blocks.chunks_mut(size[0]).enumerate() { + row(by, out); + } + } + Stats { rect, factor, size, blocks } +} + +/// The display colour of a pixel clipped to black in the channels of `black` and to white in +/// those of `white` (bit 0 red, 1 green, 2 blue). +pub fn colour(end: ClipEnd, black: u8, white: u8) -> Color32 { + let on = |mask: u8, c: u8| if mask & (1 << c) != 0 { 255 } else { 0 }; + match end { + ClipEnd::Shadows => { + let m = 7 ^ black; + Color32::from_rgb(on(m, 0), on(m, 1), on(m, 2)) + } + ClipEnd::Highlights => Color32::from_rgb(on(white, 0), on(white, 1), on(white, 2)), + } +} + +/// The display of `stats` for `end` under the per-channel `thresholds`, one colour per block (in +/// parallel off the web: this runs on every slider move). +pub fn image(stats: &Stats, thresholds: &Thresholds, end: ClipEnd) -> Vec { + // Integer bounds (none clipped: below every key / above every key) and the 8 possible colours. + let lo = thresholds.map(|(lo, _)| lo.map_or(-1, i32::from)); + let hi = thresholds.map(|(_, hi)| hi.map_or(i32::from(u16::MAX) + 1, i32::from)); + let palette: [Color32; 8] = std::array::from_fn(|m| match end { + ClipEnd::Shadows => colour(end, m as u8, 0), + ClipEnd::Highlights => colour(end, 0, m as u8), + }); + let block = |e: &Extremes| { + let mut mask = 0usize; + for c in 0..3 { + let (min, max) = (i32::from(e[c]), i32::from(e[c + 3])); + let clipped = match end { + ClipEnd::Shadows => min <= max && min <= lo[c], + ClipEnd::Highlights => min <= max && max >= hi[c], + }; + mask |= usize::from(clipped) << c; + } + palette[mask] + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + stats.blocks.par_iter().map(block).collect() + } + #[cfg(target_arch = "wasm32")] + { + stats.blocks.iter().map(block).collect() + } +} + +/// What the display needs from the app: the end shown and the Levels adjustment, for the active +/// document `idx`'s target. None when no Levels dialog shows clipping or the document can't. +struct Request { + end: ClipEnd, + adj: Adjustment, + doc: std::sync::Arc, + revision: u64, + target: LayerId, +} + +/// The open Levels dialog's fields, if any. +fn dialog(app: &PhotocraftApp) -> Option<&Map> { + app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels")) +} + +fn request(app: &PhotocraftApp, idx: usize) -> Option { + let fields = dialog(app)?; + let end = ClipEnd::parse(fields.get(FIELD))?; + if app.session.active_index() != Some(idx) || crate::adjust_preview::targets_channel(app, idx, "levels") { + return None; + } + let st = app.session.documents().get(idx)?; + if !matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { + return None; + } + let target = st.active_layer?; + if !matches!(st.doc.layer(target).map(|l| &l.content), Some(LayerContent::Raster(_))) { + return None; + } + let adj = photocraft_engine::adjust_params::from_params("levels", &crate::filter_dialog::params_of(fields), None, st.doc.mode).ok()?; + Some(Request { end, adj, doc: st.doc.clone(), revision: st.revision, target }) +} + +/// The display's per-view state on the app. +pub struct Cache { + /// What `stats` scanned: document, revision, target, area and block size. + key: (DocId, u64, LayerId, Rect, u32), + stats: Stats, + /// The end and thresholds the texture shows. + drawn: Option<(ClipEnd, Thresholds)>, + tex: Option, +} + +/// The visible part of the document in `xf` and the block size giving about one texel per screen +/// pixel (`ppp` physical pixels per point), within `max_side` texels a side. +fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(Rect, u32)> { + let device_zoom = xf.zoom * ppp; + if !(device_zoom.is_finite() && device_zoom > 0.0) { + return None; + } + let visible = crate::canvas::visible_doc_rect(xf).intersect(&bounds); + if visible.is_empty() { + return None; + } + let max_side = max_side.max(1); + let factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(visible.width().div_ceil(max_side)).max(visible.height().div_ceil(max_side)); + // Snap to the block grid so panning keeps the blocks where they were. + let f = factor as i32; + let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds); + Some((r, factor)) +} + +/// Draw the Levels clipping display over the image in canvas view `xf` of document `idx`, if one +/// is asked for. Drops the cache once no Levels dialog is open. +pub fn paint(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, idx: usize) { + if dialog(app).is_none() { + app.levels_clipping = None; + return; + } + let Some(req) = request(app, idx) else { return }; + let Some(thr) = thresholds(&req.adj, req.doc.pixel_format().sample) else { return }; + let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 8192); + let Some((rect, factor)) = view_area(xf, req.doc.bounds(), ctx.pixels_per_point(), max_side) else { return }; + let key = (req.doc.id, req.revision, req.target, rect, factor); + if app.levels_clipping.as_ref().is_none_or(|c| c.key != key) { + let Some(LayerContent::Raster(surface)) = req.doc.layer(req.target).map(|l| &l.content) else { return }; + let stats = scan(surface, req.doc.selection.as_ref(), rect, factor); + let tex = app.levels_clipping.take().and_then(|c| c.tex); + app.levels_clipping = Some(Cache { key, stats, drawn: None, tex }); + } + let Some(cache) = app.levels_clipping.as_mut() else { return }; + if cache.drawn != Some((req.end, thr)) || cache.tex.is_none() { + let img = egui::ColorImage::new(cache.stats.size, image(&cache.stats, &thr, req.end)); + match &mut cache.tex { + Some(t) => t.set(img, TextureOptions::NEAREST), + None => cache.tex = Some(ctx.load_texture("levels-clipping", img, TextureOptions::NEAREST)), + } + cache.drawn = Some((req.end, thr)); + } + let Some(tex) = cache.tex.as_ref().map(egui::TextureHandle::id) else { return }; + // The texture covers whole blocks; the last row and column may reach past the area. + let s = &cache.stats; + let f = s.factor as f32; + let uv = [s.rect.width() as f32 / (s.size[0] as f32 * f).max(1.0), s.rect.height() as f32 / (s.size[1] as f32 * f).max(1.0)]; + let (x0, y0, x1, y1) = (s.rect.x0 as f32, s.rect.y0 as f32, s.rect.x1 as f32, s.rect.y1 as f32); + let mut mesh = Mesh::with_texture(tex); + for (p, t) in [((x0, y0), (0.0, 0.0)), ((x1, y0), (uv[0], 0.0)), ((x1, y1), (uv[0], uv[1])), ((x0, y1), (0.0, uv[1]))] { + mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(p.0, p.1), uv: pos2(t.0, t.1), color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +#[cfg(test)] +#[path = "levels_clipping_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs new file mode 100644 index 0000000000..b0205c0667 --- /dev/null +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -0,0 +1,448 @@ +use super::*; +use egui_kittest::Harness; +use photocraft_color::{Color, PixelFormat}; +use photocraft_compose::Buffer; +use photocraft_compose::adjust::{Transfer, apply_depth}; +use photocraft_doc::{Document, Size}; + +const DEPTHS: [SampleType; 3] = [SampleType::U8, SampleType::U16, SampleType::F32]; + +fn lv(in_black: f32, gamma: f32, in_white: f32) -> LevelsChannel { + LevelsChannel { in_black: in_black / 255.0, gamma, in_white: in_white / 255.0, ..LevelsChannel::default() } +} + +fn levels(master: LevelsChannel, per_channel: [LevelsChannel; 3]) -> Adjustment { + Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, black: LevelsChannel::default() } +} + +/// Samples to try at `depth`: every 8-bit level, a 16-bit sweep, and float values past both ends. +fn samples(depth: SampleType) -> Vec { + match depth { + SampleType::U8 => (0..=255).map(|n| n as f32 / 255.0).collect(), + SampleType::U16 => (0..=65535).step_by(13).map(|n| n as f32 / 65535.0).collect(), + SampleType::F32 => (-40..=1100).map(|n| n as f32 / 1000.0).collect(), + } +} + +/// With gamma 1 and the output levels at their defaults, a channel is clipped exactly where the +/// compositor's Levels result sits at an end: 0 for black, 1 for white (the 8-bit LUT staircase +/// and the 32-bit formula; 16-bit against the whole-level chain the LUT samples). +#[test] +fn clipping_matches_the_levels_result() { + let master = lv(30.0, 1.0, 200.0); + let channels = [lv(10.0, 1.0, 240.0), LevelsChannel::default(), lv(60.0, 1.0, 120.0)]; + let adj = levels(master.clone(), channels.clone()); + for depth in DEPTHS { + let quantum = photocraft_compose::adjustment_quantum(depth); + for v in samples(depth) { + let result: [f32; 3] = if depth == SampleType::U16 { + std::array::from_fn(|c| levels_q(&master, levels_q(&channels[c], v, quantum), quantum)) + } else { + let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [v, v, v, 1.0]); + apply_depth(&adj, &mut b, Transfer::for_document(ColorMode::Rgb, depth), Some(depth)); + [b.px[0][0], b.px[0][1], b.px[0][2]] + }; + for (c, (ch, r)) in channels.iter().zip(result).enumerate() { + let (black, white) = classify(&master, ch, v, quantum); + assert_eq!(black, r <= 0.0, "{depth:?} v={v} channel {c}: {r}"); + assert_eq!(white, r >= 1.0, "{depth:?} v={v} channel {c}: {r}"); + } + } + } +} + +/// Gamma and the output levels don't change what the input levels clip. Gamma above 1 keeps the +/// result just under white at the top (Photoshop's soft toe), which an "is it 1" test would miss. +#[test] +fn gamma_and_output_levels_do_not_hide_clipping() { + let q = Some(255.0); + let master = LevelsChannel { gamma: 1.5, ..lv(20.0, 1.0, 200.0) }; + assert!(levels_q(&master, 210.0 / 255.0, q) < 1.0, "the soft toe stays under white"); + let plain = lv(20.0, 1.0, 200.0); + let outputs = LevelsChannel { out_black: 25.0 / 255.0, out_white: 230.0 / 255.0, gamma: 0.6, ..lv(20.0, 1.0, 200.0) }; + for n in 0..=255 { + let v = n as f32 / 255.0; + let id = LevelsChannel::default(); + let want = (n <= 20, n >= 200); + assert_eq!(classify(&master, &id, v, q), want, "gamma 1.5 composite, level {n}"); + assert_eq!(classify(&plain, &id, v, q), want, "level {n}"); + assert_eq!(classify(&outputs, &id, v, q), want, "outputs and gamma 0.6, level {n}"); + assert_eq!(classify(&id, &master, v, q), want, "gamma 1.5 channel, level {n}"); + } +} + +/// The per-channel thresholds give the same answer as [`classify`] for every key tried. +#[test] +fn thresholds_agree_with_classify() { + let cases = [ + levels(lv(30.0, 1.0, 200.0), Default::default()), + levels(LevelsChannel::default(), [lv(10.0, 0.4, 240.0), lv(0.0, 2.5, 90.0), lv(128.0, 1.0, 130.0)]), + levels(lv(5.0, 3.0, 250.0), [LevelsChannel { out_black: 0.2, out_white: 0.9, ..lv(40.0, 0.7, 220.0) }, lv(0.0, 1.0, 255.0), lv(200.0, 9.0, 255.0)]), + ]; + for adj in &cases { + let Adjustment::Levels { master, per_channel, .. } = adj else { panic!("Levels") }; + for depth in DEPTHS { + let quantum = photocraft_compose::adjustment_quantum(depth); + let thr = thresholds(adj, depth).unwrap(); + let keys: Vec = match depth { + SampleType::U8 => (0..=255u16).map(|n| n * 257).collect(), + _ => (0..=65535u16).step_by(7).chain([u16::MAX]).collect(), + }; + for k in keys { + for (c, (ch, (lo, hi))) in per_channel.iter().zip(thr).enumerate() { + let (black, white) = classify(master, ch, f32::from(k) / 65535.0, quantum); + assert_eq!(black, lo.is_some_and(|lo| k <= lo), "{depth:?} key {k} channel {c} black"); + assert_eq!(white, hi.is_some_and(|hi| k >= hi), "{depth:?} key {k} channel {c} white"); + } + } + } + } +} + +/// Photoshop's threshold display: black slider, a clipped channel drops to 0 on white; white +/// slider, a clipped channel rises to 255 on black. +#[test] +fn colours_follow_the_clipped_channels() { + let rgb = Color32::from_rgb; + assert_eq!(colour(ClipEnd::Shadows, 0, 7), Color32::WHITE); + assert_eq!(colour(ClipEnd::Shadows, 0b001, 0), rgb(0, 255, 255), "red alone: cyan"); + assert_eq!(colour(ClipEnd::Shadows, 0b110, 0), rgb(255, 0, 0), "green and blue: red"); + assert_eq!(colour(ClipEnd::Shadows, 7, 0), Color32::BLACK); + assert_eq!(colour(ClipEnd::Highlights, 7, 0), Color32::BLACK); + assert_eq!(colour(ClipEnd::Highlights, 0, 0b001), rgb(255, 0, 0), "red alone: red"); + assert_eq!(colour(ClipEnd::Highlights, 0, 0b011), rgb(255, 255, 0)); + assert_eq!(colour(ClipEnd::Highlights, 0, 7), Color32::WHITE); +} + +fn surface(fmt: PixelFormat, w: u32, h: u32, px: impl Fn(u32, u32) -> Vec) -> Surface { + let mut s = Surface::new(fmt); + let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| px(x, y)).collect(); + s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + s +} + +/// A block shows what any counted pixel in it clips; transparent, unselected (under half) and +/// non-finite pixels don't count. +#[test] +fn blocks_keep_lone_extremes_of_the_pixels_that_count() { + let s = surface(PixelFormat::RGBA32F, 8, 8, |x, y| match (x, y) { + (5, 5) => vec![0.0, 0.5, 0.5, 1.0], + (1, 1) => vec![1.0, 1.0, 1.0, 0.0], + (2, 2) => vec![f32::NAN, 1.0, 1.0, 1.0], + (7, 1) => vec![1.0, 1.0, 1.0, 1.0], + _ => vec![0.5, 0.5, 0.5, 1.0], + }); + let thr = [(key(0.1), key(0.9)); 3]; + let grey = surface(PixelFormat::GRAY8, 8, 8, |x, _| vec![if x < 6 { 1.0 } else { 0.4 }]); + for (selection, top_right) in [(None, Color32::WHITE), (Some(&grey), Color32::BLACK)] { + let stats = scan(&s, selection, Rect::new(0, 0, 8, 8), 4); + assert_eq!(stats.size, [2, 2]); + let black = image(&stats, &thr, ClipEnd::Shadows); + assert_eq!(black, vec![Color32::WHITE, Color32::WHITE, Color32::WHITE, Color32::from_rgb(0, 255, 255)], "{selection:?}"); + let white = image(&stats, &thr, ClipEnd::Highlights); + assert_eq!(white, vec![Color32::BLACK, top_right, Color32::BLACK, Color32::BLACK], "{selection:?}"); + } +} + +/// Gray documents' Levels act on one channel, so the display is black and white only. +#[test] +fn gray_layers_show_black_and_white_only() { + let s = surface(PixelFormat::GRAYA8, 16, 1, |x, _| vec![x as f32 / 15.0, 1.0]); + let adj = levels(lv(100.0, 1.0, 180.0), Default::default()); + let thr = thresholds(&adj, SampleType::U8).unwrap(); + let stats = scan(&s, None, Rect::new(0, 0, 16, 1), 1); + for end in [ClipEnd::Shadows, ClipEnd::Highlights] { + for (x, c) in image(&stats, &thr, end).into_iter().enumerate() { + let v = x as f32 / 15.0 * 255.0; + let clipped = if end == ClipEnd::Shadows { v <= 100.0 } else { v >= 180.0 }; + assert!(c == Color32::BLACK || c == Color32::WHITE, "x={x}: {c:?}"); + assert_eq!(c == colour(end, 7, 7), clipped, "{end:?} x={x}"); + } + } +} + +/// Out-of-range and non-finite settings never panic. +#[test] +fn hostile_settings_do_not_panic() { + let bad = LevelsChannel { in_black: f32::NAN, in_white: -3.0, gamma: 0.0, out_black: f32::INFINITY, out_white: f32::NEG_INFINITY }; + for adj in [levels(bad.clone(), [bad.clone(), LevelsChannel::default(), lv(255.0, 100.0, 0.0)]), levels(LevelsChannel::default(), Default::default())] { + for depth in DEPTHS { + let _ = thresholds(&adj, depth); + } + } + let cmyk = + Adjustment::Levels { master: LevelsChannel::default(), per_channel: Default::default(), space: ToneSpace::Cmyk, black: LevelsChannel::default() }; + assert!(thresholds(&cmyk, SampleType::U8).is_none()); + assert!(thresholds(&Adjustment::Invert, SampleType::U8).is_none()); + for params in [json!({"inBlack": 1e9, "inWhite": -5, "gamma": 0}), json!({"red": {"gamma": 100, "inWhite": 0}}), json!({"inBlack": "x"})] { + if let Ok(adj) = photocraft_engine::adjust_params::from_params("levels", ¶ms, None, ColorMode::Rgb) { + let _ = thresholds(&adj, SampleType::U16); + } + } +} + +/// A 16×8 document: the background's red channel ramps 0..1 left to right, green is 0.5, blue 1. +fn ramp_app(mode: ColorMode, depth: SampleType) -> PhotocraftApp { + let mut doc = Document::with_background("t", Size::new(16, 8), mode, depth, Color::rgba(1.0, 1.0, 1.0, 1.0)); + let gray = mode == ColorMode::Grayscale; + if let Some(s) = doc.layers[0].surface_mut() { + let data: Vec = + (0..8).flat_map(|_| 0..16).flat_map(|x| if gray { vec![x as f32 / 15.0, 1.0] } else { vec![x as f32 / 15.0, 0.5, 1.0, 1.0] }).collect(); + s.write_region(Rect::new(0, 0, 16, 8), &data); + } + let target = doc.layers[0].id; + let mut session = photocraft_engine::Session::new(); + session.add_document(doc, None); + session.select_layer(target).unwrap(); + PhotocraftApp::new(session, crate::Services::default()) +} + +fn open_levels(app: &mut PhotocraftApp, params: Value, end: Option<&str>) -> u64 { + let id = crate::adjust_dialog::open(app, "image.adjustments.levels").unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + if let Value::Object(p) = params { + fields.extend(p); + } + if let Some(end) = end { + fields.insert(FIELD.into(), json!(end)); + } + id +} + +/// A canvas view of the 16×8 document at `zoom` points per pixel (1 pixel per point). +fn view(zoom: f32) -> ViewXform { + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(16.0 * zoom, 8.0 * zoom)), + zoom, + center: [8.0, 4.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> Option> { + let painter = egui::Painter::new(ctx.clone(), egui::LayerId::background(), egui::Rect::EVERYTHING); + paint(app, ctx, &painter, xf, 0); + let c = app.levels_clipping.as_ref()?; + let (end, thr) = c.drawn?; + Some(image(&c.stats, &thr, end)) +} + +/// The display covers the view at about one texel per screen pixel, in every depth and in Gray, +/// and goes away with the dialog. +#[test] +fn paint_shows_the_target_clipping_for_the_view() { + let ctx = egui::Context::default(); + for (mode, depth) in + [(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Grayscale, SampleType::U8)] + { + let mut app = ramp_app(mode, depth); + let id = open_levels(&mut app, json!({"inBlack": 100, "inWhite": 200}), Some("shadows")); + let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap_or_else(|| panic!("{mode:?} {depth:?}")); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [16, 8]); + let gray = mode == ColorMode::Grayscale; + let clipped = if gray { Color32::BLACK } else { Color32::from_rgb(0, 255, 255) }; + for (x, p) in px.iter().take(16).enumerate() { + let want = if x as f32 / 15.0 * 255.0 <= 100.0 { clipped } else { Color32::WHITE }; + assert_eq!(*p, want, "{mode:?} {depth:?} shadows x={x}"); + } + app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!("highlights")); + let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap(); + for (x, p) in px.iter().skip(16 * 7).enumerate() { + let red = x as f32 / 15.0 * 255.0 >= 200.0; + let want = match (gray, red) { + (true, true) => Color32::WHITE, + (true, false) => Color32::BLACK, + (false, true) => Color32::from_rgb(255, 0, 255), + (false, false) => Color32::from_rgb(0, 0, 255), + }; + assert_eq!(*p, want, "{mode:?} {depth:?} highlights x={x}"); + } + // Zoomed out, a texel covers a block of pixels. + paint_view(&mut app, &ctx, &view(0.25)).unwrap(); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.factor, 4); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [4, 2]); + // Off: nothing drawn; closed: the cache goes. + app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), Value::Null); + assert!(request(&app, 0).is_none()); + app.ui.close_dialog(id); + paint_view(&mut app, &ctx, &view(10.0)); + assert!(app.levels_clipping.is_none(), "{mode:?} {depth:?}"); + } +} + +/// CMYK and Lab documents, a Quick Mask, and a target that isn't a pixel layer keep the normal +/// preview. +#[test] +fn ineligible_documents_show_no_display() { + for mode in ["cmyk", "lab"] { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "mode": mode})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "{mode}"); + } + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.quick_mask.is_some()); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "Quick Mask"); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + app.run("layer.newFillLayer.solidColor", json!({"color": "#808080"})).unwrap(); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "fill layer"); +} + +fn dialog_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h +} + +fn clipping(h: &Harness<'static, PhotocraftApp>) -> Option { + h.state().ui.dialogs.first().and_then(|d| d.fields.get(FIELD).cloned()) +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2, pressed: bool, modifiers: egui::Modifiers) { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn modifiers(h: &mut Harness<'static, PhotocraftApp>, m: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(m)); + h.run_steps(1); +} + +/// Alt-dragging the black slider shows the shadows display while both are held, the white slider +/// the highlights; the gamma slider, a drag without Alt and the Properties panel show nothing. +/// The document stays untouched throughout. +#[test] +fn alt_drag_on_the_black_and_white_sliders_turns_the_display_on() { + let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8)); + let original = h.state().session.active().unwrap().doc.clone(); + let id = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.levels").unwrap(); + h.run_steps(3); + let track = h.ctx.data(|d| d.get_temp::(egui::Id::new(("adjust-dialog", "levels")).with("levels-slider"))).unwrap(); + let at = |level: f32| egui::pos2(track.left() + level / 255.0 * track.width(), track.center().y + 4.0); + let alt = egui::Modifiers::ALT; + // Black slider: on while Alt and the button are held, off with either. + modifiers(&mut h, alt); + h.event(egui::Event::PointerMoved(at(0.0))); + press(&mut h, at(0.0), true, alt); + assert_eq!(clipping(&h), Some(json!("shadows"))); + h.event(egui::Event::PointerMoved(at(60.0))); + h.run_steps(1); + let in_black = h.state().ui.dialogs[0].fields["inBlack"].as_f64().unwrap(); + assert!((55.0..=65.0).contains(&in_black), "the drag still moves the slider: {in_black}"); + assert_eq!(clipping(&h), Some(json!("shadows"))); + modifiers(&mut h, egui::Modifiers::NONE); + assert_eq!(clipping(&h), None, "releasing Alt shows the preview"); + modifiers(&mut h, alt); + assert_eq!(clipping(&h), Some(json!("shadows")), "Alt again"); + press(&mut h, at(60.0), false, alt); + assert_eq!(clipping(&h), None, "releasing the mouse shows the preview"); + // White slider. + h.event(egui::Event::PointerMoved(at(255.0))); + press(&mut h, at(255.0), true, alt); + assert_eq!(clipping(&h), Some(json!("highlights"))); + press(&mut h, at(255.0), false, alt); + assert_eq!(clipping(&h), None); + // Gamma slider (halfway between 60 and 255 at gamma 1). + let gamma = 60.0 + (255.0 - 60.0) / 2.0; + h.event(egui::Event::PointerMoved(at(gamma))); + press(&mut h, at(gamma), true, alt); + assert_eq!(clipping(&h), None, "the gamma slider has no display"); + press(&mut h, at(gamma), false, alt); + // No Alt. + modifiers(&mut h, egui::Modifiers::NONE); + h.event(egui::Event::PointerMoved(at(60.0))); + press(&mut h, at(60.0), true, egui::Modifiers::NONE); + assert_eq!(clipping(&h), None, "no Alt, no display"); + press(&mut h, at(60.0), false, egui::Modifiers::NONE); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); + assert!(h.state().ui.dialogs.iter().any(|d| d.id == id)); +} + +/// Set through automation, the display stays until cleared; it never re-keys the live preview, +/// touches the document or reaches OK. +#[test] +fn the_display_never_reaches_the_document() { + let commit = |end: Option<&str>| { + let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8)); + let original = h.state().session.active().unwrap().doc.clone(); + let steps = h.state().session.active().unwrap().history.past_len(); + let id = open_levels(h.state_mut(), json!({"inBlack": 60, "gamma": 1.2}), None); + h.run_steps(3); + let _ = crate::adjust_preview::display_doc(h.state_mut(), 0); + let key = crate::adjust_preview::shown_key(h.state()); + if let Some(end) = end { + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!(end)); + h.run_steps(3); + assert_eq!(clipping(&h), Some(json!(end)), "an automation-set display stays"); + let _ = crate::adjust_preview::display_doc(h.state_mut(), 0); + assert_eq!(crate::adjust_preview::shown_key(h.state()), key, "the preview is not re-keyed"); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); + } + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let st = h.state().session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1); + let mut px = Vec::new(); + st.doc.layers[0].surface().unwrap().read_region_into(Rect::new(0, 0, 16, 8), &mut px); + px + }; + let plain = commit(None); + for end in ["shadows", "highlights"] { + assert_eq!(commit(Some(end)), plain, "{end}: OK commits only the levels"); + } +} + +/// Scan once per view, then per slider move thresholds + colours (the texture upload comes on +/// top). `CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 cargo test +/// --release -p photocraft-ui-egui --lib levels_clipping_bench -- --ignored --nocapture` +#[test] +#[ignore = "benchmark"] +fn levels_clipping_bench() { + let adj = levels(lv(40.0, 1.3, 215.0), [lv(5.0, 1.0, 250.0), LevelsChannel::default(), lv(0.0, 0.8, 240.0)]); + for (w, h) in [(6000u32, 4000u32), (7360, 4912)] { + let mut s = Surface::new(PixelFormat::RGBA8); + for y0 in (0..h).step_by(256) { + let rows = 256.min(h - y0); + let data: Vec = (0..rows * w) + .flat_map(|i| { + let (x, y) = (i % w, y0 + i / w); + let n = ((x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)) >> 7) % 64; + let v = (x as f32 / w as f32 * 0.8 + n as f32 / 255.0).min(1.0); + [v, 1.0 - v, (y as f32 / h as f32), 1.0] + }) + .collect(); + s.write_region(Rect::new(0, y0 as i32, w as i32, (y0 + rows) as i32), &data); + } + let fit = w.div_ceil(2400); + for (name, rect, factor) in [("fit", Rect::new(0, 0, w as i32, h as i32), fit), ("100%", Rect::new(1000, 1000, 3560, 2440), 1)] { + let best = |f: &mut dyn FnMut()| { + (0..5) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .fold(f64::MAX, f64::min) + }; + let scan_ms = best(&mut || { + std::hint::black_box(scan(&s, None, rect, factor)); + }); + let stats = scan(&s, None, rect, factor); + let update_ms = best(&mut || { + let thr = thresholds(&adj, SampleType::U8).unwrap(); + std::hint::black_box(egui::ColorImage::new(stats.size, image(&stats, &thr, ClipEnd::Shadows))); + }); + println!( + "{} MP {name} (1/{factor}, {}×{} texels): scan {scan_ms:.1} ms, update {update_ms:.1} ms", + (w * h) / 1_000_000, + stats.size[0], + stats.size[1] + ); + } + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 49a0332bcb..4019be2300 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -100,6 +100,7 @@ pub mod layer_row_ui; pub mod layer_style; mod layer_transfer; pub mod layer_tree_ui; +pub mod levels_clipping; pub mod links; pub mod liquify_ui; pub mod magnetic_lasso_ui; @@ -565,6 +566,8 @@ pub struct PhotocraftApp { pub(crate) color_range: Option, /// Image › Adjustments dialog preview through a temporary clipped adjustment layer. pub(crate) adjust_preview: Option, + /// The Levels dialog's Alt-drag clipping display over the canvas. + pub(crate) levels_clipping: Option, /// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame. pub(crate) synthetic: Vec, /// True only while a frame is processing synthetic automation input. It @@ -732,6 +735,7 @@ impl PhotocraftApp { filter_preview_worker: Default::default(), color_range: None, adjust_preview: None, + levels_clipping: None, synthetic: Vec::new(), automation_input: false, channel_thumbs: None, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b8d38b558a..9ca08519bf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -61,6 +61,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - 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` - 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. - 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. In the app, holding Alt turns Cancel into Reset (every channel back to neutral, the dialog stays open). - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. From 70cb31610b4b70d62faebe7c87e4621b876dd6ed Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:14:05 +0400 Subject: [PATCH 03/43] Revert "Levels: Alt turns Cancel into Reset (#3328)" This reverts commit 2b5f0f598489bbabdcf198ef9d9b2d56f919902b. #3871 brings Alt+Cancel Reset to every adjustment dialog, Levels included, so this PR keeps only the clipping display. --- crates/ui-egui/src/adjust_dialog.rs | 86 +++------------------------- crates/ui-egui/src/adjust_editors.rs | 16 +----- 2 files changed, 9 insertions(+), 93 deletions(-) diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index d235afa357..5ab6916e17 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -131,23 +131,20 @@ fn dialog_mem(kind: &str) -> egui::Id { egui::Id::new(("adjust-dialog", kind)) } -/// Whether holding Alt turns the dialog's Cancel into Reset, as in Photoshop's Color Balance -/// (measured in 25.4) and Levels dialogs; other kinds keep Cancel until checked against Photoshop. +/// Whether holding Alt turns the dialog's Cancel into Reset. Measured in Photoshop 25.4 for Color +/// Balance; other kinds keep Cancel until checked against Photoshop. pub fn resets(fields: &Map) -> bool { - matches!(fields.get("__adjust").and_then(Value::as_str), Some("colorBalance" | "levels")) + fields.get("__adjust").and_then(Value::as_str) == Some("colorBalance") } /// Alt+Cancel (Reset): back to the defaults Photoshop's Reset restores, dialog stays open. pub fn reset(ctx: &egui::Context, fields: &mut Map) { - let mut values = crate::filter_dialog::params_of(fields); - match fields.get("__adjust").and_then(Value::as_str) { - Some("colorBalance") => adjust_editors::reset_color_balance(ctx, dialog_mem("colorBalance"), &mut values), - Some("levels") => adjust_editors::reset_levels(ctx, dialog_mem("levels"), &mut values), - _ => return, + if !resets(fields) { + return; } + let mut values = crate::filter_dialog::params_of(fields); + adjust_editors::reset_color_balance(ctx, dialog_mem("colorBalance"), &mut values); if let Value::Object(v) = values { - // Replace the parameter keys, keep the private ones (as `body` does). - fields.retain(|k, _| k.starts_with("__")); fields.extend(v); } } @@ -397,79 +394,12 @@ mod tests { use egui_kittest::kittest::Queryable; let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "image.adjustments.curves").unwrap(); + open(h.state_mut(), "image.adjustments.levels").unwrap(); h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); h.run_steps(3); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); } - /// #3328: holding Alt turns the Levels dialog's Cancel into Reset, as in Photoshop: every - /// channel's levels back to neutral and the Channel choice back to the composite, with the - /// dialog still open and the document untouched. - #[test] - fn levels_dialog_alt_cancel_resets_every_channel() { - use egui_kittest::kittest::Queryable; - let mut h = Harness::builder() - .with_size(egui::vec2(1200.0, 900.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let original = h.state().session.active().unwrap().doc.clone(); - let id = open(h.state_mut(), "image.adjustments.levels").unwrap(); - let defaults = crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(id).unwrap().fields); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("inBlack".into(), json!(30)); - d.fields.insert("red".into(), json!({"inBlack": 0, "gamma": 1.0, "inWhite": 200, "outBlack": 0, "outWhite": 255})); - d.fields.insert("green".into(), json!({"inBlack": 0, "gamma": 1.4, "inWhite": 255, "outBlack": 0, "outWhite": 255})); - d.fields.insert("blue".into(), json!({"inBlack": 0, "gamma": 1.0, "inWhite": 255, "outBlack": 20, "outWhite": 255})); - let channel = egui::Id::new(("adjust-dialog", "levels")).with("levels-ch"); - h.ctx.data_mut(|d| d.insert_temp(channel, 2usize)); - h.run_steps(3); - assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); - h.run_steps(2); - let reset = h.get_by_label("Reset").rect(); - assert!(h.query_by_label("Cancel").is_none()); - let click = - |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; - input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); - let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.clone()).expect("Reset keeps the dialog open"); - assert_eq!(crate::filter_dialog::params_of(&fields), defaults, "every channel back to neutral"); - assert_eq!(fields.get("__preview"), Some(&json!(true)), "Reset keeps Preview"); - assert_eq!(h.ctx.data(|d| d.get_temp::(channel)), Some(0), "Reset shows the composite channel"); - assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original), "Reset leaves the document alone"); - // Without Alt it is Cancel again, and it closes. - let cancel = h.get_by_label("Cancel").rect(); - let click = - |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); - assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); - assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); - } - - /// Levels' Reset writes the parameter set the dialog opened with in every colour mode (RGB - /// channels, Gray's composite, CMYK's inks, Lab's lightness/a/b), dropping stray keys. - #[test] - fn levels_reset_restores_the_opening_parameters_in_every_mode() { - let ctx = egui::Context::default(); - for mode in ["rgb", "gray", "cmyk", "lab"] { - let mut app = app_in_mode(mode); - let id = open(&mut app, "image.adjustments.levels").unwrap(); - let fields = &mut app.ui.dialog_mut(id).unwrap().fields; - let defaults = crate::filter_dialog::params_of(fields); - fields.insert("inBlack".into(), json!(40)); - fields.insert("gray".into(), json!({"inWhite": 100})); - for key in ["red", "cyan", "a"] { - if fields.contains_key(key) { - fields.insert(key.into(), json!({"inBlack": 10, "gamma": 2.0, "inWhite": 180, "outBlack": 5, "outWhite": 250})); - } - } - reset(&ctx, fields); - assert_eq!(crate::filter_dialog::params_of(fields), defaults, "{mode}"); - assert_eq!(fields.get("__adjust"), Some(&json!("levels")), "{mode}: private keys kept"); - } - } - fn sample_params(kind: &str) -> Value { match kind { "brightnessContrast" => json!({"brightness": 40}), diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 60cb2b2891..4290bd582b 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -526,10 +526,6 @@ fn nearest(xs: &[f32], x: f32) -> Option { xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8) } -fn levels_channel_id(mem: egui::Id) -> egui::Id { - mem.with("levels-ch") -} - fn levels_drag_id(mem: egui::Id) -> egui::Id { mem.with("levels-drag") } @@ -540,23 +536,13 @@ pub(crate) fn levels_drag(ctx: &egui::Context, mem: egui::Id) -> Option { ctx.data(|d| d.get_temp::>(levels_drag_id(mem))).flatten() } -/// Levels reset to defaults (Alt+Cancel in the dialog): every channel's input, gamma and output -/// levels back to neutral in the values' channel space, and the Channel choice back to the -/// composite, as the dialog opens. -pub fn reset_levels(ctx: &egui::Context, mem: egui::Id, v: &mut Value) { - let neutral = photocraft_doc::adjust::LevelsChannel::default(); - let space = space_of(v); - *v = adjust_params::to_params(&Adjustment::Levels { master: neutral.clone(), per_channel: Default::default(), space, black: neutral }); - ctx.data_mut(|d| d.insert_temp(levels_channel_id(mem), 0usize)); -} - fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let t = Tokens::get(ui.ctx()); let chans = tone_channels(space_of(v), cx.gray); let mut ch = 0; let mut auto = false; ui.horizontal(|ui| { - ch = channel_picker(ui, levels_channel_id(cx.mem), chans, tl!("Channel:")); + ch = channel_picker(ui, cx.mem.with("levels-ch"), chans, tl!("Channel:")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { auto = widgets::secondary_button(ui, tl!("Auto"), 0.0).clicked(); }); From e0e73abb625fef9d2c65ae705ba51e471f3e5302 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:15:15 +0400 Subject: [PATCH 04/43] Docs: drop the Levels Reset note from the control protocol (#3328) The Levels Alt+Cancel Reset was reverted on this branch (#3871 brings it to every adjustment dialog), so the Levels entry describes only the __clipping field. --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9a1b28b80f..79b44d6536 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -62,7 +62,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - 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` - 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. - 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. In the app, holding Alt turns Cancel into Reset (every channel back to neutral, the dialog stays open). + - 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. - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows From 953db673e1280a882284c146e4f26c3c056c4557 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:47:30 +0400 Subject: [PATCH 05/43] Levels: clipping test follows #5143's Levels math (#3328) #5143 puts gamma's toe at black, so gamma above 1 now reaches white at the top. The test's precondition now shows why the display checks the input clamps: narrowed outputs and gamma below 1. --- crates/ui-egui/src/levels_clipping_tests.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index b0205c0667..416c21c659 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -51,15 +51,19 @@ fn clipping_matches_the_levels_result() { } } -/// Gamma and the output levels don't change what the input levels clip. Gamma above 1 keeps the -/// result just under white at the top (Photoshop's soft toe), which an "is it 1" test would miss. +/// Gamma and the output levels don't change what the input levels clip, so the display tests the +/// input-range clamps rather than the final value. Narrowed output levels never reach black or +/// white, and gamma below 1 rounds the 8-bit levels just above the black point to black although +/// the slider keeps them. (Gamma above 1 reaches white at the top: its toe is at black.) #[test] fn gamma_and_output_levels_do_not_hide_clipping() { let q = Some(255.0); let master = LevelsChannel { gamma: 1.5, ..lv(20.0, 1.0, 200.0) }; - assert!(levels_q(&master, 210.0 / 255.0, q) < 1.0, "the soft toe stays under white"); let plain = lv(20.0, 1.0, 200.0); let outputs = LevelsChannel { out_black: 25.0 / 255.0, out_white: 230.0 / 255.0, gamma: 0.6, ..lv(20.0, 1.0, 200.0) }; + let crushed = LevelsChannel { gamma: 0.5, ..lv(20.0, 1.0, 200.0) }; + assert!(levels_q(&outputs, 0.0, q) > 0.0 && levels_q(&outputs, 1.0, q) < 1.0, "narrowed outputs never reach black or white"); + assert_eq!(levels_q(&crushed, 21.0 / 255.0, q), 0.0, "gamma 0.5 rounds level 21 to black"); for n in 0..=255 { let v = n as f32 / 255.0; let id = LevelsChannel::default(); @@ -67,6 +71,7 @@ fn gamma_and_output_levels_do_not_hide_clipping() { assert_eq!(classify(&master, &id, v, q), want, "gamma 1.5 composite, level {n}"); assert_eq!(classify(&plain, &id, v, q), want, "level {n}"); assert_eq!(classify(&outputs, &id, v, q), want, "outputs and gamma 0.6, level {n}"); + assert_eq!(classify(&crushed, &id, v, q), want, "gamma 0.5 composite, level {n}"); assert_eq!(classify(&id, &master, v, q), want, "gamma 1.5 channel, level {n}"); } } From 3f73409ba2560af61586ddeb1ee7321711f5846d Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Thu, 15 Oct 2026 22:06:52 -0400 Subject: [PATCH 06/43] Context menus: an overflowing menu shows scroll arrows (#2091) Long right-click menus already scrolled when taller than the window, but only through egui's thin floating scroll bar, so nothing showed that more items were hidden. Like Photoshop's and the system menus, an overflowing menu now has arrows above and below its rows: hovering one scrolls that way, clicking jumps a page, and an arrow dims at its end. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets.rs | 97 ++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 6e841292e7..1c1f6f5a2a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1549,14 +1549,74 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R // The popup frame's margin and stroke, and a small gap to the window's edges. let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); + // An overflowing menu gets Photoshop's scroll arrows above and below its rows (#2091): the + // thin floating scroll bar alone gave no hint that more items were hidden. Whether it + // overflows is known only after layout, so it is remembered from the last frame. + let id = ui.id().with("menu_scroll"); + let overflow = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + let offset = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; + let room = (room - arrows).max(MENU_MIN_HEIGHT); + let mut step = 0.0; + if overflow { + step += menu_scroll_arrow(ui, true, offset > 0.5); + } // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. - egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner + let mut area = egui::ScrollArea::vertical().id_salt(id).max_height(room).min_scrolled_height(room); + let pending = ui.data(|d| d.get_temp::(id.with("step"))).unwrap_or(0.0); + if pending != 0.0 { + area = area.vertical_scroll_offset((offset + pending).max(0.0)); + } + let out = area.show(ui, add_contents); + let max = (out.content_size.y - out.inner_rect.height()).max(0.0); + let offset = out.state.offset.y.clamp(0.0, max); + if overflow { + step += menu_scroll_arrow(ui, false, offset < max - 0.5); + } + ui.data_mut(|d| { + d.insert_temp(id, max > 0.5); + d.insert_temp(id.with("offset"), offset); + d.insert_temp(id.with("step"), step); + }); + out.inner +} + +/// One scroll arrow of an overflowing menu: hovering scrolls that way (as in Photoshop's and the +/// system menus), clicking jumps a page. Returns the scroll step for the next frame. +fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool) -> f32 { + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(MENU_ARROW_HEIGHT), MENU_ARROW_HEIGHT), Sense::click()); + let t = Tokens::get(ui.ctx()); + let color = if enabled { t.text } else { t.text_dim.gamma_multiply(0.5) }; + let (c, h) = (rect.center(), 3.5); + let pts = if up { + vec![pos2(c.x - h * 1.4, c.y + h * 0.6), pos2(c.x + h * 1.4, c.y + h * 0.6), pos2(c.x, c.y - h * 0.8)] + } else { + vec![pos2(c.x - h * 1.4, c.y - h * 0.6), pos2(c.x + h * 1.4, c.y - h * 0.6), pos2(c.x, c.y + h * 0.8)] + }; + ui.painter().add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); + if !enabled { + return 0.0; + } + let sign = if up { -1.0 } else { 1.0 }; + if resp.clicked() { + sign * MENU_ARROW_PAGE + } else if resp.hovered() { + ui.ctx().request_repaint(); + sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1) + } else { + 0.0 + } } /// Gap kept between a context menu and the window's edges, and the shortest it gets. const MENU_EDGE: f32 = 4.0; const MENU_MIN_HEIGHT: f32 = 120.0; +/// Height of an overflowing menu's scroll arrows, how fast hovering one scrolls (points per +/// second) and how far a click on one jumps. +const MENU_ARROW_HEIGHT: f32 = 14.0; +const MENU_ARROW_SPEED: f32 = 400.0; +const MENU_ARROW_PAGE: f32 = 200.0; /// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside /// closes it. While open, its left edge stays where it first showed (at the swatch, or further @@ -1888,6 +1948,41 @@ mod tests { assert_eq!(h.state().0, "abc", "typing reaches the bound string"); } + /// #2091: a menu taller than the window shows scroll arrows; hovering the lower one scrolls + /// it, and a short menu gets none. + #[test] + fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { + // (rows, overflowing, scroll offset, bottom of the menu) + type S = (usize, bool, f32, f32); + let run = |rows: usize| { + let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..s.0 { + ui.label(format!("Item {i}")); + } + }); + s.1 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.2 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + s.3 = ui.min_rect().bottom(); + }, + (rows, false, 0.0, 0.0), + ); + h.run_steps(3); + h + }; + let short = run(3); + assert!(!short.state().1, "a short menu has no arrows"); + let mut long = run(80); + assert!(long.state().1, "a long menu overflows"); + assert_eq!(long.state().2, 0.0); + let below = egui::pos2(100.0, long.state().3 - super::MENU_ARROW_HEIGHT / 2.0); + long.event(egui::Event::PointerMoved(below)); + long.run_steps(10); + assert!(long.state().2 > 0.0, "hovering the lower arrow scrolls down"); + } + /// Sets up a test with one value field. Its state is its value and how many times it changed. fn field(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { let mut h = Harness::new_ui_state( From 43115de4ea2b4dad221e73285c599bedbeb5ab2a Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Thu, 15 Oct 2026 22:30:29 -0400 Subject: [PATCH 07/43] rustfmt; merge main (CI Format step) Co-Authored-By: Claude Opus 5.5 --- crates/automation/tests/smart_filter_authorization.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/automation/tests/smart_filter_authorization.rs b/crates/automation/tests/smart_filter_authorization.rs index a5c1681a52..30f17b795b 100644 --- a/crates/automation/tests/smart_filter_authorization.rs +++ b/crates/automation/tests/smart_filter_authorization.rs @@ -230,11 +230,9 @@ fn a_refresh_outside_command_execution_surfaces_the_denial_instead_of_rendering_ let before = h.session.active().unwrap().doc.clone(); // Session::edit is the outside-execute mutation path (an edit closure the UI or a // linked-file change runs); the stored filter must be denied there too. - assert_denied(h.session.edit("Re-render", |d, _| { - match smart_cmds::refresh(d, layer) { - Ok(_) => Ok(()), - Err(e) => Err(e), - } + assert_denied(h.session.edit("Re-render", |d, _| match smart_cmds::refresh(d, layer) { + Ok(_) => Ok(()), + Err(e) => Err(e), })); assert!(Arc::ptr_eq(&before, &h.session.active().unwrap().doc)); // A trusted session (no gate) still renders the same document. From 5f429c1fd469e0c836662065881aed3762d3e2cc Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Fri, 16 Oct 2026 10:41:38 -0400 Subject: [PATCH 08/43] Menu scroll arrows sit flush against the rows (#2091) The arrows were laid out with the menu's 6 pt item spacing above and below the scroll area, 12 pt the height budget didn't count, so a long layer menu in a short window ran 4 pt past the bottom (layer_menu_ui test). The rows keep the menu's own spacing. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 1c1f6f5a2a..5c7684286c 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1557,6 +1557,10 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R let offset = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; let room = (room - arrows).max(MENU_MIN_HEIGHT); + // The arrows sit flush against the rows, so no item spacing is added around them that `room` + // doesn't count; the rows keep the menu's own spacing. + let spacing = ui.spacing().item_spacing.y; + ui.spacing_mut().item_spacing.y = 0.0; let mut step = 0.0; if overflow { step += menu_scroll_arrow(ui, true, offset > 0.5); @@ -1568,12 +1572,16 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R if pending != 0.0 { area = area.vertical_scroll_offset((offset + pending).max(0.0)); } - let out = area.show(ui, add_contents); + let out = area.show(ui, |ui| { + ui.spacing_mut().item_spacing.y = spacing; + add_contents(ui) + }); let max = (out.content_size.y - out.inner_rect.height()).max(0.0); let offset = out.state.offset.y.clamp(0.0, max); if overflow { step += menu_scroll_arrow(ui, false, offset < max - 0.5); } + ui.spacing_mut().item_spacing.y = spacing; ui.data_mut(|d| { d.insert_temp(id, max > 0.5); d.insert_temp(id.with("offset"), offset); From e7e4556f91930276b6f20aabd57f405c97933004 Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Tue, 20 Oct 2026 21:31:23 -0400 Subject: [PATCH 09/43] Menu scroll arrows: scroll on hover only, drop stale steps on reopen egui closes a context menu on any click inside it (PopupCloseBehavior:: CloseOnClick, which nearly every menu_scroll caller uses), so the arrow's click-to-page never showed: the menu closed and the 200 pt step was left in memory, to be applied when the menu next opened. The arrows now sense hover only and scroll as Photoshop's and the system menus do. The step an arrow leaves for the next frame now carries the pass it was taken in and is applied only on the following pass, so a menu closed while an arrow was hovered doesn't jump when it reopens. The overflow flag and offset are kept: they describe the scroll area's own state, which egui keeps across openings, so a reopened long menu is laid out with its arrows from the first frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets.rs | 66 ++++++++++++++++++++++++++--------- 1 file changed, 50 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 279b197984..2f67096d3d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1658,7 +1658,10 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. let mut area = egui::ScrollArea::vertical().id_salt(id).max_height(room).min_scrolled_height(room); - let pending = ui.data(|d| d.get_temp::(id.with("step"))).unwrap_or(0.0); + // A step is taken on the pass after the arrow was hovered, and only then: a menu closed while + // an arrow was hovered doesn't jump when it next opens. + let now = ui.ctx().cumulative_pass_nr(); + let pending = ui.data(|d| d.get_temp::<(f32, u64)>(id.with("step"))).filter(|&(_, pass)| pass.saturating_add(1) == now).map_or(0.0, |(step, _)| step); if pending != 0.0 { area = area.vertical_scroll_offset((offset + pending).max(0.0)); } @@ -1675,15 +1678,16 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R ui.data_mut(|d| { d.insert_temp(id, max > 0.5); d.insert_temp(id.with("offset"), offset); - d.insert_temp(id.with("step"), step); + d.insert_temp(id.with("step"), (step, now)); }); out.inner } -/// One scroll arrow of an overflowing menu: hovering scrolls that way (as in Photoshop's and the -/// system menus), clicking jumps a page. Returns the scroll step for the next frame. +/// One scroll arrow of an overflowing menu: hovering scrolls that way, as in Photoshop's and the +/// system menus. It doesn't page on a click: egui closes a context menu on any click inside it, +/// so the page would never be seen. Returns the scroll step for the next frame. fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool) -> f32 { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(MENU_ARROW_HEIGHT), MENU_ARROW_HEIGHT), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(MENU_ARROW_HEIGHT), MENU_ARROW_HEIGHT), Sense::hover()); let t = Tokens::get(ui.ctx()); let color = if enabled { t.text } else { t.text_dim.gamma_multiply(0.5) }; let (c, h) = (rect.center(), 3.5); @@ -1696,25 +1700,21 @@ fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool) -> f32 { if !enabled { return 0.0; } - let sign = if up { -1.0 } else { 1.0 }; - if resp.clicked() { - sign * MENU_ARROW_PAGE - } else if resp.hovered() { - ui.ctx().request_repaint(); - sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1) - } else { - 0.0 + if !resp.hovered() { + return 0.0; } + ui.ctx().request_repaint(); + let sign = if up { -1.0 } else { 1.0 }; + sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1) } /// Gap kept between a context menu and the window's edges, and the shortest it gets. const MENU_EDGE: f32 = 4.0; const MENU_MIN_HEIGHT: f32 = 120.0; -/// Height of an overflowing menu's scroll arrows, how fast hovering one scrolls (points per -/// second) and how far a click on one jumps. +/// Height of an overflowing menu's scroll arrows, and how fast hovering one scrolls (points per +/// second). const MENU_ARROW_HEIGHT: f32 = 14.0; const MENU_ARROW_SPEED: f32 = 400.0; -const MENU_ARROW_PAGE: f32 = 200.0; /// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside /// closes it. While open, its left edge stays where it first showed (at the swatch, or further @@ -2081,6 +2081,40 @@ mod tests { assert!(long.state().2 > 0.0, "hovering the lower arrow scrolls down"); } + /// #2091: the step a hovered arrow leaves for the next frame isn't taken when a menu closed + /// while hovering it opens again. + #[test] + fn a_reopened_menu_takes_no_stale_scroll_step() { + // (shown, scroll offset, bottom of the menu) + type S = (bool, f32, f32); + let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.id().with("menu_scroll"); + if s.0 { + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.2 = ui.min_rect().bottom(); + } + s.1 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + }, + (true, 0.0, 0.0), + ); + h.run_steps(3); + h.event(egui::Event::PointerMoved(egui::pos2(100.0, h.state().2 - super::MENU_ARROW_HEIGHT / 2.0))); + h.run_steps(3); + let offset = h.state().1; + assert!(offset > 0.0, "hovering the lower arrow scrolls down"); + h.state_mut().0 = false; + h.run(); + h.state_mut().0 = true; + h.event(egui::Event::PointerGone); + h.run(); + assert_eq!(h.state().1, offset, "the reopened menu stays where it was left"); + } + /// Sets up a test with one value field. Its state is its value and how many times it changed. fn field(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { let mut h = Harness::new_ui_state( From ec5ebe44c393664707190f0841516d82d5bc29be Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Mon, 26 Oct 2026 23:02:39 -0400 Subject: [PATCH 10/43] Menus: use Ui::scope_id for the scroll-arrow state id (Ui::id is deprecated) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets/dropdown.rs | 2 +- crates/ui-egui/src/widgets/tests.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index da1063ee18..40663d971d 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -225,7 +225,7 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R // An overflowing menu gets Photoshop's scroll arrows above and below its rows (#2091): the // thin floating scroll bar alone gave no hint that more items were hidden. Whether it // overflows is known only after layout, so it is remembered from the last frame. - let id = ui.id().with("menu_scroll"); + let id = ui.scope_id().with("menu_scroll"); let overflow = ui.data(|d| d.get_temp::(id)).unwrap_or(false); let offset = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 0cc6efe0f0..9a6f079dbe 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1025,7 +1025,7 @@ fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { let run = |rows: usize| { let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( |ui, s: &mut S| { - let id = ui.id().with("menu_scroll"); + let id = ui.scope_id().with("menu_scroll"); super::menu_scroll(ui, |ui| { for i in 0..s.0 { ui.label(format!("Item {i}")); @@ -1059,7 +1059,7 @@ fn a_reopened_menu_takes_no_stale_scroll_step() { type S = (bool, f32, f32); let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( |ui, s: &mut S| { - let id = ui.id().with("menu_scroll"); + let id = ui.scope_id().with("menu_scroll"); if s.0 { super::menu_scroll(ui, |ui| { for i in 0..80 { From fd601d7807c471e1a6e4d2f6cdb3ab0d76009233 Mon Sep 17 00:00:00 2001 From: texjer Date: Sat, 17 Oct 2026 09:59:45 -0400 Subject: [PATCH 11/43] feat(raw): decode Canon sRAW / mRAW CR2 as camera RGB Canon's subsampled lossless JPEG (Y 2x2 or 2x1, Cb/Cr per MCU) with its own prediction chain, de-sliced into YCbCr planes, bilinear chroma, a BT.601 inverse and the per-shot sRAW gains from ColorData (version 15), developed like a three-sample LinearRaw so white balance, the fitted camera look, tone and the Camera Raw dialog all apply. Verified on EOS 6D Mark II mRAW files; other bodies decode with a warning when their gain offset is unknown. --- crates/raw/README.md | 2 +- crates/raw/src/cr2.rs | 162 +++++++++++----- crates/raw/src/lib.rs | 3 +- crates/raw/src/ljpeg.rs | 193 ++++++++++++++++++- crates/raw/src/sraw.rs | 316 ++++++++++++++++++++++++++++++++ crates/raw/src/testgen.rs | 4 +- crates/raw/src/testgen/canon.rs | 99 +++++++++- crates/raw/src/testgen/lj92.rs | 140 ++++++++++++-- crates/raw/tests/it/vendors.rs | 3 +- 9 files changed, 846 insertions(+), 76 deletions(-) create mode 100644 crates/raw/src/sraw.rs diff --git a/crates/raw/README.md b/crates/raw/README.md index 268e200b7f..0acf28165a 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -70,7 +70,7 @@ camera colour tables were copied. | DNG | Uncompressed (8–16 bit, packed or not), Deflate (compression 8, predictors 1 and 2), lossless JPEG, lossy JPEG (DNG 1.4 compression 34892: 8-bit baseline JPEG tiles or strips, gray for CFA, YCbCr-coded RGB for LinearRaw; decoded by `zune-jpeg`, the stored 8-bit values then go through the same LinearizationTable / BlackLevel / WhiteLevel as every other depth) and JPEG XL (DNG 1.7, e.g. Samsung Expert RAW; decoded by `jxl-oxide`; not in wasm32 builds, where it is `Unsupported`); strips and tiles; CFA (Bayer) and LinearRaw (three-sample colour, or one-sample monochrome such as Leica Monochrom and film-scanner DNGs, developed as neutral grey with no white balance or colour matrix); LinearizationTable, BlackLevel (+ repeat, DeltaH/V), WhiteLevel, ActiveArea, DefaultCrop, ColorMatrix1/2, CameraCalibration, ForwardMatrix, AnalogBalance, AsShotNeutral / AsShotWhiteXY, BaselineExposure, Orientation, floating-point JPEG XL raw data (DNG 1.7 lossy LinearRaw, as Adobe DNG Converter writes it; scaled by the highest WhiteLevel), OpcodeList2 GainMap (lens shading) and MapPolynomial | | DNG (floating point other than JPEG XL; opcodes other than OpcodeList2 GainMap and MapPolynomial; ProfileGainTableMap) | Unsupported / not applied (reported) | | CR2 | Lossless JPEG with slices, borders and as-shot white balance from the maker note, black measured on the masked border. CR2 has no CFA tag and the row phase varies by model, so it is measured from the data (the green diagonal), with a Canon model-ID table as the fallback (see `src/cr2.rs`) | -| CR2 sRAW / mRAW | Unsupported | +| CR2 sRAW / mRAW (subsampled YCbCr) | Decoded to camera RGB and developed like LinearRaw: Canon's subsampled lossless JPEG (Y 2×2 or 2×1), BT.601 inverse, bilinear chroma, the per-shot sRAW gains from ColorData (version 15: EOS 6D Mark II, 77D, 200D, 800D; other bodies warn and rely on the fitted camera look). See `src/sraw.rs` | | NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data | | Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) | | Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits, the curve's 512 black level when no BlackLevel tag is written (the first-generation bodies, e.g. the ILCE-7) | diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs index 8e851c5d59..990745b7e2 100644 --- a/crates/raw/src/cr2.rs +++ b/crates/raw/src/cr2.rs @@ -5,7 +5,8 @@ //! lossless JPEG (T.81 process 14) whose decoded sample sequence fills the //! sensor image in vertical slices: the private tag 0xC640 gives the slice //! count, slice width and last slice width; slice 0 is filled row by row, -//! then slice 1, and so on. sRAW/mRAW (subsampled YCbCr) is not supported. +//! then slice 1, and so on. sRAW / mRAW (subsampled YCbCr) is decoded to +//! camera RGB by `sraw.rs`. //! //! Sensor geometry and the as-shot white balance come from the Canon maker //! note (an IFD at the MakerNote offset, values relative to the TIFF header): @@ -45,7 +46,7 @@ use crate::error::{RawError, Result}; use crate::sensor::{BlackLevels, Cfa, Rect, Sensor}; use crate::tiff::{Ifd, Tiff, tag}; -use crate::{Limits, RawFormat, ljpeg}; +use crate::{Limits, RawFormat, ljpeg, sraw}; const CANON_SENSOR_INFO: u16 = 0x00E0; const CANON_COLOR_DATA: u16 = 0x4001; @@ -115,26 +116,38 @@ pub(crate) fn maker_note(t: &Tiff, ifds: &[Ifd]) -> Option { /// As-shot white-balance multipliers (R, G, B) from ColorData. fn as_shot_wb(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> { - let e = mn.get(CANON_COLOR_DATA)?; - // The entry is UNDEFINED: its bytes are a table of 16-bit words (file byte order), and the - // offsets below count words, not bytes. Reads stay inside the entry's own byte count. - let bytes = e.unit().checked_mul(e.count as usize)?; - let word = |off: usize| { - let at = off.checked_mul(2)?.checked_add(e.at)?; - (at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten().map(f64::from) - }; // Word offsets of WB_RGGBLevelsAsShot used by the ColorData versions. - for off in [0x3F, 0x47, 0x19, 0x22] { - let (Some(r), Some(g1), Some(g2), Some(b)) = (word(off), word(off + 1), word(off + 2), word(off + 3)) else { - continue; - }; - let g = (g1 + g2) / 2.0; - let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g)); - if plausible { - return Some([r / g, 1.0, b / g]); - } - } - None + [0x3F, 0x47, 0x19, 0x22].into_iter().find_map(|off| color_data_rggb(t, mn, off)) +} + +/// Word `off` of ColorData. The entry is UNDEFINED: its bytes are a table of 16-bit words (file +/// byte order), and the offsets count words, not bytes. Reads stay inside the entry's own byte +/// count. +fn color_data_word(t: &Tiff, mn: &Ifd, off: usize) -> Option { + let e = mn.get(CANON_COLOR_DATA)?; + let bytes = e.unit().checked_mul(e.count as usize)?; + let at = off.checked_mul(2)?.checked_add(e.at)?; + (at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten() +} + +/// RGGB levels at ColorData word `off` as multipliers relative to green, when plausible. +fn color_data_rggb(t: &Tiff, mn: &Ifd, off: usize) -> Option<[f64; 3]> { + let word = |k: usize| color_data_word(t, mn, off.checked_add(k)?).map(f64::from); + let (r, g1, g2, b) = (word(0)?, word(1)?, word(2)?, word(3)?); + let g = (g1 + g2) / 2.0; + let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g)); + plausible.then(|| [r / g, 1.0, b / g]) +} + +/// ColorData versions whose sRAW gains (see `sraw.rs`) sit at a word offset we observed: +/// version 15 (EOS 6D Mark II, 77D, 200D, 800D) at 0x80, just before the daylight preset. +const SRAW_GAINS: [(u16, usize); 1] = [(15, 0x80)]; + +/// The per-shot gains an sRAW's stored RGB was divided by, relative to green. +fn sraw_gains(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> { + let version = color_data_word(t, mn, 0)?; + let (_, off) = SRAW_GAINS.iter().find(|(v, _)| *v == version)?; + color_data_rggb(t, mn, *off) } /// The white (clipping) level: the largest value when a meaningful share of @@ -181,6 +194,86 @@ pub(crate) fn masked_black(data: &[u16], width: usize, area: Rect) -> Option<[f3 Some([0, 1, 2, 3].map(|k| sum[k] as f32 / n[k] as f32)) } +/// The slice widths of CR2 tag 0xC640 (count, width, last width), in samples. The tag is SHORT: +/// larger values (a LONG in a damaged file) are refused, which also bounds the sum. +fn slice_widths(tag: &[u32]) -> Option> { + let short = 1..=u32::from(u16::MAX); + match tag { + [n, w, last] if *n < 64 && short.contains(w) && short.contains(last) => { + let mut ws = vec![*w as usize; *n as usize]; + ws.push(*last as usize); + Some(ws) + } + _ => None, + } +} + +/// The image area inside `full` from the maker note's SensorInfo ([1] width, [2] height, [5] +/// left, [6] top, [7] right, [8] bottom border, inclusive); `full` when absent or empty. +fn image_area(t: &Tiff, mn: Option<&Ifd>, full: Rect) -> Rect { + let info = mn.map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default(); + let active = match info.get(5..9) { + Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full), + _ => full, + }; + if active.is_empty() { full } else { active } +} + +/// sRAW / mRAW: subsampled YCbCr, developed as three-sample camera RGB (see `sraw.rs`). +fn decode_sraw(t: &Tiff, ifds: &[Ifd], ifd0: &Ifd, slices: &[u32], src: &[u8], frame: ljpeg::Frame, limits: &Limits) -> Result { + let per_mcu = frame.h * frame.v + 2; + let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?; + let widths = slice_widths(slices).unwrap_or_else(|| vec![frame.width / frame.h * per_mcu]); + let row: usize = widths.iter().sum(); + if row == 0 || !row.is_multiple_of(per_mcu) || !total.is_multiple_of(row) { + return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame")); + } + let (width, height) = (row / per_mcu * frame.h, total / row * frame.v); + // The RGB output: three u16 per pixel. + limits.check(width as u64, height as u64, 6)?; + let (_, samples) = ljpeg::decode_subsampled(src, total)?; + let planes = sraw::planes(&frame, &samples, &widths)?; + drop(samples); + + let mut warnings = Vec::new(); + let mn = maker_note(t, ifds); + let camera_wb = mn.as_ref().and_then(|m| as_shot_wb(t, m)); + let gains = mn.as_ref().and_then(|m| sraw_gains(t, m)); + if gains.is_none() { + warnings.push("the sRAW colour gains of this camera are not known; colours rely on the look fitted to the camera's JPEG".to_string()); + } + let offset = (1u32 << (frame.precision - 1)) as f32; + let data = sraw::camera_rgb(&planes, offset, gains.unwrap_or([1.0; 3])); + drop(planes); + let full = Rect::new(0, 0, width, height); + let active = image_area(t, mn.as_ref(), full); + let white = [0, 1, 2].map(|k| sraw::clip_level(&data, k, sraw::FULL_SCALE)); + Ok(Sensor { + format: RawFormat::Cr2, + make: t.tag_ascii(ifd0, tag::MAKE), + model: t.tag_ascii(ifd0, tag::MODEL), + width, + height, + samples: 3, + data, + cfa: None, + linearization: None, + // Y is stored black-subtracted. + black: BlackLevels::uniform(0.0), + white, + active, + crop: active, + color: Default::default(), + camera_wb, + orientation: crate::tiff::orientation(t.tag_uint(ifd0, tag::ORIENTATION)), + baseline_exposure: 0.0, + gain_maps: Vec::new(), + tone_curve: Vec::new(), + black_point: 0.0, + warnings, + }) +} + pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let ifds = t.all_ifds(); let ifd0 = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("CR2 has no IFD0"))?; @@ -191,23 +284,16 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let src = t.bytes(off, len).or_else(|| t.data.get(off..)).ok_or_else(|| RawError::malformed("CR2 raw data lies outside the file"))?; let frame = ljpeg::frame(src).map_err(|e| match e { - RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("Canon sRAW / mRAW"), + RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("this Canon sRAW / mRAW layout"), e => e, })?; let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?; let slices = t.tag_uints(&raw, tag::CR2_SLICE); - let (width, widths) = match slices.as_slice() { - [n, w, last] if *n < 64 && *w > 0 && *last > 0 => { - let (n, w, last) = (*n as usize, *w as usize, *last as usize); - let mut ws = vec![w; n]; - ws.push(last); - (n * w + last, ws) - } - _ => { - let w = frame.width * frame.components; - (w, vec![w]) - } - }; + if frame.is_subsampled() { + return decode_sraw(t, &ifds, &ifd0, &slices, src, frame, limits); + } + let widths = slice_widths(&slices).unwrap_or_else(|| vec![frame.width * frame.components]); + let width: usize = widths.iter().sum(); if width == 0 || total % width != 0 { return Err(RawError::malformed("CR2 slices do not match the JPEG frame")); } @@ -231,13 +317,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let mut warnings = Vec::new(); let mn = maker_note(t, &ifds); let full = Rect::new(0, 0, width, height); - // SensorInfo: [1] width, [2] height, [5] left, [6] top, [7] right, [8] bottom border (inclusive). - let info = mn.as_ref().map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default(); - let active = match info.get(5..9) { - Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full), - _ => full, - }; - let active = if active.is_empty() { full } else { active }; + let active = image_area(t, mn.as_ref(), full); // Black: the masked columns left of the image (skipping a few edge columns). let black = if active.x >= 16 { // Only the outer half: the columns next to the image area can be partly exposed. diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 24cd852c77..2eac7d7b09 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -29,7 +29,7 @@ //! image area (the D800E, the ILCE-7). //! //! Decoded today: DNG (uncompressed, deflate, lossless-JPEG, lossy-JPEG and JPEG XL, strips and -//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or +//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices, and sRAW / mRAW), uncompressed or //! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed), //! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW), //! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed), @@ -64,6 +64,7 @@ mod rw2; mod saturation; mod sensor; mod sony; +mod sraw; mod tiff; mod tiffep; mod tone; diff --git a/crates/raw/src/ljpeg.rs b/crates/raw/src/ljpeg.rs index 070b3757fd..ffb44f0cb2 100644 --- a/crates/raw/src/ljpeg.rs +++ b/crates/raw/src/ljpeg.rs @@ -8,8 +8,10 @@ //! //! Output is the sample sequence in raster order: `height` rows of `width × //! components` interleaved samples. Only one interleaved scan holding every -//! component with sampling factors 1×1 is supported, which is how DNG, CR2 -//! and the TIFF-based raws use it. +//! component is supported, which is how DNG, CR2 and the TIFF-based raws use +//! it; [`decode`] takes sampling factors 1×1 only. Canon's sRAW / mRAW frames +//! (three components, the first sampled 2×1 or 2×2) go through +//! [`decode_subsampled`], which follows Canon's prediction rather than T.81's. use crate::error::{RawError, Result}; @@ -20,11 +22,21 @@ pub(crate) struct Frame { pub width: usize, pub height: usize, pub components: usize, + /// Horizontal and vertical sampling factors of the first component (1 and 1 unless the + /// frame is subsampled; the other components are then sampled 1×1). + pub h: usize, + pub v: usize, } impl Frame { + /// Samples in the frame: per MCU, `h × v` of the first component and one of each other. pub fn samples(&self) -> Option { - self.width.checked_mul(self.height)?.checked_mul(self.components) + let mcus = (self.width / self.h.max(1)).checked_mul(self.height / self.v.max(1))?; + mcus.checked_mul(self.h.checked_mul(self.v)?.checked_add(self.components)?.checked_sub(1)?) + } + + pub fn is_subsampled(&self) -> bool { + self.h != 1 || self.v != 1 } } @@ -343,14 +355,19 @@ fn parse(data: &[u8]) -> Result> { return Err(RawError::malformed(format!("unsupported SOF3 ({precision}-bit, {width}x{height}, {nf} components)"))); } comp_ids.clear(); + let mut factors = Vec::with_capacity(nf); for c in 0..nf { let s = &seg[6 + 3 * c..9 + 3 * c]; - if s[1] != 0x11 { - return Err(RawError::unsupported("lossless JPEG with subsampled components")); - } + factors.push(s[1]); comp_ids.push(s[0]); } - frame = Some(Frame { precision, width, height, components: nf }); + // Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, whole MCUs only. + let (h, v) = match factors.as_slice() { + f if f.iter().all(|&s| s == 0x11) => (1, 1), + [y @ (0x21 | 0x22), 0x11, 0x11] if width % 2 == 0 && height % usize::from(y & 0x0F) == 0 => (2, usize::from(y & 0x0F)), + _ => return Err(RawError::unsupported(format!("lossless JPEG with subsampled components {factors:02x?} ({width}x{height})"))), + }; + frame = Some(Frame { precision, width, height, components: nf, h, v }); } 0xC0..=0xC2 => return Err(RawError::unsupported("lossy (DCT) JPEG compressed raw data")), 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => return Err(RawError::unsupported("hierarchical or arithmetic-coded JPEG")), @@ -422,6 +439,9 @@ fn parse(data: &[u8]) -> Result> { pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec)> { let p = parse(data)?; let f = p.frame; + if f.is_subsampled() { + return Err(RawError::unsupported(format!("lossless JPEG with subsampled components ({}x{} luma)", f.h, f.v))); + } let total = f .samples() .filter(|&n| n <= max_samples) @@ -531,10 +551,100 @@ pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec Ok((f, out)) } +/// Decodes a subsampled frame (Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, see +/// [`Frame::h`]) into its sample sequence in decode order: per MCU the `h × v` Y samples +/// row-major, then Cb, then Cr; `width / h` MCUs make a row and `height / v` rows the frame. +/// +/// Only predictor 1 is supported, with Canon's rule instead of T.81's per-component sample +/// grid: each Y sample is predicted from the Y sample decoded just before it (the previous one +/// in the MCU, or the last of the previous MCU), Cb and Cr from those of the previous MCU, and +/// the first MCU of a row from the first MCU of the row above (from `2^(P−Pt−1)` on the first +/// row of a restart interval). +pub(crate) fn decode_subsampled(data: &[u8], max_samples: usize) -> Result<(Frame, Vec)> { + let p = parse(data)?; + let f = p.frame; + let total = f + .samples() + .filter(|&n| n <= max_samples) + .ok_or_else(|| RawError::LimitExceeded(format!("lossless JPEG frame {}x{}x{}", f.width, f.height, f.components)))?; + if !f.is_subsampled() || f.components != 3 { + return Err(RawError::malformed("lossless JPEG frame is not subsampled YCbCr")); + } + if p.predictor != 1 { + return Err(RawError::unsupported(format!("subsampled lossless JPEG with predictor {}", p.predictor))); + } + if p.entropy.len().saturating_mul(8) < total / 2 { + return Err(RawError::malformed("lossless JPEG data is truncated")); + } + // Each component's table (components may share one). + let [ty, tcb, tcr] = match p.comp_table.as_slice() { + &[a, b, c] => [&p.tables[a], &p.tables[b], &p.tables[c]], + _ => return Err(RawError::malformed("lossless JPEG scan tables")), + }; + let luma = f.h * f.v; + let per_mcu = luma + 2; + let mcus = f.width / f.h; + let row_len = mcus * per_mcu; + if row_len == 0 { + return Err(RawError::malformed("empty lossless JPEG frame")); + } + // The restart interval counts MCUs. + if p.restart != 0 && p.restart % mcus != 0 { + return Err(RawError::unsupported("lossless JPEG restart interval that is not whole rows")); + } + let rows_per_interval = if p.restart == 0 { usize::MAX } else { p.restart / mcus }; + let mut out = vec![0u16; total]; + let mut bits = Bits::new(p.entropy); + let initial = 1i32 << (f.precision - p.point_transform - 1); + // First Y, Cb and Cr of the row above: the first MCU's predictors. + let mut top = [initial; 3]; + let mut interval_row = 0usize; + for row in out.chunks_exact_mut(row_len) { + if interval_row == rows_per_interval { + bits.restart()?; + interval_row = 0; + } + if interval_row == 0 { + top = [initial; 3]; + } + let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]); + for (m, mcu) in row.chunks_exact_mut(per_mcu).enumerate() { + let (ys, c) = mcu.split_at_mut(luma); + for (k, s) in ys.iter_mut().enumerate() { + // The first Y of the row comes from the row above, every other from the previous Y. + let pred = if m == 0 && k == 0 { top[0] } else { y }; + *s = (pred + bits.diff(ty)?) as u16; + y = i32::from(*s); + if m == 0 && k == 0 { + top[0] = y; + } + } + if let [scb, scr] = c { + *scb = (cb + bits.diff(tcb)?) as u16; + *scr = (cr + bits.diff(tcr)?) as u16; + (cb, cr) = (i32::from(*scb), i32::from(*scr)); + } + if m == 0 { + (top[1], top[2]) = (cb, cr); + } + } + interval_row += 1; + if bits.fake > 64 { + return Err(RawError::malformed("lossless JPEG data is truncated")); + } + } + if p.point_transform > 0 { + for v in &mut out { + *v <<= p.point_transform; + } + } + Ok((f, out)) +} + #[cfg(test)] mod tests { use super::*; - use crate::testgen::{lj92_encode, lj92_encode_tables}; + use crate::testgen::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables}; /// Deterministic pseudo-random samples with some structure (smooth + noise). fn samples(n: usize, precision: u8, seed: u64) -> Vec { @@ -559,7 +669,7 @@ mod tests { let v = samples(w * h * comps, precision, u64::from(predictor) * 31 + comps as u64); let j = lj92_encode(&v, w, h, comps, precision, predictor, None); let (f, out) = decode(&j, usize::MAX).unwrap(); - assert_eq!(f, Frame { precision, width: w, height: h, components: comps }); + assert_eq!(f, Frame { precision, width: w, height: h, components: comps, h: 1, v: 1 }); assert_eq!(out, v, "P={precision} pred={predictor} comps={comps}"); } } @@ -591,7 +701,7 @@ mod tests { let v = samples(w * h * comps, 14, u64::from(predictor) * 7 + comps as u64); let j = lj92_encode_tables(&v, w, h, table_of, 14, predictor, restart_rows); let (f, out) = decode(&j, usize::MAX).unwrap(); - assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps }); + assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps, h: 1, v: 1 }); assert_eq!(out, v, "tables={table_of:?} pred={predictor} restart={restart_rows:?}"); } } @@ -663,4 +773,67 @@ mod tests { flooded.extend_from_slice(&j[2..]); // the rest of the valid stream assert!(matches!(decode(&flooded, usize::MAX), Err(RawError::Malformed(_)))); } + + #[test] + fn subsampled_roundtrip() { + for (h, v) in [(2usize, 2usize), (2, 1)] { + let (w, ht) = (14, 6); + let n = (w / h) * (ht / v) * (h * v + 2); + for precision in [12u8, 15, 16] { + for restart in [None, Some(1), Some(ht / v)] { + let seq = samples(n, precision, h as u64 * 7 + v as u64); + let j = lj92_encode_sraw(&seq, w, ht, h, v, precision, restart); + let f = frame(&j).unwrap(); + assert_eq!((f.h, f.v, f.samples()), (h, v, Some(n))); + let (_, out) = decode_subsampled(&j, usize::MAX).unwrap(); + assert_eq!(out, seq, "{h}x{v} P={precision} restart {restart:?}"); + // The plain decoder refuses subsampled frames instead of mislaying them. + assert!(matches!(decode(&j, usize::MAX), Err(RawError::Unsupported(_)))); + } + } + } + // Extreme values exercise the 16-bit and 32768 difference categories. + let seq: Vec = (0..7 * 3 * 6).map(|i| if (i / 5) % 2 == 0 { 0 } else { 65535 }).collect(); + let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 16, Some(1)); + assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq); + // Y and the chroma on separate tables, or each its own: the scan maps every component + // to its table even when components share one. + for table_of in [[0, 1, 1], [0, 1, 2], [1, 0, 0]] { + let seq = samples(7 * 3 * 6, 15, 5); + let j = lj92_encode_sraw_tables(&seq, 14, 6, (2, 2), table_of, 15, Some(1)); + assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq, "tables {table_of:?}"); + } + } + + #[test] + fn subsampled_hostile_streams_error_without_panicking() { + let seq = samples(7 * 3 * 6, 15, 3); + let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 15, Some(1)); + for n in 0..j.len() { + let _ = decode_subsampled(&j[..n], usize::MAX); + } + let mut s = 0x0123_4567u64; + for _ in 0..2000 { + let mut b = j.clone(); + for _ in 0..4 { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1); + let at = (s >> 33) as usize % b.len(); + b[at] = (s >> 20) as u8; + } + let _ = decode_subsampled(&b, 1 << 20); + } + assert!(matches!(decode_subsampled(&j, 10), Err(RawError::LimitExceeded(_)))); + // A frame that is not subsampled, or another predictor, is not Canon sRAW. + let plain = lj92_encode(&samples(14 * 6 * 3, 15, 1), 14, 6, 3, 15, 1, None); + assert!(decode_subsampled(&plain, usize::MAX).is_err()); + let mut p6 = j.clone(); + let sos = p6.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap(); + p6[sos + 11] = 6; // Ss (predictor) after Ns and three component selectors + assert!(matches!(decode_subsampled(&p6, usize::MAX), Err(RawError::Unsupported(_)))); + // Sampling layouts other than Canon's are refused at the frame header. + let mut odd = j.clone(); + let sof = odd.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); + odd[sof + 14] = 0x21; // Cb subsampled too + assert!(matches!(frame(&odd), Err(RawError::Unsupported(_)))); + } } diff --git a/crates/raw/src/sraw.rs b/crates/raw/src/sraw.rs new file mode 100644 index 0000000000..c027700661 --- /dev/null +++ b/crates/raw/src/sraw.rs @@ -0,0 +1,316 @@ +//! Canon sRAW / mRAW (CR2 with subsampled YCbCr). +//! +//! The camera demosaics the sensor data and stores it as Y, Cb, Cr in one lossless JPEG frame +//! whose Y component is sampled 2×2 (sRAW1, which Canon calls mRAW on the later bodies) or 2×1 +//! (sRAW2), sliced like the Bayer CR2 data (tag 0xC640, widths in samples). The decoder +//! ([`crate::ljpeg::decode_subsampled`]) gives the sample sequence; [`planes`] lays it out, +//! [`camera_rgb`] interpolates the chroma and converts to camera RGB, and the result is +//! developed like a three-sample LinearRaw: no CFA, the as-shot white balance, the look fitted +//! to the embedded JPEG (`photocraft-io`), tone and exposure as for every other raw. +//! +//! Observed on EOS 6D Mark II mRAW files (ColorData version 15, 4680 × 3132 data): +//! * Y is already black-subtracted (the darkest samples are 0) and on the sensor's scale; Cb and +//! Cr are colour differences offset by `2^(P−1)`. +//! * The stored RGB is camera RGB divided by per-shot gains, an RGGB entry of ColorData (word +//! 0x80 in version 15; its green is 1170, not the 1024 of the white-balance presets) that +//! roughly neutralises the scene. Multiplying them back gives camera RGB that matches an +//! independent converter's linear camera-RGB output of the same files to a diagonal of +//! (1, 1, 1) ± 1.5 % and 0.6 % RMS; the as-shot white balance then applies as for Bayer data. +//! * The inverse with the BT.601 luma weights (ITU-R BT.601: Y = 0.299 R + 0.587 G + 0.114 B) +//! and unscaled differences (Cb = B − Y, Cr = R − Y) leaves no cross-channel terms above 3 % +//! in that comparison. +//! * Chroma edges follow the luma edges slightly better half an MCU in than at its first +//! sample, so the chroma is treated as centred on its MCU and interpolated bilinearly. +//! +//! Approximate: the chroma siting and the bilinear interpolation (colour edges are softer than +//! in a Bayer development; luma keeps full resolution). The gains are read only for ColorData +//! versions where their offset was observed; for other bodies they are left at 1, which is a +//! diagonal colour error that the matrix fitted to the camera's JPEG absorbs (a warning says +//! so). Older bodies (sRAW before about 2009) are documented elsewhere to use other offsets +//! and chroma scalings; no such sample was available, so they decode with the same rule. +//! Shadow noise below black is clipped at 0 by the conversion. + +use crate::error::{RawError, Result}; +use crate::ljpeg::Frame; +use crate::par; + +/// The de-sliced YCbCr planes: Y at full resolution, Cb and Cr one sample per MCU, stored +/// values (chroma still carries its offset). +pub(crate) struct Planes { + pub width: usize, + pub height: usize, + pub h: usize, + pub v: usize, + pub y: Vec, + pub cb: Vec, + pub cr: Vec, +} + +/// Lays the decoded sample sequence out as planes. `slices` are the slice widths in samples +/// (CR2 tag 0xC640; one slice of the whole MCU row when absent): slice 0 is filled MCU row by +/// MCU row, then slice 1, and so on, as for the Bayer CR2 data. +pub(crate) fn planes(f: &Frame, samples: &[u16], slices: &[usize]) -> Result { + let (h, v) = (f.h, f.v); + let per_mcu = h * v + 2; + let total: usize = slices.iter().sum(); + if total == 0 || !total.is_multiple_of(per_mcu) || slices.iter().any(|w| !w.is_multiple_of(per_mcu)) || !samples.len().is_multiple_of(total) { + return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame")); + } + let mcus = total / per_mcu; + let rows = samples.len() / total; + let (width, height) = (mcus * h, rows * v); + let mut p = Planes { width, height, h, v, y: vec![0; width * height], cb: vec![0; mcus * rows], cr: vec![0; mcus * rows] }; + let mut runs = samples.chunks_exact(per_mcu); + let mut x0 = 0usize; + for &sw in slices { + let n = sw / per_mcu; + for r in 0..rows { + for mx in x0..x0 + n { + let mcu = runs.next().ok_or_else(|| RawError::malformed("CR2 sRAW slice data is short"))?; + let (ys, c) = mcu.split_at(h * v); + for (k, &s) in ys.iter().enumerate() { + let (x, y) = (mx * h + k % h, r * v + k / h); + if let Some(d) = p.y.get_mut(y * width + x) { + *d = s; + } + } + if let ([cb, cr], Some(dcb), Some(dcr)) = (c, p.cb.get_mut(r * mcus + mx), p.cr.get_mut(r * mcus + mx)) { + (*dcb, *dcr) = (*cb, *cr); + } + } + } + x0 += n; + } + Ok(p) +} + +/// White level of unclipped frames: 14-bit full scale less Canon's usual black of about 2048. +pub(crate) const FULL_SCALE: f32 = 14335.0; + +/// BT.601 luma weights of R and B (G's is the rest). +const KR: f32 = 0.299; +const KB: f32 = 0.114; + +/// Interpolates the chroma to every pixel and converts to camera RGB, interleaved: +/// `R = Y + Cr`, `B = Y + Cb`, `G = (Y − KR·R − KB·B) / KG`, then each channel multiplied by the +/// camera's sRAW `gains`. `offset` is the chroma's zero (`2^(P−1)`). +pub(crate) fn camera_rgb(p: &Planes, offset: f32, gains: [f64; 3]) -> Vec { + let (w, h) = (p.width, p.height); + let cw = w / p.h.max(1); + let ch = p.cb.len().checked_div(cw).unwrap_or(0); + let mut out = vec![0u16; w * h * 3]; + if w == 0 || cw == 0 || ch == 0 { + return out; + } + let gains = gains.map(|m| if m.is_finite() && m > 0.0 { m as f32 } else { 1.0 }); + let kg = 1.0 - KR - KB; + // Chroma sample positions: centred on the MCU (see the module docs). Per output column (row): + // the two chroma columns (rows) around it and the weight of the second. + let taps = |n: usize, f: usize, len: usize| -> Vec<(usize, usize, f32)> { + (0..n) + .map(|i| { + let c = ((i as f32 + 0.5) / f as f32 - 0.5).clamp(0.0, (len - 1) as f32); + let a = (c as usize).min(len - 1); + let b = (a + 1).min(len - 1); + (a, b, c - a as f32) + }) + .collect() + }; + let xs = taps(w, p.h.max(1), cw); + let ys = taps(h, p.v.max(1), ch); + let band = par::band_rows(w); + par::chunks_mut(&mut out, band * w * 3, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { + let y = b * band + r; + let (Some(luma), Some(&(ya, yb, fy))) = (p.y.get(y * w..(y + 1) * w), ys.get(y)) else { continue }; + let chroma = |plane: &[u16], xa: usize, xb: usize, fx: f32| { + let at = |cy: usize, cx: usize| plane.get(cy * cw + cx).map_or(offset, |&v| f32::from(v)); + let top = at(ya, xa) * (1.0 - fx) + at(ya, xb) * fx; + let bottom = at(yb, xa) * (1.0 - fx) + at(yb, xb) * fx; + top * (1.0 - fy) + bottom * fy - offset + }; + for ((o, &l), &(xa, xb, fx)) in row.as_chunks_mut::<3>().0.iter_mut().zip(luma).zip(&xs) { + let l = f32::from(l); + let (cb, cr) = (chroma(&p.cb, xa, xb, fx), chroma(&p.cr, xa, xb, fx)); + let (red, blue) = (l + cr, l + cb); + let green = (l - KR * red - KB * blue) / kg; + for (k, v) in [red, green, blue].into_iter().enumerate() { + o[k] = (v * gains[k]).round().clamp(0.0, 65535.0) as u16; + } + } + } + }); + out +} + +/// White level of channel `k` of interleaved RGB: the largest value when a meaningful share of +/// samples piles up there (clipped highlights), else `full`. +pub(crate) fn clip_level(rgb: &[u16], k: usize, full: f32) -> f32 { + let step = 3 * (rgb.len() / 3 / 2_000_000).max(1); + let samples = || rgb.iter().skip(k).step_by(step); + let max = samples().copied().max().unwrap_or(0); + if max == 0 { + return full; + } + let near = samples().filter(|&&v| u32::from(v) + u32::from(max / 256) >= u32::from(max)).count(); + if near * 2000 >= samples().count() { f32::from(max) * 0.995 } else { full.max(f32::from(max)) } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen::Cr2SrawSpec; + use crate::{DevelopOptions, Limits, decode, develop_sensor}; + + const OFFSET: f32 = 16384.0; + + /// A linear ramp of camera RGB (bilinear chroma interpolation reproduces it exactly away + /// from the borders). + fn camera(x: usize, y: usize) -> [f32; 3] { + let (x, y) = (x as f32, y as f32); + [1500.0 + 40.0 * x + 10.0 * y, 2500.0 + 15.0 * x + 30.0 * y, 1200.0 + 5.0 * x + 45.0 * y] + } + + /// The camera's stored YCbCr for `camera` divided by `gains`: Y per pixel, Cb / Cr at the + /// centre of each MCU (the siting the decoder assumes). + fn spec(h: usize, v: usize, gains: [f32; 3], slices: Vec, restart_rows: Option) -> Cr2SrawSpec { + let (w, ht) = (48, 24); + let stored = |x: f32, y: f32| { + let c = camera(0, 0); + let (dx, dy) = (camera(1, 0), camera(0, 1)); + [0, 1, 2].map(|k| (c[k] + (dx[k] - c[k]) * x + (dy[k] - c[k]) * y) / gains[k]) + }; + let ycc = |p: [f32; 3]| { + let y = KR * p[0] + (1.0 - KR - KB) * p[1] + KB * p[2]; + (y, p[2] - y + OFFSET, p[0] - y + OFFSET) + }; + let y = (0..w * ht).map(|i| ycc(stored((i % w) as f32, (i / w) as f32)).0.round() as u16).collect(); + let (mw, mh) = (w / h, ht / v); + let centre = |m: usize, f: usize| (m * f) as f32 + (f as f32 - 1.0) / 2.0; + let chroma: Vec<(f32, f32, f32)> = (0..mw * mh).map(|i| ycc(stored(centre(i % mw, h), centre(i / mw, v)))).collect(); + Cr2SrawSpec { + width: w, + height: ht, + h, + v, + precision: 15, + y, + cb: chroma.iter().map(|c| c.1.round() as u16).collect(), + cr: chroma.iter().map(|c| c.2.round() as u16).collect(), + slices, + restart_rows, + wb_rggb: Some([2048, 1024, 1024, 1536]), + gains: Some([(1170.0 * gains[0]) as u16, 1170, 1170, (1170.0 * gains[2]) as u16]), + borders: Some([0, 2, 47, 23]), + } + } + + #[test] + fn sraw_decodes_to_camera_rgb() { + let gains = [0.75, 1.0, 0.4]; + // sRAW1 (2×2: 6 samples an MCU) and sRAW2 (2×1: 4 samples an MCU), with and without + // slices and restart intervals. + for (h, v, slices, restart) in + [(2, 2, vec![], None), (2, 2, vec![48, 48, 48], Some(3)), (2, 2, vec![60, 60, 24], None), (2, 1, vec![], Some(1)), (2, 1, vec![32, 32, 32], None)] + { + let s = spec(h, v, gains, slices.clone(), restart); + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + assert_eq!((sensor.width, sensor.height, sensor.samples), (48, 24, 3), "{h}x{v} {slices:?}"); + assert!(sensor.cfa.is_none()); + assert_eq!(sensor.crop, crate::Rect::new(0, 2, 48, 22)); + assert_eq!(sensor.camera_wb, Some([2.0, 1.0, 1.5])); + assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings); + for y in 2..22 { + for x in 2..46 { + let at = (y * 48 + x) * 3; + for (k, (&got, want)) in sensor.data[at..at + 3].iter().zip(camera(x, y)).enumerate() { + let got = f32::from(got); + // Rounding of Y, Cb, Cr and the stored gains (whole 1/1170 steps). + assert!((got - want).abs() <= 4.0 + want * 0.002, "{h}x{v} {slices:?} ({x}, {y}) ch {k}: {got} vs {want}"); + } + } + } + } + } + + #[test] + fn unknown_gains_keep_the_stored_colour_and_say_so() { + let mut s = spec(2, 2, [1.0; 3], vec![], None); + s.gains = None; + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + assert!(sensor.warnings.iter().any(|w| w.contains("sRAW colour gains")), "{:?}", sensor.warnings); + let want = camera(10, 10); + let got = &sensor.data[(10 * 48 + 10) * 3..(10 * 48 + 10) * 3 + 3]; + assert!(got.iter().zip(want).all(|(&g, w)| (f32::from(g) - w).abs() <= 4.0), "{got:?} vs {want:?}"); + } + + #[test] + fn sraw_develops_as_linear_rgb() { + let s = spec(2, 1, [0.75, 1.0, 0.4], vec![], None); + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + let d = develop_sensor(&sensor, &DevelopOptions::default()).expect("develop"); + assert_eq!((d.width, d.height), (48, 22)); + assert_eq!(d.info.cfa, None); + assert_eq!(d.info.wb_multipliers, [2.0, 1.0, 1.5]); + } + + #[test] + fn corrupt_sraw_errors_without_panicking() { + let b = spec(2, 2, [0.75, 1.0, 0.4], vec![48, 48, 48], Some(2)).build(); + for n in (0..b.len()).step_by(7) { + let _ = decode(&b[..n], &Limits::default()); + } + let mut s = 0x9E37_79B9u64; + for _ in 0..1500 { + let mut c = b.clone(); + for _ in 0..3 { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let at = (s >> 33) as usize % c.len(); + c[at] = (s >> 20) as u8; + } + if let Ok(sensor) = decode(&c, &Limits::default()) { + let _ = develop_sensor(&sensor, &DevelopOptions::default()); + } + } + // Slices that do not split whole MCUs are refused. + let mut bad = spec(2, 2, [1.0; 3], vec![48, 48, 48], None).build(); + let tag = bad.windows(4).position(|w| w == [0x40, 0xC6, 3, 0]).expect("slice tag"); + let at = u32::from_le_bytes([bad[tag + 8], bad[tag + 9], bad[tag + 10], bad[tag + 11]]) as usize; + bad[at + 2..at + 4].copy_from_slice(&47u16.to_le_bytes()); + assert!(matches!(decode(&bad, &Limits::default()), Err(RawError::Malformed(_)))); + // The planes refuse a sample count that is not whole slice rows. + let f = Frame { precision: 15, width: 4, height: 2, components: 3, h: 2, v: 2 }; + assert!(planes(&f, &[0; 11], &[12]).is_err()); + assert!(planes(&f, &[0; 12], &[0]).is_err()); + } + + #[test] + fn white_level_follows_clipping() { + // A lone bright sample is not clipping. + let mut rgb: Vec = (0..3 * 10_000).map(|i| (i % 5000) as u16).collect(); + rgb[0] = 9000; + assert_eq!(clip_level(&rgb, 0, 14335.0), 14335.0); + for p in rgb.as_chunks_mut::<3>().0.iter_mut().take(100) { + p[1] = 12000; + } + assert!((clip_level(&rgb, 1, 14335.0) - 12000.0 * 0.995).abs() < 1e-3); + assert_eq!(clip_level(&[], 2, 14335.0), 14335.0); + } + + /// Real files: `PHOTOCRAFT_SRAW_CR2` lists CR2 paths (separated by `:`), e.g. EOS 6D Mark II + /// mRAW. Checks the size, the gains and that the development runs. + #[test] + #[ignore = "needs real sRAW CR2 files in PHOTOCRAFT_SRAW_CR2"] + fn real_sraw_files() { + let paths = std::env::var("PHOTOCRAFT_SRAW_CR2").expect("PHOTOCRAFT_SRAW_CR2"); + for path in paths.split(':').filter(|p| !p.is_empty()) { + let bytes = std::fs::read(path).expect("read"); + let s = decode(&bytes, &Limits::default()).expect("decode"); + assert_eq!(s.samples, 3, "{path}"); + assert!(s.cfa.is_none() && s.camera_wb.is_some(), "{path}"); + assert!(s.warnings.is_empty(), "{path}: {:?}", s.warnings); + let d = develop_sensor(&s, &DevelopOptions::default()).expect("develop"); + eprintln!("{path}: {}x{} from {}x{}, white {:?}", d.width, d.height, s.width, s.height, s.white); + } + } +} diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs index b5df57e3c0..7d06459365 100644 --- a/crates/raw/src/testgen.rs +++ b/crates/raw/src/testgen.rs @@ -15,9 +15,9 @@ mod raf; mod rw2; mod tiff; -pub use canon::{Cr2Spec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep}; +pub use canon::{Cr2Spec, Cr2SrawSpec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep}; pub use dng::{DngSpec, DngStorage, baseline_jpeg, gain_map_opcode_list, map_polynomial_opcode_list}; -pub use lj92::{lj92_encode, lj92_encode_tables}; +pub use lj92::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables}; pub use orf::orf; pub use raf::{RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, scene}; pub use rw2::{rw2, rw2_format4, rw2_pack, rw2_v4_pack}; diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs index 33a28d057d..2c4ad54f96 100644 --- a/crates/raw/src/testgen/canon.rs +++ b/crates/raw/src/testgen/canon.rs @@ -1,4 +1,4 @@ -use super::lj92::lj92_encode; +use super::lj92::{lj92_encode, lj92_encode_sraw}; use super::tiff::{TiffBuilder, Val}; // ---------------------------------------------------------------- CR2 @@ -94,6 +94,103 @@ impl Cr2Spec { } } +/// A synthetic Canon sRAW / mRAW CR2: Y, Cb and Cr planes in one subsampled lossless JPEG +/// (see `ljpeg::decode_subsampled` and `sraw.rs`). +#[derive(Debug, Clone)] +pub struct Cr2SrawSpec { + /// Image size in pixels (multiples of `h` and `v`). + pub width: usize, + pub height: usize, + /// Y sampling factors: 2×2 (sRAW1 / mRAW) or 2×1 (sRAW2). + pub h: usize, + pub v: usize, + pub precision: u8, + /// `width * height` Y samples, row-major. + pub y: Vec, + /// One Cb and one Cr per MCU (`width / h` by `height / v`), offset by `2^(precision−1)`. + pub cb: Vec, + pub cr: Vec, + /// Slice widths in samples (all but the last equal); empty = no slice tag. + pub slices: Vec, + /// Restart interval in MCU rows. + pub restart_rows: Option, + /// As-shot RGGB levels at ColorData word 0x3F. + pub wb_rggb: Option<[u16; 4]>, + /// sRAW gains (RGGB) at ColorData word 0x80; ColorData version 15 is written either way. + pub gains: Option<[u16; 4]>, + /// Image borders: left, top, right, bottom (inclusive), as in SensorInfo. + pub borders: Option<[u16; 4]>, +} + +impl Cr2SrawSpec { + pub fn build(&self) -> Vec { + let (h, v) = (self.h, self.v); + let per_mcu = h * v + 2; + let (mcus, rows) = (self.width / h, self.height / v); + let widths: Vec = if self.slices.is_empty() { vec![mcus * per_mcu] } else { self.slices.clone() }; + assert_eq!(widths.iter().sum::(), mcus * per_mcu); + // Slice the MCUs into the JPEG sample order. + let mut seq = Vec::with_capacity(mcus * rows * per_mcu); + let mut m0 = 0; + for &sw in &widths { + assert_eq!(sw % per_mcu, 0); + let n = sw / per_mcu; + for r in 0..rows { + for mx in m0..m0 + n { + for k in 0..h * v { + seq.push(self.y[(r * v + k / h) * self.width + mx * h + k % h]); + } + seq.push(self.cb[r * mcus + mx]); + seq.push(self.cr[r * mcus + mx]); + } + } + m0 += n; + } + let jpeg = lj92_encode_sraw(&seq, self.width, self.height, h, v, self.precision, self.restart_rows); + let mut t = TiffBuilder::default(); + let jb = t.blob(jpeg.clone()); + let mut raw = vec![ + (256, Val::Short(vec![self.width as u16])), + (257, Val::Short(vec![self.height as u16])), + (259, Val::Short(vec![6])), + (273, Val::Blobs(vec![jb])), + (279, Val::Long(vec![jpeg.len() as u32])), + ]; + if !self.slices.is_empty() { + let n = widths.len() - 1; + raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16]))); + } + let raw_ifd = t.ifd(raw); + let mut mn: Vec<(u16, Val)> = Vec::new(); + if let Some([l, tp, r, b]) = self.borders { + mn.push((0x00E0, Val::Short(vec![34, self.width as u16, self.height as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0]))); + } + let mut cd = vec![0u8; 2 * 1602]; + cd[0..2].copy_from_slice(&15u16.to_le_bytes()); + for (at, levels) in [(0x3F, self.wb_rggb), (0x80, self.gains)] { + for (i, v) in levels.iter().flatten().enumerate() { + cd[2 * (at + i)..2 * (at + i) + 2].copy_from_slice(&v.to_le_bytes()); + } + } + mn.push((0x4001, Val::Undefined(cd))); + let mi = t.ifd(mn); + let exif_ifd = t.ifd(vec![(33434, Val::Rational(vec![(1, 100)])), (37500, Val::IfdBytes(mi))]); + let ifd0 = t.ifd(vec![ + (256, Val::Long(vec![2])), + (257, Val::Long(vec![2])), + (271, Val::Ascii("Canon".into())), + (272, Val::Ascii("Canon EOS Synthetic".into())), + (274, Val::Short(vec![1])), + (34665, Val::Ifds(vec![exif_ifd])), + ]); + let ifd1 = t.ifd(vec![(256, Val::Long(vec![1]))]); + let ifd2 = t.ifd(vec![(256, Val::Long(vec![1]))]); + t.chain = vec![ifd0, ifd1, ifd2, raw_ifd]; + t.cr2_raw_ifd = Some(raw_ifd); + t.build() + } +} + // ---------------------------------------------------------------- TIFF/EP /// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the diff --git a/crates/raw/src/testgen/lj92.rs b/crates/raw/src/testgen/lj92.rs index 379d8dfdd0..fe5034c65c 100644 --- a/crates/raw/src/testgen/lj92.rs +++ b/crates/raw/src/testgen/lj92.rs @@ -56,7 +56,6 @@ pub fn lj92_encode(samples: &[u16], width: usize, height: usize, components: usi pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of: &[u8], precision: u8, predictor: u8, restart_rows: Option) -> Vec { let components = table_of.len(); assert_eq!(samples.len(), width * height * components); - assert!(table_of.iter().all(|&t| t < 4)); let row = width * components; let interval = restart_rows.unwrap_or(usize::MAX); // Differences per sample, following T.81 H.1.2.1 prediction rules. @@ -85,16 +84,118 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of _ => (ra + rb) >> 1, } }; - let mut d = (i32::from(samples[i]) - px) & 0xFFFF; - if d > 32768 { - d -= 65536; - } - diffs.push(d); + diffs.push(wrap_diff(i32::from(samples[i]) - px)); } } } + let frame = Frame { + width, + height, + factors: &vec![0x11; components], + table_of, + pattern: &(0..components as u8).collect::>(), + precision, + predictor, + restart: restart_rows.map(|r| (r * width, interval.saturating_mul(row))), + }; + lj92_stream(&diffs, &frame) +} + +/// A difference modulo 2^16, in −32767..=32768 (T.81 H.1.2.2). +fn wrap_diff(d: i32) -> i32 { + let d = d & 0xFFFF; + if d > 32768 { d - 65536 } else { d } +} + +/// Encodes a Canon sRAW / mRAW frame: `seq` is the sample sequence in decode order (per MCU the +/// `h × v` Y samples, then Cb and Cr; `width / h` MCUs a row), predicted as +/// `ljpeg::decode_subsampled` describes: each Y from the previous Y, Cb and Cr from the previous +/// MCU's, the first MCU of a row from the first of the row above. `restart_rows` counts MCU rows. +pub fn lj92_encode_sraw(seq: &[u16], width: usize, height: usize, h: usize, v: usize, precision: u8, restart_rows: Option) -> Vec { + lj92_encode_sraw_tables(seq, width, height, (h, v), [0, 0, 0], precision, restart_rows) +} + +/// Like [`lj92_encode_sraw`], but Y, Cb and Cr use Huffman tables `table_of` (0–3). +pub fn lj92_encode_sraw_tables( + seq: &[u16], + width: usize, + height: usize, + (h, v): (usize, usize), + table_of: [u8; 3], + precision: u8, + restart_rows: Option, +) -> Vec { + let (luma, mcus) = (h * v, width / h); + let per_mcu = luma + 2; + let row_len = mcus * per_mcu; + assert_eq!(seq.len(), row_len * (height / v)); + let interval = restart_rows.unwrap_or(usize::MAX); + let initial = 1i32 << (precision - 1); + let mut diffs = Vec::with_capacity(seq.len()); + let mut top = [initial; 3]; + for (r, row) in seq.chunks_exact(row_len).enumerate() { + if r % interval == 0 { + top = [initial; 3]; + } + let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]); + for (m, mcu) in row.chunks_exact(per_mcu).enumerate() { + for (k, &s) in mcu[..luma].iter().enumerate() { + let pred = if m == 0 && k == 0 { top[0] } else { y }; + diffs.push(wrap_diff(i32::from(s) - pred)); + y = i32::from(s); + if m == 0 && k == 0 { + top[0] = y; + } + } + diffs.push(wrap_diff(i32::from(mcu[luma]) - cb)); + diffs.push(wrap_diff(i32::from(mcu[luma + 1]) - cr)); + (cb, cr) = (i32::from(mcu[luma]), i32::from(mcu[luma + 1])); + if m == 0 { + (top[1], top[2]) = (cb, cr); + } + } + } + let mut pattern = vec![0u8; luma]; + pattern.extend_from_slice(&[1, 2]); + let frame = Frame { + width, + height, + factors: &[(h as u8) << 4 | v as u8, 0x11, 0x11], + table_of: &table_of, + pattern: &pattern, + precision, + predictor: 1, + restart: restart_rows.map(|r| (r * mcus, interval.saturating_mul(row_len))), + }; + lj92_stream(&diffs, &frame) +} + +/// The frame header [`lj92_stream`] writes around the differences. +struct Frame<'a> { + width: usize, + height: usize, + /// Each component's sampling factors (`h << 4 | v`). + factors: &'a [u8], + /// Each component's Huffman table id (0–3). + table_of: &'a [u8], + /// The component of each difference, repeating: `0, 1, 2` interleaved, or an MCU's Y samples + /// then Cb and Cr. + pattern: &'a [u8], + precision: u8, + predictor: u8, + /// The restart interval `(DRI value, differences per interval)`. + restart: Option<(usize, usize)>, +} + +/// Writes SOI, SOF3, one DHT per table id, the restart interval, SOS and the entropy-coded +/// `diffs`. +fn lj92_stream(diffs: &[i32], f: &Frame<'_>) -> Vec { + let components = f.factors.len(); + assert_eq!(f.table_of.len(), components); + assert!(f.table_of.iter().all(|&t| t < 4)); + let table = |i: usize| f.table_of[usize::from(f.pattern[i % f.pattern.len()])]; // Tables: categories ordered by frequency get increasing code lengths. - let mut ids: Vec = table_of.to_vec(); + let mut ids: Vec = f.table_of.to_vec(); ids.sort_unstable(); ids.dedup(); let mut code_of = [[(0u32, 0u32); 17]; 4]; @@ -102,7 +203,7 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of for &t in &ids { let mut freq = [0usize; 17]; for (i, &d) in diffs.iter().enumerate() { - if table_of[i % components] == t { + if table(i) == t { freq[category(d) as usize] += 1; } } @@ -133,12 +234,12 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of // SOF3 out.extend_from_slice(&[0xFF, 0xC3]); out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes()); - out.push(precision); - out.extend_from_slice(&(height as u16).to_be_bytes()); - out.extend_from_slice(&(width as u16).to_be_bytes()); + out.push(f.precision); + out.extend_from_slice(&(f.height as u16).to_be_bytes()); + out.extend_from_slice(&(f.width as u16).to_be_bytes()); out.push(components as u8); - for c in 0..components { - out.extend_from_slice(&[c as u8 + 1, 0x11, 0]); + for (c, &factor) in f.factors.iter().enumerate() { + out.extend_from_slice(&[c as u8 + 1, factor, 0]); } // DHT, one per table id for (t, counts, vals) in &dhts { @@ -148,28 +249,29 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of out.extend_from_slice(counts); out.extend_from_slice(vals); } - if let Some(r) = restart_rows { + if let Some((dri, _)) = f.restart { out.extend_from_slice(&[0xFF, 0xDD, 0, 4]); - out.extend_from_slice(&((r * width) as u16).to_be_bytes()); + out.extend_from_slice(&(dri as u16).to_be_bytes()); } + let every = f.restart.map_or(usize::MAX, |(_, n)| n); // SOS out.extend_from_slice(&[0xFF, 0xDA]); out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes()); out.push(components as u8); - for (c, &t) in table_of.iter().enumerate() { + for (c, &t) in f.table_of.iter().enumerate() { out.extend_from_slice(&[c as u8 + 1, t << 4]); } - out.extend_from_slice(&[predictor, 0, 0]); + out.extend_from_slice(&[f.predictor, 0, 0]); let mut w = BitWriter { out, acc: 0, n: 0 }; let mut rst = 0u8; for (i, &d) in diffs.iter().enumerate() { - if i > 0 && i % (interval.saturating_mul(row)) == 0 { + if i > 0 && i % every == 0 { w.flush(); w.out.extend_from_slice(&[0xFF, 0xD0 + rst]); rst = (rst + 1) % 8; } let s = category(d); - let (c, l) = code_of[usize::from(table_of[i % components])][s as usize]; + let (c, l) = code_of[usize::from(table(i))][s as usize]; w.put(c, l); if (1..16).contains(&s) { let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 }; diff --git a/crates/raw/tests/it/vendors.rs b/crates/raw/tests/it/vendors.rs index 1946899192..e1b70bc88f 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -56,7 +56,8 @@ fn cr2_develops() { #[test] fn cr2_srgb_raw_is_unsupported() { - // A subsampled (sRAW-style) frame: patch the first component's sampling factors. + // A subsampled frame in a layout Canon sRAW does not use (two components, Y 2×1): patch the + // first component's sampling factors. Real sRAW / mRAW decodes (see `sraw.rs`). let mut b = cr2_spec(32, 8, 2, vec![]).build(); let sof = b.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); b[sof + 11] = 0x21; From c075160d0292f6e3cfae3ee208af0ab5520eaa4f Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 14:24:37 -0600 Subject: [PATCH 12/43] Liquify: Preview checkbox and P show the image unwarped Photoshop's Liquify has a Preview checkbox above OK and Cancel (P toggles it): off, the preview shows the image as it was while strokes still change the field. Both preview paths (the proxy and the zoomed-in document-resolution view) now draw through an undisplaced field while Preview is off; turning it back on redraws the warp. The control channel takes and reports "preview". Every opening starts with Preview on. The properties now scroll above the footer instead of under it. Fixes #7905 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/liquify_ui.rs | 53 +++++++++++++++++-- .../ui-egui/src/dialogs/liquify_ui/tests.rs | 53 +++++++++++++++++++ 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 5a6725bcc5..0088789c49 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -265,6 +265,11 @@ pub struct LiquifyDialog { pub preview_ms: f64, /// The smart filter being edited: OK updates it instead of adding a new Liquify filter. smart_filter: Option, + /// Preview (P): off, the image is drawn unwarped while strokes still change the field, as + /// Photoshop's Preview checkbox does (#7905). Every opening starts with it on. + pub preview: bool, + /// The undisplaced field drawn while Preview is off (made when it's first turned off). + identity: Option, } fn union(a: Option<[usize; 4]>, b: [usize; 4]) -> Option<[usize; 4]> { @@ -297,6 +302,7 @@ impl LiquifyDialog { "strokes": self.strokes.len() + usize::from(self.cur.is_some()), "redo": self.redo.len(), "meshSize": self.cell, + "preview": self.preview, "maxDisplacement": self.field.max_displacement(), "proxy": [self.proxy.w, self.proxy.h], "dabMs": self.dab_ms, @@ -438,16 +444,31 @@ impl LiquifyDialog { /// Re-renders the dirty proxy pixels into `out` (the texture upload happens in `show`). fn render_dirty(&mut self) { if let Some(r) = self.dirty { + let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field); if let Some(source) = &self.native_proxy { let bounds = Rect::new(0, 0, self.proxy.w as i32, self.proxy.h as i32); let dirty = Rect::new(r[0] as i32, r[1] as i32, r[2] as i32, r[3] as i32); - render_components(source, bounds, &self.field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out); + render_components(source, bounds, field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out); } else { - self.proxy.render(&self.field, r, &mut self.out); + self.proxy.render(field, r, &mut self.out); } } } + /// Turns Preview on or off: the whole preview is redrawn with, or without, the warp. + pub fn set_preview(&mut self, on: bool) { + if on == self.preview { + return; + } + if !on && self.identity.is_none() { + self.identity = Some(LiquifyField::new(self.canvas, self.cell)); + } + self.preview = on; + self.dirty = Some([0, 0, self.proxy.w, self.proxy.h]); + self.render_dirty(); + self.view_dirty = self.view_bounds; + } + /// Builds or updates the visible source-resolution viewport. At ordinary zoom the whole-layer /// proxy remains cheaper; above 100%, a full-resolution crop is enough to fill the preview. fn update_view_preview(&mut self, ctx: &egui::Context, area: ERect) { @@ -494,10 +515,11 @@ impl LiquifyDialog { return; } let started = crate::gpu_canvas::now_ms(); + let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field); let rendered = if self.native_proxy.is_some() { - render_components(&self.source, self.canvas, &self.field, 1.0, &self.target, bounds, dirty, &mut self.view_out) + render_components(&self.source, self.canvas, field, 1.0, &self.target, bounds, dirty, &mut self.view_out) } else { - ProxyImage::render_full_resolution(&self.source, &self.field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch) + ProxyImage::render_full_resolution(&self.source, field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch) }; if !rendered { self.view_bounds = None; @@ -651,6 +673,8 @@ fn open_on( dab_ms: 0.0, preview_ms: 0.0, smart_filter, + preview: true, + identity: None, }; // A sensible starting brush (about a tenth of the image), then the settings last used, so // Liquify opens as it was left (#418). Saved values are clamped; a bad one is skipped. @@ -720,6 +744,9 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { applied?; let num = |k: &str| ui.get(k).and_then(Value::as_f64).map(|v| v as f32); let flag = |k: &str| ui.get(k).and_then(Value::as_bool); + if let Some(on) = flag("preview") { + d.set_preview(on); + } if flag("undo") == Some(true) { d.undo(); } @@ -839,6 +866,11 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { _ => 1.0, }; } + // P toggles Preview, as in Photoshop (#7905). + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::P)) { + let on = !d.preview; + d.set_preview(on); + } // Ctrl+H (Hide Extras) toggles the red freeze-mask overlay; the mask itself stays active. if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) { d.opts.show_mask = !d.opts.show_mask; @@ -1078,7 +1110,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height())); painter.rect_filled(right, 0.0, t.dock); painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); - let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 12.0)))); + // The properties scroll above the Preview row and the buttons. + let props_rect = ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, (right.bottom() - 84.0).max(right.top() + 12.0))); + let mut props = ui.new_child(egui::UiBuilder::new().max_rect(props_rect)); egui::ScrollArea::vertical().id_salt("liquify-props").show(&mut props, |ui| { ui.spacing_mut().item_spacing.y = 6.0; widgets::section_label(ui, tl!("Brush Tool Options")); @@ -1153,6 +1187,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { .size(11.0), ); }); + // Preview, centred above OK and Cancel as in Photoshop (#7905). + let label_w = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Preview").to_owned(), egui::TextStyle::Body.resolve(ui.style()), t.text).size().x); + let row_w = (label_w + 30.0).min(RIGHT_W - 28.0); + let preview_row = ERect::from_center_size(pos2(right.center().x, right.bottom() - 64.0), vec2(row_w, 24.0)); + let mut pr = ui.new_child(egui::UiBuilder::new().max_rect(preview_row).layout(egui::Layout::left_to_right(egui::Align::Center))); + let mut preview = d.preview; + if widgets::checkbox(&mut pr, &mut preview, tl!("Preview")).changed() { + d.set_preview(preview); + } // Footer buttons. let foot = ERect::from_min_size(pos2(right.left() + 14.0, right.bottom() - 48.0), vec2(RIGHT_W - 28.0, 32.0)); let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 546cd00f91..4761d455c8 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -1017,3 +1017,56 @@ fn workspaces_open_on_a_smart_object_with_its_filter_mask_targeted() { let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { panic!("not a smart object") }; assert_eq!(sm.smart_filters.iter().map(|f| f.command.as_str()).collect::>(), ["filter.blur.gaussianBlur", photocraft_engine::distort_cmds::LIQUIFY]); } + +/// Preview off shows the image unwarped while strokes still change the field, and P turns it back +/// on, as Photoshop's Liquify Preview checkbox does (#7905). Each opening starts with it on. +#[test] +fn preview_off_shows_the_original_and_p_toggles_it() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let render = |d: &LiquifyDialog, field: &LiquifyField| { + let mut out = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; + d.proxy.render(field, [0, 0, d.proxy.w, d.proxy.h], &mut out); + out + }; + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview && d.describe()["preview"] == json!(true), "Liquify opens with Preview on"); + let original = render(d, &LiquifyField::new(d.canvas, d.cell)); + let stroke = |app: &mut PhotocraftApp, y: f64| { + for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] { + pointer(app, ev, egui::Modifiers::NONE); + } + }; + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + stroke(&mut app, 40.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_ne!(d.out, original, "the warp shows"); + + let r = control(&mut app, &json!({"preview": false})).unwrap(); + assert_eq!(r["preview"], json!(false)); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.out, original, "Preview off: the image as it was"); + // A stroke with Preview off still warps the field, unseen. + stroke(&mut app, 30.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 2); + assert_eq!(d.out, original, "still unwarped while Preview is off"); + { + let d = app.distort.liquify.as_mut().unwrap(); + d.zoom = 2.0; + d.view_bounds = Some(Rect::new(0, 0, 20, 20)); + d.view_dirty = None; + } + + // P turns it back on, with both strokes. + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + ctx.begin_pass(input); + keys(&mut app, &ctx); + ctx.end_pass().textures_delta.clear(); + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview); + assert_eq!(d.out, render(d, &d.field), "Preview on: the warp of both strokes"); + assert_eq!(d.view_dirty, d.view_bounds, "the zoomed preview is redrawn too"); +} From 41caec921dc1591ff5d40de3a7b65c4159c60b5f Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 15:14:52 -0600 Subject: [PATCH 13/43] Re-run CI A CI job failed in photocraft-compose's proptest the_split_route_agrees_with_the_exact_path (flaky on main, #10386), which this PR doesn't touch. Co-Authored-By: Claude Opus 5.5 From 093f5ba6ac976d5882ba557d6f644aba7d08efa0 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 22:33:01 -0600 Subject: [PATCH 14/43] Liquify: test strokes and OK with Preview off (FredApps review on liquify_ui.rs) A stroke with Preview off changes the displacement field but not the display, and OK with Preview off applies the same warp as with Preview on. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/dialogs/liquify_ui/tests.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 4761d455c8..c2c1a64237 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -1070,3 +1070,57 @@ fn preview_off_shows_the_original_and_p_toggles_it() { assert_eq!(d.out, render(d, &d.field), "Preview on: the warp of both strokes"); assert_eq!(d.view_dirty, d.view_bounds, "the zoomed preview is redrawn too"); } + +/// A forward-warp stroke across the test layer, at row `y`. +fn warp_stroke(app: &mut PhotocraftApp, y: f64) { + for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] { + pointer(app, ev, egui::Modifiers::NONE); + } +} + +/// The active layer's pixels over the whole document. +fn layer_pixels(app: &PhotocraftApp) -> Vec { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 120, 80)) +} + +/// With Preview off, a stroke changes the displacement field but the display stays the original +/// image (#7905). +#[test] +fn a_stroke_with_preview_off_changes_the_field_but_not_the_display() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": false})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + let (field_before, shown_before) = (d.field.clone(), d.out.clone()); + assert_eq!(d.field.max_displacement(), 0.0); + warp_stroke(&mut app, 40.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_ne!(d.field, field_before, "the stroke changes the field"); + assert!(d.field.max_displacement() > 3.0); + assert_eq!(d.out, shown_before, "the display does not change"); +} + +/// OK with Preview off applies the warp: the layer ends up exactly as it does when the same stroke +/// is committed with Preview on. +#[test] +fn ok_with_preview_off_applies_the_warp() { + let ctx = egui::Context::default(); + let commit_with = |preview: bool| { + let mut app = app_with_layer(); + let before = layer_pixels(&app); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": preview})).unwrap(); + warp_stroke(&mut app, 40.0); + let past = app.session.active().unwrap().history.past_len(); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1, "one Liquify step"); + (before, layer_pixels(&app)) + }; + let (before, unpreviewed) = commit_with(false); + assert_ne!(unpreviewed, before, "OK with Preview off warps the layer"); + assert_eq!(unpreviewed, commit_with(true).1, "the same warp as with Preview on"); +} + From d82e631e2b5aa6943491fc0a14a9ba517d8ab0ba Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 22:33:01 -0600 Subject: [PATCH 15/43] Liquify: free the identity field when Preview is turned back on (FredApps review on liquify_ui.rs) The identity field is as large as the image's displacement field. It was made when Preview was first turned off and then kept until the dialog closed; now it exists only while Preview is off. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/liquify_ui.rs | 7 +++---- .../ui-egui/src/dialogs/liquify_ui/tests.rs | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 0088789c49..6315076cb5 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -268,7 +268,8 @@ pub struct LiquifyDialog { /// Preview (P): off, the image is drawn unwarped while strokes still change the field, as /// Photoshop's Preview checkbox does (#7905). Every opening starts with it on. pub preview: bool, - /// The undisplaced field drawn while Preview is off (made when it's first turned off). + /// The undisplaced field drawn while Preview is off. It is as large as `field`, so it exists + /// only while Preview is off: made when Preview is turned off, freed when it's turned back on. identity: Option, } @@ -460,9 +461,7 @@ impl LiquifyDialog { if on == self.preview { return; } - if !on && self.identity.is_none() { - self.identity = Some(LiquifyField::new(self.canvas, self.cell)); - } + self.identity = (!on).then(|| LiquifyField::new(self.canvas, self.cell)); self.preview = on; self.dirty = Some([0, 0, self.proxy.w, self.proxy.h]); self.render_dirty(); diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index c2c1a64237..f5fc2b5ec6 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -1124,3 +1124,24 @@ fn ok_with_preview_off_applies_the_warp() { assert_eq!(unpreviewed, commit_with(true).1, "the same warp as with Preview on"); } +/// The identity field (as large as the image's field) exists only while Preview is off: turning +/// Preview back on frees it, and closing the dialog drops it. +#[test] +fn the_identity_field_exists_only_while_preview_is_off() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let identity = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().identity.is_some(); + assert!(!identity(&app), "not made while Preview is on"); + control(&mut app, &json!({"preview": false})).unwrap(); + assert!(identity(&app)); + control(&mut app, &json!({"preview": true})).unwrap(); + assert!(!identity(&app), "freed when Preview is turned back on"); + control(&mut app, &json!({"preview": false})).unwrap(); + assert!(identity(&app), "made again when Preview is turned off again"); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert!(app.distort.liquify.is_none(), "closing drops the dialog and its identity field"); + open(&mut app, &ctx).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview && d.identity.is_none(), "a new opening starts with Preview on and no identity field"); +} From 856c6e9398810f8c2b5ef2b3841c9e88bd56f588 Mon Sep 17 00:00:00 2001 From: Lcoding15 <125505497+Lcoding15@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:17:41 +0100 Subject: [PATCH 16/43] Actions: typed text records as one step; Batch says which files failed (#10113, #10682) While an action recorded, the Type tool's every keystroke (a type.edit with the session's coalesce key) became a step. A typing session now folds into the type.create that made the layer (its text becomes the layer's text) or into one type.edit setting the whole text, with no layer id, so it plays on the new or current type layer of any document. Batch and the other folder runs went on past a file that failed and only listed it in the result's errors, which no UI showed: a Batch whose action failed on every file looked like nothing happened. The status bar and a notice now name each file that failed and why. --- crates/engine/src/cmd/type_cmds.rs | 43 +++++++++++++ crates/engine/src/cmd/type_cmds/tests.rs | 67 +++++++++++++++++++++ crates/engine/src/jobs.rs | 2 +- crates/ui-egui/src/dialogs.rs | 21 +++++++ crates/ui-egui/src/menus/view_cmds/tests.rs | 61 +++++++++++++++++++ 5 files changed, 193 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index 58a2145409..7970b9f7ce 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -910,6 +910,49 @@ pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result bool { + let Some((from, _)) = s.actions.recording else { return false }; + if id != "type.edit" { + return false; + } + let Some(st) = s.active() else { return false }; + let Some(layer) = params.get("layer").and_then(Value::as_u64) else { return false }; + if st.active_layer != Some(LayerId(layer)) { + return false; + } + let typing = + params.as_object().is_some_and(|o| o.keys().all(|k| TYPING_KEYS.contains(&k.as_str())) && (o.contains_key("replace") || o.contains_key("text"))); + let key = params.get("coalesce").filter(|k| !k.is_null()).cloned(); + let (Some(key), true) = (key, typing) else { return false }; + let Some(text) = st.doc.layer(LayerId(layer)).and_then(|l| match &l.content { + LayerContent::Text(t) => Some(t.text.clone()), + _ => None, + }) else { + return false; + }; + // The newest layer was made by the step before: the type tool makes a layer, then types in it. + let newest = st.doc.walk().into_iter().map(|(_, _, l)| l.id.0).max() == Some(layer); + let last = s.journal.len().checked_sub(1).filter(|&i| i >= from); + match last.and_then(|i| s.journal.get_mut(i)) { + Some((last_id, p)) if last_id == "type.create" && newest => p["text"] = json!(text), + Some((last_id, p)) if last_id == "type.edit" && p.get("coalesce") == Some(&key) && p.get("layer").is_none() => { + *p = json!({"text": text, "coalesce": key}); + } + _ => s.journal.push((id.to_string(), json!({"text": text, "coalesce": key}))), + } + true +} + pub fn specs() -> Vec { vec![ CommandSpec { diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index b9851d27e1..bce1c1b5b0 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -793,3 +793,70 @@ fn relative_steps_move_each_character_from_its_own_value() { s.execute("type.setStyle", json!({"layer": empty, "range": [0, 0], "leadingBy": -2})).unwrap(); assert_eq!(text_layer(&s, empty).char_runs()[0].style.leading_pt, Some(10.0)); } + +/// Keystrokes as the Type tool sends them: one `replace` per character, in one session. +fn type_in(s: &mut Session, layer: u64, at: usize, text: &str, session: &str) { + for (i, c) in text.chars().enumerate() { + let p = json!({"layer": layer, "replace": {"start": at + i, "end": at + i, "text": c.to_string()}, "coalesce": session}); + s.execute("type.edit", p).unwrap(); + } +} + +fn the_active_text(s: &Session) -> String { + let d = s.active().unwrap(); + match &d.doc.layer(d.active_layer.unwrap()).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + other => panic!("{}", other.kind_name()), + } +} + +/// #10113: recording a new type layer records one "make a text layer" step with the typed text, +/// not one step per keystroke, and it names no layer id, so Batch plays it in other documents. +#[test] +fn recording_typed_text_records_one_step_that_plays_in_another_document() { + let mut s = session(); + s.execute("actions.record", json!({"name": "Caption"})).unwrap(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + type_in(&mut s, id, 0, "Hello", "s1"); + s.execute("actions.stop", json!({})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps.len(), 1, "one step, not one per keystroke: {steps:?}"); + assert_eq!(steps[0].0, "type.create"); + assert_eq!(steps[0].1["text"], "Hello"); + assert!(steps[0].1.get("layer").is_none()); + // Another document, as Batch opens one per file. + s.execute("file.new", json!({"width": 120, "height": 80})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Caption"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(the_active_text(&s), "Hello"); +} + +/// Typing into an existing type layer records one "set the current text layer's text" step with +/// no layer id; it plays on the current type layer of another document. +#[test] +fn recording_an_edit_of_existing_text_records_the_whole_text_once() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Hi", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + s.execute("actions.record", json!({"name": "Greet"})).unwrap(); + type_in(&mut s, id, 2, " there", "s2"); + s.execute("actions.stop", json!({})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps.len(), 1, "{steps:?}"); + assert_eq!((steps[0].0.as_str(), steps[0].1.get("layer"), steps[0].1["text"].as_str()), ("type.edit", None, Some("Hi there"))); + s.execute("file.new", json!({"width": 120, "height": 80, "background": "transparent"})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 40, "text": "Hey", "size": 24})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Greet"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(the_active_text(&s), "Hi there"); +} + +/// Outside a recording the journal keeps every edit as it ran. +#[test] +fn typing_without_recording_keeps_the_journal_as_it_ran() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + let before = s.journal.len(); + type_in(&mut s, id, 0, "abc", "s3"); + assert_eq!(s.journal.len(), before + 3); + assert!(s.journal.iter().rev().take(3).all(|(id, p)| id == "type.edit" && p.get("replace").is_some())); +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ac9e38a723..078210ccd2 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -959,7 +959,7 @@ impl Session { if let Some(from) = nested_from.filter(|_| crate::actions_cmds::replayable(id)) { self.journal.truncate(from); } - if !crate::brush_cmds::coalesce_journal(self, id, ¶ms) { + if !crate::brush_cmds::coalesce_journal(self, id, ¶ms) && !crate::type_cmds::coalesce_journal(self, id, ¶ms) { let params = match id { _ if self.actions.recording.is_none() => params, "layer.duplicate" => crate::artboard_cmds::recorded_duplicate(self, crate::layer_multi_cmds::recorded_step(self, id, params, pre_selected)), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d38a75f101..cd613b0160 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -895,6 +895,24 @@ fn file_command(fields: &Fields) -> Option<&'static str> { /// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's /// parameters, then settle the filter preview and the playing action. +/// Batch and the other folder runs (Image Processor, …) go on past a file that fails and list it +/// in their result's `errors`; the status bar and a notice say which files failed and why, so a run +/// that fails on every file isn't silent (#10682). +fn report_file_errors(app: &mut PhotocraftApp, d: &Dialog, r: &Value) { + let Some(errors) = r.get("errors").and_then(Value::as_array).filter(|e| !e.is_empty()) else { return }; + let lines: Vec = errors + .iter() + .map(|e| { + let file = e.get("file").and_then(Value::as_str).unwrap_or_default(); + let name = std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned()); + format!("{name}: {}", e.get("error").and_then(Value::as_str).unwrap_or_default()) + }) + .collect(); + let label = d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command"); + let what = crate::i18n::t(label).trim_end_matches('…').to_string(); + crate::notices::io_warnings(app, &what, &lines); +} + fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result { let Some(cmd) = d.fields.get("__command").and_then(Value::as_str).map(str::to_string) else { app.filter_preview = None; @@ -926,6 +944,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result Date: Mon, 2 Nov 2026 19:40:33 +0000 Subject: [PATCH 17/43] #10113, #10682: fold typing only into its own document's new layer, keep styled edits apart, name failed files whole Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GbuSKAS2k5248LGFEapMUR --- crates/engine/src/cmd/actions_cmds.rs | 5 +++ crates/engine/src/cmd/type_cmds.rs | 30 ++++++++++++------ crates/engine/src/cmd/type_cmds/tests.rs | 34 +++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 12 ++++---- crates/ui-egui/src/menus/view_cmds/tests.rs | 5 ++- crates/ui-egui/src/notices.rs | 12 ++++++++ 6 files changed, 82 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index ea68d86b50..8c5135f38b 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -119,6 +119,11 @@ pub struct ActionState { /// started in is still the one running when its result lands. #[serde(skip)] pub take: u64, + /// The document and type layer the last recorded `type.create` made, while recording: the + /// typing that follows folds into that step only when it types in that layer of that + /// document (`type_cmds::coalesce_journal`, #10113). + #[serde(skip)] + pub typing_layer: Option<(u64, u64)>, } /// Visibility gestures name a layer for replay, since document-local ids change on another image. diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index 7970b9f7ce..cf3859415a 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -915,13 +915,20 @@ const TYPING_KEYS: [&str; 4] = ["layer", "coalesce", "replace", "text"]; /// While an action records, one typing session is one step, as Photoshop records "Make text /// layer" or "Set current text layer" once (#10113). Its keystrokes (`type.edit` with the -/// session's `coalesce` key, changing the text) fold into the `type.create` that made the layer, -/// whose `text` becomes the layer's text, or into one `type.edit` that sets the whole text. Neither -/// names the layer, so the step plays on the new or the current type layer of any document, as -/// Batch needs. Other edits are journaled as before (`recorded_step` drops the id of a sole -/// selected layer). Returns true when it journaled the step itself. +/// session's `coalesce` key, changing the text) fold into the `type.create` that made the layer +/// (in the same document), whose `text` becomes the layer's text, or into one `type.edit` that +/// sets the whole text. Neither names the layer, so the step plays on the new or the current type +/// layer of any document, as Batch needs. A layer with more than one character or paragraph style +/// keeps a step per edit, as before: setting its whole text would give it one style on replay. +/// Other edits are journaled as before (`recorded_step` drops the id of a sole selected layer). +/// Returns true when it journaled the step itself. pub fn coalesce_journal(s: &mut Session, id: &str, params: &Value) -> bool { let Some((from, _)) = s.actions.recording else { return false }; + if id == "type.create" { + // Remembered for the typing that follows; journaled as usual. + s.actions.typing_layer = s.active().and_then(|st| Some((st.doc.id.0, st.active_layer?.0))); + return false; + } if id != "type.edit" { return false; } @@ -935,16 +942,16 @@ pub fn coalesce_journal(s: &mut Session, id: &str, params: &Value) -> bool { let key = params.get("coalesce").filter(|k| !k.is_null()).cloned(); let (Some(key), true) = (key, typing) else { return false }; let Some(text) = st.doc.layer(LayerId(layer)).and_then(|l| match &l.content { - LayerContent::Text(t) => Some(t.text.clone()), + LayerContent::Text(t) if one_style(&t.runs, |r| &r.style) && one_style(&t.paragraphs, |r| &r.style) => Some(t.text.clone()), _ => None, }) else { return false; }; - // The newest layer was made by the step before: the type tool makes a layer, then types in it. - let newest = st.doc.walk().into_iter().map(|(_, _, l)| l.id.0).max() == Some(layer); + // The step before made this very layer: the type tool makes a layer, then types in it. + let made_here = s.actions.typing_layer == Some((st.doc.id.0, layer)); let last = s.journal.len().checked_sub(1).filter(|&i| i >= from); match last.and_then(|i| s.journal.get_mut(i)) { - Some((last_id, p)) if last_id == "type.create" && newest => p["text"] = json!(text), + Some((last_id, p)) if last_id == "type.create" && made_here => p["text"] = json!(text), Some((last_id, p)) if last_id == "type.edit" && p.get("coalesce") == Some(&key) && p.get("layer").is_none() => { *p = json!({"text": text, "coalesce": key}); } @@ -953,6 +960,11 @@ pub fn coalesce_journal(s: &mut Session, id: &str, params: &Value) -> bool { true } +/// Do `runs` all have the same style? +fn one_style(runs: &[R], style: impl Fn(&R) -> &S) -> bool { + runs.windows(2).all(|w| matches!(w, [a, b] if style(a) == style(b))) +} + pub fn specs() -> Vec { vec![ CommandSpec { diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index bce1c1b5b0..2f779df3c4 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -860,3 +860,37 @@ fn typing_without_recording_keeps_the_journal_as_it_ran() { assert_eq!(s.journal.len(), before + 3); assert!(s.journal.iter().rev().take(3).all(|(id, p)| id == "type.edit" && p.get("replace").is_some())); } + +/// CodeRabbit on #10730: typing in a type layer of another document, switched to as a tab is +/// (no step), after a recorded `type.create` is no part of that step, even with the same layer id. +#[test] +fn typing_in_another_document_is_not_folded_into_the_layer_made_in_the_first() { + let mut s = session(); + let other = s.execute("type.create", json!({"x": 10, "y": 40, "text": "Old", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + s.execute("actions.record", json!({"name": "Two"})).unwrap(); + let made = s.execute("type.create", json!({"x": 20, "y": 50, "text": "", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(made, other, "the setup gives both layers one id"); + assert!(s.set_active(0)); + type_in(&mut s, other, 3, "!", "s4"); + s.execute("actions.stop", json!({})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps.len(), 2, "{steps:?}"); + assert_eq!((steps[0].0.as_str(), steps[0].1["text"].as_str()), ("type.create", Some("")), "the new layer keeps its own text"); + assert_eq!((steps[1].0.as_str(), steps[1].1["text"].as_str()), ("type.edit", Some("Old!"))); +} + +/// CodeRabbit on #10730: typing in a layer with more than one style keeps a step per edit, as +/// before: a step setting its whole text would give all of it one style on replay. +#[test] +fn typing_in_styled_text_keeps_a_step_per_edit() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Hi there", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [3, 8], "fauxBold": true})).unwrap(); + s.execute("actions.record", json!({"name": "Bold"})).unwrap(); + type_in(&mut s, id, 8, "!!", "s5"); + s.execute("actions.stop", json!({})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps.len(), 2, "{steps:?}"); + assert!(steps.iter().all(|(id, p)| id == "type.edit" && p.get("replace").is_some()), "{steps:?}"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a3153f7146..82af02034f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -895,26 +895,26 @@ fn file_command(fields: &Fields) -> Option<&'static str> { } } -/// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's -/// parameters, then settle the filter preview and the playing action. /// Batch and the other folder runs (Image Processor, …) go on past a file that fails and list it /// in their result's `errors`; the status bar and a notice say which files failed and why, so a run -/// that fails on every file isn't silent (#10682). +/// that fails on every file isn't silent (#10682). Each file is named by its whole path: files of +/// the same name in different subfolders are told apart. fn report_file_errors(app: &mut PhotocraftApp, d: &Dialog, r: &Value) { let Some(errors) = r.get("errors").and_then(Value::as_array).filter(|e| !e.is_empty()) else { return }; let lines: Vec = errors .iter() .map(|e| { let file = e.get("file").and_then(Value::as_str).unwrap_or_default(); - let name = std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned()); - format!("{name}: {}", e.get("error").and_then(Value::as_str).unwrap_or_default()) + format!("{file}: {}", e.get("error").and_then(Value::as_str).unwrap_or_default()) }) .collect(); let label = d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command"); let what = crate::i18n::t(label).trim_end_matches('…').to_string(); - crate::notices::io_warnings(app, &what, &lines); + crate::notices::file_failures(app, &what, &lines); } +/// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's +/// parameters, then settle the filter preview and the playing action. fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result { let Some(cmd) = d.fields.get("__command").and_then(Value::as_str).map(str::to_string) else { app.filter_preview = None; diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 08d6cf4add..7252d65871 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -504,7 +504,10 @@ fn a_batch_that_fails_on_its_files_says_which_and_why() { assert!(app.ui.status_error, "the status bar reports it: {}", app.ui.status); let notice = app.ui.notices.get(notices).expect("a notice lists the files"); assert_eq!(notice.lines.len(), 2); - assert!(notice.lines[0].starts_with("a.png: ") && notice.lines[1].starts_with("b.png: "), "{:?}", notice.lines); + // CodeRabbit on #10730: a failure, not a warning, and each file by its whole path. + assert!(notice.error && notice.title.ends_with("2 files failed"), "{}", notice.title); + let path = |name: &str| format!("{}: ", dir.join("in").join(name).to_string_lossy()); + assert!(notice.lines[0].starts_with(&path("a.png")) && notice.lines[1].starts_with(&path("b.png")), "{:?}", notice.lines); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index 4b3ae45cac..2b26aa4b20 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -167,6 +167,18 @@ pub fn io_warnings(app: &mut PhotocraftApp, what: &str, warnings: &[String]) { post(app, title, warnings.to_vec(), false, None); } +/// Report the files a folder run (Batch, Image Processor, …) could not process, one line each: +/// the status bar shows the first as an error, and a notice titled with how many failed lists +/// them all until dismissed (#10682). +pub fn file_failures(app: &mut PhotocraftApp, what: &str, failures: &[String]) { + let Some(first) = failures.first() else { return }; + let n = failures.len(); + let title = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n as u64, "{what}: {n} file failed", "{what}: {n} files failed"), &[("what", what)]); + app.ui.status = if n == 1 { format!("{what}: {first}") } else { format!("{title}: {first} …") }; + app.ui.status_error = true; + post(app, title, failures.to_vec(), true, None); +} + /// Report a failed file operation: the status bar shows it as an error and a notice keeps it on /// screen until dismissed. pub fn error(app: &mut PhotocraftApp, message: String) { From 468e092bffcfeba500c22b16d47452e17852a2e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 20:45:05 +0000 Subject: [PATCH 18/43] #10113: layer ids are unique across documents; the test types in the first one's newest layer Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GbuSKAS2k5248LGFEapMUR --- crates/engine/src/cmd/type_cmds/tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index 2f779df3c4..256a02e663 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -862,15 +862,16 @@ fn typing_without_recording_keeps_the_journal_as_it_ran() { } /// CodeRabbit on #10730: typing in a type layer of another document, switched to as a tab is -/// (no step), after a recorded `type.create` is no part of that step, even with the same layer id. +/// (no step), after a recorded `type.create` is no part of that step, though that layer is the +/// newest of its own document. #[test] fn typing_in_another_document_is_not_folded_into_the_layer_made_in_the_first() { let mut s = session(); let other = s.execute("type.create", json!({"x": 10, "y": 40, "text": "Old", "size": 24})).unwrap()["layer"].as_u64().unwrap(); s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); s.execute("actions.record", json!({"name": "Two"})).unwrap(); - let made = s.execute("type.create", json!({"x": 20, "y": 50, "text": "", "size": 24})).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(made, other, "the setup gives both layers one id"); + s.execute("type.create", json!({"x": 20, "y": 50, "text": "", "size": 24})).unwrap(); + // Back in the first document, its own type layer is its newest layer. assert!(s.set_active(0)); type_in(&mut s, other, 3, "!", "s4"); s.execute("actions.stop", json!({})).unwrap(); From 91e86c5fb64aeca904c36ecab42831dc55e153b2 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:58:16 +0400 Subject: [PATCH 19/43] Levels clipping: draw on the main canvas only (#3328) canvas_view runs once per viewport, and the display keeps one cache and texture sized to its view. Extra document windows no longer draw it or replace that cache. --- crates/ui-egui/src/canvas.rs | 7 ++-- crates/ui-egui/src/levels_clipping_tests.rs | 38 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 9080a198e9..fa6ddab638 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -113,12 +113,12 @@ use tabs::{dots, paint_dots}; use tabs::{main_canvas_document, move_target_after_filter}; #[cfg(test)] pub(crate) use textures::detail_plan; +pub(crate) use textures::visible_doc_rect; pub(crate) use textures::{DetailPlan, damage_since, effect_reach, ensure_texture_in_view, retain_gpu_documents, shown_as_document}; pub use textures::{MAX_TEXTURE, ensure_texture}; #[cfg(test)] use textures::{clamp_texture_side, preview_bounds, texture_factor}; use textures::{ensure_gpu, redraw_focus}; -pub(crate) use textures::visible_doc_rect; pub use tool_input::{ToolEvent, selection_drag_kind, tool_event}; pub(crate) use tool_input::{command_guide_at, command_moves_layer, event_tool}; pub(crate) use transform_controls::{LAYER_EDGES, layer_edges_rect}; @@ -505,7 +505,10 @@ fn paint_canvas( } } // Image › Adjustments › Levels: Alt-drag on the black / white Input slider (levels_clipping.rs). - crate::levels_clipping::paint(app, ctx, painter, &xf, idx); + // The main canvas only: the display keeps one cache, sized to that view. + if primary { + crate::levels_clipping::paint(app, ctx, painter, &xf, idx); + } crate::color_range_ui::paint_selection_preview(app, ctx, painter, doc.id, img_rect, flip); // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). if doc.has_artboards() { diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index c4f25d69fe..85fc01ca98 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -234,6 +234,44 @@ fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> O Some(image(&c.stats, &thr, end)) } +/// How many meshes among `shapes` (shape lists included) draw texture `tex`. +fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize { + fn count(s: &egui::Shape, tex: egui::TextureId) -> usize { + match s { + egui::Shape::Mesh(m) => usize::from(m.texture_id == tex), + egui::Shape::Vec(v) => v.iter().map(|s| count(s, tex)).sum(), + _ => 0, + } + } + shapes.iter().map(|c| count(&c.shape, tex)).sum() +} + +/// The display keeps one cache, sized to the main canvas's view: an extra document window's +/// canvas (not primary) neither draws it nor replaces that cache with its own view. +#[test] +fn only_the_main_canvas_draws_the_display() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + app.sync_views(); + let main = crate::state::View { zoom: 10.0, center: [8.0, 4.0], fit_pending: false, fill_pending: false, ..app.ui.views[0].clone() }; + let other = crate::state::View { zoom: 0.25, ..main.clone() }; + let frame = |app: &mut PhotocraftApp, view: &crate::state::View, primary: bool| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + crate::canvas::canvas_view(app, ui, 0, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(160.0, 80.0)), view.clone(), primary); + }); + out.textures_delta.clear(); + out.shapes + }; + let shapes = frame(&mut app, &main, true); + let cache = app.levels_clipping.as_ref().expect("the main canvas builds the display"); + let (key, tex) = (cache.key, cache.tex.as_ref().map(egui::TextureHandle::id).expect("its texture")); + assert_eq!(meshes_with(&shapes, tex), 1, "the main canvas draws the display"); + let shapes = frame(&mut app, &other, false); + assert_eq!(meshes_with(&shapes, tex), 0, "an extra window doesn't draw it"); + assert_eq!(app.levels_clipping.as_ref().map(|c| c.key), Some(key), "nor replaces the main canvas's cache"); +} + /// The display covers the view at about one texel per screen pixel, in every depth and in Gray, /// and goes away with the dialog. #[test] From c907fe59f1a2053c2cee7d74df7dd2e61c9eaed0 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:00:48 +0400 Subject: [PATCH 20/43] Levels clipping: doc comments on name, request and paint (#3328) --- crates/ui-egui/src/levels_clipping.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 312a10cabd..27e6e2c64a 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -49,6 +49,7 @@ pub enum ClipEnd { } impl ClipEnd { + /// The [`FIELD`] value that asks for this end. fn name(self) -> &'static str { match self { ClipEnd::Shadows => "shadows", @@ -270,7 +271,7 @@ pub fn image(stats: &Stats, thresholds: &Thresholds, end: ClipEnd) -> Vec Option<&Map> { app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels")) } +/// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog +/// shows clipping, `idx` isn't the active document, or the document can't show it: CMYK and Lab, +/// a channel, mask or Quick Mask target, or a target that isn't a pixel layer. fn request(app: &PhotocraftApp, idx: usize) -> Option { let fields = dialog(app)?; let end = ClipEnd::parse(fields.get(FIELD))?; @@ -333,7 +337,8 @@ fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(R } /// Draw the Levels clipping display over the image in canvas view `xf` of document `idx`, if one -/// is asked for. Drops the cache once no Levels dialog is open. +/// is asked for. Drops the cache once no Levels dialog is open. Only the main canvas calls it: +/// the one cache follows that view. pub fn paint(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, idx: usize) { if dialog(app).is_none() { app.levels_clipping = None; From dfdb3a782738294a9739be76f251f7202a8cdb1e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 06:05:00 +0000 Subject: [PATCH 21/43] #10113: typing in another document is a step of its own; an edit naming no layer coalesces Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GbuSKAS2k5248LGFEapMUR --- crates/engine/src/cmd/actions_cmds.rs | 6 ++-- crates/engine/src/cmd/type_cmds.rs | 14 +++++---- crates/engine/src/cmd/type_cmds/tests.rs | 33 +++++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/tests.rs | 6 ++++ 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 8c5135f38b..bfbb2f910a 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -119,9 +119,9 @@ pub struct ActionState { /// started in is still the one running when its result lands. #[serde(skip)] pub take: u64, - /// The document and type layer the last recorded `type.create` made, while recording: the - /// typing that follows folds into that step only when it types in that layer of that - /// document (`type_cmds::coalesce_journal`, #10113). + /// The document and type layer the last recorded `type.create` made, or the last recorded + /// typing edited, while recording: the typing that follows folds into that step only when it + /// types in that layer of that document (`type_cmds::coalesce_journal`, #10113). #[serde(skip)] pub typing_layer: Option<(u64, u64)>, } diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index cf3859415a..987f101bf4 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -933,7 +933,8 @@ pub fn coalesce_journal(s: &mut Session, id: &str, params: &Value) -> bool { return false; } let Some(st) = s.active() else { return false }; - let Some(layer) = params.get("layer").and_then(Value::as_u64) else { return false }; + // An edit that names no layer edits the active one, and coalesces the same. + let Some(layer) = params.get("layer").and_then(Value::as_u64).or(st.active_layer.map(|l| l.0)) else { return false }; if st.active_layer != Some(LayerId(layer)) { return false; } @@ -947,16 +948,19 @@ pub fn coalesce_journal(s: &mut Session, id: &str, params: &Value) -> bool { }) else { return false; }; - // The step before made this very layer: the type tool makes a layer, then types in it. - let made_here = s.actions.typing_layer == Some((st.doc.id.0, layer)); + // The step before made, or typed in, this very layer of this document: the type tool makes a + // layer, then types in it. Typing in another document is a step of its own. + let here = Some((st.doc.id.0, layer)); + let same_target = s.actions.typing_layer == here; let last = s.journal.len().checked_sub(1).filter(|&i| i >= from); match last.and_then(|i| s.journal.get_mut(i)) { - Some((last_id, p)) if last_id == "type.create" && made_here => p["text"] = json!(text), - Some((last_id, p)) if last_id == "type.edit" && p.get("coalesce") == Some(&key) && p.get("layer").is_none() => { + Some((last_id, p)) if last_id == "type.create" && same_target => p["text"] = json!(text), + Some((last_id, p)) if last_id == "type.edit" && same_target && p.get("coalesce") == Some(&key) && p.get("layer").is_none() => { *p = json!({"text": text, "coalesce": key}); } _ => s.journal.push((id.to_string(), json!({"text": text, "coalesce": key}))), } + s.actions.typing_layer = here; true } diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index 256a02e663..6b82a4ba4c 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -895,3 +895,36 @@ fn typing_in_styled_text_keeps_a_step_per_edit() { assert_eq!(steps.len(), 2, "{steps:?}"); assert!(steps.iter().all(|(id, p)| id == "type.edit" && p.get("replace").is_some()), "{steps:?}"); } + +/// CodeRabbit on #10730: one typing session's key going on in another document (a tab switched +/// mid-session, no step) is a step of its own there, not folded into the first document's. +#[test] +fn a_typing_session_going_on_in_another_document_is_a_step_of_its_own() { + let mut s = session(); + let first = s.execute("type.create", json!({"x": 10, "y": 40, "text": "One", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + let second = s.execute("type.create", json!({"x": 10, "y": 40, "text": "Two", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + s.execute("actions.record", json!({"name": "Both"})).unwrap(); + type_in(&mut s, second, 3, "!", "same"); + assert!(s.set_active(0)); + type_in(&mut s, first, 3, "?", "same"); + s.execute("actions.stop", json!({})).unwrap(); + let texts: Vec<_> = s.actions.list[0].steps.iter().map(|(_, p)| p["text"].as_str().map(str::to_string)).collect(); + assert_eq!(texts, [Some("Two!".to_string()), Some("One?".to_string())], "one step per document"); +} + +/// CodeRabbit on #10730: an edit that names no layer edits the active one, and coalesces like one +/// that names it. +#[test] +fn typing_edits_that_name_no_layer_coalesce_too() { + let mut s = session(); + s.execute("type.create", json!({"x": 20, "y": 50, "text": "Hi", "size": 24})).unwrap(); + s.execute("actions.record", json!({"name": "Plain"})).unwrap(); + for (i, c) in "!!".chars().enumerate() { + s.execute("type.edit", json!({"replace": {"start": 2 + i, "end": 2 + i, "text": c.to_string()}, "coalesce": "s6"})).unwrap(); + } + s.execute("actions.stop", json!({})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps.len(), 1, "{steps:?}"); + assert_eq!(steps[0].1["text"], "Hi!!"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 7252d65871..ba7444c2aa 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -465,6 +465,8 @@ fn batch_runs_an_action_recorded_with_the_type_tool() { } app.run("actions.stop", json!({})).unwrap(); assert_eq!(crate::actions::selected_action(&app).map(|a| a.steps.len()), Some(1), "one step for the typing"); + // CodeRabbit on #10730: and that step makes the layer with the text typed. + assert_eq!(crate::actions::selected_action(&app).and_then(|a| a.steps.first()).map(|(_, p)| p["text"].clone()), Some(json!("Hi"))); let d = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap(); let fields = &mut app.ui.dialog_mut(d).unwrap().fields; fields.insert("input".into(), json!(dir.join("in").to_string_lossy())); @@ -508,6 +510,10 @@ fn a_batch_that_fails_on_its_files_says_which_and_why() { assert!(notice.error && notice.title.ends_with("2 files failed"), "{}", notice.title); let path = |name: &str| format!("{}: ", dir.join("in").join(name).to_string_lossy()); assert!(notice.lines[0].starts_with(&path("a.png")) && notice.lines[1].starts_with(&path("b.png")), "{:?}", notice.lines); + // CodeRabbit on #10730: each with its reason after the path. + for (line, name) in notice.lines.iter().zip(["a.png", "b.png"]) { + assert!(line.strip_prefix(&path(name)).is_some_and(|why| !why.trim().is_empty()), "{line}"); + } let _ = std::fs::remove_dir_all(&dir); } From a30e90a011b92793a66650aa5dcf721dd73a57db Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 11:22:57 +0000 Subject: [PATCH 22/43] #10682: the Batch tests check the pixels the action changed and each failure line word for word Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GbuSKAS2k5248LGFEapMUR --- crates/ui-egui/src/menus/view_cmds/tests.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index ba7444c2aa..93676fc982 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -476,6 +476,9 @@ fn batch_runs_an_action_recorded_with_the_type_tool() { assert!(r.get("failed").is_none_or(|f| f.as_array().is_some_and(Vec::is_empty)), "{r}"); for name in ["a.png", "b.png"] { assert!(dir.join("out").join(name).is_file(), "{name} saved: {r}"); + // CodeRabbit on #10730: the action ran on each file: the typed text is in its pixels. + let pixels = |folder: &str| photocraft_codecs::decode(&std::fs::read(dir.join(folder).join(name)).unwrap()).unwrap().data().to_vec(); + assert_ne!(pixels("out"), pixels("in"), "{name}: the text was laid on it"); } let _ = std::fs::remove_dir_all(&dir); } @@ -510,9 +513,11 @@ fn a_batch_that_fails_on_its_files_says_which_and_why() { assert!(notice.error && notice.title.ends_with("2 files failed"), "{}", notice.title); let path = |name: &str| format!("{}: ", dir.join("in").join(name).to_string_lossy()); assert!(notice.lines[0].starts_with(&path("a.png")) && notice.lines[1].starts_with(&path("b.png")), "{:?}", notice.lines); - // CodeRabbit on #10730: each with its reason after the path. - for (line, name) in notice.lines.iter().zip(["a.png", "b.png"]) { - assert!(line.strip_prefix(&path(name)).is_some_and(|why| !why.trim().is_empty()), "{line}"); + // CodeRabbit on #10730: each line is its file's error, word for word, path then reason. + let errors = r["errors"].as_array().unwrap(); + for (line, e) in notice.lines.iter().zip(errors) { + assert!(!e["error"].as_str().unwrap_or_default().trim().is_empty(), "{e}"); + assert_eq!(*line, format!("{}: {}", e["file"].as_str().unwrap(), e["error"].as_str().unwrap())); } let _ = std::fs::remove_dir_all(&dir); } From 0a209116e6576b3ec831d37b8725e4216b6f29e8 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:04:21 +0400 Subject: [PATCH 23/43] Levels clipping: no display for Smart Filter dialogs (#3328) A Smart Filter's Levels edits the filter, not the layer's pixels, so the display skips __smartFilter dialogs as the live preview does. --- crates/ui-egui/src/levels_clipping.rs | 6 ++++-- crates/ui-egui/src/levels_clipping_tests.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 27e6e2c64a..ac797ceee1 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -280,9 +280,11 @@ struct Request { target: LayerId, } -/// The open Levels dialog's fields, if any. +/// The open Levels dialog's fields, if any. A Smart Filter's Levels (`__smartFilter`) edits the +/// filter, not the layer's pixels, so it has no display (`adjust_preview` keeps it off the layer +/// path too). fn dialog(app: &PhotocraftApp) -> Option<&Map> { - app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels")) + app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels") && !f.contains_key("__smartFilter")) } /// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index 85fc01ca98..820eef3407 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -337,6 +337,21 @@ fn ineligible_documents_show_no_display() { assert!(request(&app, 0).is_none(), "fill layer"); } +/// A Smart Filter's Levels dialog edits the filter, not the layer's pixels: no display, and its +/// cache goes as if no Levels dialog were open, even over a pixel layer. +#[test] +fn smart_filter_levels_show_no_display() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + let id = open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "a plain Levels dialog shows it"); + let layer = app.session.active().and_then(|s| s.active_layer).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("__smartFilter".into(), json!({"layer": layer.0})); + assert!(request(&app, 0).is_none()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none()); + assert!(app.levels_clipping.is_none(), "the cache goes"); +} + fn dialog_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { let h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); From 216a4260b04a998fae79a6a5c38f9889943053bd Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:07:09 +0400 Subject: [PATCH 24/43] Levels clipping: snapped area stays within the texture limit (#3328) Snapping the visible area to the block grid can widen it by a block, so the block size now grows until the snapped area fits max_side. --- crates/ui-egui/src/levels_clipping.rs | 18 +++++++---- crates/ui-egui/src/levels_clipping_tests.rs | 33 +++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index ac797ceee1..81a602d1f0 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -331,11 +331,19 @@ fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(R return None; } let max_side = max_side.max(1); - let factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(visible.width().div_ceil(max_side)).max(visible.height().div_ceil(max_side)); - // Snap to the block grid so panning keeps the blocks where they were. - let f = factor as i32; - let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds); - Some((r, factor)) + let (w, h) = (visible.width(), visible.height()); + let mut factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(w.div_ceil(max_side)).max(h.div_ceil(max_side)); + // Snap to the block grid so panning keeps the blocks where they were. That can widen the area + // by up to a block, so grow the blocks until the snapped area fits. + loop { + let f = i32::try_from(factor).ok()?; + let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds); + let (bw, bh) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); + if bw <= max_side && bh <= max_side { + return Some((r, factor)); + } + factor = factor.checked_add(1)?; + } } /// Draw the Levels clipping display over the image in canvas view `xf` of document `idx`, if one diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index 820eef3407..98b3e08a2e 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -234,6 +234,39 @@ fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> O Some(image(&c.stats, &thr, end)) } +/// A view at one device pixel per document pixel whose visible document rect (with +/// `visible_doc_rect`'s 2 px margin) is exactly `x0..x1` × `y0..y1`. +fn xf_over(x0: i32, x1: i32, y0: i32, y1: i32) -> ViewXform { + let size = egui::vec2((x1 - x0 - 4) as f32, (y1 - y0 - 4) as f32); + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, size), + zoom: 1.0, + center: [(x0 + x1) as f32 / 2.0, (y0 + y1) as f32 / 2.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// Snapping the area to the block grid can widen it by up to a block; the blocks grow until the +/// snapped area still fits the texture limit (here a 2048 px device limit) on both sides. +#[test] +fn the_snapped_area_fits_the_texture_limit() { + let bounds = Rect::new(0, 0, 20000, 20000); + let (r, f) = view_area(&xf_over(1, 4097, 0, 100), bounds, 1.0, 2048).unwrap(); + assert_eq!((r.x0, f), (0, 3), "4096 px from x 1: blocks of 2 would need 2049"); + for (x0, y0) in [(0, 0), (1, 1), (2, 3), (5, 7), (1023, 2047)] { + for span in 4090..4100 { + let (x1, y1) = (x0 + span, y0 + span / 2); + let (r, f) = view_area(&xf_over(x0, x1, y0, y1), bounds, 1.0, 2048).unwrap(); + let fi = f as i32; + assert!(r.width().div_ceil(f) <= 2048 && r.height().div_ceil(f) <= 2048, "{x0},{y0} span {span}: {r:?} / {f}"); + assert!(r.x0 % fi == 0 && r.y0 % fi == 0, "snapped to the grid: {r:?} / {f}"); + assert!(r.x0 <= x0 && r.y0 <= y0 && r.x1 >= x1 && r.y1 >= y1, "covers the view: {r:?}"); + } + } +} + /// How many meshes among `shapes` (shape lists included) draw texture `tex`. fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize { fn count(s: &egui::Shape, tex: egui::TextureId) -> usize { From 8878ff335fdb00d7eb8e34b91d0db9619c04ea43 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:09:58 +0400 Subject: [PATCH 25/43] Levels clipping: cap the display at 2048 x 2048 blocks (#3328) A huge canvas grows the block size instead of building a 33M-texel texture (8K at 100 %). 2560x1440 keeps one block per device pixel. --- crates/ui-egui/src/levels_clipping.rs | 12 +++++++++--- crates/ui-egui/src/levels_clipping_tests.rs | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 81a602d1f0..01e175a094 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -319,8 +319,13 @@ pub struct Cache { tex: Option, } +/// Most blocks the display builds (2048 × 2048). A 2560×1440 canvas still gets one block per +/// device pixel, a bigger one bigger blocks: the block stats stay under 50 MB, the texture at +/// 16 MB, and a slider move near the 2 ms `levels_clipping_bench` measures for 3.7M blocks. +const MAX_BLOCKS: u64 = 2048 * 2048; + /// The visible part of the document in `xf` and the block size giving about one texel per screen -/// pixel (`ppp` physical pixels per point), within `max_side` texels a side. +/// pixel (`ppp` physical pixels per point), within `max_side` texels a side and [`MAX_BLOCKS`]. fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(Rect, u32)> { let device_zoom = xf.zoom * ppp; if !(device_zoom.is_finite() && device_zoom > 0.0) { @@ -332,14 +337,15 @@ fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(R } let max_side = max_side.max(1); let (w, h) = (visible.width(), visible.height()); - let mut factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(w.div_ceil(max_side)).max(h.div_ceil(max_side)); + let budget = ((u64::from(w) * u64::from(h)) as f64 / MAX_BLOCKS as f64).sqrt().ceil() as u32; + let mut factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(w.div_ceil(max_side)).max(h.div_ceil(max_side)).max(budget); // Snap to the block grid so panning keeps the blocks where they were. That can widen the area // by up to a block, so grow the blocks until the snapped area fits. loop { let f = i32::try_from(factor).ok()?; let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds); let (bw, bh) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); - if bw <= max_side && bh <= max_side { + if bw <= max_side && bh <= max_side && u64::from(bw) * u64::from(bh) <= MAX_BLOCKS { return Some((r, factor)); } factor = factor.checked_add(1)?; diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index 98b3e08a2e..116e72dd0c 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -267,6 +267,22 @@ fn the_snapped_area_fits_the_texture_limit() { } } +/// However big the display, the display builds at most `MAX_BLOCKS` blocks: an 8K canvas at +/// 100 % gets bigger blocks instead of a 33M-texel texture, while 2560×1440 keeps one block per +/// device pixel. +#[test] +fn a_huge_display_grows_the_blocks() { + let bounds = Rect::new(0, 0, 20000, 20000); + let (_, f) = view_area(&xf_over(0, 2564, 0, 1444), bounds, 1.0, 8192).unwrap(); + assert_eq!(f, 1, "2560×1440: one block per device pixel"); + for (w, h) in [(7680, 4320), (8192, 8192), (15360, 8640)] { + let (r, f) = view_area(&xf_over(0, w, 0, h), bounds, 1.0, 8192).unwrap(); + let blocks = u64::from(r.width().div_ceil(f)) * u64::from(r.height().div_ceil(f)); + assert!(blocks <= MAX_BLOCKS, "{w}×{h}: {blocks} blocks of {f}"); + assert!(blocks > MAX_BLOCKS / 4, "{w}×{h}: no coarser than needed ({blocks} blocks of {f})"); + } +} + /// How many meshes among `shapes` (shape lists included) draw texture `tex`. fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize { fn count(s: &egui::Shape, tex: egui::TextureId) -> usize { From fadef65cc88229dab60f07360663e16d007585b8 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:12:15 +0400 Subject: [PATCH 26/43] Levels clipping: draw nothing while a background job runs (#3328) paint now returns before thresholds, scan and image while the session has jobs, and the display comes back once they are done. --- crates/ui-egui/src/levels_clipping.rs | 5 +++ crates/ui-egui/src/levels_clipping_tests.rs | 38 +++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs index 01e175a094..66a334e4a6 100644 --- a/crates/ui-egui/src/levels_clipping.rs +++ b/crates/ui-egui/src/levels_clipping.rs @@ -360,6 +360,11 @@ pub fn paint(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Paint app.levels_clipping = None; return; } + // A background job holds the workers and may replace the document: no thresholds, scan or + // image until it ends. + if app.session.has_jobs() { + return; + } let Some(req) = request(app, idx) else { return }; let Some(thr) = thresholds(&req.adj, req.doc.pixel_format().sample) else { return }; let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 8192); diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index 116e72dd0c..f9fc4c4011 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -386,6 +386,44 @@ fn ineligible_documents_show_no_display() { assert!(request(&app, 0).is_none(), "fill layer"); } +/// While a background job runs the display draws nothing and neither scans nor builds its +/// texture. It comes back once the job is done. +#[test] +fn a_running_job_holds_the_display() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + let gate = Arc::new(AtomicBool::new(false)); + let open = gate.clone(); + let started = app + .session + .start_job( + "test.slow", + json!({}), + "Slow", + false, + move |job| { + while !open.load(Ordering::Relaxed) { + job.check()?; + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Ok(()) + }, + |_, ()| Ok(json!({})), + ) + .unwrap(); + let photocraft_engine::jobs::Started::Job(job) = started else { panic!("ran inline") }; + assert!(app.session.has_jobs()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none()); + assert!(app.levels_clipping.is_none(), "no scan and no texture while the job runs"); + gate.store(true, Ordering::Relaxed); + app.session.wait_job(job).unwrap(); + assert!(!app.session.has_jobs()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "back once the job is done"); +} + /// A Smart Filter's Levels dialog edits the filter, not the layer's pixels: no display, and its /// cache goes as if no Levels dialog were open, even over a pixel layer. #[test] From 01cbd41e2bd636442e5ad585faa1b84ad9122d4d Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:14:17 +0400 Subject: [PATCH 27/43] Levels clipping: drop the cache when the last document closes (#3328) With no document there is no canvas to paint the display away, so sync_views drops its cache and texture. --- crates/ui-egui/src/app/commands.rs | 4 ++++ crates/ui-egui/src/levels_clipping_tests.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1a43ffe77f..197a345ae8 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -354,6 +354,10 @@ impl PhotocraftApp { let docs = self.session.documents(); self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); } + // 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; + } // Commands may close and reopen a preserved-ID document before the next repaint. canvas::retain_gpu_documents(self); } diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index f9fc4c4011..ea83004221 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -424,6 +424,18 @@ fn a_running_job_holds_the_display() { assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "back once the job is done"); } +/// Closing the last document drops the display's cache: no canvas is left to paint it away. +#[test] +fn closing_the_last_document_drops_the_cache() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some()); + app.run("file.close", json!({})).unwrap(); + assert!(app.session.documents().is_empty()); + assert!(app.levels_clipping.is_none()); +} + /// A Smart Filter's Levels dialog edits the filter, not the layer's pixels: no display, and its /// cache goes as if no Levels dialog were open, even over a pixel layer. #[test] From cb9e0f82d8b1a9e17e75f2502887d5d106a70d58 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:23:15 +0400 Subject: [PATCH 28/43] Levels clipping: test that a null __clipping draws no mesh (#3328) The test paints a canvas frame with the dialog still open and checks the cached texture draws nothing. paint_view now paints in a frame of its own so its meshes don't spill into the next frame's shapes. --- crates/ui-egui/src/levels_clipping_tests.rs | 48 +++++++++++++++------ 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index ea83004221..bed7134a4e 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -226,9 +226,14 @@ fn view(zoom: f32) -> ViewXform { } } +/// [`paint`] in a frame of its own (so its mesh doesn't spill into a later frame's shapes), then +/// the colours of the blocks it shows. fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> Option> { - let painter = egui::Painter::new(ctx.clone(), egui::LayerId::background(), egui::Rect::EVERYTHING); - paint(app, ctx, &painter, xf, 0); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = egui::Painter::new(ui.ctx().clone(), egui::LayerId::background(), egui::Rect::EVERYTHING); + paint(app, ui.ctx(), &painter, xf, 0); + }); + out.textures_delta.clear(); let c = app.levels_clipping.as_ref()?; let (end, thr) = c.drawn?; Some(image(&c.stats, &thr, end)) @@ -283,6 +288,21 @@ fn a_huge_display_grows_the_blocks() { } } +/// The main canvas's view of the 16×8 document at 10 device pixels per pixel. +fn main_view(app: &mut PhotocraftApp) -> crate::state::View { + app.sync_views(); + crate::state::View { zoom: 10.0, center: [8.0, 4.0], fit_pending: false, fill_pending: false, ..app.ui.views[0].clone() } +} + +/// The shapes of one 160×80 canvas frame of document 0 in `view`. +fn canvas_frame(ctx: &egui::Context, app: &mut PhotocraftApp, view: &crate::state::View, primary: bool) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + crate::canvas::canvas_view(app, ui, 0, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(160.0, 80.0)), view.clone(), primary); + }); + out.textures_delta.clear(); + out.shapes +} + /// How many meshes among `shapes` (shape lists included) draw texture `tex`. fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize { fn count(s: &egui::Shape, tex: egui::TextureId) -> usize { @@ -302,21 +322,13 @@ fn only_the_main_canvas_draws_the_display() { let ctx = egui::Context::default(); let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); - app.sync_views(); - let main = crate::state::View { zoom: 10.0, center: [8.0, 4.0], fit_pending: false, fill_pending: false, ..app.ui.views[0].clone() }; + let main = main_view(&mut app); let other = crate::state::View { zoom: 0.25, ..main.clone() }; - let frame = |app: &mut PhotocraftApp, view: &crate::state::View, primary: bool| { - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - crate::canvas::canvas_view(app, ui, 0, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(160.0, 80.0)), view.clone(), primary); - }); - out.textures_delta.clear(); - out.shapes - }; - let shapes = frame(&mut app, &main, true); + let shapes = canvas_frame(&ctx, &mut app, &main, true); let cache = app.levels_clipping.as_ref().expect("the main canvas builds the display"); let (key, tex) = (cache.key, cache.tex.as_ref().map(egui::TextureHandle::id).expect("its texture")); assert_eq!(meshes_with(&shapes, tex), 1, "the main canvas draws the display"); - let shapes = frame(&mut app, &other, false); + let shapes = canvas_frame(&ctx, &mut app, &other, false); assert_eq!(meshes_with(&shapes, tex), 0, "an extra window doesn't draw it"); assert_eq!(app.levels_clipping.as_ref().map(|c| c.key), Some(key), "nor replaces the main canvas's cache"); } @@ -355,9 +367,17 @@ fn paint_shows_the_target_clipping_for_the_view() { paint_view(&mut app, &ctx, &view(0.25)).unwrap(); assert_eq!(app.levels_clipping.as_ref().unwrap().stats.factor, 4); assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [4, 2]); - // Off: nothing drawn; closed: the cache goes. + // Off with the dialog still open: the cached texture stays but no canvas frame draws it. + let main = main_view(&mut app); + let shapes = canvas_frame(&ctx, &mut app, &main, true); + let tex = app.levels_clipping.as_ref().and_then(|c| c.tex.as_ref()).map(egui::TextureHandle::id).unwrap(); + assert_eq!(meshes_with(&shapes, tex), 1, "{mode:?} {depth:?}: on, it draws"); app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), Value::Null); assert!(request(&app, 0).is_none()); + let shapes = canvas_frame(&ctx, &mut app, &main, true); + assert_eq!(meshes_with(&shapes, tex), 0, "{mode:?} {depth:?}: off, it draws nothing"); + assert!(app.levels_clipping.is_some(), "{mode:?} {depth:?}: the cache stays while the dialog is open"); + // Closed: the cache goes. app.ui.close_dialog(id); paint_view(&mut app, &ctx, &view(10.0)); assert!(app.levels_clipping.is_none(), "{mode:?} {depth:?}"); From 2932e7fcdd68a424c595c5d75b9fe36f98a6c2d5 Mon Sep 17 00:00:00 2001 From: funkvay-star <71777367+funkvay-star@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:23:29 +0400 Subject: [PATCH 29/43] Docs: where the Levels clipping display shows (#3328) Only RGB and Grayscale documents with a raster layer target show it. Other targets accept __clipping and keep the normal preview. --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 814a7b244d..b49c29c67d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -77,7 +77,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - 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. - 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. + - 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. - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized. - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. From 66414681870b1316bd1eaa8bb54c1f63767f0482 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 18:33:26 +0000 Subject: [PATCH 30/43] #10682: the Batch test compares its output with the text typed by hand --- crates/ui-egui/src/menus/view_cmds/tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 93676fc982..c43fdc24f4 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -464,6 +464,7 @@ fn batch_runs_an_action_recorded_with_the_type_tool() { app.run("type.edit", json!({"layer": id, "replace": {"start": i, "end": i, "text": c.to_string()}, "coalesce": "typing"})).unwrap(); } app.run("actions.stop", json!({})).unwrap(); + app.run("file.saveACopy", json!({"path": dir.join("ref.png").to_string_lossy()})).unwrap(); assert_eq!(crate::actions::selected_action(&app).map(|a| a.steps.len()), Some(1), "one step for the typing"); // CodeRabbit on #10730: and that step makes the layer with the text typed. assert_eq!(crate::actions::selected_action(&app).and_then(|a| a.steps.first()).map(|(_, p)| p["text"].clone()), Some(json!("Hi"))); @@ -480,6 +481,10 @@ fn batch_runs_an_action_recorded_with_the_type_tool() { let pixels = |folder: &str| photocraft_codecs::decode(&std::fs::read(dir.join(folder).join(name)).unwrap()).unwrap().data().to_vec(); assert_ne!(pixels("out"), pixels("in"), "{name}: the text was laid on it"); } + // CodeRabbit on #10730: all of it, as typed by hand: the document the action was recorded + // on (the same image, with the text typed into it) has the pixels Batch wrote. + let decoded = |path: std::path::PathBuf| photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap().data().to_vec(); + assert_eq!(decoded(dir.join("out").join("a.png")), decoded(dir.join("ref.png")), "Batch laid the whole text, as it was typed by hand"); let _ = std::fs::remove_dir_all(&dir); } From caf7b95dc25c3eb53ed8e32461e2afda5ffaa6ee Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Thu, 5 Nov 2026 15:29:13 -0500 Subject: [PATCH 31/43] Menu scroll arrows: import what dropdown.rs uses; arrows as wide as the rows (#2091) The upstream split of widgets.rs moved menu_scroll into widgets/dropdown.rs, whose imports lacked Sense, Stroke, Tokens, pos2 and vec2 that the arrows use, so photocraft-ui-egui no longer compiled. The arrows were also allocated at the popup's whole available width, which widened an overflowing menu on later opens; they now take the rows' width from last frame (the scroll area's content width; its inner_rect is the width asked for, before auto-shrink). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets/dropdown.rs | 19 ++++++---- crates/ui-egui/src/widgets/tests.rs | 50 ++++++++++++++++++++------ 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index 5bb8070db5..30ca569cbd 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,7 +1,7 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; use super::slider::wheel_notches_of; -use super::{Pos2, Rect, Response, Ui, Vec2, type_ahead}; +use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, type_ahead, vec2}; /// A compact labelled dropdown in the studio style. pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { @@ -228,6 +228,10 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R let id = ui.scope_id().with("menu_scroll"); let overflow = ui.data(|d| d.get_temp::(id)).unwrap_or(false); let offset = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + // The arrows are as wide as the rows were last frame, not the popup's whole available width: + // that widened an overflowing menu on every later open (a layer menu went from ~230 to ~600 + // pt). The output's `inner_rect` is the width asked for, before auto-shrink fits the rows. + let width = ui.data(|d| d.get_temp::(id.with("width"))).unwrap_or(0.0); let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; let room = (room - arrows).max(MENU_MIN_HEIGHT); // The arrows sit flush against the rows, so no item spacing is added around them that `room` @@ -236,7 +240,7 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R ui.spacing_mut().item_spacing.y = 0.0; let mut step = 0.0; if overflow { - step += menu_scroll_arrow(ui, true, offset > 0.5); + step += menu_scroll_arrow(ui, true, offset > 0.5, width); } // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. @@ -255,12 +259,13 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R let max = (out.content_size.y - out.inner_rect.height()).max(0.0); let offset = out.state.clamped_offset().y.clamp(0.0, max); if overflow { - step += menu_scroll_arrow(ui, false, offset < max - 0.5); + step += menu_scroll_arrow(ui, false, offset < max - 0.5, width); } ui.spacing_mut().item_spacing.y = spacing; ui.data_mut(|d| { d.insert_temp(id, max > 0.5); d.insert_temp(id.with("offset"), offset); + d.insert_temp(id.with("width"), out.content_size.x); d.insert_temp(id.with("step"), (step, now)); }); out.inner @@ -268,9 +273,11 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R /// One scroll arrow of an overflowing menu: hovering scrolls that way, as in Photoshop's and the /// system menus. It doesn't page on a click: egui closes a context menu on any click inside it, -/// so the page would never be seen. Returns the scroll step for the next frame. -fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool) -> f32 { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(MENU_ARROW_HEIGHT), MENU_ARROW_HEIGHT), Sense::hover()); +/// so the page would never be seen. `width` is the rows' width. Returns the scroll step for the +/// next frame. +fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool, width: f32) -> f32 { + let width = if width.is_finite() { width.max(MENU_ARROW_HEIGHT) } else { MENU_ARROW_HEIGHT }; + let (rect, resp) = ui.allocate_exact_size(vec2(width, MENU_ARROW_HEIGHT), Sense::hover()); let t = Tokens::get(ui.ctx()); let color = if enabled { t.text } else { t.text_dim.gamma_multiply(0.5) }; let (c, h) = (rect.center(), 3.5); diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 8ed71e5624..1d9d004a51 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1443,12 +1443,18 @@ fn the_wheel_leaves_a_plain_dropdown_alone() { assert_eq!(*h.state(), 0); } +/// The middle of an overflowing menu's lower scroll arrow, from the menu's laid-out rect. +fn lower_menu_arrow(menu: egui::Rect) -> egui::Pos2 { + let half = super::dropdown::MENU_ARROW_HEIGHT / 2.0; + egui::pos2(menu.left() + half, menu.bottom() - half) +} + /// #2091: a menu taller than the window shows scroll arrows; hovering the lower one scrolls /// it, and a short menu gets none. #[test] fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { - // (rows, overflowing, scroll offset, bottom of the menu) - type S = (usize, bool, f32, f32); + // (rows, overflowing, scroll offset, the menu's rect) + type S = (usize, bool, f32, egui::Rect); let run = |rows: usize| { let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( |ui, s: &mut S| { @@ -1460,9 +1466,9 @@ fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { }); s.1 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); s.2 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); - s.3 = ui.min_rect().bottom(); + s.3 = ui.min_rect(); }, - (rows, false, 0.0, 0.0), + (rows, false, 0.0, egui::Rect::NOTHING), ); h.run_steps(3); h @@ -1472,7 +1478,7 @@ fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { let mut long = run(80); assert!(long.state().1, "a long menu overflows"); assert_eq!(long.state().2, 0.0); - let below = egui::pos2(100.0, long.state().3 - super::dropdown::MENU_ARROW_HEIGHT / 2.0); + let below = lower_menu_arrow(long.state().3); long.event(egui::Event::PointerMoved(below)); long.run_steps(10); assert!(long.state().2 > 0.0, "hovering the lower arrow scrolls down"); @@ -1482,8 +1488,8 @@ fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { /// while hovering it opens again. #[test] fn a_reopened_menu_takes_no_stale_scroll_step() { - // (shown, scroll offset, bottom of the menu) - type S = (bool, f32, f32); + // (shown, scroll offset, the menu's rect) + type S = (bool, f32, egui::Rect); let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( |ui, s: &mut S| { let id = ui.scope_id().with("menu_scroll"); @@ -1493,14 +1499,14 @@ fn a_reopened_menu_takes_no_stale_scroll_step() { ui.label(format!("Item {i}")); } }); - s.2 = ui.min_rect().bottom(); + s.2 = ui.min_rect(); } s.1 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); }, - (true, 0.0, 0.0), + (true, 0.0, egui::Rect::NOTHING), ); h.run_steps(3); - h.event(egui::Event::PointerMoved(egui::pos2(100.0, h.state().2 - super::dropdown::MENU_ARROW_HEIGHT / 2.0))); + h.event(egui::Event::PointerMoved(lower_menu_arrow(h.state().2))); h.run_steps(3); let offset = h.state().1; assert!(offset > 0.0, "hovering the lower arrow scrolls down"); @@ -1511,3 +1517,27 @@ fn a_reopened_menu_takes_no_stale_scroll_step() { h.run(); assert_eq!(h.state().1, offset, "the reopened menu stays where it was left"); } + +/// #2091: an overflowing menu's scroll arrows are as wide as its rows, so they don't widen the +/// menu to the whole width it is offered. +#[test] +fn menu_scroll_arrows_do_not_widen_the_menu() { + // (overflowing, width of the menu) + type S = (bool, f32); + let mut h = Harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.0 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.1 = ui.min_rect().width(); + }, + (false, 0.0), + ); + h.run_steps(4); + assert!(h.state().0, "the menu overflows"); + assert!(h.state().1 < 200.0, "the arrows follow the rows' width, not the 600 pt window: {}", h.state().1); +} From 0d924e6fcc757d1c8c00fe320b2fe2b99d6f171d Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Thu, 5 Nov 2026 20:51:17 -0500 Subject: [PATCH 32/43] fix(ui): keep both menu scroll arrows inside a short window (#2091) The arrows were taken from the room and then the scroll area was raised back to the 120 pt minimum, so with 120-148 pt of room the menu grew 28 pt taller than the room and the lower arrow could fall off screen. The minimum now applies to the whole menu, arrows included. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets/dropdown.rs | 15 ++++++---- crates/ui-egui/src/widgets/tests.rs | 39 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index 30ca569cbd..b380296f8d 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -217,7 +217,8 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long /// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running /// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the -/// screen first shifts up and only scrolls when it is taller than the window. +/// screen first shifts up and only scrolls when it is taller than the window. An overflowing +/// menu's ▲/▼ scroll arrows (#2091) count toward that height, so both stay on screen. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { // The popup frame's margin and stroke, and a small gap to the window's edges. let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; @@ -232,8 +233,12 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R // that widened an overflowing menu on every later open (a layer menu went from ~230 to ~600 // pt). The output's `inner_rect` is the width asked for, before auto-shrink fits the rows. let width = ui.data(|d| d.get_temp::(id.with("width"))).unwrap_or(0.0); + // The arrows come out of the room, so both stay on screen: the minimum is the whole menu's + // height, arrows included. `room` is at least `MENU_MIN_HEIGHT`, which is taller than the two + // arrows, so the rows always keep a positive height; a window shorter than that minimum still + // gets a menu of that height, as one without arrows does. let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; - let room = (room - arrows).max(MENU_MIN_HEIGHT); + let room = (room - arrows).max(MENU_MIN_HEIGHT - arrows); // The arrows sit flush against the rows, so no item spacing is added around them that `room` // doesn't count; the rows keep the menu's own spacing. let spacing = ui.spacing().item_spacing.y; @@ -298,10 +303,10 @@ fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool, width: f32) -> f32 { sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1) } -/// Gap kept between a context menu and the window's edges, and the shortest it gets. +/// Gap kept between a context menu and the window's edges. const MENU_EDGE: f32 = 4.0; - -const MENU_MIN_HEIGHT: f32 = 120.0; +/// The shortest a context menu gets, scroll arrows included. +pub(super) const MENU_MIN_HEIGHT: f32 = 120.0; /// Height of an overflowing menu's scroll arrows, and how fast hovering one scrolls (points per /// second). pub(super) const MENU_ARROW_HEIGHT: f32 = 14.0; diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 1d9d004a51..66e00f3e67 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1541,3 +1541,42 @@ fn menu_scroll_arrows_do_not_widen_the_menu() { assert!(h.state().0, "the menu overflows"); assert!(h.state().1 < 200.0, "the arrows follow the rows' width, not the 600 pt window: {}", h.state().1); } + +/// #2091: in a short window, between the shortest menu and that plus its arrows, an overflowing +/// menu's arrows come out of the room rather than being added under it, so the lower arrow stays +/// on screen. A window shorter than a menu's minimum gets a menu of the minimum height, arrows +/// included. +#[test] +fn menu_scroll_arrows_stay_inside_a_short_window() { + // (overflowing, the menu's rect) + type S = (bool, egui::Rect); + let run = |height: f32| { + let mut h = Harness::builder().with_size(egui::vec2(220.0, height)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.0 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.1 = ui.min_rect(); + }, + (false, egui::Rect::NOTHING), + ); + h.run_steps(4); + let screen = h.ctx.content_rect(); + (h.state().0, h.state().1, screen) + }; + // The room is 150 - 22 (the popup frame and edge gaps) = 128 pt: more than the shortest menu, + // less than it plus both 14 pt arrows. + let (overflow, menu, screen) = run(150.0); + assert!(overflow, "the menu overflows and shows its arrows"); + assert!(menu.top() >= screen.top(), "the upper arrow is on screen: {menu:?} in {screen:?}"); + assert!(menu.bottom() <= screen.bottom(), "the lower arrow is on screen: {menu:?} in {screen:?}"); + assert!(menu.height() <= 128.5, "the menu, arrows included, fits the room: {}", menu.height()); + let (overflow, menu, _) = run(60.0); + assert!(overflow, "a tiny window's menu overflows too"); + let min = super::dropdown::MENU_MIN_HEIGHT; + assert!((menu.height() - min).abs() < 0.5, "a tiny window's menu is the minimum height, arrows included: {}", menu.height()); +} From 0eb6ba9dea0b826f99034dcdfa2afb09129486c6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 01:40:56 +0100 Subject: [PATCH 33/43] #10730: keep the filter-preview comment the main merge cut; check both Batch outputs The merge of main into #10730 dropped the first line of the comment above the filter-preview check in confirm_generic_command; it is back. The Batch test now compares out/b.png with the hand-typed reference as well as out/a.png, so a replay that stops after the first file fails it (review on #10730). Co-Authored-By: Lcoding15 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/menus/view_cmds/tests.rs | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 678ccd1ebb..469ee1b49d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -972,6 +972,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result Date: Sat, 7 Nov 2026 00:35:13 -0500 Subject: [PATCH 34/43] fix(ui): Delete with a note selected asks to delete the note, not the layer (#11788) With the Note tool and a note selected, Delete and Backspace went the usual way and deleted the active layer, leaving the note. They now ask "Delete this note?" (Yes / No, "Don't show again"); Yes deletes the note as one "Delete Note" step and selects nothing, No changes nothing. The Notes panel's trash asks the same, and "Don't show again" skips the question for both. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 21 +++- crates/ui-egui/src/input/shortcuts.rs | 4 + crates/ui-egui/src/tools/analysis_ui.rs | 101 ++++++++++++++++- .../src/tools/note_delete_key_tests.rs | 107 ++++++++++++++++++ 4 files changed, 227 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/tools/note_delete_key_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0cfeb7fdc1..157c38281d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -277,6 +277,19 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { /// it. Returns `Some(true)` / `Some(false)` when the body itself answered OK / Cancel. /// The body of a command dialog: the first handler whose marker the fields carry. The prompts and /// small editors come first; the rest are in `command_body_more`. +/// The delete confirmations: a layer from the Layers panel's trash, or a note (#11788). +fn delete_prompt(fields: &Fields) -> bool { + crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields) +} + +fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) { + if crate::analysis_ui::owns_delete_note(fields) { + crate::analysis_ui::delete_note_body(ui, fields); + } else { + crate::delete_layer_prompt::body(ui, fields); + } +} + fn command_body(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 { @@ -292,7 +305,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::channel_options_ui::owns(fields) => crate::channel_options_ui::body(ui, fields), _ if crate::channel_options_ui::owns_new_spot(fields) => crate::channel_options_ui::new_spot_body(ui, fields), _ if crate::shape_dialog::owns(fields) => crate::shape_dialog::body(app, ui, fields), - _ if crate::delete_layer_prompt::owns(fields) => crate::delete_layer_prompt::body(ui, fields), + _ if delete_prompt(fields) => delete_prompt_body(ui, fields), _ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields), _ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields), _ if crate::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields), @@ -464,6 +477,8 @@ fn button_row( tl!("Reset") } else if d.kind == DialogKind::NewDocument { tl!("Close") + } else if crate::analysis_ui::owns_delete_note(fields) { + tl!("No") } else { tl!("Cancel") }; @@ -533,6 +548,8 @@ fn ok_label(d: &Dialog) -> &'static str { tl!("Continue") } else if crate::delete_layer_prompt::owns(&d.fields) { tl!("Delete") + } else if crate::analysis_ui::owns_delete_note(&d.fields) { + tl!("Yes") } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) { tl!("Replace") } else if d.fields.contains_key("__export") { @@ -864,6 +881,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ merge_channels_ui::owns, crate::shape_dialog::owns, crate::delete_layer_prompt::owns, + crate::analysis_ui::owns_delete_note, crate::disk_change_prompt::owns, crate::actions::owns_stop_message, crate::actions::owns_insert_stop, @@ -1059,6 +1077,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result { match d.kind { _ 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::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), _ if crate::color_picker_ui::owns(&d.fields) => { diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 0abd096530..ab1c6a1614 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -745,6 +745,10 @@ fn handle_object_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool if crate::slice_ui::keys(app, ctx) { return true; } + // A note selected with the Note tool: ⌫/Delete asks to delete the note, not the layer (#11788). + if crate::analysis_ui::note_keys(app, ctx) { + return true; + } // A selected smart filter row: ⌫/Delete removes the filter, not its smart object (#4751). crate::smart_ui::keys(app, ctx) } diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 6cad2b2158..2175ea708d 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -821,11 +821,8 @@ fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(p) = edit { let _ = app.run("notes.set", p); } - if delete - && let Some(i) = sel - && app.run("notes.delete", json!({"index": i})).is_ok() - { - app.ui.analysis.note_selected = (n > 1).then(|| i.min(n - 2)); + if delete && let Some(i) = sel { + ask_delete_note(app, i); } if close { app.ui.analysis.notes = false; @@ -988,3 +985,97 @@ fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] pub(crate) mod tests; + +/// Marks the "Delete this note?" alert (#11788). +const DELETE_NOTE_MARK: &str = "__deleteNote"; +/// Its "Don't show again", kept with the other dialog preferences. +const DELETE_NOTE_PREF: &str = "notes.delete.confirmation"; + +/// Delete note `index` of the active document, as the Note tool's ⌫/Delete and the Notes panel's +/// trash do: after the alert "Delete this note?" ([Yes] [No], "Don't show again"), or at once once +/// that is ticked. Nothing is selected afterwards. +pub fn ask_delete_note(app: &mut PhotocraftApp, index: usize) { + let skip = app.session.prefs().dialogs.get(DELETE_NOTE_PREF).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true); + let Some(doc) = app.session.active().map(|s| s.doc.id.0) else { return }; + if skip { + delete_note(app, index); + return; + } + if app.ui.dialogs.iter().any(|d| owns_delete_note(&d.fields)) { + return; + } + let mut f = Map::new(); + f.insert(DELETE_NOTE_MARK.into(), json!(true)); + f.insert("__command".into(), json!("notes.delete")); + f.insert("__label".into(), json!(tl!("Delete Note"))); + f.insert("document".into(), json!(doc)); + f.insert("index".into(), json!(index)); + f.insert("skip".into(), json!(false)); + app.ui.open_dialog(crate::state::DialogKind::Command, f); +} + +fn delete_note(app: &mut PhotocraftApp, index: usize) { + match app.run("notes.delete", json!({"index": index})) { + Ok(_) => app.ui.analysis.note_selected = None, + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +pub fn owns_delete_note(fields: &Map) -> bool { + fields.contains_key(DELETE_NOTE_MARK) +} + +pub fn delete_note_body(ui: &mut egui::Ui, fields: &mut Map) { + ui.label(tl!("Delete this note?")); + ui.add_space(8.0); + let mut skip = fields.get("skip").and_then(Value::as_bool).unwrap_or(false); + ui.checkbox(&mut skip, tl!("Don't show again")); + fields.insert("skip".into(), json!(skip)); +} + +/// Yes: the note goes (one "Delete Note" step), and "Don't show again" is remembered. +pub fn confirm_delete_note(app: &mut PhotocraftApp, fields: &Map) -> Result { + let index = fields.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or(tl!("No note to delete"))?; + let doc = app.session.active().map(|s| (s.doc.id.0, s.doc.notes.len())); + if doc.map(|d| d.0) != fields.get("document").and_then(Value::as_u64) || doc.is_none_or(|d| index >= d.1) { + return Err(tl!("The document or its notes changed. Please delete the note again.").into()); + } + let result = app.run("notes.delete", json!({"index": index}))?; + app.ui.analysis.note_selected = None; + if fields.get("skip").and_then(Value::as_bool) == Some(true) { + app.session.edit_prefs(|prefs| { + prefs.dialogs.insert(DELETE_NOTE_PREF.into(), json!({"skip": true})); + }); + if let Err(error) = crate::prefs_ui::save_preferences(app) { + app.ui.status = crate::i18n::fmt(tl!("Note deleted, but the preference could not be saved: {error}"), &[("error", &error)]); + app.ui.status_error = true; + } + } + Ok(result) +} + +/// The Note tool with a note selected: ⌫/Delete asks to delete the note (#11788), never the +/// layer (Delete Layer) or the pixels (Edit › Clear). Text fields keep the keys. +pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + use crate::shortcut_dispatch::Focus; + let Some(index) = app.ui.analysis.note_selected else { return false }; + if app.ui.tool != Tool::Note || app.ui.text_edit.is_some() || matches!(Focus::of(ctx), Focus::Text | Focus::DeletingWidget) { + return false; + } + if app.session.active().is_none_or(|s| index >= s.doc.notes.len()) { + return false; + } + let mods = ctx.input(|i| i.modifiers); + if !mods.is_none() || !ctx.input_mut(|i| i.consume_key(mods, egui::Key::Delete) || i.consume_key(mods, egui::Key::Backspace)) { + return false; + } + ask_delete_note(app, index); + true +} + +#[cfg(test)] +#[path = "note_delete_key_tests.rs"] +mod note_delete_key_tests; diff --git a/crates/ui-egui/src/tools/note_delete_key_tests.rs b/crates/ui-egui/src/tools/note_delete_key_tests.rs new file mode 100644 index 0000000000..9a1630e4e7 --- /dev/null +++ b/crates/ui-egui/src/tools/note_delete_key_tests.rs @@ -0,0 +1,107 @@ +//! #11788: with the Note tool, ⌫/Delete on a selected note asks "Delete this note?" and deletes +//! the note, never the layer; the Notes panel's trash asks the same. + +use super::*; + +/// A document with a second layer and one note, the Note tool on and the note selected. +fn app() -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); + s.execute("notes.add", json!({"x": 10, "y": 12, "text": "fix this"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::Note; + app.ui.analysis.note_selected = Some(0); + app +} + +/// 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 = egui::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 layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn notes(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.notes.len() +} + +fn alert(app: &PhotocraftApp) -> Option { + app.ui.dialogs.iter().find(|d| owns_delete_note(&d.fields)).map(|d| d.id) +} + +#[test] +fn delete_with_a_note_selected_asks_and_deletes_the_note_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let steps = app.session.active().unwrap().history.past_len(); + press(&mut app, key); + let id = alert(&app).unwrap_or_else(|| panic!("{key:?}: the alert")); + assert_eq!((layers(&app), notes(&app)), (2, 1), "{key:?}: nothing changes before the answer"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!((layers(&app), notes(&app)), (2, 0), "{key:?}: the note goes, the layers stay"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1); + assert_eq!(st.history.undo_label(), Some("Delete Note")); + assert_eq!(app.ui.analysis.note_selected, None, "nothing selected after"); + } +} + +#[test] +fn no_keeps_the_document_and_history() { + let mut app = app(); + let steps = app.session.active().unwrap().history.past_len(); + press(&mut app, egui::Key::Delete); + let id = alert(&app).expect("the alert"); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!((layers(&app), notes(&app)), (2, 1)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); +} + +#[test] +fn dont_show_again_skips_the_alert_next_time() { + let mut app = app(); + app.run("notes.add", json!({"x": 30, "y": 30})).unwrap(); + press(&mut app, egui::Key::Delete); + let id = alert(&app).expect("the alert"); + app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(notes(&app), 1); + // The panel's trash goes the same way: no alert, the note is deleted at once. + ask_delete_note(&mut app, 0); + assert!(alert(&app).is_none()); + assert_eq!((layers(&app), notes(&app)), (2, 0)); +} + +#[test] +fn the_notes_panel_trash_asks_too() { + let mut app = app(); + ask_delete_note(&mut app, 0); + assert!(alert(&app).is_some()); + assert_eq!(notes(&app), 1, "nothing goes before Yes"); +} + +#[test] +fn without_a_selected_note_delete_keeps_its_usual_route() { + let mut app = app(); + app.ui.analysis.note_selected = None; + press(&mut app, egui::Key::Delete); + assert!(alert(&app).is_none()); + assert_eq!(notes(&app), 1, "the note stays"); + // Another tool with a note still selected: the note isn't asked about. + let mut other = self::app(); + other.ui.tool = Tool::Move; + press(&mut other, egui::Key::Delete); + assert!(alert(&other).is_none()); + assert_eq!(notes(&other), 1); +} From ccc263e49e628ab8e26ccf6a86011ea8c76feb17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 07:22:59 +0100 Subject: [PATCH 35/43] fix(paint): Pressure for Size starts off, as the reference does BrushSettings::default() turned Pressure for Size on, so a fresh brush - and the brush Reset Tool hands back, which is that default plus Photoshop's 10 % smoothing - reported pressureSize: true from brush.get and drew the options bar's "Always use pressure for size" button highlighted, while the reference application leaves both pressure toggles off after Reset Tool. Neither is on now. The toggle itself is untouched: it still switches both ways, Shape Dynamics' Pen Pressure control is unaffected, and path.stroke's Simulate Pressure still tapers a brush that follows pen pressure. A brush JSON that omits pressureSize now reads as off, as the reference's default is. Two engine tests took their expectation from the old default and set pressureSize explicitly instead: cmd::brush_cmds::tests::stroke_backwards_compatible and cmd::vector_cmds::tests::stroke_path_simulate_pressure_tapers_both_ends. The new crates/engine/src/brush_pressure_size_default_tests.rs covers the default, brush.get on a fresh session, an omitted field, switching the toggle, and that a pressure ramp with the default brush paints like pressureSize: false. Fixes #11809 --- .../src/brush_pressure_size_default_tests.rs | 87 +++++++++++++++++++ crates/engine/src/cmd/brush_cmds/tests.rs | 5 +- crates/engine/src/cmd/vector_cmds/tests.rs | 3 + crates/engine/src/lib.rs | 2 + crates/paint/src/brush.rs | 3 +- crates/ui-egui/src/panels/brush_preview.rs | 4 +- 6 files changed, 100 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/brush_pressure_size_default_tests.rs diff --git a/crates/engine/src/brush_pressure_size_default_tests.rs b/crates/engine/src/brush_pressure_size_default_tests.rs new file mode 100644 index 0000000000..c09fe26313 --- /dev/null +++ b/crates/engine/src/brush_pressure_size_default_tests.rs @@ -0,0 +1,87 @@ +//! Pressure for Size starts off (#11809). The reference application leaves both pressure toggles +//! in the options bar unhighlighted after Reset Tool, so a fresh brush has neither on — and the +//! brush Reset Tool hands back is `BrushSettings::default()` plus smoothing +//! (`crates/ui-egui/src/canvas/paint_mouse.rs::fresh_brush`), so the default is what the tool +//! reset reports through `brush.get`. The options bar's two `circle-dot` buttons are drawn from +//! these same two fields (`crates/ui-egui/src/panels/options_bar.rs`), so off here means drawn +//! off there. + +use crate::Session; +use photocraft_paint::brush::BrushSettings; +use serde_json::{Value, json}; + +/// The brush a fresh session starts with: neither pressure toggle on. +#[test] +fn the_default_brush_has_neither_pressure_toggle_on() { + let b = BrushSettings::default(); + assert!(!b.pressure_size, "Pressure for Size is off by default, as the reference leaves it after Reset Tool (#11809)"); + assert!(!b.pressure_opacity, "Pressure for Opacity stays off"); +} + +/// What `brush.get` answers on a fresh session, which is what the options bar reads to draw the +/// two toggles. +#[test] +fn brush_get_reports_both_pressure_toggles_off() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let got = s.execute("brush.get", json!({})).unwrap(); + assert_eq!(got["pressureSize"], json!(false), "brush.get reports Pressure for Size off (#11809)"); + assert_eq!(got["pressureOpacity"], json!(false), "brush.get reports Pressure for Opacity off"); + // The session's own starting brush is the default brush at Photoshop's 10 % smoothing — the + // same brush Reset Tool hands back — so only the smoothing differs. + assert_eq!( + s.tools.brush, + BrushSettings { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..BrushSettings::default() } + ); +} + +/// A brush that does not name the field — a preset saved before #11809, an older recorded +/// command — takes the off default rather than the old on one. +#[test] +fn a_brush_that_omits_the_field_takes_the_off_default() { + let b: BrushSettings = serde_json::from_value(json!({"size": 30.0, "hardness": 1.0})).unwrap(); + assert!(!b.pressure_size, "an omitted pressureSize reads as off (#11809)"); + assert!(!b.pressure_opacity, "an omitted pressureOpacity reads as off"); + assert_eq!(b.size, 30.0, "the fields that are there still apply"); +} + +/// Switching it on still works: `tools.setBrush` writes the field `brush.get` reads back, and the +/// same field the options-bar button is drawn from. +#[test] +fn pressure_for_size_still_switches_on_and_off() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + assert!(s.tools.brush.pressure_size, "the toggle still turns on"); + assert_eq!(s.execute("brush.get", json!({})).unwrap()["pressureSize"], json!(true)); + s.execute("tools.setBrush", json!({"brush": {"pressureSize": false}})).unwrap(); + assert!(!s.tools.brush.pressure_size, "and off again"); + assert!(!s.tools.brush.pressure_opacity, "it never touches Pressure for Opacity"); +} + +/// One stroke of a pressure ramp (0.3 → 0.65 → 1.0) across a new empty layer with `brush`: the +/// layer's pixels and what the stroke covers. +fn ramp(brush: Value) -> (Vec, photocraft_geom::Rect) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 40})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.stroke", json!({"points": [[20.0, 20.0, 0.3], [40.0, 20.0, 0.65], [60.0, 20.0, 1.0]], "size": 24.0, "color": "#ff0000", "brush": brush})) + .unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (surf.read_region(st.doc.bounds()), surf.content_bounds()) +} + +/// Done when 2: a pen stroke with varying pressure and the default brush keeps a constant size, +/// so it paints exactly what the same stroke with Pressure for Size turned off does — and +/// something else with it turned on, which is what makes this say anything. +#[test] +fn a_default_brush_stroke_keeps_its_size_under_a_pressure_ramp() { + let (off, off_box) = ramp(json!({"spacing": 0.25, "pressureSize": false})); + let (on, on_box) = ramp(json!({"spacing": 0.25, "pressureSize": true})); + let (dflt, dflt_box) = ramp(json!({"spacing": 0.25})); + assert_ne!(on, off, "the ramp alone does not change the stroke: Pressure for Size has to"); + assert_eq!(dflt, off, "the default brush paints like Pressure for Size off (#11809)"); + assert_eq!(dflt_box, off_box, "and reaches as far under the whole ramp"); + assert_ne!(dflt_box, on_box, "the turned-on brush still tapers the stroke's ends"); +} diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index c29d4c3146..f72a0e207b 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -26,8 +26,9 @@ fn stroke_backwards_compatible() { assert_eq!(r["damage"].as_array().unwrap().len(), 4); assert_eq!(rgba(&s, 30, 20), [0.0, 0.0, 1.0, 1.0]); assert_eq!(rgba(&s, 30, 30)[3], 0.0); - // [x, y, pressure] with the default pressure-size brush: light pressure → thinner line. - s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10})).unwrap(); + // [x, y, pressure] with Pressure for Size on: light pressure → a thinner line. The default + // brush has it off since #11809, so this stroke asks for it. + s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10, "brush": {"pressureSize": true}})).unwrap(); assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 47394823d6..5a44943345 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -653,6 +653,9 @@ fn stroke_path_simulate_pressure_tapers_both_ends() { let coverage = |simulate: bool, x: i32| -> usize { let mut s = session(200, 60, 8); s.execute("layer.new.layer", json!({})).unwrap(); + // Simulate Pressure tapers a brush that follows pen pressure; the default brush stopped + // doing that on its own (#11809). + s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); s.execute("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": [[20, 30], [180, 30]]}]}})).unwrap(); let p = json!({"tool": "brush", "size": 20, "hardness": 1.0, "color": "#000000", "opacity": 100, "simulatePressure": simulate}); s.execute("path.stroke", p).unwrap(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 468efec851..b66eaa15dd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -332,6 +332,8 @@ pub struct Session { pub damage_misses: usize, } +#[cfg(test)] +mod brush_pressure_size_default_tests; #[cfg(test)] mod embed_all_linked_tests; #[cfg(test)] diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index e43da363c5..a4de8a0c85 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -630,7 +630,8 @@ impl Default for BrushSettings { spacing_enabled: true, opacity: 1.0, flow: 1.0, - pressure_size: true, + // Off, as the reference application leaves it after Reset Tool (#11809). + pressure_size: false, pressure_opacity: false, color: [0.0, 0.0, 0.0, 1.0], color_cmyk: None, diff --git a/crates/ui-egui/src/panels/brush_preview.rs b/crates/ui-egui/src/panels/brush_preview.rs index f77975d45c..ba345d51e7 100644 --- a/crates/ui-egui/src/panels/brush_preview.rs +++ b/crates/ui-egui/src/panels/brush_preview.rs @@ -296,7 +296,9 @@ mod tests { #[test] fn preview_draws_a_stroke_that_fits() { - let mut b = BrushSettings { size: 400.0, ..Default::default() }; + // The preview's S-curve carries a pressure ramp, so the coverage window below is a + // tapering stroke's: Pressure for Size is off by default since #11809, so the brush asks. + let mut b = BrushSettings { size: 400.0, pressure_size: true, ..Default::default() }; let px = preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]); assert_eq!(px.len(), 120 * 40 * 4); let covered = px.as_chunks::<4>().0.iter().filter(|p| p[3] > 128).count(); From c392cb8cdfd71d6e0a9b12aac461693b26b3718b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 22:25:05 -0800 Subject: [PATCH 36/43] Sample the targeted layer mask with the Eyedropper --- crates/ui-egui/src/canvas/cursors.rs | 47 ++++- .../src/eyedropper_mask_sample_tests.rs | 177 ++++++++++++++++++ 2 files changed, 220 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/eyedropper_mask_sample_tests.rs diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index dee8017444..d7fedca6df 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -204,15 +204,50 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: } pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - if let Some(mut rgb) = eyedropper_color(app, x, y) { - if super::paint_target(app) != json!("pixels") { - rgb = [photocraft_color::convert::rgb_to_gray(rgb); 3]; - } + let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { + sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) + } else { + eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] }) + }; + if let Some(rgb) = rgb { let key = if mods.alt { "background" } else { "foreground" }; let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); } } +/// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask. +fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> { + use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds}; + + if app.active_tool() != Tool::Eyedropper + || app.ui.vector_mask_target + || !matches!(app.ui.tool_options.eyedropper_sample.as_str(), "current" | "currentAndBelow") + { + return None; + } + let st = app.session.active()?; + // Painting can implicitly edit an adjustment's mask even with its content thumbnail selected. + let targeted = app.ui.mask_target || st.channel_view.target == ChannelTarget::LayerMask || mask_view_cmds::current(st).is_some_and(|v| !v.filter); + if !targeted || st.doc.quick_mask.is_some() || !app.layer_mask_targeted() { + return None; + } + let mask = st.doc.layer(st.active_layer?)?.mask.as_ref()?; + Some((&mask.surface, st.doc.bounds())) +} + +/// Read the stored mask channel, including its sparse default, rather than its composited coverage. +fn sample_layer_mask(surface: &photocraft_raster::Surface, canvas: photocraft_geom::Rect, x: f64, y: f64, size: u32) -> Option<[f32; 3]> { + let rect = photocraft_engine::cmd::sample_cmds::sample_rect(x, y, size, canvas)?; + let mut sum = 0.0; + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + sum += f64::from(surface.sample_channel(x, y, 0)); + } + } + let gray = (sum / (f64::from(rect.width()) * f64::from(rect.height()))) as f32; + gray.is_finite().then_some([gray; 3]) +} + /// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel, /// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`). /// `None` off the image or over transparency. @@ -248,3 +283,7 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: egui::Modifiers) -> bool { pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { alt_samples(tool, mods) || alt_loads_mixer(tool, mods) } + +#[cfg(test)] +#[path = "../eyedropper_mask_sample_tests.rs"] +mod eyedropper_mask_sample_tests; diff --git a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs new file mode 100644 index 0000000000..671d04b345 --- /dev/null +++ b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs @@ -0,0 +1,177 @@ +use egui::Modifiers; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + +fn app_with_mask(adjustment: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); + app.session + .edit("Paint red", |doc, _| { + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 0, 8, 8), &photocraft_raster::from_rgba(&surface.format(), RED)); + Ok(()) + }) + .unwrap(); + let add = if adjustment { "layer.newAdjustmentLayer.invert" } else { "layer.layerMask.revealAll" }; + app.run(add, json!({})).unwrap(); + assert!(app.ui.mask_target); + app.ui.tool = Tool::Eyedropper; + app +} + +fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("Paint mask", |doc, _| { + doc.layer_mut(layer).unwrap().mask.as_mut().unwrap().surface.fill_rect(rect, &[gray]); + Ok(()) + }) + .unwrap(); +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); +} + +fn gray(value: f32) -> [f32; 4] { + [value, value, value, 1.0] +} + +/// Both measured modes pick white and mid-grey from the selected mask on either layer kind. +#[test] +fn targeted_pixel_and_adjustment_masks_supply_point_samples() { + for adjustment in [false, true] { + let mut app = app_with_mask(adjustment); + paint_mask(&mut app, Rect::new(2, 2, 3, 3), 0.5); + for mode in ["current", "currentAndBelow"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + app.run("tools.setColors", json!({"foreground": "#222222"})).unwrap(); + click(&mut app, 1.5, 1.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(1.0), "adjustment={adjustment} {mode}"); + click(&mut app, 2.5, 2.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(128.0 / 255.0), "adjustment={adjustment} {mode}"); + } + } +} + +/// The average at the corner counts only four in-canvas mask pixels and Alt writes background. +#[test] +fn mask_average_clips_at_canvas_edge_and_alt_sets_background() { + let mut app = app_with_mask(false); + paint_mask(&mut app, Rect::new(0, 0, 1, 2), 0.0); + app.ui.tool_options.eyedropper_sample = "currentAndBelow".into(); + app.ui.tool_options.eyedropper_size = 3; + app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap(); + let foreground = app.session.tools.foreground; + click(&mut app, 0.5, 0.5, Modifiers::ALT); + assert_eq!(app.session.tools.background, gray(0.5)); + assert_eq!(app.session.tools.foreground, foreground); +} + +/// Composite modes use the image, and selecting contents restores the same sampling as before. +#[test] +fn composite_modes_and_pixel_targets_still_sample_the_image() { + let mut app = app_with_mask(true); + for mode in ["all", "allNoAdjustments", "currentAndBelowNoAdjustments"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": mode})).unwrap(); + let [r, g, b, _]: [f32; 4] = serde_json::from_value(sample).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(photocraft_color::convert::rgb_to_gray([r, g, b])), "{mode}"); + } + // An adjustment's content thumbnail can still route painting to its mask. That is not an + // explicit Eyedropper target. + app.run("channel.target.composite", json!({})).unwrap(); + assert!(!app.ui.mask_target); + app.ui.tool_options.eyedropper_sample = "current".into(); + let before = app.session.tools.foreground; + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, before, "the adjustment alone has no image pixels"); + + let mut app = app_with_mask(false); + app.run("channel.target.composite", json!({})).unwrap(); + for mode in ["current", "currentAndBelow"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, RED, "{mode}"); + } +} + +/// A white raster mask beside another selected target cannot take over that target's sample. +#[test] +fn vector_alpha_quick_mask_and_temporary_samples_keep_their_source() { + let red_gray = gray(photocraft_color::convert::rgb_to_gray([1.0, 0.0, 0.0])); + let mut app = app_with_mask(false); + app.ui.tool_options.eyedropper_sample = "current".into(); + app.ui.tool = Tool::Brush; + click(&mut app, 4.5, 4.5, Modifiers::ALT); + assert_eq!(app.session.tools.foreground, red_gray, "the brush's Alt-click still samples the image"); + + app.ui.tool = Tool::Eyedropper; + app.run("layer.vectorMask.revealAll", json!({})).unwrap(); + assert!(app.ui.vector_mask_target); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, RED, "a vector target does not pick the raster mask"); + + app.run("channel.new", json!({"name": "Alpha"})).unwrap(); + app.run("channel.target", json!({"channel": {"alpha": 0}})).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, red_gray, "an alpha target does not pick the raster mask"); + + app.run("channel.target.layerMask", json!({})).unwrap(); + app.run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, red_gray, "Quick Mask does not pick the raster mask"); +} + +/// A smart filter's mask keeps its image-based sample even when the same layer has a raster mask. +#[test] +fn filter_mask_target_keeps_the_image_based_sample() { + let mut app = app_with_mask(false); + app.background_jobs = false; + app.run("channel.target.composite", json!({})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + assert!(app.session.active().unwrap().doc.layer(layer).unwrap().mask.is_some()); + app.select_filter_mask_target(Some(layer.0)); + assert!(app.filter_mask_targeted()); + app.ui.tool_options.eyedropper_sample = "current".into(); + let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": "current"})).unwrap(); + let [r, g, b, a]: [f32; 4] = serde_json::from_value(sample).unwrap(); + let want = gray(photocraft_color::convert::rgb_to_gray([r, g, b])); + assert!(a > 0.0 && want != gray(1.0), "the image and layer mask are distinct"); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, want); +} + +/// Out-of-canvas points and invalid sample options leave both swatches intact. +#[test] +fn invalid_mask_samples_leave_both_swatches_unchanged() { + let mut app = app_with_mask(false); + app.ui.tool_options.eyedropper_sample = "current".into(); + app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap(); + let before = (app.session.tools.foreground, app.session.tools.background); + let assert_unchanged = |app: &PhotocraftApp| assert_eq!((app.session.tools.foreground, app.session.tools.background), before); + for (x, y) in [(-0.1, 1.0), (1.0, 8.0), (f64::NAN, 1.0), (1.0, f64::INFINITY)] { + for mods in [Modifiers::NONE, Modifiers::ALT] { + click(&mut app, x, y, mods); + assert_unchanged(&app); + } + } + app.ui.tool_options.eyedropper_size = 2; + click(&mut app, 1.0, 1.0, Modifiers::NONE); + assert_unchanged(&app); + app.ui.tool_options.eyedropper_size = 1; + app.ui.tool_options.eyedropper_sample = "invalid".into(); + click(&mut app, 1.0, 1.0, Modifiers::ALT); + assert_unchanged(&app); +} From daf1d48d880936d9c568e62181d360e9055e5df0 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 01:50:14 -0500 Subject: [PATCH 37/43] fix(engine): deleting the current count group makes the first group current (#11771) count.deleteGroup kept the same index current after deleting the current group, so with three groups and the second current the third became current. The first remaining group now becomes current, as the reference application does. Deleting another group by index still keeps the current one (#5654), and deleting the last group still leaves none. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/analysis_cmds.rs | 10 ++- .../src/cmd/count_delete_group_tests.rs | 61 +++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/count_delete_group_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4c911e6be0..6aa64b7921 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -67,6 +67,8 @@ pub mod color_cmds; pub mod color_to_alpha_cmds; pub mod comps_cmds; pub mod contour_lib_cmds; +#[cfg(test)] +mod count_delete_group_tests; pub mod cutout_cmds; pub mod distort_cmds; pub mod document_preset_cmds; diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 0bf2a335ad..d9d7d1510c 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -896,9 +896,15 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result { s.edit("Delete Count Group", |d, _| { d.measurement.count_groups.remove(g); let n = d.measurement.count_groups.len(); - // Removing a group before the active one shifts it down a slot. + // Deleting the current group makes the first one current (#11771); removing a group + // before the current one shifts it down a slot (#5654). let a = d.measurement.active_count_group; - d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1)); + let next = match g.cmp(&a) { + std::cmp::Ordering::Equal => 0, + std::cmp::Ordering::Less => a - 1, + std::cmp::Ordering::Greater => a, + }; + d.measurement.active_count_group = next.min(n.saturating_sub(1)); Ok(()) })?; Ok(count_json(doc(s)?.as_ref())) diff --git a/crates/engine/src/cmd/count_delete_group_tests.rs b/crates/engine/src/cmd/count_delete_group_tests.rs new file mode 100644 index 0000000000..bdabca1c73 --- /dev/null +++ b/crates/engine/src/cmd/count_delete_group_tests.rs @@ -0,0 +1,61 @@ +//! #11771: deleting the current count group makes the first remaining group current. Deleting +//! another group by index keeps the current one (#5654), and the last group goes without error. + +use serde_json::{Value, json}; + +use crate::Session; + +/// Three groups, each with one marker, and the second one current. +fn three_groups() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + for (i, name) in ["One", "Two", "Three"].iter().enumerate() { + s.execute("count.newGroup", json!({"name": name})).unwrap(); + s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap(); + } + s.execute("count.setGroup", json!({"group": 1})).unwrap(); + assert_eq!(current(&mut s), (1, "Two".to_string())); + s +} + +/// The current group's index and name. +fn current(s: &mut Session) -> (u64, String) { + let c = s.execute("image.analysis.countTool", json!({})).unwrap(); + let i = c["activeGroup"].as_u64().unwrap(); + let name = c["groups"].get(i as usize).and_then(|g| g["name"].as_str()).unwrap_or_default().to_string(); + (i, name) +} + +fn groups(s: &mut Session) -> usize { + s.execute("image.analysis.countTool", json!({})).unwrap()["groups"].as_array().map_or(0, Vec::len) +} + +#[test] +fn deleting_the_current_group_makes_the_first_one_current() { + for params in [json!({}), json!({"group": 1})] { + let mut s = three_groups(); + s.execute("count.deleteGroup", params.clone()).unwrap(); + assert_eq!(groups(&mut s), 2, "{params}"); + assert_eq!(current(&mut s), (0, "One".to_string()), "{params}"); + } +} + +#[test] +fn deleting_another_group_keeps_the_current_one() { + let mut s = three_groups(); + s.execute("count.deleteGroup", json!({"group": 2})).unwrap(); + assert_eq!(current(&mut s), (1, "Two".to_string())); + let mut s = three_groups(); + s.execute("count.deleteGroup", json!({"group": 0})).unwrap(); + assert_eq!(current(&mut s), (0, "Two".to_string())); +} + +#[test] +fn deleting_the_last_group_leaves_none() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("count.newGroup", json!({"name": "Only"})).unwrap(); + s.execute("count.deleteGroup", json!({})).unwrap(); + let c: Value = s.execute("image.analysis.countTool", json!({})).unwrap(); + assert_eq!(c["groups"].as_array().map(Vec::len), Some(0)); +} From 3b3c648f61c8e481b2e528f3ec288490146f8461 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 23:12:35 -0800 Subject: [PATCH 38/43] Reveal notes after creating one with the Note tool --- crates/ui-egui/src/tools/analysis_ui.rs | 22 +++-- .../src/tools/note_show_on_new_tests.rs | 82 +++++++++++++++++++ 2 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/tools/note_show_on_new_tests.rs diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 6cad2b2158..277d89e537 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -230,6 +230,21 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) { let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor})); } +#[cfg(test)] +#[path = "note_show_on_new_tests.rs"] +mod note_show_on_new_tests; + +/// Create a note with the tool's options and enable Show Notes after success. +pub(crate) fn create_note(app: &mut PhotocraftApp, x: f64, y: f64) -> Result { + let a = &app.ui.analysis; + let params = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": a.note_color}); + let result = app.run("notes.add", params)?; + app.ui.analysis.note_selected = result["index"].as_u64().map(|v| v as usize); + app.ui.analysis.notes = true; + app.ui.view.show.notes = true; + Ok(result) +} + /// Pointer input for the Ruler, Count, Note and Color Sampler tools. Returns true when consumed. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { let tool = app.active_tool(); @@ -318,12 +333,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.ui.analysis.drag = Some(Drag::Note(i, [x - doc.notes[i].position[0], y - doc.notes[i].position[1]])); } None => { - let a = &app.ui.analysis; - let p = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": [a.note_color[0], a.note_color[1], a.note_color[2]]}); - if let Ok(r) = app.run("notes.add", p) { - app.ui.analysis.note_selected = r["index"].as_u64().map(|v| v as usize); - app.ui.analysis.notes = true; - } + let _ = create_note(app, x, y); } } } diff --git a/crates/ui-egui/src/tools/note_show_on_new_tests.rs b/crates/ui-egui/src/tools/note_show_on_new_tests.rs new file mode 100644 index 0000000000..a2e2cb8e8c --- /dev/null +++ b/crates/ui-egui/src/tools/note_show_on_new_tests.rs @@ -0,0 +1,82 @@ +use super::{PhotocraftApp, Tool, ToolEvent, create_note, json}; + +fn note_tool() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.ui.tool = Tool::Note; + (app, egui::Context::default()) +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + if [x, y] != [end_x, end_y] { + crate::canvas::tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, egui::Modifiers::NONE); + } + crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE); +} + +#[test] +fn creating_a_note_rechecks_show_notes_and_reveals_both_notes() { + let (mut app, ctx) = note_tool(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + app.run("notes.add", json!({"x": 20, "y": 20})).unwrap(); + assert!(!app.ui.view.show.notes && !app.ui.analysis.notes); + assert!(!app.ui.view.shows(app.ui.view.show.notes)); + + app.ui.analysis.note_author = "QA".into(); + app.ui.analysis.note_color = [0.25, 0.5, 1.0]; + gesture(&mut app, [130.0, 70.0], [130.0, 70.0]); + + let notes = &app.session.active().unwrap().doc.notes; + assert_eq!(notes.len(), 2); + assert_eq!(notes[0].position, [20.0, 20.0]); + assert_eq!(notes[1].position, [130.0, 70.0]); + assert_eq!(notes[1].author, "QA"); + assert_eq!(notes[1].color.to_rgb(), [0.25, 0.5, 1.0]); + assert_eq!(app.ui.analysis.note_selected, Some(1)); + assert!(app.ui.analysis.notes && app.ui.view.shows(app.ui.view.show.notes)); + + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + assert!(!app.ui.view.shows(app.ui.view.show.notes)); +} + +#[test] +fn selecting_and_dragging_an_existing_note_preserve_hidden_notes() { + let (mut app, ctx) = note_tool(); + app.run("notes.add", json!({"x": 30, "y": 40, "author": "QA"})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + + gesture(&mut app, [32.0, 42.0], [32.0, 42.0]); + assert!(!app.ui.view.show.notes); + assert_eq!(app.ui.analysis.note_selected, Some(0)); + assert_eq!(app.ui.analysis.note_author, "QA"); + + gesture(&mut app, [32.0, 42.0], [62.0, 52.0]); + assert!(!app.ui.view.show.notes); + let notes = &app.session.active().unwrap().doc.notes; + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].position, [60.0, 50.0]); +} + +#[test] +fn creating_a_note_leaves_extras_off() { + let (mut app, ctx) = note_tool(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(!app.ui.view.show.notes && !app.ui.view.extras); + + gesture(&mut app, [130.0, 70.0], [130.0, 70.0]); + + assert_eq!(app.session.active().unwrap().doc.notes.len(), 1); + assert!(app.ui.view.show.notes); + assert!(!app.ui.view.extras && !app.ui.view.shows(app.ui.view.show.notes)); +} + +#[test] +fn rejected_note_creation_does_not_change_visibility_or_selection() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.view.show.notes = false; + assert!(create_note(&mut app, 20.0, 20.0).is_err()); + assert!(!app.ui.view.show.notes && !app.ui.analysis.notes); + assert_eq!(app.ui.analysis.note_selected, None); +} From 619576ebae5dfeaaf921f9ee40334c8e74a62f67 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 00:37:18 -0800 Subject: [PATCH 39/43] Preview the targeted layer mask in the Eyedropper ring --- crates/ui-egui/src/canvas/cursors.rs | 31 ++++++++++++++----- .../src/eyedropper_mask_sample_tests.rs | 29 ++++++++++++++++- 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index d7fedca6df..a9f694bd79 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -54,11 +54,11 @@ fn display_color(c: [f32; 3]) -> Color32 { Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) } -/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer -/// (what a click would pick) and the current foreground, or `None` where there is no colour -/// to sample (#213). +/// The Eyedropper ring's two colours at document point (x, y): the targeted raster mask or +/// image colour under the pointer, and the current foreground. Returns `None` when the +/// selected source has no sample (#213). pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> { - let new = eyedropper_color(app, x, y)?; + let new = sample_eyedropper_target(app, x, y, eyedropper_color)?; let fg = app.session.tools.foreground; Some((display_color(new), display_color([fg[0], fg[1], fg[2]]))) } @@ -203,18 +203,33 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: true } +/// Write the picked colour to the foreground, or to the background while Alt is held. +/// Image samples are converted to grey when the active paint target requires it. pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { - sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) - } else { + let rgb = sample_eyedropper_target(app, x, y, |app, x, y| { eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] }) - }; + }); if let Some(rgb) = rgb { let key = if mods.alt { "background" } else { "foreground" }; let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); } } +/// Share the raster-mask sample between the click and ring, with each caller choosing how +/// to use image samples. An unavailable sample from a targeted mask stays unavailable. +fn sample_eyedropper_target( + app: &mut PhotocraftApp, + x: f64, + y: f64, + sample_image: impl FnOnce(&mut PhotocraftApp, f64, f64) -> Option<[f32; 3]>, +) -> Option<[f32; 3]> { + if let Some((surface, canvas)) = eyedropper_mask_source(app) { + sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) + } else { + sample_image(app, x, y) + } +} + /// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask. fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> { use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds}; diff --git a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs index 671d04b345..3807ce21f0 100644 --- a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs +++ b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs @@ -1,13 +1,15 @@ -use egui::Modifiers; +use egui::{Color32, Modifiers}; use photocraft_geom::Rect; use serde_json::json; +use super::{display_color, eyedropper_color, eyedropper_ring_colors}; use crate::canvas::{ToolEvent, tool_event}; use crate::state::Tool; use crate::{PhotocraftApp, Services}; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +/// Put a fully revealed raster mask over red image content and select the mask and Eyedropper. fn app_with_mask(adjustment: bool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); @@ -25,6 +27,7 @@ fn app_with_mask(adjustment: bool) -> PhotocraftApp { app } +/// Set the stored mask channel directly while leaving the image pixels unchanged. fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { let layer = app.session.active().unwrap().active_layer.unwrap(); app.session @@ -35,11 +38,13 @@ fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { .unwrap(); } +/// Use the canvas tool events so swatch assertions exercise the normal click path. fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); tool_event(app, ToolEvent::Up { x, y }, mods); } +/// The opaque greyscale RGBA value stored in a swatch after a mask sample. fn gray(value: f32) -> [f32; 4] { [value, value, value, 1.0] } @@ -61,6 +66,24 @@ fn targeted_pixel_and_adjustment_masks_supply_point_samples() { } } +/// The held ring previews the same adjustment-mask value that the click writes in both modes. +#[test] +fn targeted_mask_ring_previews_the_click_sample() { + let mut app = app_with_mask(true); + paint_mask(&mut app, Rect::new(0, 0, 1, 2), 0.0); + app.ui.tool_options.eyedropper_sample = "current".into(); + assert!(eyedropper_color(&mut app, 4.5, 4.5).is_none(), "the adjustment alone has no image pixels"); + + for (mode, size, point, ring, swatch) in [("current", 1, 4.5, Color32::WHITE, gray(1.0)), ("currentAndBelow", 3, 0.5, Color32::from_gray(128), gray(0.5))] { + app.ui.tool_options.eyedropper_sample = mode.into(); + app.ui.tool_options.eyedropper_size = size; + app.run("tools.setColors", json!({"foreground": "#222222"})).unwrap(); + assert_eq!(eyedropper_ring_colors(&mut app, point, point), Some((ring, Color32::from_gray(34))), "{mode}"); + click(&mut app, point, point, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, swatch, "{mode}"); + } +} + /// The average at the corner counts only four in-canvas mask pixels and Alt writes background. #[test] fn mask_average_clips_at_canvas_edge_and_alt_sets_background() { @@ -83,6 +106,7 @@ fn composite_modes_and_pixel_targets_still_sample_the_image() { app.ui.tool_options.eyedropper_sample = mode.into(); let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": mode})).unwrap(); let [r, g, b, _]: [f32; 4] = serde_json::from_value(sample).unwrap(); + assert_eq!(eyedropper_ring_colors(&mut app, 4.5, 4.5).map(|(sample, _)| sample), Some(display_color([r, g, b])), "{mode}"); click(&mut app, 4.5, 4.5, Modifiers::NONE); assert_eq!(app.session.tools.foreground, gray(photocraft_color::convert::rgb_to_gray([r, g, b])), "{mode}"); } @@ -162,16 +186,19 @@ fn invalid_mask_samples_leave_both_swatches_unchanged() { let before = (app.session.tools.foreground, app.session.tools.background); let assert_unchanged = |app: &PhotocraftApp| assert_eq!((app.session.tools.foreground, app.session.tools.background), before); for (x, y) in [(-0.1, 1.0), (1.0, 8.0), (f64::NAN, 1.0), (1.0, f64::INFINITY)] { + assert!(eyedropper_ring_colors(&mut app, x, y).is_none()); for mods in [Modifiers::NONE, Modifiers::ALT] { click(&mut app, x, y, mods); assert_unchanged(&app); } } app.ui.tool_options.eyedropper_size = 2; + assert!(eyedropper_ring_colors(&mut app, 1.0, 1.0).is_none()); click(&mut app, 1.0, 1.0, Modifiers::NONE); assert_unchanged(&app); app.ui.tool_options.eyedropper_size = 1; app.ui.tool_options.eyedropper_sample = "invalid".into(); + assert!(eyedropper_ring_colors(&mut app, 1.0, 1.0).is_none()); click(&mut app, 1.0, 1.0, Modifiers::ALT); assert_unchanged(&app); } From 2fffb1038686494b7bc49467b3b1e20ab06eb562 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 00:46:06 -0800 Subject: [PATCH 40/43] Test denied note creation through the pointer handler --- crates/ui-egui/src/tools/analysis_ui.rs | 4 +- .../src/tools/note_show_on_new_tests.rs | 42 ++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 277d89e537..d0cb841424 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -234,7 +234,9 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) { #[path = "note_show_on_new_tests.rs"] mod note_show_on_new_tests; -/// Create a note with the tool's options and enable Show Notes after success. +/// Create a note at the rounded document position using the Note tool's options. +/// After `notes.add` succeeds, select the note and open the Notes panel. Enable Show Notes +/// while leaving the master Extras switch alone. pub(crate) fn create_note(app: &mut PhotocraftApp, x: f64, y: f64) -> Result { let a = &app.ui.analysis; let params = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": a.note_color}); diff --git a/crates/ui-egui/src/tools/note_show_on_new_tests.rs b/crates/ui-egui/src/tools/note_show_on_new_tests.rs index a2e2cb8e8c..eb9d876fe8 100644 --- a/crates/ui-egui/src/tools/note_show_on_new_tests.rs +++ b/crates/ui-egui/src/tools/note_show_on_new_tests.rs @@ -1,5 +1,10 @@ -use super::{PhotocraftApp, Tool, ToolEvent, create_note, json}; +use std::cell::Cell; +use std::rc::Rc; +use super::{PhotocraftApp, Tool, ToolEvent, json}; +use crate::control::{ControlRequest, Outcome, handle}; + +/// Open a document with the Note tool active and no notes yet. fn note_tool() -> (PhotocraftApp, egui::Context) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); @@ -7,6 +12,7 @@ fn note_tool() -> (PhotocraftApp, egui::Context) { (app, egui::Context::default()) } +/// Send a click or drag to the canvas in document coordinates. fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); if [x, y] != [end_x, end_y] { @@ -15,6 +21,7 @@ fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE); } +/// A new note reveals both icons, and the menu can hide them again. #[test] fn creating_a_note_rechecks_show_notes_and_reveals_both_notes() { let (mut app, ctx) = note_tool(); @@ -40,6 +47,7 @@ fn creating_a_note_rechecks_show_notes_and_reveals_both_notes() { assert!(!app.ui.view.shows(app.ui.view.show.notes)); } +/// Selecting or moving a stored note keeps Show Notes off. #[test] fn selecting_and_dragging_an_existing_note_preserve_hidden_notes() { let (mut app, ctx) = note_tool(); @@ -58,6 +66,7 @@ fn selecting_and_dragging_an_existing_note_preserve_hidden_notes() { assert_eq!(notes[0].position, [60.0, 50.0]); } +/// Creating a note rechecks Show Notes while Extras still suppresses the overlay. #[test] fn creating_a_note_leaves_extras_off() { let (mut app, ctx) = note_tool(); @@ -72,11 +81,34 @@ fn creating_a_note_leaves_extras_off() { assert!(!app.ui.view.extras && !app.ui.view.shows(app.ui.view.show.notes)); } +/// A denied canvas creation preserves the selected note and visibility settings. #[test] fn rejected_note_creation_does_not_change_visibility_or_selection() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let (mut app, ctx) = note_tool(); + app.run("notes.add", json!({"x": 20, "y": 20})).unwrap(); + app.run("notes.add", json!({"x": 70, "y": 20})).unwrap(); + gesture(&mut app, [72.0, 22.0], [72.0, 22.0]); + assert_eq!(app.ui.analysis.note_selected, Some(1)); app.ui.view.show.notes = false; - assert!(create_note(&mut app, 20.0, 20.0).is_err()); - assert!(!app.ui.view.show.notes && !app.ui.analysis.notes); - assert_eq!(app.ui.analysis.note_selected, None); + app.ui.analysis.notes = false; + app.ui.view.extras = false; + + let denials = Rc::new(Cell::new(0)); + let observed_denials = Rc::clone(&denials); + app.services.automation_command = Some(Box::new(move |id, _| { + if id == "notes.add" { + observed_denials.set(observed_denials.get() + 1); + return Err("note creation denied".into()); + } + Ok(()) + })); + app.automation_input = true; + let (request, _reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 130, "y": 70}, {"kind": "up", "x": 130, "y": 70}]})); + let Outcome::Done(reply) = handle(&mut app, &ctx, &request) else { panic!("ui.pointer should reply immediately") }; + + assert_eq!(reply["ok"], true); + assert_eq!(denials.get(), 1); + assert!(!app.ui.view.show.notes && !app.ui.analysis.notes && !app.ui.view.extras); + assert_eq!(app.ui.analysis.note_selected, Some(1)); + assert_eq!(app.session.active().unwrap().doc.notes.len(), 2); } From c2ce77df7768b1a76b19d71663537d95e3718a19 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 01:06:13 -0800 Subject: [PATCH 41/43] Keep the Eyedropper mask fix within the click sampling scope --- crates/ui-egui/src/canvas/cursors.rs | 31 +++++-------------- .../src/eyedropper_mask_sample_tests.rs | 29 +---------------- 2 files changed, 9 insertions(+), 51 deletions(-) diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index a9f694bd79..d7fedca6df 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -54,11 +54,11 @@ fn display_color(c: [f32; 3]) -> Color32 { Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) } -/// The Eyedropper ring's two colours at document point (x, y): the targeted raster mask or -/// image colour under the pointer, and the current foreground. Returns `None` when the -/// selected source has no sample (#213). +/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer +/// (what a click would pick) and the current foreground, or `None` where there is no colour +/// to sample (#213). pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> { - let new = sample_eyedropper_target(app, x, y, eyedropper_color)?; + let new = eyedropper_color(app, x, y)?; let fg = app.session.tools.foreground; Some((display_color(new), display_color([fg[0], fg[1], fg[2]]))) } @@ -203,33 +203,18 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: true } -/// Write the picked colour to the foreground, or to the background while Alt is held. -/// Image samples are converted to grey when the active paint target requires it. pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - let rgb = sample_eyedropper_target(app, x, y, |app, x, y| { + let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { + sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) + } else { eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] }) - }); + }; if let Some(rgb) = rgb { let key = if mods.alt { "background" } else { "foreground" }; let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); } } -/// Share the raster-mask sample between the click and ring, with each caller choosing how -/// to use image samples. An unavailable sample from a targeted mask stays unavailable. -fn sample_eyedropper_target( - app: &mut PhotocraftApp, - x: f64, - y: f64, - sample_image: impl FnOnce(&mut PhotocraftApp, f64, f64) -> Option<[f32; 3]>, -) -> Option<[f32; 3]> { - if let Some((surface, canvas)) = eyedropper_mask_source(app) { - sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) - } else { - sample_image(app, x, y) - } -} - /// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask. fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> { use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds}; diff --git a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs index 3807ce21f0..671d04b345 100644 --- a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs +++ b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs @@ -1,15 +1,13 @@ -use egui::{Color32, Modifiers}; +use egui::Modifiers; use photocraft_geom::Rect; use serde_json::json; -use super::{display_color, eyedropper_color, eyedropper_ring_colors}; use crate::canvas::{ToolEvent, tool_event}; use crate::state::Tool; use crate::{PhotocraftApp, Services}; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; -/// Put a fully revealed raster mask over red image content and select the mask and Eyedropper. fn app_with_mask(adjustment: bool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); @@ -27,7 +25,6 @@ fn app_with_mask(adjustment: bool) -> PhotocraftApp { app } -/// Set the stored mask channel directly while leaving the image pixels unchanged. fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { let layer = app.session.active().unwrap().active_layer.unwrap(); app.session @@ -38,13 +35,11 @@ fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { .unwrap(); } -/// Use the canvas tool events so swatch assertions exercise the normal click path. fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); tool_event(app, ToolEvent::Up { x, y }, mods); } -/// The opaque greyscale RGBA value stored in a swatch after a mask sample. fn gray(value: f32) -> [f32; 4] { [value, value, value, 1.0] } @@ -66,24 +61,6 @@ fn targeted_pixel_and_adjustment_masks_supply_point_samples() { } } -/// The held ring previews the same adjustment-mask value that the click writes in both modes. -#[test] -fn targeted_mask_ring_previews_the_click_sample() { - let mut app = app_with_mask(true); - paint_mask(&mut app, Rect::new(0, 0, 1, 2), 0.0); - app.ui.tool_options.eyedropper_sample = "current".into(); - assert!(eyedropper_color(&mut app, 4.5, 4.5).is_none(), "the adjustment alone has no image pixels"); - - for (mode, size, point, ring, swatch) in [("current", 1, 4.5, Color32::WHITE, gray(1.0)), ("currentAndBelow", 3, 0.5, Color32::from_gray(128), gray(0.5))] { - app.ui.tool_options.eyedropper_sample = mode.into(); - app.ui.tool_options.eyedropper_size = size; - app.run("tools.setColors", json!({"foreground": "#222222"})).unwrap(); - assert_eq!(eyedropper_ring_colors(&mut app, point, point), Some((ring, Color32::from_gray(34))), "{mode}"); - click(&mut app, point, point, Modifiers::NONE); - assert_eq!(app.session.tools.foreground, swatch, "{mode}"); - } -} - /// The average at the corner counts only four in-canvas mask pixels and Alt writes background. #[test] fn mask_average_clips_at_canvas_edge_and_alt_sets_background() { @@ -106,7 +83,6 @@ fn composite_modes_and_pixel_targets_still_sample_the_image() { app.ui.tool_options.eyedropper_sample = mode.into(); let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": mode})).unwrap(); let [r, g, b, _]: [f32; 4] = serde_json::from_value(sample).unwrap(); - assert_eq!(eyedropper_ring_colors(&mut app, 4.5, 4.5).map(|(sample, _)| sample), Some(display_color([r, g, b])), "{mode}"); click(&mut app, 4.5, 4.5, Modifiers::NONE); assert_eq!(app.session.tools.foreground, gray(photocraft_color::convert::rgb_to_gray([r, g, b])), "{mode}"); } @@ -186,19 +162,16 @@ fn invalid_mask_samples_leave_both_swatches_unchanged() { let before = (app.session.tools.foreground, app.session.tools.background); let assert_unchanged = |app: &PhotocraftApp| assert_eq!((app.session.tools.foreground, app.session.tools.background), before); for (x, y) in [(-0.1, 1.0), (1.0, 8.0), (f64::NAN, 1.0), (1.0, f64::INFINITY)] { - assert!(eyedropper_ring_colors(&mut app, x, y).is_none()); for mods in [Modifiers::NONE, Modifiers::ALT] { click(&mut app, x, y, mods); assert_unchanged(&app); } } app.ui.tool_options.eyedropper_size = 2; - assert!(eyedropper_ring_colors(&mut app, 1.0, 1.0).is_none()); click(&mut app, 1.0, 1.0, Modifiers::NONE); assert_unchanged(&app); app.ui.tool_options.eyedropper_size = 1; app.ui.tool_options.eyedropper_sample = "invalid".into(); - assert!(eyedropper_ring_colors(&mut app, 1.0, 1.0).is_none()); click(&mut app, 1.0, 1.0, Modifiers::ALT); assert_unchanged(&app); } From d40d8a527882d5cc4cdfa4004cdafb623f3919f9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 01:19:26 -0800 Subject: [PATCH 42/43] Document the Eyedropper sample and mask fixture --- crates/ui-egui/src/canvas/cursors.rs | 2 ++ crates/ui-egui/src/eyedropper_mask_sample_tests.rs | 1 + 2 files changed, 3 insertions(+) diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index d7fedca6df..e692c4fe07 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -203,6 +203,8 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: true } +/// Sample the image or targeted raster mask at (x, y) using the configured Sample Size. +/// Write a valid sample to the foreground swatch, or to the background swatch with Alt. pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) diff --git a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs index 671d04b345..d36de6b33c 100644 --- a/crates/ui-egui/src/eyedropper_mask_sample_tests.rs +++ b/crates/ui-egui/src/eyedropper_mask_sample_tests.rs @@ -8,6 +8,7 @@ use crate::{PhotocraftApp, Services}; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +/// Select the Eyedropper and target a fully revealed mask on a red pixel layer or an Invert adjustment above it. fn app_with_mask(adjustment: bool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); From 3c4431945502852092f9096f403dae5c8ef0481d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 13:56:20 +0100 Subject: [PATCH 43/43] docs: regenerate the scorecard after #11322 added a setting (#11983) The prefs audit counts 193 settings since Preferences.groupTools landed; docs/scorecard.md still said 192, which failed the gate and the Windows staleness test on main. Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 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`.