From 5d3557281ea87108970f397794c4f3c332fb0da9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 13:02:10 +0200 Subject: [PATCH 01/27] Dropdowns: popups as tall as their items, up to the window (#5495) egui's ComboBox capped every list at the size its popup takes on the frame it opens (default_area_size, 400 pt), so the Layers panel's 27 blend modes scrolled even in tall windows. widgets::combo_list draws the button and its list itself (keeping egui's ids): the list is as tall as its options up to the visible window and scrolls only past that. It opens below the button at its left edge, or moves up over it to fit, never beside it, so it stays put while wheel steps change the value and the button's width (#1747). All five former .height(420) dropdowns use it. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/adjust_editors.rs | 55 ++-- .../ui-egui/src/blend_dropdown_wheel_tests.rs | 11 +- crates/ui-egui/src/crop_presets.rs | 2 +- crates/ui-egui/src/type_tool.rs | 20 +- crates/ui-egui/src/widgets.rs | 305 ++++++++++++++---- 5 files changed, 282 insertions(+), 111 deletions(-) diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 2678cc65f2..605c4b8c58 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -1384,38 +1384,33 @@ fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { label(ui, tl!("Preset:")); let mut picked = None; let (press, close) = crate::press_menu::PressCombo::before(ui, cx.mem.with("gm-preset")); - let combo = egui::ComboBox::from_id_salt(cx.mem.with("gm-preset")) - .selected_text(tl!("Custom")) - .width(ui.available_width().min(190.0)) - .height(420.0) - .icon(widgets::chevron_icon) - .close_behavior(close) - .show_ui(ui, |ui| { - let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); - egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { - if ui.button(tl!("Import .GRD")).clicked() { - e.import_gradients = true; - ui.close(); - } - }); - ui.separator(); - for g in &cx.gradients { - ui.label(RichText::new(&g.name).color(t.text_faint)); - for p in &g.items { - ui.horizontal(|ui| { - // A map has no transparency: colour stops only, shown opaque. - let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); - let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); - crate::preset_panels::paint_gradient(ui, r, &rgba); - // Both, not short-circuited: the name is drawn either way. - let name = ui.selectable_label(false, &p.name); - if press.chosen(ui, &swatch) | press.chosen(ui, &name) { - picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); - } - }); - } + let width = ui.available_width().min(190.0); + let combo = widgets::combo_list(ui, cx.mem.with("gm-preset"), tl!("Custom"), width, close, |ui| { + let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); + egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { + if ui.button(tl!("Import .GRD")).clicked() { + e.import_gradients = true; + ui.close(); } }); + ui.separator(); + for g in &cx.gradients { + ui.label(RichText::new(&g.name).color(t.text_faint)); + for p in &g.items { + ui.horizontal(|ui| { + // A map has no transparency: colour stops only, shown opaque. + let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); + let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); + crate::preset_panels::paint_gradient(ui, r, &rgba); + // Both, not short-circuited: the name is drawn either way. + let name = ui.selectable_label(false, &p.name); + if press.chosen(ui, &swatch) | press.chosen(ui, &name) { + picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); + } + }); + } + } + }); press.after(&combo.response); if let Some(p) = picked { stops = p; diff --git a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs index c6b9186f86..31b28adbda 100644 --- a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs @@ -165,16 +165,17 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { let mut h = harness(pixel_layer); let at = dropdown(&h).center(); click(&mut h, at); - // Unscrolled, the list shows its first entry at the top and is at most 420 pt tall. - let (top, darken) = (entry(&h, "Normal").top(), entry(&h, "Darken").center()); + // The open list, unscrolled, shows its first entry at the top. + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))).unwrap(); + let darken = entry(&h, "Darken").center(); for _ in 0..22 { wheel(&mut h, darken, -1.0); } h.run_steps(30); assert_eq!(blend(&h), BlendMode::Divide); - let in_view = |r: Rect| r.top() >= top - 0.5 && r.bottom() <= top + 420.0 + 0.5; + let in_view = |r: Rect| list.contains_rect(r); let chosen = entry(&h, "Divide"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); // The wheel over the button scrolls the open list along too. for _ in 0..21 { wheel(&mut h, at, 1.0); @@ -182,7 +183,7 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { h.run_steps(30); assert_eq!(blend(&h), BlendMode::Dissolve); let chosen = entry(&h, "Dissolve"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); } /// The mode the canvas previews on the active layer, if any (#970). diff --git a/crates/ui-egui/src/crop_presets.rs b/crates/ui-egui/src/crop_presets.rs index e049fdfa8c..33966178c0 100644 --- a/crates/ui-egui/src/crop_presets.rs +++ b/crates/ui-egui/src/crop_presets.rs @@ -142,7 +142,7 @@ pub fn dropdown(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let current_user = users.iter().rev().find(|(_, f)| matches(o, f)).map(|(n, _)| n.clone()); let can_new = savable(o).is_some(); let mut chosen: Option = None; - egui::ComboBox::from_id_salt("crop-ratio").selected_text(label).width(140.0).height(420.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| { + crate::widgets::combo_list(ui, "crop-ratio", label, 140.0, egui::PopupCloseBehavior::CloseOnClick, |ui| { let (before, after): (Vec<_>, Vec<_>) = builtin.iter().partition(|(k, _)| k != crop_size::FRONT); for (k, l) in &before { if ui.selectable_label(current_user.is_none() && *k == o.crop_ratio, tl!(l)).clicked() { diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index f00fb57157..286b05e8c1 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1884,20 +1884,14 @@ fn kerning_field(ui: &mut egui::Ui, shown: &str, width: f32) -> Option(ui: &mut Ui, id: &str, current: &mut T, o let mut reveal = wheel && ui.data_mut(|d| d.remove_temp::(reveal_id)).unwrap_or(false); // The list opens on the press: press, drag onto an option and release to choose it (#2735). let (press, close) = crate::press_menu::PressCombo::before(ui, id); - let response = - egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, options.iter().map(|(_, l)| tl!(l))); - // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). - let labels: Vec<&str> = options.iter().map(|(_, l)| tl!(l)).collect(); - let shown = options.iter().position(|(v, _)| v == current); - if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, options.iter().map(|(_, l)| tl!(l))); + // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). + let labels: Vec<&str> = options.iter().map(|(_, l)| tl!(l)).collect(); + let shown = options.iter().position(|(v, _)| v == current); + if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + chosen.push(v.clone()); + reveal = true; + keyed = true; + } + // Over the open list the wheel steps the value too, instead of scrolling the list. + over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); + if over_list { + let stepped = wheel_steps(ui, wheel_id, true, current, options); + wheeled = !stepped.is_empty(); + reveal |= wheeled; + chosen.extend(stepped); + } + // The row nearest the pointer, by its distance to each row. + let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); + let mut nearest: Option<(f32, &T)> = None; + for (v, l) in options { + let item = ui.selectable_label(v == current, tl!(l)); + if reveal && v == current { + item.scroll_to_me(None); + } + if item.hovered() { + hovered = Some(v.clone()); + } + if let Some(p) = pointer { + let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); + if nearest.is_none_or(|(n, _)| d < n) { + nearest = Some((d, v)); + } + } + if press.chosen(ui, &item) { *current = v.clone(); chosen.push(v.clone()); - reveal = true; - keyed = true; } - // Over the open list the wheel steps the value too, instead of scrolling the list. - over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); - if over_list { - let stepped = wheel_steps(ui, wheel_id, true, current, options); - wheeled = !stepped.is_empty(); - reveal |= wheeled; - chosen.extend(stepped); - } - // The row nearest the pointer, by its distance to each row. - let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); - let mut nearest: Option<(f32, &T)> = None; - for (v, l) in options { - let item = ui.selectable_label(v == current, tl!(l)); - if reveal && v == current { - item.scroll_to_me(None); - } - if item.hovered() { - hovered = Some(v.clone()); - } - if let Some(p) = pointer { - let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); - if nearest.is_none_or(|(n, _)| d < n) { - nearest = Some((d, v)); - } - } - if press.chosen(ui, &item) { - *current = v.clone(); - chosen.push(v.clone()); - } - } - // Between two rows (item spacing) the pointer hovers neither; it is still over the list, - // so keep previewing the nearest row instead of flashing the current value back (#2553). - if hovered.is_none() { - hovered = nearest.map(|(_, v)| v.clone()); - } - }); + } + // Between two rows (item spacing) the pointer hovers neither; it is still over the list, + // so keep previewing the nearest row instead of flashing the current value back (#2553). + if hovered.is_none() { + hovered = nearest.map(|(_, v)| v.clone()); + } + }); press.after(&response.response); if combo_box_arrow_keys(ui, &response.response, current, options) { chosen.push(current.clone()); @@ -1473,14 +1472,117 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// 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. 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); + let room = popup_max_height(ui.ctx(), ui.spacing()); // 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 } +/// The most a popup's rows may take: the part of the window that can be seen (clear of a taskbar a +/// too-tall window runs under, #315), less the popup frame's margin and stroke and a small gap to +/// the window's edges. egui moves a popup up to keep it in the window, so a popup this tall fits. +pub fn popup_max_height(ctx: &egui::Context, spacing: &egui::style::Spacing) -> f32 { + let frame = spacing.menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; + (crate::work_area::visible_rect(ctx).height() - frame).max(MENU_MIN_HEIGHT) +} + +/// A dropdown: a button showing `selected_text` (at least `width` wide, wider for a longer text) +/// whose list (`add_contents`) opens below it on a click. The list is as tall as its options up to +/// the part of the window that can be seen, scrolling only past that (#5495): Photoshop's dropdowns +/// open at full height. egui's `ComboBox` capped every list at the size its popup takes on the +/// frame it opens (`default_area_size`, 400 pt), so the Layers panel's 27 blend modes scrolled. +/// +/// The list's left edge is the button's, and a list that doesn't fit below the button moves up +/// over it to stay in the window, never beside it: so it stays put while its value (and with it +/// the button's width) changes, as the wheel steps it over the open list (#1747). The ids are +/// egui's `ComboBox` ones, so `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. +pub fn combo_list( + ui: &mut Ui, + id_salt: impl egui::AsIdSalt, + selected_text: impl Into, + width: f32, + close: egui::PopupCloseBehavior, + add_contents: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let button_id = ui.make_persistent_id(egui::IdSalt::new(id_salt)); + let popup_id = button_id.with("popup"); + let selected_text = selected_text.into(); + ui.horizontal(|ui| { + let ctx = ui.ctx().clone(); + let button = combo_button(ui, button_id, &selected_text, width, egui::Popup::is_id_open(&ctx, popup_id)); + let enabled = ui.is_enabled(); + button.widget_info(|| { + let mut info = egui::WidgetInfo::new(egui::WidgetType::ComboBox); + info.enabled = enabled; + info.current_text_value = Some(selected_text.text().to_owned()); + info + }); + let room = popup_max_height(&ctx, ui.spacing()); + // Below the button, or as far up as the list's height (from the last frame) needs. + let visible = crate::work_area::visible_rect(&ctx).shrink(MENU_EDGE); + let height = egui::AreaState::load(&ctx, popup_id).and_then(|s| s.size).map_or(0.0, |s| s.y); + let top = button.rect.bottom().min(visible.bottom() - height).max(visible.top()); + let left = button.rect.left(); + let inner = egui::Popup::menu(&button) + .id(popup_id) + .anchor(Rect::from_x_y_ranges(left..=left, top..=top)) + .align(egui::RectAlign::BOTTOM_START) + .align_alternatives(&[]) + .width(button.rect.width()) + .close_behavior(close) + .style(egui::style::StyleModifier::default()) + .show(|ui| { + ui.set_min_width(ui.available_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. + egui::ScrollArea::vertical() + .max_height(room) + .min_scrolled_height(room) + .show(ui, |ui| { + // Options don't wrap in a list as narrow as its button: they widen it. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + add_contents(ui) + }) + .inner + }) + .map(|r| r.inner); + egui::InnerResponse::new(inner, button) + }) + .inner +} + +/// The button of a [`combo_list`], drawn as egui's `ComboBox` draws its own. +fn combo_button(ui: &mut Ui, id: egui::Id, text: &egui::WidgetText, width: f32, open: bool) -> Response { + let background = ui.painter().add(egui::Shape::Noop); + let margin = ui.spacing().button_padding; + let min_height = ui.spacing().interact_size.y; + let mut outer = ui.available_rect_before_wrap(); + outer.set_height(outer.height().max(min_height)); + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(outer.shrink2(margin))); + let icon_spacing = content.spacing().icon_spacing; + let icon_size = Vec2::splat(content.spacing().icon_width); + let wrap_mode = content.wrap_mode(); + let wrap_width = if wrap_mode == egui::TextWrapMode::Extend { f32::INFINITY } else { content.available_width() - icon_spacing - icon_size.x }; + let galley = text.clone().into_galley(&content, Some(wrap_mode), wrap_width, egui::TextStyle::Button); + let size = vec2((galley.size().x + icon_spacing + icon_size.x).max(width - 2.0 * margin.x), galley.size().y.max(icon_size.y)); + let (_, rect) = content.allocate_space(size); + let mut outer = content.min_rect().expand2(margin); + outer.set_height(outer.height().max(min_height)); + let response = ui.interact(outer, id, Sense::click()); + if ui.is_rect_visible(outer) { + let visuals = if open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; + let shape = + egui::epaint::RectShape::new(outer.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, StrokeKind::Inside); + ui.painter().set(background, shape); + let icon_rect = Align2::RIGHT_CENTER.align_size_within_rect(icon_size, rect); + chevron_icon(ui, icon_rect.expand(visuals.expansion), visuals, open); + let text_rect = Align2::LEFT_CENTER.align_size_within_rect(galley.size(), rect); + ui.painter().galley(text_rect.min, galley, visuals.text_color()); + } + ui.advance_cursor_after_rect(outer); + response +} + /// 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; @@ -1519,23 +1621,22 @@ pub fn dropdown_with_tooltips(ui: &mut Ui, id: &str, curre let label = options.iter().find(|(v, _, _)| v == current).map(|(_, l, _)| tl!(l)).unwrap_or("—"); let mut changed = false; let (press, close) = crate::press_menu::PressCombo::before(ui, id); - let response = - egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); - let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); - let shown = options.iter().position(|(v, _, _)| v == current); - if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); + let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); + let shown = options.iter().position(|(v, _, _)| v == current); + if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + changed = true; + } + for (v, l, tip) in options { + let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); + if press.chosen(ui, &item) { *current = v.clone(); changed = true; } - for (v, l, tip) in options { - let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); - if press.chosen(ui, &item) { - *current = v.clone(); - changed = true; - } - } - }); + } + }); press.after(&response.response); if let Some((_, _, tip)) = options.iter().find(|(v, _, _)| v == current) { let _ = response.response.on_hover_text(tl!(tip)); @@ -2237,6 +2338,86 @@ mod tests { } } + /// A window `height` tall with the Layers panel's blend mode dropdown (all 27 modes, wheel + /// steps them) `down` from its top, opened. + fn open_blend_modes(height: f32, down: f32) -> Harness<'static, photocraft_color::BlendMode> { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, height)).build_ui_state( + move |ui, mode: &mut BlendMode| { + ui.add_space(down); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + h + } + + /// The open list's rect. + fn open_list(h: &Harness<'_, T>) -> egui::Rect { + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); + let Some(list) = list else { panic!("the list is open") }; + list + } + + /// Each mode's row in the open list: its label's last node, as the box shows the chosen one's. + fn mode_rows(h: &Harness<'_, T>) -> Vec { + use photocraft_color::BlendMode; + BlendMode::LAYER_MODES.iter().map(|m| h.get_all_by_label(m.label()).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING)).collect() + } + + /// Photoshop opens the Layers panel's blend modes at full height when the window has room, no + /// scroll bar (#5495): not capped at a fixed height. A short window still scrolls the list, + /// which stays inside the window. + #[test] + fn dropdown_list_is_as_tall_as_its_options_up_to_the_window() { + let h = open_blend_modes(1000.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + for (i, row) in rows.iter().enumerate() { + assert!(list.contains_rect(*row), "row {i} {row:?} shows in the list {list:?}"); + } + let h = open_blend_modes(300.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + assert!(list.top() >= 0.0 && list.bottom() <= 300.0, "the list {list:?} stays in the window"); + assert!(list.height() > 200.0, "the list {list:?} uses the window's height"); + assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); + } + + /// The open list opens at the button's left edge, below it or moved up over it to fit, and + /// stays put while the wheel steps through every mode over it (#1747), although the button + /// widens for the longer names (#5495). + #[test] + fn dropdown_list_stays_put_while_the_wheel_steps_its_value() { + use photocraft_color::BlendMode; + // A tall window with room below the button, and a 900 pt one with the button half way down. + for (height, down) in [(1000.0, 0.0), (900.0, 420.0)] { + let mut h = open_blend_modes(height, down); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}: the list {list:?} is in the window"); + assert!((list.left() - button.left()).abs() < 8.0, "{height}: the list {list:?} starts at the button {button:?}"); + let rows = mode_rows(&h); + assert!(rows.iter().all(|r| list.contains_rect(*r)), "{height}: all modes show in {list:?}"); + let over = list.center(); + for _ in 1..BlendMode::LAYER_MODES.len() { + h.hover_at(over); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(3); + assert_eq!(open_list(&h), list, "{height}: the list stays put at {:?}", h.state()); + } + assert_eq!(*h.state(), BlendMode::Luminosity, "{height}: the wheel stepped through every mode"); + } + } + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; /// A wheel dropdown (or a plain one) of [`MODES`], whose state is the chosen index. From 097027edb0186f0321b2fe5eb29c4dca3640efb6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 14:06:18 +0200 Subject: [PATCH 02/27] Layers: separators between the Blend Mode groups (#5532) Photoshop's blend mode lists draw a line between their six groups (Normal, Dissolve | darken | lighten | contrast | difference | colour). The Layers panel's Blend Mode list and the options bar's Mode lists (Brush/Pencil, Gradient) now do too. The lines are only drawn: options, order, wheel, arrow keys, type-ahead and hover preview are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/blend_dropdown_groups_tests.rs | 64 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/panels.rs | 21 +++++- crates/ui-egui/src/widgets.rs | 53 +++++++++++++-- 4 files changed, 134 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/blend_dropdown_groups_tests.rs diff --git a/crates/ui-egui/src/blend_dropdown_groups_tests.rs b/crates/ui-egui/src/blend_dropdown_groups_tests.rs new file mode 100644 index 0000000000..de3d1d7d93 --- /dev/null +++ b/crates/ui-egui/src/blend_dropdown_groups_tests.rs @@ -0,0 +1,64 @@ +//! #5532: the Layers panel's Blend Mode list draws a line between Photoshop's six groups of modes: +//! Normal, Dissolve | Darken … Darker Color | Lighten … Lighter Color | Overlay … Hard Mix | +//! Difference … Divide | Hue … Luminosity. + +use egui::accesskit::Role; +use egui::{Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use photocraft_doc::BlendMode; +use serde_json::json; + +use crate::PhotocraftApp; + +/// The app with a new document and a pixel layer above the Background, active. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app + }); + h.run_steps(8); + h +} + +fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) { + h.hover_at(at); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(1); + } + h.run_steps(2); +} + +#[test] +fn the_layers_blend_mode_list_has_a_line_between_each_group() { + let mut h = harness(); + // The Layers panel's dropdown: the lowest one (the options bar and the title bar have some too). + let button = h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + click(&mut h, button.center()); + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))).unwrap(); + // Each mode's row in the open list. + let rows: Vec = BlendMode::LAYER_MODES + .iter() + .map(|m| h.get_all_by_label(m.label()).map(|n| n.rect()).rfind(|r| list.contains_rect(*r)).unwrap_or_else(|| panic!("{m:?} is in the list"))) + .collect(); + let gaps: Vec = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect(); + let row_gap = gaps.iter().copied().fold(f32::INFINITY, f32::min); + let lines: Vec<(BlendMode, BlendMode)> = + gaps.iter().enumerate().filter(|(_, g)| **g > row_gap + 2.0).map(|(i, _)| (BlendMode::LAYER_MODES[i], BlendMode::LAYER_MODES[i + 1])).collect(); + assert_eq!( + lines, + [ + (BlendMode::Dissolve, BlendMode::Darken), + (BlendMode::DarkerColor, BlendMode::Lighten), + (BlendMode::LighterColor, BlendMode::Overlay), + (BlendMode::HardMix, BlendMode::Difference), + (BlendMode::Divide, BlendMode::Hue), + ], + "row gaps {gaps:?}" + ); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38118955c3..56f7796f9f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2563,6 +2563,9 @@ mod warp_text_dialog_tests; #[cfg(test)] mod blend_dropdown_wheel_tests; +#[cfg(test)] +mod blend_dropdown_groups_tests; + #[cfg(test)] mod options_bar_mode_wheel_tests; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 733f923c8a..0d84710549 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1263,7 +1263,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { opt_label(ui, tl!("Mode")); let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); // The wheel over it steps the mode, as over the Layers panel's (#2061). - widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0); + widgets::dropdown_wheel_grouped( + ui, + "gradient-blend-mode", + &mut app.ui.tool_options.gradient_blend_mode, + &opts, + 96.0, + |m| starts_blend_group(*m), + ); opt_label(ui, tl!("Opacity")); let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); // Live while scrubbed, one undo step per scrub (#5012). @@ -2149,6 +2156,13 @@ fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static s std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() } +/// Whether blend mode `m` starts one of the groups Photoshop's blend mode lists draw a line above: +/// Normal, Dissolve (and Pass Through, Clear) | darken | lighten | contrast | difference | colour +/// (#5532). The first mode of a list never gets a line. +pub(crate) fn starts_blend_group(m: BlendMode) -> bool { + matches!(m, BlendMode::Darken | BlendMode::Lighten | BlendMode::Overlay | BlendMode::Difference | BlendMode::Hue) +} + /// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them. /// /// Returns the *content* displacement in points for this frame, so positive moves the @@ -2240,7 +2254,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") }; let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); - let (chosen, hovered) = widgets::dropdown_wheel_hovered(ui, "blend", &mut m, &blend_options(l.is_group(), l.blend), blend_width); + let (chosen, hovered) = + widgets::dropdown_wheel_grouped(ui, "blend", &mut m, &blend_options(l.is_group(), l.blend), blend_width, |m| starts_blend_group(*m)); // One step per choice: a click, an arrow key or each wheel notch (#1747). for m in &chosen { actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "blend": m.label()}))); @@ -3748,7 +3763,7 @@ fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::B let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1); opts.insert(at, (None, "Clear")); let mut mode = if *clear || held { None } else { Some(b.mode) }; - if !widgets::dropdown_wheel_hovered(ui, id, &mut mode, &opts, 96.0).0.is_empty() { + if !widgets::dropdown_wheel_grouped(ui, id, &mut mode, &opts, 96.0, |m| m.is_some_and(starts_blend_group)).0.is_empty() { *clear = mode.is_none(); if let Some(m) = mode { b.mode = m; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index e642dfc3e6..bfaab548e7 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1295,7 +1295,7 @@ pub fn dropdown(ui: &mut Ui, id: &str, current: &mut T, op /// [`dropdown`], also returning the option under the pointer in its open list (live previews). pub fn dropdown_hovered(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { - let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false); + let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false, &|_| false); (!chosen.is_empty(), hovered) } @@ -1306,10 +1306,32 @@ pub fn dropdown_hovered(ui: &mut Ui, id: &str, current: &m /// in order (one per notch; the last is `current`) and the option under the pointer in the open /// list, none while the pointer rests where the wheel last stepped. pub fn dropdown_wheel_hovered(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (Vec, Option) { - dropdown_with(ui, id, current, options, width, true) + dropdown_with(ui, id, current, options, width, true, &|_| false) } -fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32, wheel: bool) -> (Vec, Option) { +/// [`dropdown_wheel_hovered`] whose open list draws a line above each option (but the first) that +/// `starts_group`: Photoshop's blend mode lists group their modes (#5532). The lines are only +/// drawn: the options, their order and how the wheel, the keys and the pointer pick them stay. +pub fn dropdown_wheel_grouped( + ui: &mut Ui, + id: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + starts_group: impl Fn(&T) -> bool, +) -> (Vec, Option) { + dropdown_with(ui, id, current, options, width, true, &starts_group) +} + +fn dropdown_with( + ui: &mut Ui, + id: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + wheel: bool, + starts_group: &dyn Fn(&T) -> bool, +) -> (Vec, Option) { let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| tl!(l)).unwrap_or("—"); let (mut chosen, mut hovered) = (Vec::new(), None); // The wheel's notches add up over the button and the open list alike. @@ -1344,7 +1366,10 @@ fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, o // The row nearest the pointer, by its distance to each row. let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); let mut nearest: Option<(f32, &T)> = None; - for (v, l) in options { + for (i, (v, l)) in options.iter().enumerate() { + if i > 0 && starts_group(v) { + list_separator(ui); + } let item = ui.selectable_label(v == current, tl!(l)); if reveal && v == current { item.scroll_to_me(None); @@ -1388,6 +1413,15 @@ fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, o (chosen, hovered) } +/// A line between two groups of an open dropdown list's options, as wide as the list. Like egui's +/// separator it takes no width while egui sizes the list, so it never widens it. +fn list_separator(ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let width = if ui.is_sizing_pass() { 0.0 } else { ui.available_width() }; + let (rect, _) = ui.allocate_exact_size(vec2(width, 1.0), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, t.separator)); +} + /// Makes an open dropdown list as wide as its widest option is when hovered, from the start. egui /// takes a plain row's frame stroke off its padding but draws a hovered row with the stroke, so a /// row grows by two stroke widths under the pointer, and the list never shrinks back: scrolling @@ -2387,6 +2421,17 @@ mod tests { assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); } + /// A dropdown not given groups draws no lines between its options: the rows are evenly spaced + /// (#5532, only blend mode lists group theirs). + #[test] + fn dropdown_list_without_groups_has_no_separators() { + let h = open_blend_modes(1000.0, 0.0); + let rows = mode_rows(&h); + let gaps: Vec = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect(); + let (lo, hi) = gaps.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), g| (lo.min(*g), hi.max(*g))); + assert!(hi - lo < 1.0, "even row gaps: {gaps:?}"); + } + /// The open list opens at the button's left edge, below it or moved up over it to fit, and /// stays put while the wheel steps through every mode over it (#1747), although the button /// widens for the longer names (#5495). From a218cf17b5d3542a534a6398132ffe64da25b64f Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 17:10:19 +0200 Subject: [PATCH 03/27] Dropdowns: open the list beside its button, never over it (#5495) A full-height list that didn't fit below its button moved up over it, so the release of the click that opened it chose the row under the pointer (the Layers panel's Blend Mode box picked Hard Light). As in Photoshop the list now opens below the button, or above it when the whole list doesn't fit below and there is more room above, capped to that side's room (the rest scrolls). A release back on the box that opened the list chooses nothing, also where a too-short window still makes a list cover it. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/blend_dropdown_wheel_tests.rs | 29 ++++ crates/ui-egui/src/press_menu.rs | 13 +- crates/ui-egui/src/widgets.rs | 149 +++++++++++++----- 3 files changed, 148 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs index 31b28adbda..5e00133164 100644 --- a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs @@ -212,3 +212,32 @@ fn a_wheel_step_ends_the_hover_preview_until_the_pointer_moves() { h.run_steps(3); assert_eq!(previewed(&mut h), Some(BlendMode::Multiply), "a moved pointer previews again"); } + +/// The open list's rect (the one foreground area: no other popup is open). +fn open_list(h: &Harness<'_, PhotocraftApp>) -> Option { + h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) +} + +/// A plain click on the Layers panel's Blend Mode box, released where it was pressed (after one +/// frame, or after a few as a person's click takes), opens the list beside the box and chooses +/// nothing (#5495 review): the full-height list doesn't fit below the box low in the panel, and +/// it must not open over the box, where the release would pick the row under the pointer. +#[test] +fn a_click_on_the_blend_mode_box_opens_the_list_beside_it_and_changes_nothing() { + for held in [6, 1] { + let mut h = harness(pixel_layer); + let undo = steps(&h); + let button = dropdown(&h); + let at = button.center(); + h.hover_at(at); + h.run_steps(1); + for (pressed, frames) in [(true, held), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(frames); + } + assert_eq!((blend(&h), steps(&h)), (BlendMode::Normal, undo), "held {held}: the click chose nothing"); + let Some(list) = open_list(&h) else { panic!("held {held}: the list is open") }; + assert!(!list.intersects(button.shrink(1.0)), "held {held}: the list {list:?} leaves the box {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 900.0, "held {held}: the list {list:?} is in the window"); + } +} diff --git a/crates/ui-egui/src/press_menu.rs b/crates/ui-egui/src/press_menu.rs index 7110e833b4..ec0be0439e 100644 --- a/crates/ui-egui/src/press_menu.rs +++ b/crates/ui-egui/src/press_menu.rs @@ -130,7 +130,13 @@ impl PressCombo { /// Was option `item` (in the open list `ui`) chosen this frame: clicked, or the press-drag /// gesture that opened the list released on it? The list closes when it was. pub fn chosen(&self, ui: &Ui, item: &Response) -> bool { - let released_on = item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()); + // A release back on the box chooses nothing, also where a list covers the box. + let on_box = |ctx: &egui::Context| { + let at = ctx.input(|i| i.pointer.interact_pos()); + ctx.data(|d| d.get_temp::(gesture_id().with(self.popup))).zip(at).is_some_and(|(b, p)| b.contains(p)) + }; + let released_on = + item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()) && !on_box(ui.ctx()); if released_on { ui.close(); } @@ -145,7 +151,10 @@ impl PressCombo { if pressed && !Popup::is_id_open(ctx, self.popup) { // Opened now, the list counts as open this frame and egui shows it from the next. Popup::open_id(ctx, self.popup); - ctx.data_mut(|d| d.insert_temp(gesture_id(), self.popup)); + ctx.data_mut(|d| { + d.insert_temp(gesture_id(), self.popup); + d.insert_temp(gesture_id().with(self.popup), button.rect); + }); ctx.request_repaint(); } else if self.owns_gesture(ctx) && ctx.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) { ctx.data_mut(|d| d.remove::(gesture_id())); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 57fd0db5fc..48bd5c7617 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1635,30 +1635,27 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// 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. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - let room = popup_max_height(ui.ctx(), ui.spacing()); + // 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); // 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 } -/// The most a popup's rows may take: the part of the window that can be seen (clear of a taskbar a -/// too-tall window runs under, #315), less the popup frame's margin and stroke and a small gap to -/// the window's edges. egui moves a popup up to keep it in the window, so a popup this tall fits. -pub fn popup_max_height(ctx: &egui::Context, spacing: &egui::style::Spacing) -> f32 { - let frame = spacing.menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; - (crate::work_area::visible_rect(ctx).height() - frame).max(MENU_MIN_HEIGHT) -} - /// A dropdown: a button showing `selected_text` (at least `width` wide, wider for a longer text) /// whose list (`add_contents`) opens below it on a click. The list is as tall as its options up to -/// the part of the window that can be seen, scrolling only past that (#5495): Photoshop's dropdowns +/// the room the window has on that side, scrolling only past that (#5495): Photoshop's dropdowns /// open at full height. egui's `ComboBox` capped every list at the size its popup takes on the /// frame it opens (`default_area_size`, 400 pt), so the Layers panel's 27 blend modes scrolled. /// -/// The list's left edge is the button's, and a list that doesn't fit below the button moves up -/// over it to stay in the window, never beside it: so it stays put while its value (and with it -/// the button's width) changes, as the wheel steps it over the open list (#1747). The ids are -/// egui's `ComboBox` ones, so `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. +/// The list never covers its button, as in Photoshop: it opens below the button, or above it when +/// the whole list doesn't fit below and there is more room above, and scrolls when it doesn't fit +/// on that side either. Over the button, the release of the click that opened it would choose the +/// row under the pointer. Its left edge is the button's and its side only depends on its rows' +/// height, so it stays put while its value (and with it the button's width) changes, as the wheel +/// steps it over the open list (#1747). The ids are egui's `ComboBox` ones, so +/// `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. pub fn combo_list( ui: &mut Ui, id_salt: impl egui::AsIdSalt, @@ -1680,16 +1677,21 @@ pub fn combo_list( info.current_text_value = Some(selected_text.text().to_owned()); info }); - let room = popup_max_height(&ctx, ui.spacing()); - // Below the button, or as far up as the list's height (from the last frame) needs. + // The room below and above the button, less the popup frame's margin and stroke. The + // rows' full height is measured on the (invisible) pass that sizes the list as it opens. let visible = crate::work_area::visible_rect(&ctx).shrink(MENU_EDGE); - let height = egui::AreaState::load(&ctx, popup_id).and_then(|s| s.size).map_or(0.0, |s| s.y); - let top = button.rect.bottom().min(visible.bottom() - height).max(visible.top()); - let left = button.rect.left(); + let frame = ui.spacing().menu_margin.sum().y + 2.0; + let below = visible.bottom() - button.rect.bottom() - frame; + let above = button.rect.top() - visible.top() - frame; + let rows_id = popup_id.with("rows"); + let rows = ctx.data(|d| d.get_temp::(rows_id)); + let up = rows.is_some_and(|rows| rows > below) && above > below; + let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; + let room = room.max(MENU_MIN_HEIGHT); let inner = egui::Popup::menu(&button) .id(popup_id) - .anchor(Rect::from_x_y_ranges(left..=left, top..=top)) - .align(egui::RectAlign::BOTTOM_START) + .anchor(button.rect) + .align(align) .align_alternatives(&[]) .width(button.rect.width()) .close_behavior(close) @@ -1698,15 +1700,14 @@ pub fn combo_list( ui.set_min_width(ui.available_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. - egui::ScrollArea::vertical() - .max_height(room) - .min_scrolled_height(room) - .show(ui, |ui| { - // Options don't wrap in a list as narrow as its button: they widen it. - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - add_contents(ui) - }) - .inner + let scroll = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, |ui| { + // Options don't wrap in a list as narrow as its button: they widen it. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + add_contents(ui) + }); + let rows = scroll.content_size.y; + ui.ctx().data_mut(|d| d.insert_temp(rows_id, rows)); + scroll.inner }) .map(|r| r.inner); egui::InnerResponse::new(inner, button) @@ -2655,21 +2656,32 @@ mod tests { assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); } - /// The open list opens at the button's left edge, below it or moved up over it to fit, and - /// stays put while the wheel steps through every mode over it (#1747), although the button - /// widens for the longer names (#5495). + /// The open list opens at the button's left edge, below the button or above it, never over it + /// (#5495 review: a click released in place would choose the row under the pointer): below + /// when the whole list fits there, else on the side with more room, scrolling when it doesn't + /// fit there either. It stays put while the wheel steps through every mode over it (#1747), + /// although the button widens for the longer names. #[test] - fn dropdown_list_stays_put_while_the_wheel_steps_its_value() { + fn dropdown_list_opens_beside_its_button_and_stays_put_while_the_wheel_steps_its_value() { use photocraft_color::BlendMode; - // A tall window with room below the button, and a 900 pt one with the button half way down. - for (height, down) in [(1000.0, 0.0), (900.0, 420.0)] { + // (window height, button's distance from the top, list below it, all modes in sight) + let cases = [ + (1000.0, 0.0, true, true), // room below + (900.0, 420.0, true, false), // room on neither side, more below + (900.0, 520.0, false, false), // room on neither side, more above + (1000.0, 900.0, false, true), // room above only, near the bottom edge + (300.0, 150.0, false, false), // a window shorter than the list + ]; + for (height, down, below, all) in cases { let mut h = open_blend_modes(height, down); let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); let list = open_list(&h); - assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}: the list {list:?} is in the window"); - assert!((list.left() - button.left()).abs() < 8.0, "{height}: the list {list:?} starts at the button {button:?}"); + assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}/{down}: the list {list:?} is in the window"); + assert!((list.left() - button.left()).abs() < 8.0, "{height}/{down}: the list {list:?} starts at the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{height}/{down}: the list {list:?} leaves the button {button:?} free"); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{height}/{down}: the list {list:?} is below the button {button:?}"); let rows = mode_rows(&h); - assert!(rows.iter().all(|r| list.contains_rect(*r)), "{height}: all modes show in {list:?}"); + assert_eq!(rows.iter().all(|r| list.contains_rect(*r)), all, "{height}/{down}: all modes show in {list:?}"); let over = list.center(); for _ in 1..BlendMode::LAYER_MODES.len() { h.hover_at(over); @@ -2680,12 +2692,67 @@ mod tests { modifiers: Modifiers::NONE, }); h.run_steps(3); - assert_eq!(open_list(&h), list, "{height}: the list stays put at {:?}", h.state()); + assert_eq!(open_list(&h), list, "{height}/{down}: the list stays put at {:?}", h.state()); } - assert_eq!(*h.state(), BlendMode::Luminosity, "{height}: the wheel stepped through every mode"); + assert_eq!(*h.state(), BlendMode::Luminosity, "{height}/{down}: the wheel stepped through every mode"); } } + /// A short list opens below its button when it fits there, and above it near the window's + /// bottom edge, whole either way. + #[test] + fn a_short_dropdown_list_opens_below_or_above_its_button_whole() { + for (down, below) in [(100.0, true), (360.0, false)] { + let mut h = Harness::builder().with_size(egui::vec2(300.0, 400.0)).build_ui_state( + move |ui, selected: &mut usize| { + ui.add_space(down); + super::dropdown(ui, "blend-mode", selected, &MODES, 120.0); + }, + 0, + ); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{down}: the list {list:?} is below the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{down}: the list {list:?} leaves the button {button:?} free"); + for (_, label) in MODES { + let row = h.get_all_by_label(label).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING); + assert!(list.contains_rect(row), "{down}: {label} {row:?} shows in {list:?}"); + } + assert!(list.height() < 150.0, "{down}: the list {list:?} is only as tall as its rows"); + assert_eq!(*h.state(), 0, "{down}: the click chose nothing"); + } + } + + /// In a window too short for the list on either side the list still covers its button; the + /// release of the click that opened it, held a few frames, chooses nothing (#5495 review). + #[test] + fn the_release_of_the_opening_click_chooses_nothing_where_the_list_covers_the_button() { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, 110.0)).build_ui_state( + |ui, mode: &mut BlendMode| { + ui.add_space(40.0); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + h.run(); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let at = button.center(); + h.hover_at(at); + h.run(); + for (pressed, frames) in [(true, 6), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(frames); + } + let list = open_list(&h); + assert!(list.contains(at), "the list {list:?} covers the button {button:?} here"); + assert_eq!(*h.state(), BlendMode::Normal, "the click chose nothing"); + } + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; /// A wheel dropdown (or a plain one) of [`MODES`], whose state is the chosen index. From a4812f6270034ac8291c93ae09bd59648ed390a2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 17:26:44 +0200 Subject: [PATCH 04/27] Layers: the separator test opens the Blend Mode list in a window tall enough for all of it (#5532) Since #5501's review fix a list that fits on neither side of its box opens below it and scrolls, as at 1440x900, so the test now uses a 1600 pt window to see every group. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/blend_dropdown_groups_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/blend_dropdown_groups_tests.rs b/crates/ui-egui/src/blend_dropdown_groups_tests.rs index de3d1d7d93..8d14adc1f8 100644 --- a/crates/ui-egui/src/blend_dropdown_groups_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_groups_tests.rs @@ -11,9 +11,10 @@ use serde_json::json; use crate::PhotocraftApp; -/// The app with a new document and a pixel layer above the Background, active. +/// The app with a new document and a pixel layer above the Background, active. The window is tall +/// enough for the whole Blend Mode list below its box (at 900 pt it fits on neither side and scrolls). fn harness() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(vec2(1440.0, 1600.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); From bf67b1c43f2cf9756f38789c689dc534c589d3bb Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 20:26:26 +0200 Subject: [PATCH 05/27] Address CodeRabbit review: a dropdown list only takes the room its side has combo_list floored the list's scroll height at 120 pt, so where a side had less room the taller list was pushed back into the window, over its button (and past the window's top in a 110 pt window). It now takes just that side's room and scrolls. The 110 pt test now checks the list leaves the button free and stays in the window, and that the opening click still chooses nothing. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 48bd5c7617..2e3761840b 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1687,7 +1687,9 @@ pub fn combo_list( let rows = ctx.data(|d| d.get_temp::(rows_id)); let up = rows.is_some_and(|rows| rows > below) && above > below; let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; - let room = room.max(MENU_MIN_HEIGHT); + // Only the room that side has, even when it is small: a taller list would be pushed back + // into the window, over its button (#5495 review). + let room = room.max(0.0); let inner = egui::Popup::menu(&button) .id(popup_id) .anchor(button.rect) @@ -2726,10 +2728,11 @@ mod tests { } } - /// In a window too short for the list on either side the list still covers its button; the - /// release of the click that opened it, held a few frames, chooses nothing (#5495 review). + /// In a window with less than 120 pt on either side of the button the list still leaves + /// its button free, scrolling in the room that side has, and stays in the window; the release + /// of the click that opened it, held a few frames, chooses nothing (#5495 review). #[test] - fn the_release_of_the_opening_click_chooses_nothing_where_the_list_covers_the_button() { + fn in_a_very_short_window_the_list_still_leaves_its_button_free_and_the_opening_click_chooses_nothing() { use photocraft_color::BlendMode; let mut h = Harness::builder().with_size(egui::vec2(400.0, 110.0)).build_ui_state( |ui, mode: &mut BlendMode| { @@ -2749,7 +2752,8 @@ mod tests { h.run_steps(frames); } let list = open_list(&h); - assert!(list.contains(at), "the list {list:?} covers the button {button:?} here"); + assert!(!list.intersects(button.shrink(1.0)), "the list {list:?} leaves the button {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 110.0, "the list {list:?} is in the window"); assert_eq!(*h.state(), BlendMode::Normal, "the click chose nothing"); } From b2b402939a8cfe3fd2969ab42918a04f8ac27d12 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 00:56:48 +0200 Subject: [PATCH 06/27] Crop W x H budgets the hidden pixels it resamples (#9212) image.crop's target size, Image Size and Bitmap's Output resolution budgeted only the new canvas, but resample_doc scales every surface's whole content, including the pixels a non-deleting crop kept outside the canvas. A 20 px frame of a 2000 px image resampled to 2000 px tried to allocate 160 GB. resample_doc now refuses, before touching the document, when the largest surface it scales would pass the budget (at that surface's own bytes per pixel). A failed compound (the turned crop) also rolls back the painting symmetry its rotation moved. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/analysis_cmds.rs | 3 + crates/engine/src/image_cmds.rs | 116 ++++++++++++++++++++++++--- crates/engine/src/mode_cmds.rs | 2 +- crates/engine/src/mode_cmds/tests.rs | 12 +++ 4 files changed, 121 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 8932295d52..55f1ce5b44 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -187,6 +187,8 @@ pub(crate) fn compound(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess // Color Sampler points are view state a step may move (crop, rotation): roll them back too, so // a failed second step can't leave them pinned to pixels the restored document no longer has. let samplers = st.color_samplers.clone(); + // So is the painting symmetry, which a rotation moves with the pixels. + let symmetry = st.symmetry.clone(); let r = f(s); if r.is_err() { s.journal.truncate(journal); @@ -210,6 +212,7 @@ pub(crate) fn compound(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess st.channel_view = channel_view; st.coalesce = coalesce; st.color_samplers = samplers; + st.symmetry = symmetry; st.revision += 1; // A failed compound does not make an otherwise untouched document dirty. if was_clean { diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..6c30d204f0 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -254,8 +254,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; - resample_doc(doc, nw, nh, filter); - Ok(()) + resample_doc(doc, "image.imageSize", nw, nh, filter) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -290,13 +289,15 @@ pub(crate) fn check_working_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, /// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to /// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution -/// mode. Callers check [`check_resample_budget`] first. -pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { +/// mode. Callers check [`check_resample_budget`] for the new canvas first; the pixels outside the +/// canvas are scaled too, so a surface they would grow past the budget is refused here (#9212). +pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filter: Resample) -> Result<()> { let (ow, oh) = (doc.size.width, doc.size.height); let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64); if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { - return; + return Ok(()); } + check_hidden_resample_budget(cmd, doc, sx, sy)?; // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. let canvas = Rect::from_xywh(0, 0, ow, oh); let taken = crate::smart_cmds::take_caches(&mut doc.layers); @@ -325,6 +326,53 @@ pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resampl doc.size = Size::new(nw, nh); crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All); let Ok(()) = crate::smart_cmds::restore_unrendered(doc, taken, |c| Ok::<_, Infallible>(resize_surface_in_canvas(c, sx, sy, filter, canvas))); + Ok(()) +} + +/// [`check_resample_budget`] for the largest surface [`resample_doc`] scales by `sx` x `sy`: each +/// keeps its pixels outside the canvas (a crop that didn't delete them, a layer moved off the +/// canvas), and those grow with the scale like the rest. +fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) -> Result<()> { + let canvas = doc.bounds(); + // The largest surface by bytes: its scaled width, height and bytes per pixel (a mask has one + // channel, the layers the document's). + let mut largest = (0u32, 0u32, 1u64); + let mut visit = |surf: &Surface| { + let r = surf.content_bounds(); + // What lies within the canvas scales to within the new canvas, already budgeted. + if r.is_empty() || canvas.union(&r) == canvas { + return; + } + // The output's extent, as `resize_surface_in_canvas` lays it out. + let side = |a: i32, b: i32, k: f64| ((f64::from(b) * k).ceil() - (f64::from(a) * k).floor()).clamp(0.0, f64::from(u32::MAX)) as u32; + let (w, h) = (side(r.x0, r.x1, sx), side(r.y0, r.y1, sy)); + let bpp = surf.format().bytes_per_pixel().max(1) as u64; + let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); + if bytes((w, h, bpp)) > bytes(largest) { + largest = (w, h, bpp); + } + }; + // The surfaces `resample_doc` scales, smart object caches included. + for_each_surface(&mut doc.layers, true, &mut |surf, _| visit(surf)); + for ch in doc.channels.iter().chain(doc.quick_mask.as_ref()) { + visit(&ch.surface); + } + if let Some(sel) = &doc.selection { + visit(sel); + } + let (w, h, bpp) = largest; + let px = u64::from(w).saturating_mul(u64::from(h)); + if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { + return Ok(()); + } + let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; + Err(bad( + cmd, + format!( + "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)", + px / 1_000_000 + ), + )) } fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -614,8 +662,7 @@ fn crop(s: &mut Session, p: &Value) -> Result { crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?; } doc.selection = None; - target.apply(doc); - Ok(()) + target.apply(doc) })?; Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))) } @@ -630,15 +677,16 @@ struct CropTarget { impl CropTarget { /// Applies the target to a document that has just been cropped (inside the crop's history step). - fn apply(&self, doc: &mut Document) { + fn apply(&self, doc: &mut Document) -> Result<()> { if let Some((w, h)) = self.size { // As for Image Size: an Indexed Color document holds only its colour table's colours (#6019). let filter = if doc.mode == ColorMode::Indexed { Resample::Nearest } else { self.filter }; - resample_doc(doc, w, h, filter); + resample_doc(doc, "image.crop", w, h, filter)?; } if let Some(r) = self.resolution { doc.resolution_dpi = r; } + Ok(()) } /// Where Color Sampler points go: shifted by the crop's origin, then scaled with the pixels @@ -803,8 +851,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar crate::crop_fill::fill_uncovered(doc, *active, &coverage)?; } doc.selection = None; - crop_target.apply(doc); - Ok(()) + crop_target.apply(doc) }) })?; Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))) @@ -1850,6 +1897,53 @@ mod tests { assert_eq!(doc(&s).size, Size::new(40, 20)); } + /// #9212: a non-deleting crop keeps the pixels outside the frame, and W x H resamples them + /// too. A 20 px frame of a 2000 px Background resampled to 2000 px scales its hidden pixels + /// x100, to 200000 px a side (160 GB at 8 bits, past the 8 GiB budget): refused before + /// allocating, like a target size past the budget. + #[test] + fn crop_target_budgets_the_hidden_pixels_it_resamples() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2000, "height": 2000})).unwrap(); + s.execute("paint.setSymmetry", json!({"mode": "vertical", "center": [500, 700]})).unwrap(); + let symmetry = s.active().unwrap().symmetry.clone(); + let past = s.active().unwrap().history.past_len(); + let mut p = json!({"x": 0, "y": 0, "width": 20, "height": 20, "deleteCroppedPixels": false, "targetWidth": 2000, "targetHeight": 2000}); + for angle in [None, Some(90)] { + let mut p = p.clone(); + if let Some(a) = angle { + p["angle"] = json!(a); + } + let err = s.execute("image.crop", p).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{angle:?}: {err}"); + assert_eq!(doc(&s).size, Size::new(2000, 2000), "{angle:?}: the document is unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{angle:?}: no history step"); + // The turned crop rotates first: the painting symmetry turns back with the document. + assert_eq!(s.active().unwrap().symmetry, symmetry, "{angle:?}: the painting symmetry stays"); + } + // Deleting the cropped pixels leaves only the frame to resample. + p["deleteCroppedPixels"] = json!(true); + s.execute("image.crop", p).unwrap(); + assert_eq!(doc(&s).size, Size::new(2000, 2000)); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + } + + /// #9212: Image Size resamples the pixels outside the canvas as well. After a non-deleting + /// crop to 10 px, 20000 px (400 MP, within the budget) scales the hidden 100 px Background x2000. + #[test] + fn image_size_budgets_the_hidden_pixels_it_resamples() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap(); + let past = s.active().unwrap().history.past_len(); + let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (Size::new(10, 10), past)); + // Without resampling only the resolution changes. + s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(10, 10), 300.0)); + } + #[test] fn crop_target_rejects_bad_params_without_changing_the_document() { let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs index 180f940e91..e809c03dae 100644 --- a/crates/engine/src/mode_cmds.rs +++ b/crates/engine/src/mode_cmds.rs @@ -481,7 +481,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result { } s.edit("Bitmap", |doc, active| { if (nw, nh) != (doc.size.width, doc.size.height) { - crate::image_cmds::resample_doc(doc, nw, nh, photocraft_algo::resample::Resample::Bicubic); + crate::image_cmds::resample_doc(doc, CMD, nw, nh, photocraft_algo::resample::Resample::Bicubic)?; } doc.resolution_dpi = dpi; let px = composite(doc, true); diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs index 84d816a349..57493dcc32 100644 --- a/crates/engine/src/mode_cmds/tests.rs +++ b/crates/engine/src/mode_cmds/tests.rs @@ -399,6 +399,18 @@ fn bitmap_output_resolution_resamples_and_sets_the_resolution() { assert_eq!(first_white(doc(&s), 0, 1, 0), Some(128)); } +/// #9212: the Output resolution resamples the pixels outside the canvas too. A 10 px crop that +/// kept a 1000 px document's pixels, converted from 1 to 100 ppi, would grow them to 100000 px a +/// side (20 GB of gray and alpha at 8 bits, past the 8 GiB budget): refused before allocating. +#[test] +fn bitmap_output_resolution_budgets_the_hidden_pixels() { + let mut s = ramp(1000, 1000, 8, 1.0); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap(); + let err = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 100})).unwrap_err().to_string(); + assert!(err.contains("100000 x 100000 px is 10000 megapixels"), "{err}"); + assert_eq!((doc(&s).size.width, doc(&s).mode), (10, ColorMode::Grayscale)); +} + #[test] fn bitmap_halftone_screen_is_laid_out_at_the_output_resolution() { // The same 10 lines/inch screen has twice the cell (in pixels) at twice the resolution: the From 1e75581a963a2633c73c066189f7c59d1898390a Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 01:24:01 +0200 Subject: [PATCH 07/27] Crop: a tool switch during a frame drag ends the drag (#9223) A tool key pressed while dragging the crop frame left crop.drag set when the new tool's handler takes every event before the Crop tool's (Perspective Crop, Ruler, Slice, Frame, Artboard), so the frame was neither committed on leave nor cancelled. tool_event now ends the gesture before any handler runs. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 5 +++++ crates/ui-egui/src/crop_ui.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ab3e6939a7..00f6dacfdb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5906,6 +5906,11 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { crate::guide_select::clear(app); } + // A tool key pressed mid-drag ends the crop gesture here: a later handler can take every event + // of the new tool, and a drag left set keeps the frame from committing on leave (#9223). + if app.ui.tool != Tool::Crop { + app.crop.drag = None; + } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { return; } diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..e651507524 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1855,6 +1855,27 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); } + /// A tool key pressed while a drag on the frame is held (⇧C to Perspective Crop): the next + /// tool's events end the gesture, even a tool that takes every event before the Crop tool's + /// handler, and leaving then commits the frame as it does for any other tool (#3368). + #[test] + fn a_tool_switch_during_a_drag_ends_it_and_commits_the_frame() { + for tool in [Tool::PerspectiveCrop, Tool::Ruler, Tool::Slice, Tool::Frame, Tool::Artboard, Tool::Brush] { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + drag(&mut app, &[[20.0, 20.0], [120.0, 80.0]], NONE); + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 50.0, pressure: 1.0 }, NONE); + assert!(app.crop.drag.is_some()); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE); + assert!(app.crop.drag.is_none(), "{tool:?}"); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None, "{tool:?}"); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 60), "{tool:?}"); + } + } + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From 60cd5002c455541cff4b5107b6c3091a6a31fe7e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:40:19 +0200 Subject: [PATCH 08/27] Address CodeRabbit review: a tool switch mid-drag ends the crop gesture as a release would A box drawn over the untouched default frame, or that frame resized by a handle, kept `default_frame` set when another tool's key ended the drag, so leaving dropped the edit instead of committing it. The release logic is now one function both paths run. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/canvas.rs | 5 +- crates/ui-egui/src/crop_ui.rs | 93 ++++++++++++++++++++++++++--------- 2 files changed, 73 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 00f6dacfdb..e1a818091b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5907,9 +5907,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) crate::guide_select::clear(app); } // A tool key pressed mid-drag ends the crop gesture here: a later handler can take every event - // of the new tool, and a drag left set keeps the frame from committing on leave (#9223). + // of the new tool, and a drag left set keeps the frame from committing on leave. It ends as a + // release would, so a box drawn over the untouched default frame is committed, not dropped (#9223). if app.ui.tool != Tool::Crop { - app.crop.drag = None; + crate::crop_ui::end_drag(app); } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { return; diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index e651507524..a575cefa73 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -760,7 +760,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { /// Pointer input for the Crop tool. Returns true when the event was its. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool { if app.ui.tool != Tool::Crop { - app.crop.drag = None; + end_drag(app); return false; } let p = match ev { @@ -828,34 +828,52 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool ToolEvent::Move { .. } => update(app, p, mods), ToolEvent::Up { .. } => { update(app, p, mods); - let Some(drag) = app.crop.drag.take() else { return true }; - let ok = app.ui.crop_rect.is_some_and(size_ok); - // A click outside the untouched default frame (no turn) leaves it the default. - let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) - && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); - if ok && changed { - app.crop.default_frame = false; - } - match drag { - CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, - CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), - // A live-centred resize collapsed: the frame and the view it moved go back. - CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), - // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized - // one stays where its centre was: `crop_mode::live_resize`.) - CropDrag::Draw { .. } if ok => { - crate::crop_mode::sync_frame(app); - crate::crop_mode::auto_center(app); - } - _ => {} - } - push_press_step(app); + release(app); } } crate::crop_mode::sync_frame(app); true } +/// Another tool was picked while a drag on the frame is held (a tool key, #9223): the gesture ends +/// where the pointer last moved it, as a release there would, so a box drawn over the untouched +/// default frame counts as drawn and leaving the tool commits it. +pub fn end_drag(app: &mut PhotocraftApp) { + if app.crop.drag.is_none() { + return; + } + let tool = std::mem::replace(&mut app.ui.tool, Tool::Crop); + release(app); + crate::crop_mode::sync_frame(app); + app.ui.tool = tool; +} + +/// The release of a drag on the frame, the pointer's last move already applied. +fn release(app: &mut PhotocraftApp) { + let Some(drag) = app.crop.drag.take() else { return }; + let ok = app.ui.crop_rect.is_some_and(size_ok); + // A click outside the untouched default frame (no turn) leaves it the default. + let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); + if ok && changed { + app.crop.default_frame = false; + } + match drag { + CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, + CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), + // A live-centred resize collapsed: the frame and the view it moved go back. + CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), + // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized + // one stays where its centre was: `crop_mode::live_resize`.) + CropDrag::Draw { .. } if ok => { + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); + } + _ => {} + } + push_press_step(app); +} + /// On release: the frame state at the press becomes a box Undo step when the gesture changed it. fn push_press_step(app: &mut PhotocraftApp) { if let Some(before) = app.crop.press_step.take() @@ -1876,6 +1894,35 @@ mod tests { } } + /// The same mid-drag tool switch on the untouched default frame: a box drawn over it, or the + /// frame resized by a handle, is an edit and commits on leave; a box too small to keep goes back + /// to the default frame, which leaving drops (#9223). + #[test] + fn a_tool_switch_during_a_drag_on_the_default_frame_keeps_the_edit() { + let cases: [(&[[f64; 2]], Size); 3] = [ + (&[[20.0, 20.0], [120.0, 80.0]], Size::new(100, 60)), + (&[[200.0, 100.0], [150.0, 80.0]], Size::new(150, 80)), + (&[[20.0, 20.0], [20.0, 20.0]], Size::new(200, 100)), + ]; + for (path, size) in cases { + for tool in [Tool::PerspectiveCrop, Tool::Brush] { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert!(app.crop.default_frame); + tool_event(&mut app, ToolEvent::Down { x: path[0][0], y: path[0][1], pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: path[1][0], y: path[1][1], pressure: 1.0 }, NONE); + assert!(app.crop.drag.is_some()); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE); + assert!(app.crop.drag.is_none(), "{tool:?} {path:?}"); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None, "{tool:?} {path:?}"); + assert_eq!(app.session.active().unwrap().doc.size, size, "{tool:?} {path:?}"); + } + } + } + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From 9b84eebad8e656b8b61025db35e8b2bd06675fc9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:50:06 +0200 Subject: [PATCH 09/27] Image Size: refuse a resolution outside 1..30000 ppi instead of clamping it (#9260) `image.imageSize` read `resolution` as `as f32` and clamped it to 1..10000, so 1e39 (inf) silently became 10000 ppi, -5 and 0 became 1 ppi, a string was ignored, and a valid 20000 ppi (allowed by File > New, Bitmap and the dialog's own field) dropped to 10000. Parse it once like `image.crop`: non-finite, non-number or outside 1..=MAX_RESOLUTION is an error and the document is untouched; the keepPrintSize path uses the same value. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 38 +++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..eb29f9a96d 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -11,6 +11,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::CommandSpec; +use crate::document_preset_cmds::MAX_RESOLUTION; use crate::{EngineError, Result, Session}; fn has_doc(s: &Session) -> std::result::Result<(), String> { @@ -212,14 +213,22 @@ fn image_size(s: &mut Session, p: &Value) -> Result { pw = pw.or(Some(ow as f64 * pc / 100.0)); ph = ph.or(Some(oh as f64 * pc / 100.0)); } + // The document range File › New and the dialog's field allow; outside it, refuse rather than + // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). + let dpi = match p.get("resolution") { + None | Some(Value::Null) => None, + Some(v) => { + let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_RESOLUTION).contains(r)); + Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) + } + }; // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size // with Resample on, as an action records it). if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) && pw.is_none() && ph.is_none() - && let Some(r) = p.get("resolution").and_then(Value::as_f64) + && let Some(r) = dpi { - let r = r.clamp(1.0, 10_000.0); let old = f64::from(d.doc.resolution_dpi).max(1.0); pw = Some(ow as f64 * r / old); ph = Some(oh as f64 * r / old); @@ -237,7 +246,6 @@ fn image_size(s: &mut Session, p: &Value) -> Result { if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?; } - let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32); if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { // Color Sampler points scale with the pixels (same map `transform_geometry` applies). let (sx, sy) = (f64::from(nw) / f64::from(ow.max(1)), f64::from(nh) / f64::from(oh.max(1))); @@ -246,7 +254,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { s.edit("Image Size", |doc, _| { if let Some(r) = dpi { // Type keeps its pixel size; resampling below then scales it with the pixels. - crate::canvas_geom::set_resolution(doc, r.clamp(1.0, 10_000.0)); + crate::canvas_geom::set_resolution(doc, r as f32); } let filter = match resample { Method::None => return Ok(()), @@ -1270,6 +1278,28 @@ mod tests { assert_eq!(r, json!({"width": 40, "height": 20})); } + /// #9260: a resolution outside the document range (1..=30000 ppi, as File › New and the + /// dialog's field) is refused and leaves the document as it was, instead of being clamped; + /// one inside it, also above 10000, is set as given. + #[test] + fn image_size_refuses_a_resolution_out_of_range() { + for extra in [json!({"resample": "none"}), json!({"resample": "bicubic"}), json!({"resample": "bicubic", "keepPrintSize": true})] { + for r in [json!(1e39), json!(-5), json!(0), json!(0.5), json!(30_001), json!("300")] { + let mut s = session(); + let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); + let mut p = extra.clone(); + p["resolution"] = r; + assert!(s.execute("image.imageSize", p.clone()).is_err(), "{p}"); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); + } + } + let mut s = session(); + s.execute("image.imageSize", json!({"resolution": 20_000, "resample": "none"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 20_000.0)); + s.execute("image.imageSize", json!({"resolution": null, "resample": "none"})).unwrap(); + assert_eq!(doc(&s).resolution_dpi, 20_000.0, "null leaves the resolution as it is"); + } + /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is /// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. #[test] From d1353e90a744f15b44cb1445d6ac5f66cf8b7fe7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:05:42 +0100 Subject: [PATCH 10/27] Image Size: a document's own out-of-range resolution still passes (#9260) An imported file can carry a resolution outside 1..30000 ppi (PNG pHYs 1 px/m, PSD 0, TIFF in cm), and the Image Size dialog sends it back unchanged on OK; refusing it would block a plain resize that worked before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 20 ++++++++++++++++++-- crates/ui-egui/src/sizing.rs | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index eb29f9a96d..2c8e2e53b3 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -214,11 +214,14 @@ fn image_size(s: &mut Session, p: &Value) -> Result { ph = ph.or(Some(oh as f64 * pc / 100.0)); } // The document range File › New and the dialog's field allow; outside it, refuse rather than - // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). + // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). The document's own + // resolution always passes: an imported file may have one outside the range, and the dialog + // sends it back unchanged. let dpi = match p.get("resolution") { None | Some(Value::Null) => None, Some(v) => { - let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_RESOLUTION).contains(r)); + let own = |r: f64| r as f32 == d.doc.resolution_dpi; + let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || own(r))); Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) } }; @@ -1298,6 +1301,19 @@ mod tests { assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 20_000.0)); s.execute("image.imageSize", json!({"resolution": null, "resample": "none"})).unwrap(); assert_eq!(doc(&s).resolution_dpi, 20_000.0, "null leaves the resolution as it is"); + // An imported document's own resolution outside the range (a PNG pHYs of 1 px/m is + // 0.0254 ppi) still resizes: the Image Size dialog sends it back unchanged on OK. + for own in [0.0254_f32, 40_000.0] { + let mut s = session(); + s.edit("ppi", |doc, _| { + doc.resolution_dpi = own; + Ok(()) + }) + .unwrap(); + s.execute("image.imageSize", json!({"width": 80, "height": 40, "resolution": f64::from(own), "resample": "bicubic"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}"); + assert!(s.execute("image.imageSize", json!({"resolution": 0.03, "resample": "none"})).is_err(), "{own}: another value is still checked"); + } } /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index bf8adf549f..f450e4fab0 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -518,6 +518,30 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50)); } + /// #9260: OK with a new Width resizes a document whose own resolution is outside the range + /// the command accepts (an imported PNG's pHYs of 1 px/m is 0.0254 ppi); the dialog sends that + /// resolution back unchanged. + #[test] + fn ok_resizes_a_document_with_an_imported_resolution_out_of_range() { + for own in [0.0254_f32, 40_000.0] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); + app.session + .edit("ppi", |doc, _| { + doc.resolution_dpi = own; + Ok(()) + }) + .unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(100)); + d.fields.insert("height".into(), json!(50)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(100, 50), own), "{own}"); + } + } + #[test] fn alt_reset_restores_open_dimensions() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 1e695c5a28cffd940e799cd7c931989125711dde Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:09:27 +0100 Subject: [PATCH 11/27] Crop: Esc in full screen cancels a drag on the default frame (#9275) The untouched default frame lets Esc leave full screen (#7315), but the frame stays the default until the gesture's release, so Esc mid-drag left full screen and the drag went on. A gesture in progress now keeps Esc. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/shortcuts.rs | 8 ++++++-- crates/ui-egui/src/view_cmds/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 023bbb4d79..5df8d24f28 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -692,8 +692,12 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } // In a full screen mode, the Crop tool's untouched default frame (Straighten off) has nothing to cancel: cancelling only - // makes the next one, so Esc goes on to leave full screen (#7315). - let untouched = app.ui.view.screen_mode != "standard" && app.ui.polygon.is_empty() && app.crop.default_frame && !crate::crop_straighten::mode(app); + // makes the next one, so Esc goes on to leave full screen (#7315). A gesture on it is still cancelled (#9275). + let untouched = app.ui.view.screen_mode != "standard" + && app.ui.polygon.is_empty() + && app.crop.default_frame + && app.crop.drag.is_none() + && !crate::crop_straighten::mode(app); if !untouched && pressed(Key::Escape) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rs index 05c1f1bb60..82baf593ac 100644 --- a/crates/ui-egui/src/view_cmds/tests.rs +++ b/crates/ui-egui/src/view_cmds/tests.rs @@ -577,6 +577,29 @@ fn esc_leaves_full_screen_with_the_crop_tool_showing_its_default_frame() { assert_eq!(app.ui.view.screen_mode, "standard"); } +/// #9275: a gesture on the default frame is something to cancel, so Esc in full screen cancels it +/// (as in Standard Screen Mode) and full screen stays. +#[test] +fn esc_in_full_screen_cancels_a_crop_drag_on_the_default_frame() { + use crate::canvas::{ToolEvent, tool_event}; + let none = egui::Modifiers::NONE; + // Inside draws a new box, on the corner handle resizes, outside turns. + for (what, from) in [("draw", [20.0, 20.0]), ("resize", [100.0, 80.0]), ("turn", [130.0, 110.0])] { + let (mut app, ctx) = app_with(1); + app.ui.tool = crate::Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + menu(&mut app, &ctx, "view.screenMode.fullScreen", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 50.0, pressure: 1.0 }, none); + assert!(app.crop.drag.is_some() && app.crop.default_frame, "{what}: mid-gesture on the default frame"); + press_esc(&mut app, &ctx); + assert_eq!(app.ui.view.screen_mode, "fullScreen", "{what}: Esc cancels the gesture, full screen stays"); + assert!(app.crop.drag.is_none(), "{what}: the gesture is cancelled"); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 50.0 }, none); + assert!(!crate::crop_ui::pending(&app), "{what}: the release leaves no pending crop"); + } +} + #[test] fn esc_leaves_full_screen_modes_unless_something_else_owns_it() { let (mut app, ctx) = app_with(1); From 617d40d2683fac3e5d6a2d1ba4e7b139e0f62d1e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:30:33 +0100 Subject: [PATCH 12/27] Address CodeRabbit review: only the exact own resolution passes, and keepPrintSize with it keeps the pixels (#9260) An out-of-range value that merely rounded to the document's resolution as f32 was accepted, and keepPrintSize with an own resolution below 1 ppi resampled the canvas against old.max(1.0), shrinking it to 1 x 1. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 2c8e2e53b3..49b95c1c05 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -216,23 +216,24 @@ fn image_size(s: &mut Session, p: &Value) -> Result { // The document range File › New and the dialog's field allow; outside it, refuse rather than // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). The document's own // resolution always passes: an imported file may have one outside the range, and the dialog - // sends it back unchanged. + // sends it back unchanged (exactly: a value that only rounds to it as f32 is refused). + let own_dpi = f64::from(d.doc.resolution_dpi); let dpi = match p.get("resolution") { None | Some(Value::Null) => None, Some(v) => { - let own = |r: f64| r as f32 == d.doc.resolution_dpi; - let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || own(r))); + let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || r == own_dpi)); Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) } }; // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size - // with Resample on, as an action records it). + // with Resample on, as an action records it). An unchanged resolution keeps the pixels. if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) && pw.is_none() && ph.is_none() && let Some(r) = dpi + && r != own_dpi { - let old = f64::from(d.doc.resolution_dpi).max(1.0); + let old = own_dpi.max(1.0); pw = Some(ow as f64 * r / old); ph = Some(oh as f64 * r / old); } @@ -1313,6 +1314,13 @@ mod tests { s.execute("image.imageSize", json!({"width": 80, "height": 40, "resolution": f64::from(own), "resample": "bicubic"})).unwrap(); assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}"); assert!(s.execute("image.imageSize", json!({"resolution": 0.03, "resample": "none"})).is_err(), "{own}: another value is still checked"); + // Only the exact value: one that merely rounds to it as f32 is refused. + let near = if own < 1.0 { f64::from(own) * (1.0 + 1e-9) } else { f64::from(own) + 0.001 }; + assert_eq!(near as f32, own); + assert!(s.execute("image.imageSize", json!({"resolution": near, "resample": "none"})).is_err(), "{own}: {near}"); + // keepPrintSize with the unchanged resolution keeps the pixels. + s.execute("image.imageSize", json!({"resolution": f64::from(own), "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}: keepPrintSize"); } } From 3640b3162505d2484c0972fb54b66e702a93e06e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 03:13:26 +0100 Subject: [PATCH 13/27] Crop / Perspective Crop: a drag held past the canvas edge scrolls the view (#9307) The edge auto-scroll (#4183) ran only while app.drag was set, but both crop tools keep their gestures in app.crop.drag / app.pcrop.drag. Frame draws, moves and classic resizes, and Perspective Crop box, corner and quad drags, now scroll too; turns and the default mode's camera-driven drags stay as they were. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/crop_ui.rs | 61 ++++++++++++++++++++++ crates/ui-egui/src/perspective_crop_ui.rs | 62 +++++++++++++++++++++++ 3 files changed, 125 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ab3e6939a7..50900231fd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4895,9 +4895,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. + // drag's next move then extends into what scrolled in. The crop tools keep their own drags. if primary - && app.drag.is_some() + && (app.drag.is_some() || crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..25aacdb5b8 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -419,6 +419,13 @@ pub fn active(app: &PhotocraftApp) -> bool { app.ui.tool == Tool::Crop && app.crop.drag.is_some() } +/// A drag that sizes or moves the frame over the image, which scrolls the view when held past the +/// canvas edge (#4183). Not the turns, nor the default mode's image moves and live-centred resizes: +/// those drive the camera themselves. +pub fn autoscrolls(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::Crop && matches!(app.crop.drag, Some(CropDrag::Draw { .. } | CropDrag::Move { .. } | CropDrag::Resize { view: None, .. })) +} + /// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the /// Crop tool still picked, [`ensure_frame`] then makes the active document a new default frame. pub fn cancel(app: &mut PhotocraftApp) { @@ -1536,6 +1543,60 @@ mod tests { assert!(st.crop.drag.is_none()); } + /// Real egui input: a handle dragged past the canvas edge and held there scrolls the view, as a + /// marquee drag does (#4183), so the frame can reach the part of the image that was off screen. + #[test] + fn a_handle_held_past_the_canvas_edge_scrolls_the_view() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + // 200x100 at 400% in a 600x400 canvas: document x 25..175 shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.ui.extras.rulers = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // The right edge's middle handle: document (100, 25). + let p0 = h.state().ui.views[0].center; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: p0, flip: false, rotation: 0.0, aspect: 1.0 }; + let grab = xf.to_screen(100.0, 25.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.crop.drag, Some(CropDrag::Resize { .. })), "{:?}", st.crop.drag); + assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.crop_rect.is_some_and(|r| r[2] > 175.0), "the frame reached past what showed: {:?}", st.ui.crop_rect); + h.event(button(out, false)); + h.step(); + } + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and diff --git a/crates/ui-egui/src/perspective_crop_ui.rs b/crates/ui-egui/src/perspective_crop_ui.rs index 2a696bd5ed..1753eb3d7b 100644 --- a/crates/ui-egui/src/perspective_crop_ui.rs +++ b/crates/ui-egui/src/perspective_crop_ui.rs @@ -53,6 +53,11 @@ pub fn pending(app: &PhotocraftApp) -> bool { app.ui.perspective_crop.is_some() || !app.pcrop.clicks.is_empty() || app.pcrop.drag.is_some() } +/// A box, corner or quad drag in progress: held past the canvas edge, it scrolls the view (#4183). +pub fn dragging(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::PerspectiveCrop && app.pcrop.drag.is_some() +} + pub fn cancel(app: &mut PhotocraftApp) { app.ui.perspective_crop = None; app.pcrop.drag = None; @@ -327,6 +332,63 @@ mod tests { assert_eq!(app.ui.perspective_crop, None); } + /// Real egui input: a corner dragged past the canvas edge and held there scrolls the view, as a + /// marquee drag does (#4183), so the corner can reach the part of the image that was off screen. + #[test] + fn a_corner_held_past_the_canvas_edge_scrolls_the_view() { + use egui::{Event, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x100 at 400% in a 600x400 canvas: document x 25..175 shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // The top-right corner: document (100, 10). + let grab = xf.to_screen(100.0, 10.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.pcrop.drag, Some(Drag::Corner { index: 1, .. })), "{:?}", st.pcrop.drag); + assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.perspective_crop.is_some_and(|q| q[1][0] > 175.0), "the corner reached past what showed: {:?}", st.ui.perspective_crop); + h.event(button(out, false)); + h.step(); + } + /// A box drag makes the quad, corners drag alone, and ↵'s commit crops the document to the /// quad's size; four clicks in any order make a quad in TL, TR, BR, BL order. #[test] From 92dfbca72f024fc858fd7ff8f822a2398810f5c6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 03:26:57 +0100 Subject: [PATCH 14/27] Crop auto-scroll: only for a press on the canvas (#9307) A crop drag left over by a tool switch (#9223) must not scroll the view while a panel slider beside the canvas is held. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 5 ++-- crates/ui-egui/src/crop_ui.rs | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 50900231fd..d6e7b0e4a1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4895,9 +4895,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. The crop tools keep their own drags. + // drag's next move then extends into what scrolled in. The crop tools keep their own drags, + // pressed on this canvas (not a panel slider held while a stale crop drag lingers). if primary - && (app.drag.is_some() || crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)) + && (app.drag.is_some() || (pointer_here && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)))) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 25aacdb5b8..c589714106 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1597,6 +1597,51 @@ mod tests { h.step(); } + /// A press that started off the canvas (a panel slider beside it) doesn't scroll the view, + /// even with a crop drag still recorded: only a drag on the canvas auto-scrolls. + #[test] + fn a_press_beside_the_canvas_does_not_scroll_it_for_a_crop_drag() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.ui.extras.rulers = false; + // Left over from a drag a tool switch didn't end. + a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None }); + // The canvas takes the left 400 points; the rest stands in for a panel. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let p = pos2(500.0, 100.0); + h.event(Event::PointerMoved(p)); + h.event(button(p, true)); + h.step(); + h.event(Event::PointerMoved(pos2(550.0, 100.0))); + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "the view stayed put"); + h.event(button(pos2(550.0, 100.0), false)); + h.step(); + } + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and From a4bb2d90469071d7a9ab1f0909b245a11f32838c Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 10:43:32 +0100 Subject: [PATCH 15/27] Address CodeRabbit review: a click-sized Perspective Crop press doesn't auto-scroll A new-box press held past egui's click time and slipped a point or two past the canvas edge counted as a drag for auto-scroll, while the release still classifies it as a corner-placing click; the scroll then moved the pointer's document position and turned the click into a box. `dragging` now uses the same click test as the release (`is_click`). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/perspective_crop_ui.rs | 90 ++++++++++++++++++++++- 1 file changed, 87 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/perspective_crop_ui.rs b/crates/ui-egui/src/perspective_crop_ui.rs index 1753eb3d7b..d3c5488d04 100644 --- a/crates/ui-egui/src/perspective_crop_ui.rs +++ b/crates/ui-egui/src/perspective_crop_ui.rs @@ -54,8 +54,21 @@ pub fn pending(app: &PhotocraftApp) -> bool { } /// A box, corner or quad drag in progress: held past the canvas edge, it scrolls the view (#4183). +/// A press that hasn't moved further than a click doesn't: scrolling would turn a corner-placing +/// click near the edge into a box. pub fn dragging(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::PerspectiveCrop && app.pcrop.drag.is_some() + app.ui.tool == Tool::PerspectiveCrop + && match app.pcrop.drag { + Some(Drag::New { start, cur }) => !is_click(app, start, cur), + Some(_) => true, + None => false, + } +} + +/// A new-box press released within [`CLICK_PX`] screen points of where it began places a corner. +fn is_click(app: &PhotocraftApp, start: [f64; 2], cur: [f64; 2]) -> bool { + let click = crate::distort_ui::tolerance(app) * CLICK_PX / 8.0; + (cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click } pub fn cancel(app: &mut PhotocraftApp) { @@ -126,8 +139,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { ToolEvent::Up { .. } => { drag_to(app, p); if let Some(Drag::New { start, cur }) = app.pcrop.drag { - let click = tol * CLICK_PX / 8.0; - if (cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click { + if is_click(app, start, cur) { app.pcrop.clicks.push(start); if let [a, b, c, d] = app.pcrop.clicks[..] { app.ui.perspective_crop = Some(ordered([a, b, c, d])); @@ -389,6 +401,78 @@ mod tests { h.step(); } + /// A corner-placing click pressed just inside the canvas edge that slips a point past it doesn't + /// scroll the view (scrolling would turn it into a box); a new box dragged past the edge does. + #[test] + fn a_click_at_the_canvas_edge_places_a_corner_without_scrolling() { + use egui::{Event, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x100 at 400% in a 600x400 canvas 100 points from the window's left: document x 25..175 + // shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // Pressed a point inside the left edge (the scrollbars sit right and bottom), slipping two + // points past it: still a click. + let press = pos2(101.0, 200.0); + let slip = pos2(99.0, 200.0); + h.event(Event::PointerMoved(press)); + h.event(button(press, true)); + h.step(); + // Held past egui's click time, the press becomes a drag that hasn't left the click size. + for p in [slip, pos2(98.5, 200.0), slip] { + h.event(Event::PointerMoved(p)); + h.run_steps(4); + } + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view"); + h.event(button(slip, false)); + h.step(); + let st = h.state(); + assert_eq!(st.pcrop.clicks.len(), 1, "the click placed a corner: {:?}", st.pcrop.clicks); + assert_eq!(st.ui.perspective_crop, None); + // A new box dragged from inside the canvas past its edge does scroll. + let start = pos2(200.0, 200.0); + h.event(Event::PointerMoved(start)); + h.event(button(start, true)); + h.step(); + for p in [pos2(140.0, 220.0), pos2(50.0, 220.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.pcrop.drag, Some(Drag::New { .. })), "{:?}", st.pcrop.drag); + assert!(st.ui.views[0].center[0] < before[0], "the box drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center); + h.event(button(pos2(50.0, 220.0), false)); + h.step(); + } + /// A box drag makes the quad, corners drag alone, and ↵'s commit crops the document to the /// quad's size; four clicks in any order make a quad in TL, TR, BR, BL order. #[test] From 130b2b373fa1efaa9b2ec0f894dc2a52682e00f7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 11:08:24 +0100 Subject: [PATCH 16/27] SVG: read the DOCTYPE's internal subset when checking the markup Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 49 +++++++++++++++++++++++++++++++++++---- crates/io/tests/it/svg.rs | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 6363945d7e..bc4881cf27 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -263,7 +263,7 @@ fn parse(bytes: &[u8]) -> Result { /// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one). fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Result { let xml = inflate(bytes)?; - if nesting_depth(&xml, MAX_XML_DEPTH) > MAX_XML_DEPTH { + if nesting_depth(&xml, MAX_XML_DEPTH)? > MAX_XML_DEPTH { return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); } let has_text = xml.windows(4).any(|w| w == b"text"); @@ -297,8 +297,10 @@ fn inflate(bytes: &[u8]) -> Result, IoError> { /// The deepest element nesting in `xml`, stopping as soon as it passes `limit` (the result is /// then `limit + 1`). Comments, CDATA sections, processing instructions and the DOCTYPE add /// nothing; quoted attribute values may hold `>` or `/>`. Malformed markup is only counted -/// loosely: the parser rejects it afterwards. -fn nesting_depth(xml: &[u8], limit: usize) -> usize { +/// loosely: the parser rejects it afterwards. The parser expands the DTD's entities after this +/// count, so an entity holding markup (a `<`) is an error: it could nest deeper than anything +/// counted here. A `<` there stays text. +fn nesting_depth(xml: &[u8], limit: usize) -> Result { let after = |from: usize, pat: &[u8]| -> usize { xml.get(from..).and_then(|s| s.windows(pat.len()).position(|w| w == pat)).map_or(xml.len(), |p| from.saturating_add(p).saturating_add(pat.len())) }; @@ -320,6 +322,41 @@ fn nesting_depth(xml: &[u8], limit: usize) -> usize { } (xml.len(), false) }; + // The byte after the DOCTYPE starting at `from`: its internal subset `[...]` is walked + // declaration by declaration, so a quote in a comment there can't hide the markup after it. + let doctype_end = |from: usize| -> Result { + let (mut quote, mut j) = (None, from); + loop { + let Some(&b) = xml.get(j) else { return Ok(xml.len()) }; + j = j.saturating_add(1); + match quote { + Some(q) if b == q => quote = None, + Some(_) => {} + None if b == b'"' || b == b'\'' => quote = Some(b), + None if b == b'>' => return Ok(j), + None if b == b'[' => break, + None => {} + } + } + while let Some(rest) = xml.get(j..).filter(|r| !r.is_empty()) { + j = if rest.starts_with(b"") + } else if rest.starts_with(b"") + } else if rest.starts_with(b" usize { after(at.saturating_add(9), b"]]>") } else if rest.starts_with(b"") + } else if rest.starts_with(b" usize { depth = depth.saturating_add(1); deepest = deepest.max(depth); if deepest > limit { - return deepest; + return Ok(deepest); } } end }; } - deepest + Ok(deepest) } /// The document canvas for a drawing: its size in px, scaled down to [`MAX_SIDE`] when needed. diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index c71bb0ae4f..527067508b 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -351,6 +351,47 @@ fn deeply_nested_markup_is_an_error_not_a_stack_overflow() { assert_eq!(r.document.layers.len(), 1); } +/// The parser expands a DTD's internal entities after the depth check: an entity holding +/// markup, or a quote in a DTD comment that made the check skip ahead, hid 20 000 nested groups +/// from it and overflowed the stack again. Both are errors now; same small stack as above. +#[test] +fn a_dtd_cannot_hide_nesting_from_the_depth_check() { + let deep = |open: &str, close: &str| format!("{}{}", open.repeat(20_000), close.repeat(20_000)); + let with_dtd = |subset: &str, body: &str| format!("{body}"); + let cases = [ + ("entity", with_dtd(&format!("", deep("", "")), "&a;")), + ("single-quoted entity", with_dtd(&format!("", deep("", "")), "&a;")), + ("quote in a comment", with_dtd("", &format!("{}'", deep("", "")))), + ]; + std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(move || { + for (name, svg) in &cases { + let gz = gzip(svg.as_bytes()); + for bytes in [svg.as_bytes(), gz.as_slice()] { + let e = import("deep.svg", bytes).err().unwrap_or_else(|| panic!("{name} opened")); + assert!(matches!(&e, IoError::Svg(_)), "{name}: {e}"); + } + } + }) + .unwrap() + .join() + .unwrap(); +} + +/// Text-only entities, as Illustrator declares its namespaces, still open, `<` included: +/// the parser keeps a character reference in an entity as text. +#[test] +fn text_entities_in_a_dtd_still_open() { + let r = open( + " ?> ]>\ + &c;", + ); + assert_eq!(r.document.layers.len(), 1); + assert!(close(px(&r.document, 4, 4), [1.0, 0.0, 0.0, 1.0])); +} + /// The depth check reads the markup, not the parser's tree: it must not count `<` in comments, /// CDATA, processing instructions or the DOCTYPE, nor end a tag at a `>` inside quotes. #[test] From b05e02c9b319beccf58ddd8ad000b05dc91064e2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 11:20:04 +0100 Subject: [PATCH 17/27] SVG: end the DTD's element, attribute and notation declarations as the parser does Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 7 +++++-- crates/io/tests/it/svg.rs | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index bc4881cf27..17eaef221d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -343,12 +343,15 @@ fn nesting_depth(xml: &[u8], limit: usize) -> Result { after(j.saturating_add(4), b"-->") } else if rest.starts_with(b"") - } else if rest.starts_with(b"`, quotes or not. + after(j.saturating_add(2), b">") } else if rest.starts_with(b"]") { return Ok(tag_end(j.saturating_add(1)).0); } else { diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index 527067508b..f856616989 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -352,7 +352,7 @@ fn deeply_nested_markup_is_an_error_not_a_stack_overflow() { } /// The parser expands a DTD's internal entities after the depth check: an entity holding -/// markup, or a quote in a DTD comment that made the check skip ahead, hid 20 000 nested groups +/// markup, or a quote in a DTD comment or declaration that made the check skip ahead, hid 20 000 nested groups /// from it and overflowed the stack again. Both are errors now; same small stack as above. #[test] fn a_dtd_cannot_hide_nesting_from_the_depth_check() { @@ -362,6 +362,12 @@ fn a_dtd_cannot_hide_nesting_from_the_depth_check() { ("entity", with_dtd(&format!("", deep("", "")), "&a;")), ("single-quoted entity", with_dtd(&format!("", deep("", "")), "&a;")), ("quote in a comment", with_dtd("", &format!("{}'", deep("", "")))), + ("quote in an element declaration", with_dtd("", &format!("{}'", deep("", "")))), + ( + "entity between quoted attribute lists", + with_dtd(&format!("", deep("", "")), "&a;"), + ), + ("entity between quoted notations", with_dtd(&format!("", deep("", "")), "&a;")), ]; std::thread::Builder::new() .stack_size(512 * 1024) @@ -385,7 +391,7 @@ fn a_dtd_cannot_hide_nesting_from_the_depth_check() { fn text_entities_in_a_dtd_still_open() { let r = open( " ?> ]>\ + ?> ]>\ &c;", ); assert_eq!(r.document.layers.len(), 1); From 21d0ac3a1026c01d8d4b1906e91940956165d53b Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 13:27:52 +0100 Subject: [PATCH 18/27] Tests: a .pcraft smart object with a hostile SVG source does not abort Image Size or a PSD save Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/tests/it/svg_smart_object.rs | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/engine/tests/it/svg_smart_object.rs b/crates/engine/tests/it/svg_smart_object.rs index 16d8f3d459..450d54c175 100644 --- a/crates/engine/tests/it/svg_smart_object.rs +++ b/crates/engine/tests/it/svg_smart_object.rs @@ -62,3 +62,32 @@ fn re_placing_at_another_scale_re_renders_the_vector_source() { assert!(alpha(&surf, 268, 60) > 0.99 && alpha(&surf, 271, 60) < 0.01); assert!(red(&surf, 150, 81) < 0.02 && red(&surf, 150, 75) > 0.98 && red(&surf, 150, 87) > 0.98); } + +/// A `.pcraft` opens from its cached pixels and parses an embedded SVG source only on a later +/// edit. A source whose DTD entity hides 20 000 nested groups from the depth check used to open +/// clean and then overflow the stack on Image Size or a PSD save; both are an error or a fallback +/// now. Run on a 2 MB stack, as the app's import and command threads are. +#[test] +fn a_pcraft_smart_object_with_a_hostile_svg_does_not_abort_a_later_edit() { + let deep = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let hostile = format!("]>&a;"); + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(move || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + photocraft_engine::file_cmds::place_bytes(&mut s, "logo.svg", SVG.as_bytes().to_vec(), None, &json!({"scale": 100})).unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let LayerContent::Smart(sm) = &mut doc.layers.last_mut().unwrap().content else { panic!("smart object") }; + sm.source = photocraft_doc::SmartSource::Embedded { file_name: "logo.svg".into(), bytes: std::sync::Arc::new(hostile.into_bytes()) }; + let carrier = photocraft_format::save_to_bytes(&doc, &photocraft_format::SaveOptions::default()).unwrap(); + + photocraft_engine::file_cmds::open_bytes_as(&mut s, "carrier.pcraft", &carrier, None, None).unwrap(); + let _ = s.execute("image.imageSize", json!({"width": 50, "height": 50})); + let dir = tempfile::tempdir().unwrap(); + let _ = s.execute("file.saveACopy", json!({"path": dir.path().join("copy.psd").to_string_lossy()})); + }) + .unwrap() + .join() + .unwrap(); +} From da87348f8612c701c008a75835ed7a0841154ae9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 13:52:42 +0100 Subject: [PATCH 19/27] SVG: the fallback font search reads each font's character map once (#9671) A character the text's font lacks made usvg's fallback search ask every face in the database whether it has the character, and for a face loaded from a file (every system font) that reads the whole font file. Once per text element: 20 elements with U+10FF00 took 3 s with 273 installed faces. The fallback selector is now our own copy of usvg's loop (same order, used-face exclusion and style filter), and the per-face check answers from a per-process cache of each file face's cmap table, picked as ttf-parser's Face::parse picks it (last record of a linear walk, so an unsorted table directory gives the same table) and looked up the same way. Bounded at 64 MiB; a file that doesn't load isn't remembered. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 1 + crates/io/Cargo.toml | 2 + crates/io/src/svg.rs | 141 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 142 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 128d0f35bd..1930841ac3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5139,6 +5139,7 @@ dependencies = [ "serde_json", "thiserror 2.0.21", "tiff", + "ttf-parser", "zune-core 0.5.3", "zune-jpegxl", ] diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 83ccd3b784..5cf15cf62d 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -44,6 +44,8 @@ roxmltree = "0.21" # already in the tree through the UI's icon loader; text shaping needs the fonts feature set. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } +# The SVG fallback font search keeps each font file's character map (already in the tree through usvg). +ttf-parser = { version = "0.25", default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 7ff563d466..4532c33697 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -268,15 +268,78 @@ fn in_memory(id: usvg::fontdb::ID, db: &mut Arc) -> usvg loaded.into_iter().find(|&n| db.face_source(n).is_some_and(|(_, i)| i == index)).unwrap_or(id) } +/// Most `cmap` table bytes [`has_char`] keeps; past it a face is asked on disk (slow, still right). +#[cfg(not(target_arch = "wasm32"))] +const MAX_CACHED_CMAP_BYTES: usize = 64 << 20; + +/// Whether face `face` maps `c` to a glyph, as usvg's own check decides it. usvg reads a font +/// file's whole font for every face it asks, so one character no font has re-read every +/// installed font once per text element (430 ms each with 273 faces). A file face's `cmap` table +/// is kept instead, read once per process; a file that doesn't load isn't remembered. +#[cfg(not(target_arch = "wasm32"))] +fn has_char(db: &usvg::fontdb::Database, face: &usvg::fontdb::FaceInfo, c: char) -> bool { + use std::collections::HashMap; + use std::path::PathBuf; + use std::sync::{Mutex, PoisonError}; + use ttf_parser::{Face, Tag, cmap}; + type Cmaps = (HashMap<(PathBuf, u32), Arc>>, usize); + static CMAPS: OnceLock> = OnceLock::new(); + let maps = || CMAPS.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner); + let in_cmap = + |table: &[u8]| cmap::Table::parse(table).is_some_and(|t| t.subtables.into_iter().any(|s| s.is_unicode() && s.glyph_index(u32::from(c)).is_some())); + let usvg_check = |data: &[u8], index| Face::parse(data, index).is_ok_and(|f| f.glyph_index(c).is_some()); + let usvg::fontdb::Source::File(path) = &face.source else { + return db.with_face_data(face.id, usvg_check).unwrap_or(false); + }; + let key = (path.clone(), face.index); + if let Some(table) = maps().0.get(&key).cloned() { + return in_cmap(&table); + } + // usvg's check parses the whole face first: one that doesn't parse has no characters. Its + // `cmap` is the last such table record (a linear walk, unsorted directories included). + let cmap_of = |data: &[u8], index| { + let face = Face::parse(data, index).ok()?; + let raw = face.raw_face(); + let record = raw.table_records.into_iter().filter(|r| r.tag == Tag::from_bytes(b"cmap")).last(); + let table = record.and_then(|r| { + let start = usize::try_from(r.offset).ok()?; + raw.data.get(start..start.checked_add(usize::try_from(r.length).ok()?)?) + }); + Some(table.unwrap_or_default().to_vec()) + }; + let Some(table) = db.with_face_data(face.id, cmap_of).flatten() else { + return false; + }; + let found = in_cmap(&table); + let mut maps = maps(); + // An import that missed at the same time may have kept it already. + if !maps.0.contains_key(&key) && maps.1.saturating_add(table.len()) <= MAX_CACHED_CMAP_BYTES { + maps.1 = maps.1.saturating_add(table.len()); + maps.0.insert(key, Arc::new(table)); + } + found +} + +/// usvg's fallback choice (the first face, in database order, not used yet, sharing the base +/// face's style, weight or stretch and having `c`), asked through [`has_char`]. +#[cfg(not(target_arch = "wasm32"))] +fn fallback_face(c: char, used: &[usvg::fontdb::ID], db: &usvg::fontdb::Database) -> Option { + let base = db.face(*used.first()?)?; + db.faces() + .filter(|f| !used.contains(&f.id)) + .filter(|f| base.style == f.style || base.weight == f.weight || base.stretch == f.stretch) + .find(|f| has_char(db, f, c)) + .map(|f| f.id) +} + /// usvg's font choice, with the chosen faces read from memory ([`in_memory`]). fn font_resolver() -> usvg::FontResolver<'static> { #[cfg(not(target_arch = "wasm32"))] { let select = usvg::FontResolver::default_font_selector(); - let fallback = usvg::FontResolver::default_fallback_selector(); usvg::FontResolver { select_font: Box::new(move |font, db| select(font, db).map(|id| in_memory(id, db))), - select_fallback: Box::new(move |c, used, db| fallback(c, used, db).map(|id| in_memory(id, db))), + select_fallback: Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))), } } #[cfg(target_arch = "wasm32")] @@ -1281,6 +1344,80 @@ mod tests { } } + /// #9671: the fallback search for a character the text's font lacks reads each font file's + /// character map once per process, not the whole file on every text element (430 ms an + /// element with 273 installed faces). A second import still finds the fallback face after + /// its file stopped being readable, so it didn't go back to the disk. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_fallback_search_reads_each_font_file_once() { + use std::sync::atomic::{AtomicBool, Ordering}; + static GONE: AtomicBool = AtomicBool::new(false); + fn path() -> std::path::PathBuf { + std::env::temp_dir().join(format!("photocraft-svg-test-fallback-{}.ttf", std::process::id())) + } + fn inter_and_mono_on_disk() -> Arc { + std::fs::write(path(), include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf")).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_file(path()).unwrap(); + if GONE.load(Ordering::SeqCst) { + std::fs::write(path(), b"not a font any more").unwrap(); + } + Arc::new(db) + } + // Inter has no box-drawing characters; JetBrains Mono has. + let svg = "I\u{2500}I"; + let outlines = |parsed: Parsed| { + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + let groups = layers.into_iter().filter_map(|l| if let LayerContent::Group(g) = l.content { Some(g) } else { None }); + groups.flat_map(|g| g.children).filter_map(|l| if let LayerContent::Shape(s) = l.content { Some(s.path) } else { None }).collect::>() + }; + let first = parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap(); + let mono = + first.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_))); + assert!(mono, "the box-drawing character falls back to JetBrains Mono"); + let first = outlines(first); + GONE.store(true, Ordering::SeqCst); + let second = outlines(parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap()); + let _ = std::fs::remove_file(path()); + assert!(first.iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); + assert!(second == first, "the second import set the character in the same fallback face"); + } + + /// #9671: the kept `cmap` is the one usvg reads (the last such record of a linear walk), also + /// in a font whose table directory isn't sorted by tag, where a binary search misses it. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_fallback_search_reads_the_cmap_of_an_unsorted_font() { + fn inter_and_unsorted_mono_on_disk() -> Arc { + let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); + let count = usize::from(u16::from_be_bytes([font[4], font[5]])); + // The `cmap` record moves to the end of the directory. + let mut records: Vec> = font[12..12 + count * 16].chunks(16).map(<[u8]>::to_vec).collect(); + let at = records.iter().position(|r| r.starts_with(b"cmap")).unwrap(); + let cmap = records.remove(at); + records.push(cmap); + font.splice(12..12 + count * 16, records.concat()); + let raw = ttf_parser::RawFace::parse(&font, 0).unwrap(); + assert!(raw.table(ttf_parser::Tag::from_bytes(b"cmap")).is_none(), "a binary search misses the cmap"); + assert!(raw.table(ttf_parser::Tag::from_bytes(b"name")).is_some(), "fontdb still finds the name"); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id())); + std::fs::write(&path, font).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let svg = + b"I\xE2\x94\x80I"; + let parsed = parse_with(svg, inter_and_unsorted_mono_on_disk).unwrap(); + let _ = std::fs::remove_file(std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id()))); + let mono = + parsed.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_))); + assert!(mono, "the box-drawing character falls back to JetBrains Mono"); + } + /// #9406: moving a font collection into memory keeps its faces in their order, so the /// fallback search for a later text still finds the face it found on disk first. #[cfg(not(target_arch = "wasm32"))] From bfa718f20b8f3af2ecdd50eb73acf24b7c750b49 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 14:43:48 +0100 Subject: [PATCH 20/27] Dropdowns: a list opening above its box is in place from its first visible frame (#5495) egui placed an upward list's bottom by the size it had the frame before, so it moved up by ~46 pt as it settled and a click two frames after opening missed the row (main's intermediate_ui_scale_choices test). Its top is now placed from the rows' measured height plus the popup frame's margin. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/widgets.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index cf860b2b93..e5115bc12d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1769,15 +1769,25 @@ pub fn combo_list( let rows_id = popup_id.with("rows"); let rows = ctx.data(|d| d.get_temp::(rows_id)); let up = rows.is_some_and(|rows| rows > below) && above > below; - let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; // Only the room that side has, even when it is small: a taller list would be pushed back // into the window, over its button (#5495 review). - let room = room.max(0.0); + let room = (if up { above } else { below }).max(0.0); + // Above the button the list's top is placed from its known height: egui would place its + // bottom by the size the list had last frame, so it would move as it settles, under a + // click aimed at a row. `chrome` is the popup frame's margin and stroke. + let anchor = match rows.filter(|_| up) { + Some(rows) => { + let chrome = egui::Frame::popup(&ctx.global_style()).total_margin().sum().y; + let top = button.rect.top() - rows.min(room) - chrome; + egui::Rect::from_x_y_ranges(button.rect.x_range(), top - button.rect.height()..=top) + } + None => button.rect, + }; let parent_layer = ui.layer_id(); let inner = egui::Popup::menu(&button) .id(popup_id) - .anchor(button.rect) - .align(align) + .anchor(anchor) + .align(egui::RectAlign::BOTTOM_START) .align_alternatives(&[]) .width(button.rect.width()) .close_behavior(close) From ec49d0b5820ea1e84decc549f772d035747bdf7c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:19:25 +0100 Subject: [PATCH 21/27] Address CodeRabbit review: end a crop drag before the frame sees a tool switch The canvas ends the gesture before `ensure_frame` (which dropped the untouched default frame under the box being drawn, and the Hand never reached `tool_event`), keeping the pen eraser exception. A press inside the default frame that never moves is no edit, so leaving still drops a selection-derived default frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 ++ crates/ui-egui/src/tools/crop_ui.rs | 12 +++- crates/ui-egui/src/tools/crop_ui/tests.rs | 70 +++++++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3896b84cf6..374c6a6e5a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1876,6 +1876,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::crop_straighten::set_held(app, !ctx.text_edit_focused() && ui.input(|i| i.modifiers.command)); // A tab switched this frame drops the other document's pending crop (#1918). crate::crop_ui::cancel_stale(app); + // A tool picked mid-drag ends the crop gesture before the frame sees the switch, which would + // otherwise drop the untouched default frame under the box being drawn (#9223). The Hand and + // Zoom never reach `tool_event`, so this is the one place that sees every tool. + crate::crop_ui::end_drag_on_leave(app); crate::crop_ui::ensure_frame(app); let mut drawing = crate::crop_ui::active(app); if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index 249ba88f5c..6a569aa68f 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -863,7 +863,9 @@ fn release(app: &mut PhotocraftApp, drag: CropDrag) { let ok = app.ui.crop_rect.is_some_and(size_ok); // A click outside the untouched default frame (no turn) leaves it the default. let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) - && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)) + // A press that never moved draws nothing: the frame shown is still the previous one. + && !matches!(drag, CropDrag::Draw { anchor, cur, .. } if anchor == cur); if ok && changed { app.crop.default_frame = false; } @@ -886,6 +888,14 @@ pub fn end_drag(app: &mut PhotocraftApp) { app.ui.tool = tool; } +/// [`end_drag`] once another tool is current, except while the pen's eraser end stands in for the +/// Crop tool (`stylus`): the gesture goes on when the tip comes back. +pub fn end_drag_on_leave(app: &mut PhotocraftApp) { + if app.ui.tool != Tool::Crop && app.stylus.tool_before_eraser != Some(Tool::Crop) { + end_drag(app); + } +} + /// On release: the frame state at the press becomes a box Undo step when the gesture changed it. fn push_press_step(app: &mut PhotocraftApp) { if let Some(before) = app.crop.press_step.take() diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 4c00297a02..8160a3c42f 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -858,6 +858,76 @@ fn a_tool_switch_during_a_drag_on_the_default_frame_keeps_the_edit() { } } +/// Real egui input: a tool picked while a box is being drawn over the untouched default frame +/// (a tool key mid-drag) commits that box on leaving, whichever tool it is; the canvas ends the +/// gesture before the frame sees the switch, also for the Hand, whose events never reach +/// `tool_event` (#9223). +#[test] +fn a_tool_switch_during_a_real_drag_commits_the_drawn_box() { + use egui::{Event, PointerButton, pos2}; + for tool in [Tool::Brush, Tool::PerspectiveCrop, Tool::Hand] { + let mut a = app(SampleType::U8); + a.sync_views(); + let v = &mut a.ui.views[0]; + (v.zoom, v.center, v.fit_pending, v.doc_size, v.rotation) = (2.0, [100.0, 50.0], false, [200, 100], 0.0); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + assert!(h.state().crop.default_frame, "{tool:?}"); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let p0 = pos2(200.0, 150.0); + h.event(Event::PointerMoved(p0)); + h.event(button(p0, true)); + h.step(); + for p in [pos2(220.0, 170.0), pos2(260.0, 190.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + assert!(h.state().crop.drag.is_some(), "{tool:?}"); + h.state_mut().ui.tool = tool; + h.event(Event::PointerMoved(pos2(270.0, 195.0))); + h.step(); + h.event(button(pos2(270.0, 195.0), false)); + h.run_steps(2); + let st = h.state(); + assert!(st.crop.drag.is_none(), "{tool:?}"); + assert_eq!(st.ui.crop_rect, None, "{tool:?}"); + assert_eq!(st.session.active().unwrap().doc.size, Size::new(30, 20), "{tool:?}: the drawn 60x40 screen px at 200%"); + } +} + +/// A press inside the untouched default frame that never moves draws nothing, so the frame +/// stays the default one and leaving drops it: no crop to the selection's bounds, released or +/// cut short by a tool switch (#9223). +#[test] +fn a_press_that_never_moves_leaves_the_default_frame_untouched() { + for switch in [false, true] { + let mut app = app(SampleType::U8); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 40.0, 60.0])); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, NONE); + if switch { + app.ui.tool = Tool::Brush; + end_drag_on_leave(&mut app); + } else { + tool_event(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }, NONE); + assert!(app.crop.default_frame, "a click is no edit"); + app.ui.tool = Tool::Brush; + } + ensure_frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "switch: {switch}"); + assert_eq!(app.ui.crop_rect, None, "switch: {switch}"); + } +} + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From cf9a7254d597a8903c2326bc383684c1af55d389 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:20:25 +0100 Subject: [PATCH 22/27] Address CodeRabbit review: budget the image between bicubic passes A bicubic shrink of both axes stores the image between its two passes with one axis still at its old size, larger than the result. The hidden pixel budget now checks the largest rectangle of each surface's pass plan (algo::resample::largest_resize_rect), masks, channels and the selection with their Bilinear filter. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/resample.rs | 18 +++++++++++- crates/algo/src/resample/tests.rs | 19 ++++++++++++ crates/engine/src/cmd/image_cmds.rs | 36 +++++++++++------------ crates/engine/src/cmd/image_cmds/tests.rs | 18 ++++++++++++ 4 files changed, 72 insertions(+), 19 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 4dcf0b6944..c8c0580bbf 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -288,6 +288,21 @@ pub fn scaled_rect(r: Rect, sx: f64, sy: f64) -> Rect { Rect::new((r.x0 as f64 * sx).floor() as i32, (r.y0 as f64 * sy).floor() as i32, (r.x1 as f64 * sx).ceil() as i32, (r.y1 as f64 * sy).ceil() as i32) } +/// The largest rectangle a resize of content at `r` by `(sx, sy)` with `filter` stores: the +/// result, or the image between the passes of a two-pass bicubic. That one keeps an axis at its +/// old size, so when both axes shrink it is larger than the result (#9212). +pub fn largest_resize_rect(r: Rect, sx: f64, sy: f64, filter: Resample) -> Rect { + let area = |r: Rect| u64::from(r.width()) * u64::from(r.height()); + let (mut cur, mut largest) = (r, Rect::EMPTY); + for p in plan(filter, sx, sy) { + cur = scaled_rect(cur, p.sx, p.sy); + if area(cur) > area(largest) { + largest = cur; + } + } + largest +} + /// Resizes a surface by `(sx, sy)` about the document origin. The surface's /// default pixel is kept (masks keep their "reveal all" background). pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surface { @@ -346,7 +361,8 @@ fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option) /// Runs `filter`'s passes. Between two passes the image is stored in its own format, which /// clips it (and rounds it at 8 and 16 bits) as Photoshop does; the smaller scale goes first, so -/// the intermediate image is never larger than the result. +/// the intermediate image is never larger than the result when an axis grows, but is when both +/// shrink ([`largest_resize_rect`]). fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option, budget: usize) -> Surface { let mut cur: Option = None; let mut canvas = canvas; diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index 0ee08847e1..3fb68936d3 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -400,3 +400,22 @@ fn nearest_neighbor_reduction_does_not_average() { } } } + +/// #9212: a bicubic shrink of both axes stores the image between its passes with one axis at the +/// old size, larger than the result; single-pass filters and growing axes store nothing larger. +#[test] +fn largest_resize_rect_counts_the_image_between_the_passes() { + let r = Rect::new(0, 0, 100, 80); + for f in [Resample::Bicubic, Resample::BicubicSharper, Resample::BicubicAutomatic, Resample::PreserveDetails] { + assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 80), "{f:?}"); + } + // The axis with the smaller scale goes first. + assert_eq!(largest_resize_rect(r, 0.5, 0.25, Resample::Bicubic), Rect::new(0, 0, 100, 20)); + for f in [Resample::Bilinear, Resample::Nearest, Resample::Lanczos] { + assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 40), "{f:?}"); + } + for f in [Resample::Bicubic, Resample::BicubicAutomatic] { + assert_eq!(largest_resize_rect(r, 2.0, 3.0, f), Rect::new(0, 0, 200, 240), "{f:?} grows"); + assert_eq!(largest_resize_rect(r, 0.5, 2.0, f), Rect::new(0, 0, 50, 160), "{f:?} shrinks x, grows y"); + } +} diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 4494b5d13d..ad4203ece5 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -3,7 +3,7 @@ use std::convert::Infallible; -use photocraft_algo::resample::{Resample, crop_surface, resize_surface_in_canvas, translate_surface}; +use photocraft_algo::resample::{Resample, crop_surface, largest_resize_rect, resize_surface_in_canvas, scaled_rect, translate_surface}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, LayerId, Size}; use photocraft_geom::Rect; @@ -297,7 +297,7 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { return Ok(()); } - check_hidden_resample_budget(cmd, doc, sx, sy)?; + check_hidden_resample_budget(cmd, doc, sx, sy, filter)?; // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. let canvas = Rect::from_xywh(0, 0, ow, oh); let taken = crate::smart_cmds::take_caches(&mut doc.layers); @@ -329,23 +329,23 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt Ok(()) } -/// [`check_resample_budget`] for the largest surface [`resample_doc`] scales by `sx` x `sy`: each -/// keeps its pixels outside the canvas (a crop that didn't delete them, a layer moved off the -/// canvas), and those grow with the scale like the rest. -fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) -> Result<()> { - let canvas = doc.bounds(); - // The largest surface by bytes: its scaled width, height and bytes per pixel (a mask has one +/// [`check_resample_budget`] for the largest surface [`resample_doc`] stores while scaling by +/// `sx` x `sy` with `filter` (masks, channels and the selection with Bilinear): each keeps its +/// pixels outside the canvas (a crop that didn't delete them, a layer moved off the canvas), and +/// those grow with the scale like the rest. A bicubic shrink also stores the image between its +/// two passes, one axis still at its old size ([`largest_resize_rect`]). +fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, filter: Resample) -> Result<()> { + let new_canvas = scaled_rect(doc.bounds(), sx, sy); + // The largest surface by bytes: its width, height and bytes per pixel (a mask has one // channel, the layers the document's). let mut largest = (0u32, 0u32, 1u64); - let mut visit = |surf: &Surface| { - let r = surf.content_bounds(); - // What lies within the canvas scales to within the new canvas, already budgeted. - if r.is_empty() || canvas.union(&r) == canvas { + let mut visit = |surf: &Surface, filter: Resample| { + let r = largest_resize_rect(surf.content_bounds(), sx, sy, filter); + // What stays within the new canvas is already budgeted. + if r.is_empty() || new_canvas.union(&r) == new_canvas { return; } - // The output's extent, as `resize_surface_in_canvas` lays it out. - let side = |a: i32, b: i32, k: f64| ((f64::from(b) * k).ceil() - (f64::from(a) * k).floor()).clamp(0.0, f64::from(u32::MAX)) as u32; - let (w, h) = (side(r.x0, r.x1, sx), side(r.y0, r.y1, sy)); + let (w, h) = (r.width(), r.height()); let bpp = surf.format().bytes_per_pixel().max(1) as u64; let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); if bytes((w, h, bpp)) > bytes(largest) { @@ -353,12 +353,12 @@ fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) } }; // The surfaces `resample_doc` scales, smart object caches included. - for_each_surface(&mut doc.layers, true, &mut |surf, _| visit(surf)); + for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| visit(surf, if is_mask { Resample::Bilinear } else { filter })); for ch in doc.channels.iter().chain(doc.quick_mask.as_ref()) { - visit(&ch.surface); + visit(&ch.surface, Resample::Bilinear); } if let Some(sel) = &doc.selection { - visit(sel); + visit(sel, Resample::Bilinear); } let (w, h, bpp) = largest; let px = u64::from(w).saturating_mul(u64::from(h)); diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index fe9af44182..19b12a5200 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -1008,3 +1008,21 @@ fn duplicate_document() { assert_eq!(doc(&s).layers.len(), 1); assert!(doc(&s).name.ends_with("copy")); } + +/// #9212: a bicubic shrink stores the image between its two passes with one axis at its old +/// size. A Background whose kept pixels reach (69999, 69999), halved from 200 to 100 px, ends at +/// about 35000 x 35000 px (4.9 GB, within the 8 GiB budget) but passes through about +/// 35000 x 70000 px (9.8 GB): refused before allocating. Bilinear has one pass and fits. The +/// check alone runs, so nothing that large is allocated either way. +#[cfg(target_pointer_width = "64")] +#[test] +fn hidden_resample_budget_counts_the_image_between_bicubic_passes() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut d = doc(&s).clone(); + let bg = d.background_mut().unwrap().surface_mut().unwrap(); + bg.fill_rect(Rect::new(69_999, 69_999, 70_000, 70_000), &[1.0, 0.0, 0.0, 1.0]); + let err = check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bicubic).unwrap_err().to_string(); + assert!(err.contains(" x 70000 px is "), "{err}"); + check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bilinear).unwrap(); +} From 25782b0ca94f9ad9a36c9317dc918379e20bfb09 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 18:25:17 +0100 Subject: [PATCH 23/27] Address CodeRabbit review: crop auto-scroll only for real crop drags - Crop: a new-frame drag still within 3 screen points of its press (a long press near the edge that slipped past it) doesn't scroll, so it can't grow a frame under a still pointer; Move and Resize still scroll. - Both crop tools scroll only while the canvas widget itself holds the press (not a scrollbar or panel with a stale crop drag) and the crop tool has the pointer (not a temporary Zoom held mid-drag). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 14 +- crates/ui-egui/src/tools/crop_ui.rs | 20 ++- crates/ui-egui/src/tools/crop_ui/tests.rs | 121 ++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 67 ++++++++++ 4 files changed, 213 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0669106626..ffdf5d11bb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1608,8 +1608,6 @@ struct CanvasTailInput<'a> { bars_id: egui::Id, layer_edges: egui::layers::ShapeIdx, camera: Option<([f32; 2], f32)>, - /// The pointer was pressed on this canvas (not on a panel over it). - pointer_here: bool, } fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasTailInput<'_>) { @@ -1629,16 +1627,19 @@ fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut Vie let bars_id = input.bars_id; let layer_edges = input.layer_edges; let camera = input.camera; - let pointer_here = input.pointer_here; app.tool_override = None; if let Some(b) = layer_edges_rect(app, idx) { painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. The crop tools keep their own drags, - // pressed on this canvas (not a panel slider held while a stale crop drag lingers). + // drag's next move then extends into what scrolled in. The crop tools keep their own drags: + // they scroll only while the press is the canvas's own (not a panel slider or a scrollbar held + // while a stale crop drag lingers) and the crop tool has it (not a temporary Zoom, which + // freezes the drag). + let crop_drag = + response.is_pointer_button_down_on() && tool == app.ui.tool && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)); if primary - && (app.drag.is_some() || (pointer_here && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)))) + && (app.drag.is_some() || crop_drag) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) @@ -2032,7 +2033,6 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: bars_id, layer_edges, camera, - pointer_here, }; finish_canvas_view(app, ui, &mut view, &tail); view diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index f9eeee5f7c..92f65104cc 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -421,9 +421,25 @@ pub fn active(app: &PhotocraftApp) -> bool { /// A drag that sizes or moves the frame over the image, which scrolls the view when held past the /// canvas edge (#4183). Not the turns, nor the default mode's image moves and live-centred resizes: -/// those drive the camera themselves. +/// those drive the camera themselves. A new frame's drag that hasn't left the size of a click (a +/// long press that slipped past the edge) doesn't either: scrolling would draw a frame under the +/// still pointer. pub fn autoscrolls(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Crop && matches!(app.crop.drag, Some(CropDrag::Draw { .. } | CropDrag::Move { .. } | CropDrag::Resize { view: None, .. })) + app.ui.tool == Tool::Crop + && match app.crop.drag { + Some(CropDrag::Draw { anchor, cur, .. }) => !is_click(app, anchor, cur), + Some(CropDrag::Move { .. } | CropDrag::Resize { view: None, .. }) => true, + _ => false, + } +} + +/// A new-frame drag shorter than this (screen points) on both axes is still a click. +const CLICK_PX: f64 = 3.0; + +/// Document points `a` and `b` lie within [`CLICK_PX`] screen points of each other on both axes. +fn is_click(app: &PhotocraftApp, a: [f64; 2], b: [f64; 2]) -> bool { + let click = CLICK_PX / (app.point_zoom() as f64).max(0.01); + (b[0] - a[0]).abs() <= click && (b[1] - a[1]).abs() <= click } /// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 1069c3bd47..cf5391606c 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -588,6 +588,127 @@ fn a_press_beside_the_canvas_does_not_scroll_it_for_a_crop_drag() { h.step(); } +/// The 200x100 test document at 400% (document x 25..175 shows in a 600-point canvas). +fn zoomed_view(height: u32) -> crate::state::View { + crate::state::View { + zoom: 4.0, + center: [100.0, height as f32 / 2.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, height], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + } +} + +/// A press held just inside the canvas edge (past egui's click time, so egui starts a drag) that +/// slips a point past it is still a click: it draws no frame and doesn't scroll the view, which +/// would grow a frame under the still pointer. A new frame dragged past the edge does scroll. +#[test] +fn a_held_click_at_the_canvas_edge_draws_no_frame_and_does_not_scroll() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + a.ui.views = vec![zoomed_view(100)]; + a.ui.extras.rulers = false; + // The canvas starts 100 points from the window's left, so its left edge (no scrollbar there) + // has room past it. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let frame = h.state().ui.crop_rect; + assert!(h.state().crop.default_frame, "{frame:?}"); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let press = pos2(101.0, 200.0); + let slip = pos2(99.0, 200.0); + h.event(Event::PointerMoved(press)); + h.event(button(press, true)); + h.step(); + for p in [slip, pos2(98.5, 200.0), slip] { + h.event(Event::PointerMoved(p)); + h.run_steps(4); + } + assert!(matches!(h.state().crop.drag, Some(CropDrag::Draw { .. })), "egui started a drag: {:?}", h.state().crop.drag); + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view"); + h.event(button(slip, false)); + h.step(); + let st = h.state(); + assert_eq!(st.ui.crop_rect, frame, "the click drew no frame"); + assert!(st.crop.default_frame); + // A new frame dragged from inside the canvas past its edge does scroll. + let start = pos2(300.0, 200.0); + h.event(Event::PointerMoved(start)); + h.event(button(start, true)); + h.step(); + for p in [pos2(240.0, 220.0), pos2(50.0, 220.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.crop.drag, Some(CropDrag::Draw { .. })), "{:?}", st.crop.drag); + assert!(st.ui.views[0].center[0] < before[0], "the frame drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.crop_rect.is_some_and(|r| r[0] < 25.0), "the frame reached past what showed: {:?}", st.ui.crop_rect); + h.event(button(pos2(50.0, 220.0), false)); + h.step(); +} + +/// A scrollbar drag is the scrollbar's, even with a crop drag still recorded (left over from a +/// drag a tool switch didn't end): dragged out past the canvas edge, it doesn't auto-scroll the +/// view as a crop drag would. +#[test] +fn a_scrollbar_drag_past_the_canvas_edge_does_not_scroll_for_a_crop_drag() { + use egui::{Event, PointerButton, pos2}; + let doc = Document::with_background("crop", Size::new(200, 200), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::Crop; + a.ui.tool_options.crop_shield.classic_mode = true; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x200 at 400% in a 600x400 canvas: both scrollbars show. + a.ui.views = vec![zoomed_view(200)]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None }); + // The window is taller than the canvas, so the pointer can leave it below the bottom bar. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 500.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + assert!(h.state().ui.view.shows_scrollbars()); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // The horizontal bar's thumb (the view is centred, so is the thumb), dragged straight down + // out of the canvas: the bar keeps x, and nothing else may move the view. + let thumb = pos2(294.0, 400.0 - crate::canvas::scrollbars::THICKNESS / 2.0); + h.event(Event::PointerMoved(thumb)); + h.event(button(thumb, true)); + h.step(); + for p in [pos2(294.0, 420.0), pos2(294.0, 480.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, [100.0, 100.0], "the view stayed put"); + h.event(button(pos2(294.0, 480.0), false)); + h.step(); +} + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index d3c5488d04..ed60c90d41 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -401,6 +401,73 @@ mod tests { h.step(); } + /// ⌘Space (Ctrl+Space off the Mac) pressed during a corner drag held past the canvas edge + /// selects the temporary Zoom, which takes the pointer from the drag: the view no longer + /// scrolls for the corner the Zoom froze. + #[test] + fn a_temporary_zoom_during_a_corner_drag_stops_the_scrolling() { + use egui::{Event, Key, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(800, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 800x100 at 400% in a 600x400 canvas: document x 25..175 shows, with room to scroll right. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [800, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let grab = xf.to_screen(100.0, 10.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true, Modifiers::NONE)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + // Scrolling while the crop tool has the pointer. + let before = h.state().ui.views[0].center; + h.run_steps(2); + assert!(h.state().ui.views[0].center[0] > before[0], "the corner drag scrolls: {:?} -> {:?}", before, h.state().ui.views[0].center); + let zoom = Modifiers::COMMAND; + let zoom = if cfg!(target_os = "macos") { Modifiers { mac_cmd: true, ..zoom } } else { Modifiers { ctrl: true, ..zoom } }; + h.event(Event::ModifiersChanged(zoom)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: zoom }); + h.step(); + assert_eq!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomIn)); + assert!(h.state().pcrop.drag.is_some(), "the corner drag is still recorded"); + let before = h.state().ui.views[0].center; + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, before, "the temporary Zoom's press doesn't scroll for the corner"); + h.event(button(out, false, zoom)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: zoom }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.step(); + } + /// A corner-placing click pressed just inside the canvas edge that slips a point past it doesn't /// scroll the view (scrolling would turn it into a box); a new box dragged past the edge does. #[test] From 79fee531168dce1c02161acdc0cefb2dd133ad06 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 2 Nov 2026 19:05:38 +0100 Subject: [PATCH 24/27] Address CodeRabbit review: the hidden-pixel resample refusal suggests Delete Cropped Pixels only when it would help Delete Cropped Pixels clips pixel layers, fill caches and video frames only. When a layer mask, channel, the quick mask, the selection, type, a shape or a smart object holds the hidden pixels over the budget, the refusal now says so instead of pointing to an option that can't clear it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds.rs | 54 ++++++++++++++++------- crates/engine/src/cmd/image_cmds/tests.rs | 23 ++++++++++ 2 files changed, 62 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index df27a24ae3..76880145cf 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1,6 +1,7 @@ //! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and //! bit depth) conversions, Duplicate. +use std::collections::HashSet; use std::convert::Infallible; use photocraft_algo::resample::{Resample, crop_surface, largest_resize_rect, resize_surface_in_canvas, scaled_rect, translate_surface}; @@ -333,23 +334,39 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt /// `sx` x `sy` with `filter` (masks, channels and the selection with Bilinear): each keeps its /// pixels outside the canvas (a crop that didn't delete them, a layer moved off the canvas), and /// those grow with the scale like the rest. A bicubic shrink also stores the image between its -/// two passes, one axis still at its old size ([`largest_resize_rect`]). +/// two passes, one axis still at its old size ([`largest_resize_rect`]). The refusal suggests +/// Delete Cropped Pixels only when the surfaces over the budget are all ones it clips +/// ([`delete_cropped_pixels`]). fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, filter: Resample) -> Result<()> { let new_canvas = scaled_rect(doc.bounds(), sx, sy); - // The largest surface by bytes: its width, height and bytes per pixel (a mask has one - // channel, the layers the document's). - let mut largest = (0u32, 0u32, 1u64); + // The surfaces Delete Cropped Pixels clips; masks, channels, the selection, type, shapes and + // smart objects keep their pixels outside the crop. + let mut clipped: HashSet<*const Surface> = HashSet::new(); + for_each_layer(&mut doc.layers, &mut |l| { + clipped.extend(l.fill_cache.as_ref().map(|fc| std::ptr::from_ref(&fc.surface))); + if let Some(v) = &l.video { + clipped.extend(v.frames.iter().chain(v.original_frames.iter().flatten()).map(std::ptr::from_ref)); + } + if let LayerContent::Raster(s) = &l.content { + clipped.insert(std::ptr::from_ref(s)); + } + }); + let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); + // The largest surface by bytes, and the largest one Delete Cropped Pixels doesn't clip: its + // width, height and bytes per pixel (a mask has one channel, the layers the document's). + let (mut largest, mut largest_kept) = ((0u32, 0u32, 1u64), (0u32, 0u32, 1u64)); let mut visit = |surf: &Surface, filter: Resample| { let r = largest_resize_rect(surf.content_bounds(), sx, sy, filter); // What stays within the new canvas is already budgeted. if r.is_empty() || new_canvas.union(&r) == new_canvas { return; } - let (w, h) = (r.width(), r.height()); - let bpp = surf.format().bytes_per_pixel().max(1) as u64; - let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); - if bytes((w, h, bpp)) > bytes(largest) { - largest = (w, h, bpp); + let this = (r.width(), r.height(), surf.format().bytes_per_pixel().max(1) as u64); + if bytes(this) > bytes(largest) { + largest = this; + } + if !clipped.contains(&std::ptr::from_ref(surf)) && bytes(this) > bytes(largest_kept) { + largest_kept = this; } }; // The surfaces `resample_doc` scales, smart object caches included. @@ -360,17 +377,24 @@ fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, if let Some(sel) = &doc.selection { visit(sel, Resample::Bilinear); } - let (w, h, bpp) = largest; - let px = u64::from(w).saturating_mul(u64::from(h)); - if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { + let (kept, (w, h, bpp)) = if bytes(largest_kept) > MAX_RESAMPLE_BYTES { + (true, largest_kept) + } else if bytes(largest) > MAX_RESAMPLE_BYTES { + (false, largest) + } else { return Ok(()); - } + }; + let hint = if kept { + "choose a smaller size (layer masks, channels, the quick mask, the selection, type, shapes and smart objects keep theirs through Crop with Delete Cropped Pixels)" + } else { + "choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)" + }; let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; Err(bad( cmd, format!( - "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)", - px / 1_000_000 + "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: {hint}", + u64::from(w).saturating_mul(u64::from(h)) / 1_000_000 ), )) } diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index ef12a7bdf1..fc34b29244 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -855,12 +855,35 @@ fn image_size_budgets_the_hidden_pixels_it_resamples() { let past = s.active().unwrap().history.past_len(); let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + // The hidden pixels are a pixel layer's: Delete Cropped Pixels would clear them. + assert!(err.contains("or delete them first (Crop with Delete Cropped Pixels)"), "{err}"); assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (Size::new(10, 10), past)); // Without resampling only the resolution changes. s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(10, 10), 300.0)); } +/// Delete Cropped Pixels clips pixel layers only: an alpha channel keeps its pixels outside the +/// crop, so the refusal doesn't send the user to an option that can't clear it. +#[test] +fn hidden_resample_budget_names_what_delete_cropped_pixels_keeps() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.edit("channel", |doc, _| { + let fmt = photocraft_color::PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); + let mut ch = Surface::new(fmt); + ch.write_region(Rect::new(0, 0, 100, 100), &[1.0; 100 * 100]); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": true})).unwrap(); + let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + assert!(err.contains("channels") && !err.contains("delete them first"), "{err}"); + assert_eq!(doc(&s).size, Size::new(10, 10)); +} + #[test] fn crop_target_rejects_bad_params_without_changing_the_document() { let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); From 7d903ba8fb4e8a92f8f65ff538b4c2eac9806dbc Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 5 Nov 2026 12:26:31 +0100 Subject: [PATCH 25/27] svg: pass the cache limits main added to import_parsed in the fallback test Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 3d84285c62..0a59cc661d 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -476,7 +476,7 @@ fn the_fallback_search_reads_each_font_file_once() { // Inter has no box-drawing characters; JetBrains Mono has. let svg = "I\u{2500}I"; let outlines = |parsed: Parsed| { - let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH, None, false).unwrap().document.layers; let groups = layers.into_iter().filter_map(|l| if let LayerContent::Group(g) = l.content { Some(g) } else { None }); groups.flat_map(|g| g.children).filter_map(|l| if let LayerContent::Shape(s) = l.content { Some(s.path) } else { None }).collect::>() }; From 5b1b6cf13d88edef9ee9b26fb9f3fd8f14c03a01 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:49:40 +0100 Subject: [PATCH 26/27] Merge fix-up: check entity markup in main's bounded embedded-SVG parse too nesting_depth now returns a Result; main's parse_image_bounded_with gets the same entity-markup rejection as the other callers. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 372e933e6e..1127971e11 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -627,7 +627,7 @@ fn parse_image_bounded_with( if left.is_none() { return Err(overrun(IoError::Svg("embedded SVG XML exceeds the decoded byte budget".into()))); } - let nesting = nesting_depth(&xml, xml_left); + let nesting = nesting_depth(&xml, xml_left)?; if nesting > xml_left { return Err(IoError::Svg(format!("elements are nested more than {xml_left} levels deep"))); } From 88704d23501f92492f8d19bb8503b31da8d32495 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 02:06:41 +0100 Subject: [PATCH 27/27] Merge fix-up: the turned crop's hidden pixels after Layer 0 replaces the Background Since #10867 the non-deleting crop turns a 2000 px layer to 2001 px bounds, so the budget refusal names 200100 x 200100 px. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 66878c6d46..c7e3189254 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -843,7 +843,10 @@ fn crop_target_budgets_the_hidden_pixels_it_resamples() { p["angle"] = json!(a); } let err = s.execute("image.crop", p).unwrap_err().to_string(); - assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{angle:?}: {err}"); + // Since the crop turns the Background into Layer 0 (#10867), the turned layer's + // bounds are 2001 px a side, resampled x100 to 200100. + let want = if angle.is_some() { "200100 x 200100 px is 40040 megapixels" } else { "200000 x 200000 px is 40000 megapixels" }; + assert!(err.contains(want) && err.contains("Delete Cropped Pixels"), "{angle:?}: {err}"); assert_eq!(doc(&s).size, Size::new(2000, 2000), "{angle:?}: the document is unchanged"); assert_eq!(s.active().unwrap().history.past_len(), past, "{angle:?}: no history step"); // The turned crop rotates first: the painting symmetry turns back with the document.