From dc78b558209b1e9e83961a6036cbcd4891ff12a4 Mon Sep 17 00:00:00 2001 From: "Eng. Mahmoud Bek ElNemer" Date: Tue, 10 Nov 2026 02:41:13 +0200 Subject: [PATCH 01/16] fix(memory): detect unmounted cgroup sandboxes with empty /sys/fs/cgroup or empty mount source (#12426) Linux sandboxes such as Flatpak/bubblewrap can leave an empty `/sys/fs/cgroup` mount-point directory exposed through `sysfs` without mounting `cgroup`/`cgroup2`, and emit `tmpfs` mountinfo entries with an empty mount source (`- tmpfs rw,...`). Both caused `cgroup_limits` to fail closed as `Unreadable`, reporting 0 B system memory. Treat a readable empty `/sys/fs/cgroup` directory the same as `NotFound` when `/proc/self/mountinfo` parses cleanly with no cgroup mounts, and accept empty mount sources in `parse_mountinfo` while keeping missing, empty, truncated, cgroup-mounted, non-empty, or unreadable states strictly fail-closed. Fixes #12426 --- crates/raster/src/memory/system.rs | 154 ++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 16 deletions(-) diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index 998720b8b5..5ad4ebf5e5 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -127,12 +127,12 @@ pub(super) mod linux { } #[derive(Clone, Debug, PartialEq, Eq)] - struct Mount { - root: String, - mount_point: String, - fstype: String, - options: String, - super_options: String, + pub(super) struct Mount { + pub(super) root: String, + pub(super) mount_point: String, + pub(super) fstype: String, + pub(super) options: String, + pub(super) super_options: String, } /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory @@ -206,14 +206,14 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); - // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) - // shows the process its membership path but no interface files, so no limit is - // observable. Failing closed there reported 0 bytes free and refused every PSD on a - // machine with tens of GB. A present directory still takes the guarded path below. - // Only a confirmed NotFound counts as absent: a stat that fails for another reason - // (permissions) leaves the directory possibly present, so that case stays fail-closed. - let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); - if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or + // only an empty mount-point directory left by `sysfs` shows the process its membership path + // but no interface files, so no limit is observable. Failing closed there reported 0 bytes + // free and refused every PSD on a machine with tens of GB. Only a present non-empty or + // unreadable directory takes the guarded path below: a stat or read_dir that fails for + // another reason (permissions, non-directory) leaves a mounted hierarchy possibly present, + // so that case stays fail-closed. + if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { return CgroupLimits::NotConstrained; } @@ -273,16 +273,34 @@ pub(super) mod linux { MembershipParse::Parsed(membership) } + /// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory. + /// + /// Permission errors, non-directory paths, and unreadable directories return `false` and stay + /// fail-closed. + pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool { + match std::fs::metadata(sys_root) { + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()), + } + } + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. /// /// Malformed lines are skipped; callers fail closed when no matching mount is found. - fn parse_mountinfo(text: &str) -> Vec { + pub(super) fn parse_mountinfo(text: &str) -> Vec { let mut mounts = Vec::new(); for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let super_options = fields.get(separator + 3).copied().or_else(|| { + // `show_mountinfo` writes ` `; an empty source + // (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options. + let after = line.split_once(" - ")?.1.trim_start(); + let fstype = fields.get(separator + 1).copied()?; + after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten() + }); let (Some(root), Some(point), Some(fstype), Some(super_options)) = - (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options) else { continue; }; @@ -966,6 +984,23 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal + // non-cgroup `mountinfo` also reports `NotConstrained`. + let (proc, sys) = fixture("empty-cgroup-mountpoint"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount + // (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`. + let (proc, _) = fixture("absent-cgroup-empty-source"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. let (proc, _) = fixture("truncated-mountinfo-line"); let sys = proc.parent().unwrap().join("absent-sys"); @@ -1269,4 +1304,91 @@ mod tests { assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_parse_mountinfo_handles_empty_mount_source() { + let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n"; + let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n"; + let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n"; + let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}")); + assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped"); + let m0 = &mounts[0]; + assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs")); + assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k")); + let m1 = &mounts[1]; + assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2")); + assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate")); + } + + /// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses + /// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/ + /// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() { + use std::os::unix::fs::PermissionsExt; + + let bad_mountinfo: [(&str, Option<&str>); 6] = [ + ("empty-sys-missing-mountinfo", None), + ("empty-sys-empty-mountinfo", Some("")), + ("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")), + ("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")), + ("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")), + ("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")), + ]; + for (name, mountinfo) in bad_mountinfo { + let (proc, sys) = fixture(name); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert!(linux::sys_root_absent_or_empty(&sys), "{name}"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed. + let (proc, sys) = fixture("empty-sys-cgroup-v1-mount"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo. + let (proc, sys) = fixture("non-empty-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + write(&sys.join("memory.max"), "1073741824\n"); + assert!(!linux::sys_root_absent_or_empty(&sys)); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed. + let (proc, _) = fixture("file-sys-root"); + let file_sys = proc.parent().unwrap().join("sys-as-file"); + write(&file_sys, ""); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + for path in [&file_sys, &file_sys.join("cgroup")] { + assert!(!linux::sys_root_absent_or_empty(path)); + assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable); + } + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed. + let (proc, sys) = fixture("unreadable-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap(); + let read_blocked = std::fs::read_dir(&sys).is_err(); + let absent = linux::sys_root_absent_or_empty(&sys); + let limits = linux::cgroup_limits(&proc, &sys); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + if read_blocked { + assert!(!absent); + assert_eq!(limits, linux::CgroupLimits::Unreadable); + } + } } From 8a73ffc14371478d66ca4582278177990caff146 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 13:10:08 -0500 Subject: [PATCH 02/16] Add Anchor Point: the pen with "+" only over a segment, a black arrow elsewhere (#12729) The Add Anchor Point cursor now shows what a click would do. Over a segment of the targeted path it stays the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted, and over a locked shape layer's segments it is a new black arrow. Ctrl shows the arrow, Alt and the Precise crosshair are unchanged. The arrow is PhotoCraft's own polygon drawing (tool_cursor/arrow.rs, Shape::Arrow, tip at the hotspot, bitmap cropped so the hotspot is (1,1)); #12746 and #12709 can reuse it. A read-only anchor_tools::adds_anchor_at, built on `target`, drives both the cursor and the badge. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 10 ++ crates/ui-egui/src/canvas/tool_cursor.rs | 34 +++- .../tool_cursor/add_anchor_cursor_tests.rs | 158 ++++++++++++++++++ .../ui-egui/src/canvas/tool_cursor/arrow.rs | 60 +++++++ crates/ui-egui/src/canvas/tool_feedback.rs | 9 +- crates/ui-egui/src/caps_lock_tests.rs | 2 +- crates/ui-egui/src/tools/anchor_tools.rs | 7 + .../ui-egui/src/tools/anchor_tools/tests.rs | 8 +- 8 files changed, 281 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs create mode 100644 crates/ui-egui/src/canvas/tool_cursor/arrow.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dbe4bca522..0c00614127 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1993,6 +1993,16 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::continue_path(painter, p) } + // Add Anchor Point: the pen with "+" only over a segment a click would split, else the + // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. + Tool::AddAnchorPoint + if !precise_other_cursor(app) && { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, xf.to_doc(p))) + } => + { + crate::tool_cursor::arrow(ui.ctx(), p) + } // The pen tools: their own icon with its nib on the point, or the crosshair for // precise Other Cursors (#4639). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 42b3e622df..f3e39ceb1d 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -12,6 +12,7 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, Vec2, vec2}; use crate::canvas::ViewXform; use crate::state::Tool; +mod arrow; mod bucket; mod hand; mod pen; @@ -30,9 +31,11 @@ const MAX_SIDE: u16 = if cfg!(any(target_os = "windows", target_os = "macos")) { /// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags; /// `Zoom` is the Zoom tool's magnifier, with a minus when it zooms out. `Outline` is a brush tip -/// outline: closed rings of logical-point offsets from the hotspot. +/// outline: closed rings of logical-point offsets from the hotspot. `Arrow` is the black arrow +/// pointer, its tip on the hotspot. #[derive(Clone, Debug, PartialEq)] enum Shape { + Arrow, Circle { radius: f32, centre: bool }, Crosshair { length: f32, gap: f32 }, Hand { closed: bool }, @@ -379,6 +382,20 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon { if closed { CursorIcon::Grabbing } else { CursorIcon::Grab } } +/// The black arrow pointer, its tip on the pointer (`_at`): an OS cursor bitmap on every platform +/// that takes one, the system arrow where none can be set. +pub(crate) fn arrow(ctx: &egui::Context, _at: Pos2) -> CursorIcon { + arrow_with(ctx, native(ctx)) +} + +fn arrow_with(ctx: &egui::Context, bitmap: bool) -> CursorIcon { + if bitmap && let Some(image) = cached_image(ctx, &Shape::Arrow, native_scale(ctx)) { + ctx.set_cursor_image(Some(image)); + return CursorIcon::None; + } + CursorIcon::Default +} + /// The bitmap [`hand`] hands Windows, for tests that check the Hand's pointer on every platform. #[cfg(test)] pub(crate) fn hand_bitmap(ctx: &egui::Context, closed: bool) -> Option { @@ -563,7 +580,7 @@ fn paint(painter: &Painter, at: Pos2, shape: &Shape) -> bool { } } // Only ever a bitmap: without one the OS draws its own grab cursors. - Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} + Shape::Arrow | Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} } } true @@ -612,6 +629,7 @@ fn extent(shape: &Shape) -> Option { } if *centre { e.max(3.0) } else { e } } + Shape::Arrow => arrow::REACH, Shape::Hand { .. } => hand::HALF, Shape::Zoom { .. } => zoom::HALF, // The 24-unit SVG extends at most 22 units from (2, 22). This extra unit plus @@ -665,6 +683,10 @@ fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (lx, ly) = (dx / scale, dy / scale); silhouette(zoom::shape(lx, ly), zoom::glyph(*out, lx, ly), 0.75, scale) } + Shape::Arrow => { + let (lx, ly) = (dx / scale, dy / scale); + silhouette(arrow::shape(lx, ly), f32::MAX, 0.0, scale) + } Shape::Pipette => (0.0, 0.0), // SVG rasterization supplies these pixels. } } @@ -778,7 +800,7 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { let hotf = f32::from(hot); let mut put = |col: usize, row: usize, cov: (f32, f32)| { if let Some(px) = row.checked_mul(n).and_then(|i| i.checked_add(col)).and_then(|i| rgba.get_mut(i * 4..i * 4 + 4)) { - px.copy_from_slice(&stroke_pixel(cov, dark, light)); + px.copy_from_slice(&if matches!(shape, Shape::Arrow) { arrow::pixel(cov) } else { stroke_pixel(cov, dark, light) }); } }; if let Shape::Outline { rings, centre } = shape { @@ -830,7 +852,8 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { } } } - Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) + let image = CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }; + if matches!(shape, Shape::Arrow) { arrow::crop(image) } else { Some(image) } } /// Use the toolbar's actual SVG, with its lower-left tip (2, 22) at the hotspot. @@ -872,3 +895,6 @@ mod tests; #[cfg(test)] mod count_tests; + +#[cfg(test)] +mod add_anchor_cursor_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs new file mode 100644 index 0000000000..27b746d7c8 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs @@ -0,0 +1,158 @@ +//! #12729: Add Anchor Point's cursor says what a click would do. Over a segment of the targeted path +//! it is the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted and +//! over a locked shape layer's segments it is the black arrow. ⌘ keeps Direct Selection's arrow, +//! ⌥ and the Precise "Other Cursors" crosshair stay as they were. The tests drive the real canvas +//! (`document_area`) and compare the OS cursor bitmap it hands the platform with the arrow's and +//! the pen's. + +use egui::{CursorIcon, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::{PenVariant, Shape, rasterize}; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{select_layer, select_saved_path, setup}; +use crate::state::Tool; + +/// Path 1 is the square (50,450)-(150,550); the shape layer is the rectangle (450,100)-(650,250). +const SQUARE_TOP: [f32; 2] = [100.0, 450.0]; +const SQUARE_CORNER: [f32; 2] = [50.0, 450.0]; +const SQUARE_MIDDLE: [f32; 2] = [100.0, 500.0]; +const SHAPE_TOP: [f32; 2] = [550.0, 100.0]; + +/// The canvas at 100 % over `app`, the view centred on `view` (a document point). +fn harness(app: PhotocraftApp, view: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = view; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// Hover the document point `at` with `mods` held. +fn hover(h: &mut Harness<'static, PhotocraftApp>, at: [f32; 2], view: [f32; 2], mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + let p: Pos2 = h.state().last_canvas_rect.center() + vec2(at[0] - view[0], at[1] - view[1]); + h.hover_at(p); + h.run_steps(3); +} + +#[derive(Debug, PartialEq)] +enum Shown { + Arrow, + Pen, + Crosshair, + Other, +} + +/// Which cursor the last frame asked the platform for. +fn shown(h: &Harness<'static, PhotocraftApp>) -> Shown { + let out = &h.output().platform_output; + let scale = super::native_scale(&h.ctx); + let same = + |a: &egui::CustomCursorImage, b: Option| b.is_some_and(|b| a.size == b.size && a.hotspot == b.hotspot && a.rgba == b.rgba); + match &out.cursor_image { + Some(i) if same(i, rasterize(&Shape::Arrow, scale)) => Shown::Arrow, + Some(i) if same(i, PenVariant::from_tool(Tool::AddAnchorPoint).and_then(|v| super::pen::rasterize(v, scale))) => Shown::Pen, + Some(i) if same(i, rasterize(&super::STANDARD_CROSSHAIR, scale)) => Shown::Crosshair, + _ => Shown::Other, + } +} + +/// The square's Path 1 targeted, the pointer at `at` on it. +fn on_path_one(at: [f32; 2], mods: Modifiers) -> Shown { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, mods); + shown(&h) +} + +#[test] +fn over_a_segment_of_the_targeted_path_it_is_the_pen_with_plus() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::NONE), Shown::Pen); +} + +#[test] +fn over_an_anchor_a_handle_end_or_empty_canvas_it_is_the_black_arrow() { + assert_eq!(on_path_one(SQUARE_CORNER, Modifiers::NONE), Shown::Arrow); + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::NONE), Shown::Arrow); + // A handle end: a curved top edge's out-handle ends in empty canvas, off every segment. + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [50, 450], "in": [50, 450], "out": [50, 400]}, [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, [50.0, 400.0], SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_no_path_targeted_it_is_the_black_arrow_everywhere() { + // The active layer is the pixel layer "Red": no path is targeted, whatever lies under the pointer. + for at in [SHAPE_TOP, [450.0, 100.0], [550.0, 175.0], [300.0, 150.0]] { + let (app, _) = setup(Tool::AddAnchorPoint); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, at, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow, "{at:?}"); + } +} + +#[test] +fn over_a_segment_of_a_locked_shape_layers_mask_it_is_the_black_arrow() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Pen, "unlocked, the same point is a segment"); + h.state_mut().run("layer.lockLayers", json!({"position": true})).unwrap(); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_ctrl_held_it_is_the_black_arrow_even_over_a_segment() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::COMMAND), Shown::Arrow); +} + +#[test] +fn with_alt_held_it_stays_the_pen_over_empty_canvas() { + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::ALT), Shown::Pen); +} + +#[test] +fn the_precise_other_cursors_crosshair_keeps_working() { + for at in [SQUARE_TOP, SQUARE_MIDDLE] { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + app.run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Crosshair, "{at:?}"); + } +} + +#[test] +fn the_arrow_bitmap_is_not_empty_and_its_hotspot_is_the_tip_at_1_1() { + let image = rasterize(&Shape::Arrow, 1.0).unwrap(); + assert_eq!(image.hotspot, [1, 1]); + let alpha = |x: usize, y: usize| image.rgba[(y * usize::from(image.size[0]) + x) * 4 + 3]; + assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] == 0), "a solid black body"); + assert!(image.rgba.chunks(4).any(|p| p[3] > 0 && p[0] == 255), "a white edge"); + assert!(alpha(1, 1) > 0, "the tip pixel is covered"); + assert_eq!(super::arrow_with(&egui::Context::default(), false), CursorIcon::Default); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/arrow.rs b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs new file mode 100644 index 0000000000..b99cd20886 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs @@ -0,0 +1,60 @@ +//! The black arrow pointer: a filled black arrow with a white edge, PhotoCraft's own drawing from +//! one polygon (tip at the top left, body down to the right, a short tail), as a signed distance +//! field (negative inside) in logical pixels from the tip with y pointing down. The hotspot is the +//! tip; the bitmap is cropped to the arrow so the tip sits one pixel in from its top left corner, +//! at (1, 1) at 100 %. Windows' stock arrow is white, so every platform gets this bitmap. + +use std::sync::Arc; + +use egui::CustomCursorImage; + +use super::hand::capsule; + +/// How far the polygon reaches from the tip, outline excluded. +pub(super) const REACH: f32 = 20.0; + +/// The arrow's corners, clockwise from the tip. +const OUTLINE: [[f32; 2]; 7] = [[0.0, 0.0], [11.5, 11.8], [6.7, 11.8], [9.2, 17.4], [6.6, 18.6], [4.0, 12.8], [0.0, 16.5]]; + +/// The arrow's silhouette: negative inside it. +pub(super) fn shape(x: f32, y: f32) -> f32 { + let mut distance = f32::MAX; + let mut inside = false; + for (&a, &b) in OUTLINE.iter().zip(OUTLINE.iter().cycle().skip(1)) { + distance = distance.min(capsule(x, y, a, b, 0.0)); + // Even-odd rule: a ray towards +x crossing this edge flips the answer. + if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + if inside { -distance } else { distance } +} + +/// One bitmap pixel in straight RGBA: black `fill` over a white edge, `outline` being the coverage +/// of the whole arrow (edge included), each 0 to 1. No coverage is `[0; 4]`. +pub(super) fn pixel((fill, outline): (f32, f32)) -> [u8; 4] { + let edge = outline * (1.0 - fill); + let alpha = fill + edge; + let white = if alpha > 0.0 { (255.0 * edge / alpha).round() as u8 } else { 0 }; + [white, white, white, (255.0 * alpha).round() as u8] +} + +/// Crop `image` (the arrow centred on its hotspot) to the pixels it covers, the hotspot moving +/// with them. `None` when nothing is covered. +pub(super) fn crop(image: CustomCursorImage) -> Option { + let [w, h] = image.size.map(usize::from); + let covered = |col: usize, row: usize| image.rgba.get((row * w + col) * 4 + 3).is_some_and(|&a| a > 0); + let cols: Vec = (0..w).filter(|&c| (0..h).any(|r| covered(c, r))).collect(); + let rows: Vec = (0..h).filter(|&r| (0..w).any(|c| covered(c, r))).collect(); + let (&c0, &c1) = (cols.first()?, cols.last()?); + let (&r0, &r1) = (rows.first()?, rows.last()?); + let mut rgba = Vec::with_capacity((c1 - c0 + 1) * (r1 - r0 + 1) * 4); + for row in r0..=r1 { + rgba.extend_from_slice(image.rgba.get((row * w + c0) * 4..(row * w + c1 + 1) * 4)?); + } + Some(CustomCursorImage { + rgba: Arc::from(rgba), + size: [u16::try_from(c1 - c0 + 1).ok()?, u16::try_from(r1 - r0 + 1).ok()?], + hotspot: [image.hotspot[0].checked_sub(u16::try_from(c0).ok()?)?, image.hotspot[1].checked_sub(u16::try_from(r0).ok()?)?], + }) +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 88aec042e5..21608f1ead 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -109,7 +109,14 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option Option<(PathRef, Path } } +/// Whether a click at `p` with Add Anchor Point (`tool`) would add an anchor: the pointer is over +/// a segment of the targeted path that the tool may edit. Read-only; the cursor and its badge +/// (#12729) ask it, so they show the pen with "+" only where a click does something. +pub(crate) fn adds_anchor_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> bool { + tool == Tool::AddAnchorPoint && target(app, tool, p).is_some() +} + /// The Pen's Auto Add/Delete (#4144): what a Pen click at `p` does to the active path instead of /// starting a new one, as the anchor tool that does it (Add Anchor Point on a segment, Delete /// Anchor Point on an anchor), the path and the hit. While a path is being drawn it edits that diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index d04b5aa1a2..1303c65046 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -144,7 +144,13 @@ fn shape_layer_paths_are_edited_and_the_added_anchor_replaces_the_selection() { #[test] fn the_cursor_shows_plus_or_minus() { use crate::tool_feedback::{Badge, badge}; - let app = app(Tool::AddAnchorPoint); + let mut app = app(Tool::AddAnchorPoint); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "no path targeted, no segment under the pointer (#12729)"); + with_path(&mut app); + app.ui.selected_path = Some("work".into()); + app.hover_doc = Some([80.0, 80.0]); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "off the path's segments"); + app.hover_doc = Some([80.0, 120.0]); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add)); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract)); assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract)); From f25e2ce9c63071241420b4d79dbb8d5dddf865aa Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:32:42 +0000 Subject: [PATCH 03/16] Keep Create Rectangle closed inside the active live rectangle --- crates/ui-egui/src/canvas/gesture.rs | 10 +- .../canvas/rectangle_click_in_shape_tests.rs | 113 ++++++++++++++++++ crates/ui-egui/src/dialogs/shape_dialog.rs | 33 ++++- 3 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 1b82804e3d..c30bcf1694 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -6,6 +6,10 @@ use super::strokes::{ use super::textures::shown_as_document; use super::{PhotocraftApp, Tool, json}; +#[cfg(test)] +#[path = "rectangle_click_in_shape_tests.rs"] +mod rectangle_click_in_shape_tests; + pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { finish(app, d, None); } @@ -110,8 +114,10 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { // mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws, // and the click's few pixels of travel would add a speck of a subpath to the work path. t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {} + && crate::shape_dialog::is_tool_click(t, &app.ui.tool_options, d.start, &d.points, app.point_zoom()) + && (crate::vector_ui::draws_path(&app.ui.tool_options) + || crate::shape_dialog::click_inside_active_rectangle(app, t, d.start) + || crate::shape_dialog::open(app, t, d.start).is_some()) => {} t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs new file mode 100644 index 0000000000..05063f0633 --- /dev/null +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -0,0 +1,113 @@ +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.ui.tool = Tool::Rectangle; + app.sync_views(); + app +} + +fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radius, "fill": "#ff0000"})).unwrap(); +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, mods); +} + +fn state(app: &PhotocraftApp) -> (usize, usize) { + let active = app.session.active().unwrap(); + (active.doc.layer_count(), active.history.past_len()) +} + +fn assert_create_rectangle(app: &PhotocraftApp) { + let [dialog] = app.ui.dialogs.as_slice() else { panic!("expected one Create Rectangle dialog") }; + assert_eq!(dialog.fields["__label"], "Create Rectangle"); + assert_eq!(dialog.fields["width"], 100.0); + assert_eq!(dialog.fields["height"], 100.0); + assert_eq!(dialog.fields["fromCenter"], false); +} + +#[test] +fn inside_the_active_live_rectangle_is_a_no_op() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + for end in [center, [501.0, 350.0]] { + gesture(&mut app, center, end); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + } +} + +#[test] +fn outside_the_rectangle_and_on_the_pasteboard_open_create_rectangle() { + for point in [[100.0, 500.0], [-20.0, 500.0]] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { + let point = [500.0, 350.0]; + for other_shape in [false, true] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + if other_shape { + shape(&mut app, "ellipse", 0.0); + } else { + app.run("layer.new", json!({"name": "Pixels"})).unwrap(); + } + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "roundedRect", 30.0); + let before = state(&app); + let center = [500.0, 350.0]; + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + let corner = [401.0, 301.0]; + gesture(&mut app, corner, corner); + assert_create_rectangle(&app); + app.ui.dialogs.clear(); + + app.ui.tool_options.shape_mode = "path".into(); + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.ui.tool_options.shape_mode = "pixels".into(); + gesture(&mut app, center, center); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); +} + +#[test] +fn more_than_one_pixel_of_travel_still_draws_a_shape() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let (layers, history) = state(&app); + gesture(&mut app, [500.0, 350.0], [502.0, 351.0]); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), (layers + 1, history + 1)); +} diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index fc9a3e9ea6..1fae471750 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -47,10 +47,41 @@ fn valid(key: &str, v: &Value) -> bool { /// True for a press and release that never left `start` by more than a few screen pixels. pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { - let slop = 3.0 / f64::from(zoom.max(0.01)); + within_click_slop(start, points, zoom, 3.0) +} + +pub(crate) fn is_tool_click(tool: Tool, options: &crate::state::ToolOptions, start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { + if tool == Tool::Rectangle && options.shape_mode == "shape" { within_click_slop(start, points, zoom, 1.0) } else { is_click(start, points, zoom) } +} + +fn within_click_slop(start: [f64; 2], points: &[[f64; 3]], zoom: f32, pixels: f64) -> bool { + let slop = pixels / f64::from(zoom.max(0.01)); points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop) } +/// A Shape-mode Rectangle click inside the active live rectangle leaves the shape alone (#13340). +pub(crate) fn click_inside_active_rectangle(app: &PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { + use photocraft_doc::{LayerContent, LiveShape}; + + if tool != Tool::Rectangle || app.ui.tool_options.shape_mode != "shape" { + return false; + } + let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) else { return false }; + let LayerContent::Shape(shape) = &layer.content else { return false }; + let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = shape.live else { return false }; + let (left, top) = (x.min(x + w), y.min(y + h)); + let (right, bottom) = (x.max(x + w), y.max(y + h)); + let [px, py] = at; + if !((left..=right).contains(&px) && (top..=bottom).contains(&py)) { + return false; + } + let (l, r, t, b) = (px - left, right - px, py - top, bottom - py); + [(l, t), (r, t), (r, b), (l, b)] + .into_iter() + .zip(photocraft_vector::shapes::clamp_radii(w.abs(), h.abs(), radii)) + .all(|((dx, dy), radius)| dx >= radius || dy >= radius || (radius - dx).hypot(radius - dy) <= radius) +} + /// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without /// one (Line, Custom Shape). pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option { From d7b001a147446dd04507093287f7bc33d23668b9 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:34:36 +0000 Subject: [PATCH 04/16] Use the registered pixel-layer command in the regression test --- crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index 05063f0633..e772826f3d 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -69,7 +69,7 @@ fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { if other_shape { shape(&mut app, "ellipse", 0.0); } else { - app.run("layer.new", json!({"name": "Pixels"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap(); } let before = state(&app); gesture(&mut app, point, point); From 3c971cfc371bfc5f0d7396fc011bffb8f4e9f3e0 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:41:24 +0000 Subject: [PATCH 05/16] Separate rectangle geometry checks from snapping and tool overlays --- .../canvas/rectangle_click_in_shape_tests.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index e772826f3d..faf81a9374 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -7,12 +7,13 @@ fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); app.ui.tool = Tool::Rectangle; + app.ui.extras.snap = false; app.sync_views(); app } fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { - app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radius, "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": [radius; 4], "fill": "#ff0000"})).unwrap(); } fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { @@ -79,7 +80,7 @@ fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { } #[test] -fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { +fn rounded_corners_use_the_outline() { let mut app = app(); shape(&mut app, "roundedRect", 30.0); let before = state(&app); @@ -88,16 +89,22 @@ fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { assert!(app.ui.dialogs.is_empty()); assert_eq!(state(&app), before); let corner = [401.0, 301.0]; - gesture(&mut app, corner, corner); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, corner, vec![[corner[0], corner[1], 1.0]], egui::Modifiers::NONE, false)); assert_create_rectangle(&app); - app.ui.dialogs.clear(); +} +#[test] +fn other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; app.ui.tool_options.shape_mode = "path".into(); gesture(&mut app, center, center); assert!(app.ui.dialogs.is_empty()); assert!(app.session.active().unwrap().doc.work_path.is_none()); app.ui.tool_options.shape_mode = "pixels".into(); - gesture(&mut app, center, center); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, center, vec![[center[0], center[1], 1.0]], egui::Modifiers::NONE, false)); assert_create_rectangle(&app); assert_eq!(state(&app), before); } From eb46134f80e64f50ec29dc81f96074542d4a6dbd Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:46:10 +0000 Subject: [PATCH 06/16] Serialize the rounded rectangle test radii as a Rust array --- crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index faf81a9374..ec3c180e7f 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -13,7 +13,8 @@ fn app() -> PhotocraftApp { } fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { - app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": [radius; 4], "fill": "#ff0000"})).unwrap(); + let radii = [radius; 4]; + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radii, "fill": "#ff0000"})).unwrap(); } fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { From 7a0c3bfca6c0a66d86c30ec136282e3e3b5b967b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 17:47:28 -0500 Subject: [PATCH 07/16] Add Anchor Point cursor: the pen tools' cursor choice in its own function (#12729) draw_default_tool_cursor went over clippy's cognitive complexity limit (31/30) once main's latest arms met this PR's guarded Add Anchor Point arm. The pen tools' arm now calls pen_tool_cursor, which holds the Precise crosshair, the Add Anchor Point arrow and the pen icon; no behaviour change. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4120297802..a44f7dfc46 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1863,6 +1863,22 @@ fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: egui::CursorIcon::None } +/// A pen tool's cursor at screen point `p` (document point `doc`): the crosshair for precise Other +/// Cursors (#4639), the black arrow for Add Anchor Point unless a click would split a segment +/// (#12729; ⌘ is Direct Selection's arrow, ⌥ keeps the pen), else the tool's own pen icon. +fn pen_tool_cursor(app: &PhotocraftApp, ui: &egui::Ui, tool: Tool, doc: [f64; 2], p: Pos2) -> egui::CursorIcon { + if precise_other_cursor(app) { + return egui::CursorIcon::Crosshair; + } + if tool == Tool::AddAnchorPoint { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, doc)) { + return crate::tool_cursor::arrow(ui.ctx(), p); + } + } + pen_cursor(ui.ctx(), tool, p) +} + fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { let painter = input.painter; let xf = input.xf; @@ -1998,18 +2014,10 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } // Add Anchor Point: the pen with "+" only over a segment a click would split, else the // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. - Tool::AddAnchorPoint - if !precise_other_cursor(app) && { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, xf.to_doc(p))) - } => - { - crate::tool_cursor::arrow(ui.ctx(), p) - } // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). + // precise Other Cursors (#4639); Add Anchor Point the black arrow off a segment (#12729). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + pen_tool_cursor(app, ui, tool, xf.to_doc(p), p) } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, From 490009277dc6da6db3e49c4979ebc1c17affc4dc Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:49:14 +0000 Subject: [PATCH 08/16] Keep dialog regressions within the new Rectangle click rules --- crates/ui-egui/src/dialogs/shape_dialog/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs index 1ca5de28f7..03f65d743d 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs @@ -174,7 +174,7 @@ fn a_click_with_jitter_opens_the_dialog_on_hidpi() { let i = app.session.active_index().unwrap(); app.ui.views[i].zoom = 1.0; let before = layers(&app); - press(&mut app, Tool::Rectangle, [20.0, 30.0], [24.0, 30.0]); + press(&mut app, Tool::Rectangle, [20.0, 30.0], [22.0, 30.0]); only_dialog(&app); assert_eq!(layers(&app), before, "a jittery click draws nothing"); } @@ -347,7 +347,7 @@ fn right_click_picks_the_unit_of_that_field_only_and_it_is_not_remembered() { set(&mut app, id, json!({"widthUnit": "mm", "width": 50})); crate::dialogs::confirm(&mut app, id).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - press(&mut app, Tool::Rectangle, [40.0, 40.0], [40.0, 40.0]); + press(&mut app, Tool::Rectangle, [140.0, 140.0], [140.0, 140.0]); let id = only_dialog(&app); let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!((f.get("widthUnit"), f["width"].as_f64()), (None, Some(50.0)), "the size is remembered, the unit isn't"); From 3b118ec008308c258fecd6697cbff045adb27f54 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Thu, 12 Nov 2026 04:14:22 +0000 Subject: [PATCH 09/16] Path Selection: a drag on a shape moves it, not the targeted saved path (#13270) --- crates/ui-egui/src/canvas/tool_input.rs | 1 + crates/ui-egui/src/tools.rs | 2 + crates/ui-egui/src/tools/path_components.rs | 11 +++ ...h_selection_shape_over_saved_path_tests.rs | 70 +++++++++++++++++++ 4 files changed, 84 insertions(+) create mode 100644 crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index b3b4c42544..5c453dae14 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -602,6 +602,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: if let Some(st) = app.session.active() && let Some(id) = crate::vector_ui::pick_shape_at(&st.doc, [x, y], tol) { + crate::path_components::untarget_saved_path_off(app, [x, y], tol); let _ = app.run("layer.select", json!({"layer": id.0})); } // The component pressed is selected, so the drag moves it (and the others selected). diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 684c8dbc32..4bc64c59ae 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -73,6 +73,8 @@ mod gradient_options_bar_mode_tests; mod gradient_refusal_messages_tests; #[cfg(test)] mod line_tool_defaults_tests; +#[cfg(test)] +mod path_selection_shape_over_saved_path_tests; #[cfg(test)] mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 74f866c624..a82ccededd 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -32,6 +32,17 @@ fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { active_paths(app).into_iter().next() } +/// A Path Selection press on a shape layer, off every component of the targeted saved path: +/// the saved path is no longer the target, so the press and drag act on the shape (#13270). +/// A press on one of the saved path's components keeps it targeted. +pub(crate) fn untarget_saved_path_off(app: &mut PhotocraftApp, at: [f64; 2], tol: f64) { + if let Some((PathRef::Saved(_), path)) = target(app) + && component_at(&path, at, tol).is_none() + { + app.ui.selected_path = None; + } +} + /// The selected components: their path and the first subpath of each, in order. `None` with /// nothing selected, a selection on a path that is not an active one any more, or a tool other /// than Path Selection (the only one that shows it, so the only one that acts on it). diff --git a/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs new file mode 100644 index 0000000000..4590657480 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs @@ -0,0 +1,70 @@ +//! #13270: with a saved path targeted in the Paths panel, a Path Selection drag on a shape layer +//! targets and moves the shape, as in the reference application; the saved path keeps its points. +//! A drag on a component of the saved path still moves that component. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; + +/// A rectangle shape at 500,100–700,200, a pixel layer "Red" above it, active, and the saved +/// path "Path 1" (a square 100,300–200,400) selected in the Paths panel, with Path Selection. +fn setup() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 200, 100], "fill": "#2050c0"})).unwrap(); + let shape = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [200, 300], [200, 400], [100, 400]]}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + (app, shape) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn shape_bounds(app: &PhotocraftApp, id: LayerId) -> Option<(f64, f64, f64, f64)> { + let doc = &app.session.active().unwrap().doc; + doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => sh.path.control_bounds(), + _ => None, + }) +} + +#[test] +fn a_drag_on_a_shape_moves_the_shape_not_the_targeted_saved_path() { + let (mut app, shape) = setup(); + let (path_before, shape_before) = (saved(&app), shape_bounds(&app, shape).unwrap()); + drag(&mut app, [600.0, 150.0], [650.0, 200.0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(shape), "the shape is the active layer"); + assert_eq!(saved(&app), path_before, "the saved path keeps its points"); + let (x0, y0, x1, y1) = shape_before; + assert_eq!(shape_bounds(&app, shape), Some((x0 + 50.0, y0 + 50.0, x1 + 50.0, y1 + 50.0)), "the shape moved by the drag"); + assert_eq!(app.ui.selected_path, None, "the saved path is no longer the target"); +} + +#[test] +fn a_drag_on_a_component_of_the_saved_path_still_moves_it() { + let (mut app, shape) = setup(); + let shape_before = shape_bounds(&app, shape); + drag(&mut app, [150.0, 350.0], [180.0, 370.0]); + assert_eq!(saved(&app).control_bounds(), Some((130.0, 320.0, 230.0, 420.0)), "the saved path moved"); + assert_eq!(shape_bounds(&app, shape), shape_before, "the shape stays"); + assert_eq!(app.ui.selected_path.as_deref(), Some(SAVED)); +} From e54921b2972a20e6254194402b11ab2afa95a5f4 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 12 Nov 2026 07:53:06 +0000 Subject: [PATCH 10/16] Retry CI after the Type options bar test flake From ec55bed7b0e553cf2a18131ba967dcc50f753f1b Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:55:36 +0100 Subject: [PATCH 11/16] algo, engine, ui: Perspective Crop commits a quad mirrored on one axis (#12489) `convex_quad` accepts a quad only when it is wound clockwise on screen, so a Perspective Crop box flipped on one axis (an Alt+corner drag past the opposite corner along x only), which is convex but wound counter-clockwise, was drawn red and refused by `image.perspectiveCrop` and `quad_to_rect`. The reference application commits it mirrored, each corner mapped as it lies. Add `convex_quad_any_winding` (the same angle and area limits, either winding; self-crossing, degenerate and non-finite quads stay invalid) and use it for Perspective Crop only: the `corners` check and its error text, `quad_to_rect`, and the overlay's validity check. The homography already maps each corner onto its own rectangle corner, so the crop comes out mirrored. Perspective Warp steps keep the clockwise-only `convex_quad`; clicked corners are still sorted clockwise and commit upright; a box turned 180 degrees still commits upside down. Tests: algo (a counter-clockwise quad maps corner to corner; bow ties, collinear, sliver and non-finite quads stay refused), and the new perspective_crop_mirrored_tests.rs (the measured Alt-drag case commits mirrored and is drawn valid, the command takes counter-clockwise corners, clicks commit upright, 180 degrees upside down, invalid quads stay red). The mirrored cases fail without the fix. Fixes #12489 --- crates/algo/src/transform.rs | 14 +- crates/algo/src/transform/tests.rs | 28 +++- .../engine/src/cmd/perspective_crop_cmds.rs | 11 +- .../tools/perspective_crop_mirrored_tests.rs | 138 ++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 13 +- 5 files changed, 191 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 5a46b472e9..5dabbd2a0c 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -210,6 +210,15 @@ pub fn convex_quad(q: &[[f64; 2]; 4]) -> bool { area2.is_finite() && area2 >= 2.0 } +/// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad in either winding: a [`convex_quad`], +/// or one wound counter-clockwise on screen (a box flipped on one axis, which crops mirrored, +/// #12489) with the same corner angle and area limits? Self-crossing, degenerate and non-finite +/// quads are not. The Perspective Warp steps keep the clockwise-only [`convex_quad`]. +pub fn convex_quad_any_winding(q: &[[f64; 2]; 4]) -> bool { + let [tl, tr, br, bl] = *q; + convex_quad(q) || convex_quad(&[tl, bl, br, tr]) +} + /// The output size a Perspective Crop of `q` (TL, TR, BR, BL) takes when none is given: the mean /// length of the top and bottom edges by the mean length of the left and right edges. pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { @@ -287,9 +296,10 @@ fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a -/// [`convex_quad`] or the size isn't positive. +/// [`convex_quad_any_winding`] or the size isn't positive. A quad wound counter-clockwise maps +/// mirrored, each corner onto its own rectangle corner. pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { - if !(convex_quad(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + if !(convex_quad_any_winding(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse() diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs index b70bc74c3d..af6e81b615 100644 --- a/crates/algo/src/transform/tests.rs +++ b/crates/algo/src/transform/tests.rs @@ -61,7 +61,7 @@ fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { } /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, -/// self-crossing, counter-clockwise and non-finite quads have none. +/// self-crossing and non-finite quads have none. #[test] fn quad_to_rect_maps_corners_and_refuses_bad_quads() { let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; @@ -75,7 +75,7 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { for bad in [ [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [50.0, 50.0], [0.0, 50.0], [50.0, 0.0]], [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], [[0.0, 0.0]; 4], ] { @@ -84,6 +84,30 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); } +/// #12489: a quad wound counter-clockwise (a box flipped on one axis) maps mirrored, each corner +/// onto its own rectangle corner. Perspective Warp's clockwise-only check still refuses it. +#[test] +fn quad_to_rect_maps_a_counter_clockwise_quad_mirrored() { + let q = [[140.0, 25.0], [30.0, 12.0], [14.0, 95.0], [128.0, 110.0]]; + assert!(!convex_quad(&q) && convex_quad_any_winding(&q)); + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + // Self-crossing in either winding, three corners on a line, and a sliver stay refused. + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [0.0, 50.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[50.0, 0.0], [25.0, 0.0], [0.0, 0.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [0.0, 0.01], [50.0, 0.01]], + [[50.0, 0.0], [0.0, f64::INFINITY], [0.0, 50.0], [50.0, 50.0]], + ] { + assert!(!convex_quad_any_winding(&bad), "{bad:?}"); + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } +} + fn rgba() -> Surface { Surface::new(PixelFormat::RGBA8) } diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index d5d4db24f5..161fa35e70 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -12,7 +12,7 @@ //! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine //! map closest to the homography (exact when the quad is a parallelogram). -use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; +use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -39,7 +39,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad clockwise on screen. +/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad. Wound counter-clockwise +/// on screen (a box flipped on one axis) it crops mirrored, each corner as it lies (#12489). fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { let shape = || bad("`corners` must be four [x, y] points: top-left, top-right, bottom-right, bottom-left"); let list = p.get("corners").and_then(Value::as_array).filter(|a| a.len() == 4).ok_or_else(shape)?; @@ -52,9 +53,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { } *slot = [x, y]; } - if !convex_quad(&q) { + if !convex_quad_any_winding(&q) { return Err(bad( - "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (clockwise on screen)", + "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (counter-clockwise on screen crops mirrored)", )); } Ok(q) @@ -387,7 +388,7 @@ mod tests { json!({"corners": [[0, 0], [10, 0], [10, 10]]}), json!({"corners": [[0, 0], [50, 0], [100, 0], [0, 50]]}), json!({"corners": [[0, 0], [50, 50], [50, 0], [0, 50]]}), - json!({"corners": [[0, 0], [0, 50], [50, 50], [50, 0]]}), + json!({"corners": [[50, 0], [0, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], [0.5, 0], [0.5, 0.5], [0, 0.5]]}), json!({"corners": [[0, 0], [1e300, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], ["a", 0], [50, 50], [0, 50]]}), diff --git a/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs new file mode 100644 index 0000000000..e01e64387c --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs @@ -0,0 +1,138 @@ +//! #12489: a Perspective Crop box flipped on one axis (⌥ dragging a corner past the opposite one +//! along x only) is wound counter-clockwise. It is drawn valid and commits mirrored, each corner +//! mapped as it lies, as in the reference application; `image.perspectiveCrop` takes the same +//! corners. Clicked corners still commit upright, a box turned 180° still commits upside down, and +//! self-crossing and degenerate quads stay invalid. + +use std::sync::Arc; + +use egui::{Modifiers, Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The measured test document: 800 x 500, red (top left), green (top right), blue (bottom left) +/// and yellow (bottom right) quadrants with a black square in the middle; the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let surf = Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0].surface_mut().unwrap(); + for (x, y, c) in [(0, 0, RED), (400, 0, GREEN), (0, 250, BLUE), (400, 250, YELLOW)] { + surf.fill_rect(photocraft_geom::Rect::from_xywh(x, y, 400, 250), &c); + } + surf.fill_rect(photocraft_geom::Rect::from_xywh(395, 245, 10, 10), &[0.0, 0.0, 0.0, 1.0]); + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2]) { + drag(app, p, p, Modifiers::NONE); +} + +/// The overlay `draw_overlay` paints: (shield polygons, whether the frame is red). +fn overlay(app: &PhotocraftApp) -> (usize, bool) { + let ctx = egui::Context::default(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)), zoom: 1.0, center: [400.0, 250.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let shield = o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count(); + let red = Color32::from_rgb(0xe5, 0x3e, 0x3e); + let frame_red = o.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == egui::epaint::ColorMode::Solid(red))); + (shield, frame_red) +} + +/// The committed canvas's size and the colours at its four corners (TL, TR, BL, BR). +fn corners(app: &PhotocraftApp) -> ((u32, u32), [[f32; 4]; 4]) { + let doc = &app.session.active().unwrap().doc; + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + let surf = doc.layers[0].surface().unwrap(); + ((doc.size.width, doc.size.height), [surf.rgba(3, 3), surf.rgba(w - 4, 3), surf.rgba(3, h - 4), surf.rgba(w - 4, h - 4)]) +} + +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_one_axis_commits_mirrored() { + let mut app = app(); + // A fresh 100 x 100 box, its bottom right corner ⌥ dragged past the fixed top left one on x only. + drag(&mut app, [450.0, 220.0], [550.0, 320.0], Modifiers::NONE); + drag(&mut app, [550.0, 320.0], [350.0, 300.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 220.0], [350.0, 220.0], [350.0, 300.0], [450.0, 300.0]]), "flipped left to right"); + let (shield, red) = overlay(&app); + assert!(shield > 0 && !red, "drawn as a valid quad: accent frame and shield, not red"); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let (size, [tl, tr, bl, br]) = corners(&app); + assert_eq!(size, (100, 80)); + assert_eq!([tl, tr, bl, br], [GREEN, RED, YELLOW, BLUE], "mirrored left to right, top stays on top"); +} + +#[test] +fn the_command_takes_counter_clockwise_corners_and_mirrors() { + let mut app = app(); + let r = app.run("image.perspectiveCrop", json!({"corners": [[450, 220], [350, 220], [350, 300], [450, 300]]})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(100), Some(80))); + assert_eq!(corners(&app).1, [GREEN, RED, YELLOW, BLUE]); + // Mirrored top to bottom the other way round. + let mut app = self::app(); + app.run("image.perspectiveCrop", json!({"corners": [[350, 300], [450, 300], [450, 220], [350, 220]]})).unwrap(); + assert_eq!(corners(&app).1, [BLUE, YELLOW, RED, GREEN]); +} + +#[test] +fn clicked_corners_commit_upright_in_any_order() { + let mut app = app(); + // Counter-clockwise clicks from the top left. + for p in [[350.0, 220.0], [350.0, 300.0], [450.0, 300.0], [450.0, 220.0]] { + click(&mut app, p); + } + assert_eq!(app.ui.perspective_crop, Some([[350.0, 220.0], [450.0, 220.0], [450.0, 300.0], [350.0, 300.0]]), "sorted clockwise"); + commit(&mut app); + assert_eq!(corners(&app), ((100, 80), [RED, GREEN, BLUE, YELLOW])); +} + +#[test] +fn a_box_turned_180_degrees_commits_upside_down() { + let mut app = app(); + drag(&mut app, [450.0, 300.0], [550.0, 400.0], Modifiers::NONE); + drag(&mut app, [550.0, 400.0], [350.0, 200.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 300.0], [350.0, 300.0], [350.0, 200.0], [450.0, 200.0]])); + commit(&mut app); + assert_eq!(corners(&app), ((100, 100), [YELLOW, BLUE, GREEN, RED])); +} + +#[test] +fn self_crossing_and_degenerate_quads_stay_invalid() { + for q in [ + // Self-crossing (a bow tie), each way round. + [[350.0, 220.0], [450.0, 220.0], [350.0, 300.0], [450.0, 300.0]], + [[450.0, 220.0], [350.0, 220.0], [450.0, 300.0], [350.0, 300.0]], + // Three corners on a line, and no area. + [[350.0, 220.0], [400.0, 220.0], [450.0, 220.0], [350.0, 300.0]], + [[400.0, 250.0]; 4], + ] { + let mut app = app(); + app.ui.perspective_crop = Some(q); + let (shield, red) = overlay(&app); + assert!(shield == 0 && red, "{q:?} is drawn red without the shield"); + assert!(app.run("image.perspectiveCrop", json!({ "corners": q })).is_err(), "{q:?}"); + commit(&mut app); + assert_eq!(app.ui.perspective_crop, Some(q), "{q:?} stays for fixing"); + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + } + let mut app = app(); + assert!(app.run("image.perspectiveCrop", json!({"corners": [[350, 220], [f64::NAN, 220], [450, 300], [350, 300]]})).is_err()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index bf0d491fb0..5a47aebe50 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -4,8 +4,8 @@ //! BL in document px; clicked corners are put in that order); //! - drag a corner to move it alone, onto an edge of a skewed object (a photographed page, a //! facade); drag inside the quad to move it; -//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad -//! wound like its box, which can't be committed; +//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad, +//! which can't be committed; one flipped on one axis (wound the other way) commits mirrored; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the @@ -14,7 +14,7 @@ //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; -use photocraft_algo::transform::{Homography, convex_quad}; +use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -393,7 +393,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { - let ok = convex_quad(&q); + // A quad flipped on one axis is wound counter-clockwise and commits mirrored (#12489). + let ok = convex_quad_any_winding(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; // The image outside the quad is dimmed (#11972), following the quad while it is dragged. if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { @@ -521,6 +522,10 @@ mod perspective_crop_shield_tests; #[path = "perspective_crop_deselect_tests.rs"] mod perspective_crop_deselect_tests; +#[cfg(test)] +#[path = "perspective_crop_mirrored_tests.rs"] +mod perspective_crop_mirrored_tests; + #[cfg(test)] mod tests { use super::*; From b374e27b9dfa0c636fb053800851119873aa9f1e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:25:19 +0100 Subject: [PATCH 12/16] engine: Pencil Auto Erase probes a CMYK pick with the picked inks (#13060) In a CMYK layer the stroke renderer paints a foreground picked as CMYK as those exact inks (`StrokeRenderer::composite`, #4344), but `apply_auto_erase` built its probe from the foreground's RGB stand-in converted back to CMYK. For a rich black (or any ink mix the RGB doesn't round-trip to) the probe never matched the stroke's own pixels, so a stroke starting on them painted the foreground again instead of the background. The probe now puts the picked inks in, under the same condition the renderer uses (CMYK target, inks picked for this foreground). Commit and live stroke share `apply_auto_erase`, so both are fixed. Test: a rich-black pencil line in a CMYK document, then an Auto Erase stroke starting on it paints the background, live and committed. It fails without the fix. Fixes #13060 --- crates/engine/src/cmd/brush_cmds.rs | 17 ++++++++++--- crates/engine/src/cmd/brush_cmds/tests.rs | 29 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 0a41092679..6a3164c07a 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -341,12 +341,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS /// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the /// background colour instead (Photoshop). The match is exact (#11966): the foreground as the /// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level -/// off paints the foreground. +/// off paints the foreground. In a CMYK layer a foreground picked as CMYK is probed as the inks +/// the stroke paints (#13060), not as its RGB stand-in converted back. fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) { let Some(p0) = start else { return }; let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32); - let mut probe = Surface::new(surf.format()); - probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0])); + let format = surf.format(); + let mut px = photocraft_raster::from_rgba(&format, [fg[0], fg[1], fg[2], 1.0]); + // The renderer's condition for painting the picked inks (`StrokeRenderer::composite`), keyed + // on the foreground being probed. + if let (photocraft_color::ColorMode::Cmyk, Some((rgb, inks))) = (format.mode, brush.color_cmyk) + && rgb == [fg[0], fg[1], fg[2]] + && let Some(channels) = px.get_mut(..4) + { + channels.copy_from_slice(&inks); + } + let mut probe = Surface::new(format); + probe.write_pixel(0, 0, &px); let stored = probe.rgba(0, 0); // Far below one 8-bit level: only the float noise of the conversion. if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) { diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7a424e2f03..5d67b14b46 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -212,6 +212,35 @@ fn pencil_is_aliased_and_auto_erases() { assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]); } +/// #13060: in a CMYK document a foreground picked as CMYK inks (a rich black, which its sRGB +/// stand-in does not convert back to) is painted as those inks, and Pencil Auto Erase recognises +/// them: a stroke that starts on it paints the background colour, live and committed. +#[test] +fn pencil_auto_erase_probes_a_cmyk_pick_with_the_picked_inks() { + let rich_black = [0.6f32, 0.4, 0.4, 1.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(rich_black).map(|c| c.clamp(0.0, 1.0)); + let mut s = session(40, 20); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": rich_black, "background": "#ffffff"})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 10], [35, 10]], "size": 5})).unwrap(); + let pixel = |s: &Session, x: i32, y: i32| -> Vec { surface(s).read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() }; + let painted = pixel(&s, 20, 10); + assert!(painted.iter().zip(rich_black).all(|(a, b)| (a - b).abs() < 0.01), "the stroke paints the picked inks: {painted:?}"); + let white = [1.0f32, 1.0, 1.0, 1.0]; + + // Live: the stroke that starts on the rich black paints the background. + let p = json!({"points": [[12, 10]], "autoErase": true, "smoothing": 0.0}); + let mut live = LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + live.push(&[StrokePoint::new(12.0, 18.0, 1.0)]).unwrap(); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 17); + assert!(shown.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "live: {shown:?}"); + + // Committed: the same. + s.execute("paint.pencil", json!({"points": [[20, 10], [20, 18]], "size": 3, "autoErase": true})).unwrap(); + let erased = rgba(&s, 20, 17); + assert!(erased.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "committed: {erased:?}"); +} + #[test] fn mixer_brush_reservoir_and_cleaning() { let mut s = session(200, 30); From 8943be1f4fae5b689e68c1826aff56f6ec179e3f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:12:26 +0100 Subject: [PATCH 13/16] engine, ui: Burn, Sponge, Blur and Smudge refuse Indexed Color and Bitmap (#12673, #13033, #12656, #12967) The colour-mode check `mode_refusal` in retouch_cmds/dab.rs only knew paint.dodge and paint.sharpen, so the other dab tools painted into Indexed Color and Bitmap documents, where the reference application refuses with an alert. Add their arms (both `dab_cmd` and the live stroke `LiveDab::begin` call it, so nothing is previewed either), and name the tools in the canvas `mode_tool_name` so a press opens the same alert with OK. Multichannel and Duotone were not measured and keep today's behaviour. Tests: one engine file per tool (refusal text from the command and the live stroke, pixels and History unchanged; RGB/Gray/CMYK/Lab at 8/16/32 bits, Multichannel and Duotone keep working) and a canvas alert test for all four. The engine refusal tests fail without the fix. Fixes #12673 Fixes #13033 Fixes #12656 Fixes #12967 --- .../blur_refuses_indexed_tests.rs | 57 +++++++++++++++++++ .../burn_refuses_indexed_tests.rs | 48 ++++++++++++++++ crates/engine/src/cmd/retouch_cmds/dab.rs | 27 ++++++++- .../smudge_refuses_indexed_tests.rs | 57 +++++++++++++++++++ .../sponge_refuses_indexed_tests.rs | 49 ++++++++++++++++ .../src/retouch_mode_refusal_alert_tests.rs | 41 +++++++++++++ crates/ui-egui/src/tools/brush_refusal.rs | 14 ++++- 7 files changed, 287 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs create mode 100644 crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs new file mode 100644 index 0000000000..16e430f650 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12656: the Blur tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the blur tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the blur tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.blur", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.blur", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.blur", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.blur", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs new file mode 100644 index 0000000000..d278633555 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs @@ -0,0 +1,48 @@ +//! #12673: the Burn tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the burn tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the burn tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "range": "midtones", "exposure": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.burn", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.burn", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.burn", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.burn", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 082fa9a28e..2a89e5527e 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -280,13 +280,18 @@ impl DabTool { } } -/// The reference application refuses a Dodge or Sharpen stroke in Indexed Color and Bitmap -/// documents, with its alert's words (#12686, #12953); other modes (Multichannel and Duotone were -/// not measured) paint as before. The live stroke checks this too, so it previews nothing there. +/// The reference application refuses a Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke in +/// Indexed Color and Bitmap documents, with its alert's words (#12686, #12673, #13033, #12656, +/// #12953, #12967); other modes (Multichannel and Duotone were not measured) paint as before. The +/// live stroke checks this too, so it previews nothing there. fn mode_refusal(s: &Session, cmd: &str) -> Result<()> { let tool = match cmd { "paint.dodge" => "dodge tool", + "paint.burn" => "burn tool", + "paint.sponge" => "sponge tool", + "paint.blur" => "blur tool", "paint.sharpen" => "sharpen tool", + "paint.smudge" => "smudge tool", _ => return Ok(()), }; let why = match s.active().map(|st| st.doc.mode) { @@ -717,6 +722,22 @@ mod dodge_refuses_indexed_tests; #[path = "sharpen_refuses_indexed_tests.rs"] mod sharpen_refuses_indexed_tests; +#[cfg(test)] +#[path = "burn_refuses_indexed_tests.rs"] +mod burn_refuses_indexed_tests; + +#[cfg(test)] +#[path = "sponge_refuses_indexed_tests.rs"] +mod sponge_refuses_indexed_tests; + +#[cfg(test)] +#[path = "blur_refuses_indexed_tests.rs"] +mod blur_refuses_indexed_tests; + +#[cfg(test)] +#[path = "smudge_refuses_indexed_tests.rs"] +mod smudge_refuses_indexed_tests; + #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..4a621b27c3 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12967: the Smudge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the smudge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the smudge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.smudge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.smudge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.smudge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.smudge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..61dd03901c --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs @@ -0,0 +1,49 @@ +//! #13033: the Sponge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the sponge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the sponge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "mode": "desaturate"}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.sponge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.sponge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +/// +/// The grey document has no saturation to take away, so this checks that the stroke runs and +/// records its History step, not that pixels change. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.sponge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + s.execute("paint.sponge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs new file mode 100644 index 0000000000..eba8c7bce4 --- /dev/null +++ b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs @@ -0,0 +1,41 @@ +//! #12673, #13033, #12656, #12967: a press with the Burn, Sponge, Blur or Smudge tool in an Indexed +//! Color or Bitmap document opens the reference application's colour-mode alert with OK, once, and +//! paints nothing; in RGB the same press still paints. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; + +const TOOLS: [(Tool, &str); 4] = [(Tool::Burn, "burn tool"), (Tool::Sponge, "sponge tool"), (Tool::Blur, "blur tool"), (Tool::Smudge, "smudge tool")]; + +#[test] +fn indexed_color_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + refused(&mut app, &format!("Could not use the {name} because it does not work with Indexed Color images (convert image to RGB Color mode to edit).")); + } +} + +#[test] +fn bitmap_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + refused(&mut app, &format!("Could not use the {name} because it does not work with Bitmap images (convert image to Grayscale mode to edit).")); + } +} + +#[test] +fn rgb_documents_keep_painting() { + for (tool, _) in TOOLS { + let mut app = app(tool); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{tool:?}: no alert"); + assert_eq!(steps(&app), before + 1, "{tool:?}: the stroke was applied"); + } +} diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index bfa63bb3ab..0fa245f0b5 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -22,13 +22,17 @@ pub const REMOVE_LOCKED: &str = "Can't use the tool because the layer is locked. pub const INDEXED: &str = "Could not use the {tool} because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; -/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge -/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge -/// tool yet (#12685). +/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge, +/// Burn, Sponge, Blur, Sharpen and Smudge tools. Kept apart from [`tool_name`]: the layer alerts +/// aren't wired for all of them yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), + Tool::Burn => Some(tl!("burn tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Blur => Some(tl!("blur tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Smudge => Some(tl!("smudge tool")), _ => None, } } @@ -110,6 +114,10 @@ mod sharpen_refusal_alert_tests; #[path = "../sponge_refusal_alert_tests.rs"] mod sponge_refusal_alert_tests; +#[cfg(test)] +#[path = "../retouch_mode_refusal_alert_tests.rs"] +mod retouch_mode_refusal_alert_tests; + #[cfg(test)] #[path = "../bucket_bitmap_alert_tests.rs"] mod bucket_bitmap_alert_tests; From 28d68162788023013ab9da661029dbbaf86073ca Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 12:53:59 -0500 Subject: [PATCH 14/16] Rectangle tool: the Radius field sets the next rectangle, not the active shape (#13338) The Rectangle tool's options-bar Radius field showed the active shape's first radius and, when changed, ran shape.edit on it (a History state). It now shows and sets only the tool's own radius, which the next drawn rectangle takes. The Properties panel and the on-canvas corner widgets still edit the active shape, and the Path Selection / Direct Selection Radius field is unchanged. Tests in rectangle_radius_target_tests.rs: the field leaves the active shape alone (no History state), the next rectangle takes the typed radius, the field shows the tool's radius, and the Path Selection / Direct Selection field still edits the active shape. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 queued; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- .../tools/rectangle_radius_target_tests.rs | 111 ++++++++++++++++++ crates/ui-egui/src/tools/shape_options.rs | 12 +- 2 files changed, 117 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/tools/rectangle_radius_target_tests.rs diff --git a/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs new file mode 100644 index 0000000000..9c9a5bf46d --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs @@ -0,0 +1,111 @@ +//! #13338: the Rectangle tool's options-bar Radius sets the next rectangle, not the active shape. +//! It shows the tool's own radius. The Path Selection / Direct Selection Radius still edits the +//! active shape. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A document with Rectangle 1 (radius 20) as the active layer, and `tool` current. +fn bar_with(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 80, 60], "radii": [20, 20, 20, 20], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn history_len(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// The first radius of every rectangle shape layer, bottom to top. +fn radii(h: &Harness<'static, PhotocraftApp>) -> Vec { + let st = h.state().session.active().unwrap(); + st.doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Rect { radii, .. }) => Some(radii[0]), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() { + let mut h = bar_with(Tool::Rectangle); + let before = history_len(&h); + type_radius(&mut h, "5000"); + assert_eq!(radii(&h), vec![20.0], "Rectangle 1 keeps its radius"); + assert_eq!(history_len(&h), before, "no History state"); + assert_eq!(h.state().ui.tool_options.corner_radius, 5000.0); +} + +#[test] +fn the_next_rectangle_takes_the_typed_radius() { + let mut h = bar_with(Tool::Rectangle); + type_radius(&mut h, "5000"); + drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]); + let all = radii(&h); + assert_eq!(all.len(), 2, "a second rectangle was drawn: {all:?}"); + assert_eq!(all[0], 20.0); + assert_eq!(all[1], 5000.0); +} + +#[test] +fn the_rectangle_tools_radius_field_shows_the_tools_radius() { + let mut h = bar_with(Tool::Rectangle); + h.state_mut().ui.tool_options.corner_radius = 0.0; + h.run_steps(3); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field"); + let shown = field + .accesskit_node() + .numeric_value() + .map(|v| v as f32) + .or_else(|| field.accesskit_node().value().and_then(|v| v.trim_end_matches(" px").trim().parse().ok())); + assert_eq!(shown, Some(0.0), "the tool's radius, not the shape's 20"); +} + +#[test] +fn the_path_selection_radius_field_still_edits_the_active_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut h = bar_with(tool); + let before = history_len(&h); + type_radius(&mut h, "30"); + assert_eq!(radii(&h), vec![30.0], "{tool:?}: the active shape takes it"); + assert_eq!(history_len(&h), before + 1, "{tool:?}: one History state"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index d0f7e3c5a8..966fdff212 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -107,16 +107,12 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool crate::widgets::vline(ui, 22.0); let label = tl!("Radius:"); lbl(ui, label); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; + // The tool's own radius for the next rectangle (#13338); the active shape is not touched. + let mut r = o.corner_radius; let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); radius_alert = out_of_range; if resp.changed() { o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); } } Tool::Polygon => { @@ -225,6 +221,10 @@ fn radius_range_alert(app: &mut PhotocraftApp, owed: bool) { #[path = "rectangle_radius_range_tests.rs"] mod rectangle_radius_range_tests; +#[cfg(test)] +#[path = "rectangle_radius_target_tests.rs"] +mod rectangle_radius_target_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. From cbcd62c8d1f304927a2f62e13ca69b741f98f8b4 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 12 Nov 2026 21:09:18 +0100 Subject: [PATCH 15/16] ci: let Cargo handle oversized Windows rustc commands --- .github/workflows/ci.yml | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1282fc662c..cf927388b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,8 +174,8 @@ jobs: # Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job # they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache, - # which needs its own action step. + # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is + # tracked by storytold/craft-common-actions#212. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' @@ -187,6 +187,10 @@ jobs: matrix: part: [unit, integration] env: + # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit + # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. + # The dependency rust-cache below stays enabled; only compiler caching is disabled. + RUSTC_WRAPPER: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). @@ -236,24 +240,6 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }} cache-on-failure: true - # sccache caches the workspace crates' compiled libraries, which rust-cache leaves out: - # warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read - # main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688). - # Test executables can't be cached, so a PR still links its tests. - - name: Install sccache - uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11 - with: - version: v0.18.0 - - - name: Use sccache - env: - MAIN: ${{ github.ref == 'refs/heads/main' }} - run: | - echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV" - echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV" - if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi - shell: bash - - name: Clippy if: matrix.part == 'integration' run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings From e660b4906bc809cfdf58e936d015e252f6811981 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:56:57 +0100 Subject: [PATCH 16/16] Clear the clippy 1.100 lints that fail the gate on main (#13531) (#13535) * Clear the clippy 1.100 lints that fail the gate on main (#13531) Clippy 1.100.0 flags needless_range_loop in cms synth.rs (the gate failure on main), algo photo_util.rs and an engine multichannel test, and, on Windows only, needless_bool in format noreplace.rs, where the cfg(unix) branch compiles away. Each loop now iterates the slice it indexed, with the same values in the same order. * Clear the Linux-only clippy 1.100 needless_bool lints (#13531) paths_match in ui-egui and is_redirect in the app ended with a cfg(not(windows)) branch that is just `false`, which clippy 1.100 flags on Linux. Each platform's branch now returns the whole comparison: the same results, in the same order. --- apps/photocraft/src/external_svg.rs | 7 ++----- crates/algo/src/photo_util.rs | 4 ++-- crates/cms/src/synth.rs | 4 ++-- crates/engine/src/cmd/multichannel_cmds/tests.rs | 4 ++-- crates/format/src/noreplace.rs | 5 +---- crates/ui-egui/src/home_recent_ui.rs | 9 ++------- 6 files changed, 11 insertions(+), 22 deletions(-) diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f552573..c34dd88bd0 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434..8f1e436d53 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce..c86bedc9bd 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/engine/src/cmd/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd6..99ad72d673 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/format/src/noreplace.rs b/crates/format/src/noreplace.rs index 75a54350c5..60d74d29c8 100644 --- a/crates/format/src/noreplace.rs +++ b/crates/format/src/noreplace.rs @@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { /// Use fallback only when the exclusive rename primitive itself is unsupported. fn unsupported_rename(error: &io::Error) -> bool { - if error.kind() == io::ErrorKind::Unsupported { - return true; - } #[cfg(unix)] if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { return true; } - false + error.kind() == io::ErrorKind::Unsupported } /// Linking claims an absent destination atomically; a later unlink failure is already published. diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 2cd4d5d2b4..e8f25a1e72 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } }