From adba2cec8fe8329cc8f3d28287767297d296a838 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:36:35 +0200 Subject: [PATCH 01/63] Docs: refresh ui, localization, brush and hardware parity docs against main (#4419) Co-Authored-By: Claude Opus 5.5 --- docs/brush-parity.md | 19 +++++------ docs/hardware-parity.md | 13 ++++---- docs/localization-parity.md | 34 ++++++++++---------- docs/ui-parity.md | 63 +++++++++++++++++++------------------ 4 files changed, 67 insertions(+), 62 deletions(-) diff --git a/docs/brush-parity.md b/docs/brush-parity.md index 119da10d662..259b81000fd 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (`~` held with the Brush or Pencil erases with its brush; Clear painting mode) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (rows refreshed against main; previously minor: `~` held with the Brush or Pencil erases with its brush; Clear painting mode) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -40,7 +40,7 @@ tablets against Photoshop side by side. | Pressure drives size/opacity/flow per sample (no shared pressure within a frame) | done | #2112 | | Global pressure curve in Preferences | done | #2195 | | Per-control pressure curves | missing | TOOL-213-11 | -| Quick taps keep their pressure | partial | #1967 fixed one case; tap paints a full blob (#1798), tap sensitivity (#1933) | +| Quick taps keep their pressure | partial | #1967 fixed one case; a tap paints at its own pressure (#1798, #2757); tap sensitivity still open (#1933) | | Smooth pressure on Windows | partial | "jumpy" (#2046) | | Tilt and rotation drive angle/roundness | partial | macOS, X11, web; not Windows; rotation not applied (#1301) | | Eraser end of the pen switches to Eraser | partial | macOS; flipped Wacom on Windows not (#2285) | @@ -50,7 +50,7 @@ tablets against Photoshop side by side. | Behaviour | Status | Evidence | |---|---|---| | No seams, hard edges stay hard, zero-scatter defaults, ABR tips never black | done | TOOL-213-13 | -| Smooth line weight along a pressure ramp | partial | stair-steps (#1776) | +| Smooth line weight along a pressure ramp | partial | stair-steps fixed by per-sample pressure (#1776, #2112); Windows still "jumpy" (#2046) | | Interpolation and smoothing match Photoshop | partial | #2138, #2057 | | Soft-edge falloff matches Photoshop's curve | partial | #2149, #1619 | | Brush preview and cursor crisp, not pixelated | partial | #1433 | @@ -71,8 +71,8 @@ tablets against Photoshop side by side. | ⇧-click draws a straight line from the last point | done | | | Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 | | Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 | -| Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980), macOS issue #2360 | -| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor requested (#2662, #1057) | +| Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980); macOS trackpad taps fixed (#2360, #2772) | +| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor done (#2662, #2694), parity request open (#1057) | | Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 | ## Symmetry @@ -81,7 +81,7 @@ tablets against Photoshop side by side. |---|---| | Vertical, Horizontal, Dual axis, Diagonal | done | | From a path (Make Symmetry Path) | done | -| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659) | +| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659 was closed after the existing symmetry control became available in every theme, #2704) | ## Brush-based tools @@ -89,10 +89,10 @@ tablets against Photoshop side by side. |---|---|---| | Brush, Pencil (aliased, Auto Erase), Eraser (Brush/Pencil/Block) | done | Pencil 1 px quality #2139 | | Mixer Brush (Wet, Load, Mix, Flow, Sample All Layers) | partial | "incomplete" (#2247) | -| Clone Stamp (opacity, flow, aligned, sample, overlay) | partial | Clone Source W/H link and Alt target cursor (TOOL-213-8) | +| Clone Stamp (opacity, flow, aligned, sample, overlay) | partial | Clone Source W/H link done (#3298, #3310); custom-tip clipping of the overlay missing (TOOL-213-8) | | Pattern Stamp (aligned, impressionist) | done | | | History Brush | done | Art History Brush missing | -| Spot Healing, Healing | partial | grain not matched on flat colour (#2104), "horrible in general" (#1092), stops responding after switching (#1751) | +| Spot Healing, Healing | partial | grain on flat colour kept by Create Texture (#2104, #2762); "horrible in general" (#1092), stops responding after switching (#1751) | | Blur, Sharpen, Smudge (premultiplied, Sample All Layers, spacing) | done | BUG-207-2/3, #2171 | | Dodge, Burn, Sponge | done | | | Background Eraser, Magic Eraser | done | | @@ -104,7 +104,7 @@ tablets against Photoshop side by side. | Behaviour | Status | Evidence | |---|---|---| | .abr import (v1/v2/v6) and export, persistent presets, folders | done | `psd/src/abr.rs` | -| Brushes panel: drag a folder into a folder | missing | #2014 | +| Brushes panel: drag a folder into a folder | done | #2014, #3851 | | Tool presets (.tpl) | partial | Tool Presets panel exists; .tpl import not found | | Import 500 brushes without blocking the UI | not run | P24 | @@ -114,3 +114,4 @@ tablets against Photoshop side by side. |---|---|---| | 2026-10-10 | major | First version, from a source audit and the open issues | | 2026-10-11 | minor | `~` held with the Brush or Pencil erases with that tool's brush, and Clear joins their Mode menus (#3439) | +| 2026-10-12 | minor | Rows refreshed against main: quick taps, pressure-ramp stair-steps, macOS right-click, round Pencil cursor, Clone Source W/H link, Spot Healing grain, brush-folder drag; the symmetry row no longer cites #2659 as the tracker | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 60175de1e59..a1d6a74e4b7 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (first version: GPU, pen tablets, displays, gestures per platform against Photoshop 2026) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (GPU, Wayland and monitor-profile rows refreshed against main; previously major: first version: GPU, pen tablets, displays, gestures per platform against Photoshop 2026) · **Target:** Adobe Photoshop 2026 Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR @@ -18,17 +18,17 @@ HDR display to verify. | Feature | Photoshop | PhotoCraft | Status | |---|---|---|---| | GPU canvas, zoom/pan, rotate view | Metal (macOS), DirectX/OpenCL (Windows) | wgpu 30: Metal, Vulkan, DX12, GL; backend selectable | done | -| GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel and > texture-limit regions fall back to CPU | done (ahead in places) | +| GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel documents and patterns larger than the texture limit fall back to CPU | done (ahead in places) | | GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects | partial | -| Documents larger than the GPU texture limit | yes (tiled) | CPU fallback; tiling in progress (#49) | partial | +| Documents larger than the GPU texture limit | yes (tiled) | paged GPU residency, composited page cell by page cell (`crates/gpu/src/lib.rs`, #49 closed) | done | | CPU-only fallback when no GPU | yes, reduced | `cpu` canvas preference; fails to start without an adapter on some Linux systems (#2519, #2412) | partial | -| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859), Rgba32Float panic (#2020) | partial | +| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859); the Rgba32Float panic is fixed (#2020) | partial | ## Pen tablets | Feature | Photoshop | macOS | Windows | Linux X11 | Linux Wayland | Web | |---|---|---|---|---|---|---| -| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622), KDE (#2297) | yes | +| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622); KDE fixed in 0.6.0 (#2297, #1070) | yes | | Tilt | yes | yes | **no** | yes | no | yes | | Barrel rotation | yes | yes (not applied to tip angle, #1301) | no | partial | no | yes (twist) | | Eraser end | yes | yes | no (#2285) | partial | no | partial | @@ -40,7 +40,7 @@ HDR display to verify. | Feature | Photoshop | PhotoCraft | Status | |---|---|---|---| | Colour-managed canvas (document → monitor profile) | yes | yes, folded into the GPU 3D LUT | done | -| Monitor profile detection | per display, live | macOS per display at launch; others sRGB or a chosen .icc | partial | +| Monitor profile detection | per display, live | macOS and Linux X11 (per XRandR output, #2962) per display, following each window's display (#591); Windows and Wayland: sRGB or a chosen .icc | partial | | HDR / EDR output for 32-bit and HDR images | yes ("Precise Color Management for HDR Display") | no; 8-bit sRGB-encoded canvas texture | missing | | High-DPI, physical 100% | yes | yes (#1943) | done | | Multiple monitors: documents in separate OS windows | yes | yes (`extra_windows`) | done | @@ -62,3 +62,4 @@ HDR display to verify. | Date | Change | Summary | |---|---|---| | 2026-10-10 | major | First version | +| 2026-10-12 | minor | GPU rows (documents past the texture limit, Rgba32Float panic), Wayland KDE pen and monitor-profile detection refreshed against main | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index cba241e1be0..61da801bef0 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Italian dynamic labels; previously minor: Czech review follow-ups) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (key universe and per-language counts re-measured with `cargo xtask i18n-coverage`; Vietnamese catalog; previously minor: Italian dynamic labels) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,9 +9,9 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (`xtask/src/i18n_coverage.rs`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**1,608 English keys** on 2026-10-10. Each catalog (`crates/ui-egui/src/i18n/.tsv`) was -checked against that universe by a source script replicating the xtask (no build). Catalogs hold -more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call +**1,772 English keys** on 2026-10-12 (1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) +is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines +of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and filter parameter help, which are English in every language; so no language is `full`. @@ -21,8 +21,10 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready composer, and its text engine handles RTL, Devanagari and Indic scripts. -**Summary.** 7 of the 12 key languages at 100% of measured keys (status `partial` because of the -engine messages), 3 absent (Hindi, Arabic, Vietnamese), plus 8 other languages. Weighted by +**Summary.** 6 of the 12 key languages at 100% of measured keys (English, Spanish, Portuguese +(Brazil), Japanese, German, Vietnamese; status `partial` because of the engine messages), 4 at 99.2% +(Simplified Chinese, French, Indonesian, Korean: 1,758 of 1,772), 2 absent (Hindi, Arabic), plus the other +shipped languages below. Weighted by speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (none recorded for any catalog). @@ -30,18 +32,18 @@ catalog). | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 1,608 / 1,608 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 1,608 / 1,608 (100%) | 2,366 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| English | `en` | 1,772 / 1,772 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 1,758 / 1,772 (99.2%) | 2,597 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | | Spanish | `es` | 1,608 / 1,608 (100%) | 2,413 | as above | Latin | no | partial | 6–10 h | | Hindi | `hi` | 0 (0%) | – | – | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | none | 20–30 h | | Arabic | `ar` | 0 (0%) | – | – | Arabic shaping and bidi in the text engine, Arabic fallback font; RTL shell layout but not inside panels, and UI labels in LTR word order (DIST-220-4), paragraph direction has no UI (TYPE-218-2), layer names as tofu (#1408, #1693) | no | none | 40–60 h | -| French | `fr` | 1,608 / 1,608 (100%) | 2,766 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 1,608 / 1,608 (100%) | 2,788 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 1,608 / 1,608 (100%) | 2,764 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 1,608 / 1,608 (100%) | 3,356 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki); installed Japanese fonts missing from the list (#2330) | no | partial | 10–16 h | -| German | `de` | 1,608 / 1,608 (100%) | 2,400 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 1,608 / 1,608 (100%) | 2,936 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 0 (0%) | – | – | Latin with stacked diacritics (shaping supported) | no | none | 12–18 h | +| French | `fr` | 1,758 / 1,772 (99.2%) | 2,981 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 1,772 / 1,772 (100%) | 3,784 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 1,758 / 1,772 (99.2%) | 2,979 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 1,772 / 1,772 (100%) | 3,579 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 1,772 / 1,772 (100%) | 2,634 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 1,758 / 1,772 (99.2%) | 3,162 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 1,772 / 1,772 (100%) | 3,426 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages @@ -68,7 +70,6 @@ engine localization or native review is complete. submenus and document tabs stay left to right. UI labels also lack an Arabic fallback font, and egui 0.36 joins letters within a word but orders a line's words left to right (no bidi). - Web build: no browser-locale detection, no CJK web fonts. -- WebAssembly plug-ins disappear from Filter › Plug-ins when the UI isn't English (#2540). - A user couldn't find the language option (#2532): it is in Preferences › Interface. ## Revision history @@ -81,3 +82,4 @@ engine localization or native review is complete. | 2026-10-11 | minor | Czech review follow-ups: English System Info diagnostics, id-aware shortcut labels, display-only auto translation, warning punctuation and wording; catalog row count refreshed | | 2026-10-11 | minor | Italian: 1,287 dynamic labels added (filter parameters, Camera Raw, lighting, panels, dialogs) and terminology made consistent | | 2026-10-12 | minor | Added Turkish (`tr`) catalog with 100% measured UI coverage | +| 2026-10-12 | minor | Re-measured with `cargo xtask i18n-coverage`: 1,772 keys; Vietnamese catalog shipped (100%, replaces "none"); Simplified Chinese, French, Indonesian and Korean at 1,758 of 1,772; plug-in menu rows stay in Filter › Plug-ins in every language (#2540, #2627) and installed Japanese fonts are listed on Linux (#2330, #2961) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 76b59de719e..bee8b522b8f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (rows refreshed against main: transform, Move, selection, Pen, Crop, ruler, navigation and panel rows; previously minor: ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -50,7 +50,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Toolbar behaviour | Status | Evidence | |---|---|---| | Letter shortcuts, ⇧+letter cycles the group, "Use Shift Key for Tool Switch" (on by default, as in Photoshop) | done | `shortcuts.rs:413` | -| Group remembers the last tool used | partial | L always resets to Lasso (#2608) | +| Group remembers the last tool used | done | a tool key brings back its group's last-used tool (#2608, #2625) | | Press-and-hold or click-drag opens the flyout | missing | right-click only (#2301) | | Edit Toolbar customization | done | `edit.toolbar` | @@ -68,19 +68,19 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Options bar X/Y, W/H % with link, angle | done | | | Options bar H/V skew fields | missing | | | Interpolation in the options bar | partial | Bicubic/Bilinear/Nearest; no Bicubic Smoother/Sharper/Automatic, Preserve Details | -| Commit/cancel buttons in the options bar | missing | #2442 | -| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | missing | TOOL-214-5 | +| Commit/cancel buttons in the options bar | done | `transform_tool.rs` ("Commit transform", "Cancel transform"); #2442 | +| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | done | TOOL-214-5 (`canvas_tool_menu.rs`) | | Arrow keys nudge the box 1 px, ⇧ 10 px | done | `move_mods.rs` | -| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); order/blend not (#2439) | +| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); plain Normal layers above keep their place (#2439, #2480), adjustment layers and other blend modes still draw under the box | | Preview clipped to the canvas, follows edits while open | done | #2201, #2099 | -| Hand (space) mid-transform doesn't interrupt it | partial | #2302 | +| Hand (space) mid-transform doesn't interrupt it | done | `transform_undo_tests.rs::holding_space_still_pans_while_transforming`; the selected Hand no longer steals a resize drag (#2302, #2327) | | Blend mode / opacity edits while transforming | missing | #1384 | -| Locked layer refused before the drag | missing | fails only at commit (#2585) | +| Locked layer refused before the drag | done | #2585, #2609 | | Transform a copy (⌥⌘T), step and repeat (⌥⇧⌘T) | done | 2026-10-07 | -| Transform a targeted alpha channel | missing | BUG-207-4 | +| Transform a targeted alpha channel | done | BUG-207-4 (`edit.transform` follows the targeted channel) | | Smart object perspective (non-affine) | missing | FILE-215-6, #579 | | Type-layer transform while editing (⌘ held), no ⌘-corner distort on type | done | `ui-design.md` | -| Puppet Warp mesh follows the outline | missing | block grid (TOOL-214-6) | +| Puppet Warp mesh follows the outline | done | TOOL-214-6 (`algo/puppet.rs` `build_mesh`, #3105) | ## Move tool and nudging @@ -90,14 +90,14 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Arrow nudge of a selection outline (selection tools) | done | #1502 | | Arrow nudge of the crop box, X swaps orientation | done | TOOL-214-19 | | Arrow nudge of path points with Direct Selection | missing | no arrow handling in `direct_select.rs` | -| ⌘-arrow nudges the layer from any tool | missing | #2474 | +| ⌘-arrow nudges the layer from any tool | done | #2474, #2556 | | ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` | -| Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 | -| Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) | -| ⌘-drag temporary Move shows the box and snaps | partial | #2681 | +| Auto-Select with hover outline, box-select layers, double-click fit | partial | hover outline and box-select done; double-click fit and drag to a tab open (TOOL-214-4) | +| Auto-Select bounding box and snapping follow the picked layer | done | #2666, #2675 | +| ⌘-drag temporary Move shows the box and snaps | done | #2681, #2684 | | ⌘-right-click layer list under the pointer | done | `layer_pick_ui.rs` | | Double-click type to edit it (caret at the pointer, Type tool) | done | #1132, `type_tool::edit_at` | -| Moving a selection on a mask moves the mask, not the pixels | partial | #2468 | +| Moving a selection on a mask moves the mask, not the pixels | done | #2468, #2486 | ## Selection modifiers @@ -106,10 +106,10 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | ⇧ square/circle, ⌥ from centre, live W × H readout (marquee) | done | `marquee_tests.rs` | | ⇧ add, ⌥ subtract, ⇧⌥ intersect from modifiers at press | partial | works; only a badge test (BUG-208-4) | | Space repositions the marquee while dragging | done | `hold_keys.rs` | -| Polygonal Lasso ⇧ snaps to 45° | missing | #2352 | +| Polygonal Lasso ⇧ snaps to 45° | done | #2352, #2396 | | Autoscroll at the window edge while selecting | missing | #2231 | -| Single-pixel rows and columns kept on release | partial | #2391 | -| Esc deselects / ⌘Z undoes the last selection | partial | #2674, #1432 | +| Single-pixel rows and columns kept on release | done | #2391, #2562 | +| Esc deselects / ⌘Z undoes the last selection | partial | Esc deselects when nothing else needs cancelling (#2674, #2765); ⌘Z of a selection step not re-checked (#1432 was closed with a Pen-anchor answer) | | Select › Modify live preview | missing | #1752 | ## Pen, paths and shapes @@ -117,12 +117,12 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Behaviour | Status | Evidence | |---|---|---| | Click corner, drag smooth, ⌥ breaks a handle, ⌘ direct-selects, ⇧ 45° | partial | TOOL-214-10 | -| Handle on the last point, close-drag handle | partial | #1482 | +| Handle on the last point, close-drag handle | done | `vector_ui.rs` (#1601, #3314); the rest of #1482 is a Make Selection dialog for paths | | Path operations in the options bar (combine, subtract, intersect, exclude) | partial | `layer.combineShapes.*`; Pen options #1397 | | On-canvas corner-radius handles on live shapes | missing | TOOL-214-12 | | Shape stroke controls (dash, caps, joins, align) | done | TOOL-1053-1, [`shape-strokes.md`](shape-strokes.md) | -| Rotated shape selection hints correct | partial | #2512 | -| Curved shape bounds exact | partial | one pixel too wide (#2537) | +| Rotated shape selection hints correct | done | #2512, #2732 | +| Curved shape bounds exact | done | #2537, #2641 | ## Crop @@ -137,7 +137,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Crop shield, Show Cropped Area (H) | done | TOOL-214-22 | | Default mode: the image turns and moves behind an upright box; Auto Center Preview; Use Classic Mode | done | TOOL-214-23 | | W × H × Resolution with units, built-in size presets, Front Image | done | TOOL-214-9 (`crop_size.rs`) | -| Saved custom crop presets | missing | TOOL-214-9 | +| Saved custom crop presets | done | TOOL-214-9 (New / Delete Crop Preset) | | Content-Aware crop fill, Delete Cropped Pixels off | partial | | ## Snapping, guides, rulers, precision @@ -150,11 +150,11 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Smart guide distance and spacing labels | missing | | | Ruler units px/in/cm/mm/pt/pica/% | done | | | ⇧-drag a guide out of a ruler: it lands on the nearest ruler tick | done | `rulers.rs` `snap_to_tick` (#3770) | -| Status bar follows the ruler unit | partial | #2602 | -| Ruler corner and gaps drawn as Photoshop | partial | #2600, #2601, #2551 | -| Guides stored as f64 | missing | `Vec` (UI-217-20) | +| Status bar follows the ruler unit | done | #2602, #2618 | +| Ruler corner and gaps drawn as Photoshop | partial | corner overlap fixed (#2600, #2617); the gap above the rulers is open (#2601, #2551) | +| Guides stored as f64 | done | `Vec`, kept through .pcraft and PSD (UI-217-20) | | Geometry precision | partial | `geom::Point` f64, paths f64; paint internals mostly f32 | -| Numeric fields: arithmetic, scrubby labels | partial | units in expressions and double-click reset missing (UI-217-13) | +| Numeric fields: arithmetic, scrubby labels | done | arithmetic with units, scrubby labels, double-click reset (UI-217-13, #3099) | ## Navigation @@ -165,13 +165,13 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Scrubby zoom | done | `zoom_tool.rs` | | Flick panning | done | `flick_pan.rs` (Preferences › Tools › Enable Flick Panning) | | Animated zoom | missing | unread pref; #566 | -| Double-click Zoom tool = 100%, double-click Hand = fit | partial | Zoom missing (#2508) | +| Double-click Zoom tool = 100%, double-click Hand = fit | done | #2508, #2527; `panels.rs::double_clicking_the_hand_tool_fits_on_screen` | | ⌥-wheel zoom in gentle steps | missing | UI-217-18 | | Wheel, smooth scrolling and pinch as in Photoshop | partial | #2485, #2463, #1989 | | Trackpad rotate drives Rotate View | done | `rotate_view.rs:136` | | Zoom levels to 3200% and beyond | partial | #1813 | | Physical 100% at any display scale | done | #1943 | -| ⌃Tab / ⌃⇧Tab switch document tabs | missing | #2340 | +| ⌃Tab / ⌃⇧Tab switch document tabs | done | #2340, #2353 | ## Keyboard shortcuts @@ -196,17 +196,17 @@ Paragraph; the rest open as in-app floating windows. | Behaviour | Status | Evidence | |---|---|---| | Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 | -| Drag panels to reorder and regroup | partial | #2272, #2305 | -| Docked resize pushes the neighbour | partial | #2573 | +| Drag panels to reorder and regroup | partial | dock tabs reorder within their group (#2272, #2774); regrouping open (#2305) | +| Docked resize pushes the neighbour | done | #2573, #2624 | | Color panel wheel and RGB/HSB/CMYK/Lab sliders | missing | UI-217-17, #2569 | | Window size and dock width remembered | done | UI-217-2 | | Command palette with recents | done | UI-217-7 | | Every preference takes effect | partial | 46 of 149 do nothing (scorecard) | | UI scale presets | missing | UI-217-9, #2492 | | History snapshots: camera button, snapshot rows (click returns, rename, delete), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`; New Snapshot dialog, first snapshot and History Options to come (#2966) | -| Themes: Photoshop's four greys | partial | five themes; #2661 | +| Themes: Photoshop's four greys | done | `theme.rs` `Pro`, `ProMedium`, `ProLightGray`, `ProLight` (#2661, #2892) | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | -| Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | +| Layers panel: wheel steps blend modes, drop on New/Trash | done | UI-217-14 | ## Revision history @@ -219,3 +219,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | ⇧-drag a guide out of a ruler lands on the nearest ruler tick (#3770) | | 2026-10-11 | minor | Layer and selection keys from Photoshop's shortcut set: ⌘, toggles, ⌘\, /, ⌘⌥2, ⌘⌥⌫, Tab rename-next, ⌥-click thumbnail to fit | | 2026-10-11 | minor | Tool keys from Photoshop's shortcut set: ← / → rotate the brush tip, ⇧-click for new type, Space+F canvas colour | +| 2026-10-12 | minor | Rows refreshed against main (scorecard ids and merged PRs cited per row): transform commit/cancel, right-click menu, locked layer, alpha channel and Puppet Warp; Move, selection, Pen, Crop preset, ruler, numeric-field, navigation, dock and theme rows; the last-used tool per group | From 8827846f6edc2452146150cc17db8dbdc6f68a9a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 20:03:09 +0200 Subject: [PATCH 02/63] Refresh translation measurements after merging current main --- docs/localization-parity.md | 39 +++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index c5f5ade440b..7c04be811e3 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (coverage re-measured, 1,871 keys; Spanish dynamic labels; previously minor: Serbian catalog) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-21 · **Last updated:** 2026-10-21 · **Change:** minor (coverage re-measured, 1,918 keys; Spanish dynamic labels; previously minor: Serbian catalog) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,7 +9,7 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (`xtask/src/i18n_coverage.rs`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**1,871 English keys** on 2026-10-14 (1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) +**1,918 English keys** on 2026-10-21 (1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and @@ -23,7 +23,7 @@ composer, and its text engine handles RTL, Devanagari and Indic scripts. **Summary.** 6 of the 12 key languages at 100% of measured keys (English, Spanish, Portuguese (Brazil), Japanese, German, Vietnamese; status `partial` because of the engine messages), 4 at 99.3% -(Simplified Chinese, French, Indonesian, Korean: 1,857 of 1,871), 2 absent (Hindi, Arabic), plus the other +(Simplified Chinese, French, Indonesian, Korean: 1,904 of 1,918), 2 absent (Hindi, Arabic), plus the other shipped languages below. Weighted by speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, 2026-10-12). @@ -32,27 +32,27 @@ speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorde | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 1,871 / 1,871 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 1,857 / 1,871 (99.3%) | 2,712 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | -| Spanish | `es` | 1,871 / 1,871 (100%) | 4,039 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | +| English | `en` | 1,918 / 1,918 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 1,904 / 1,918 (99.3%) | 2,818 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| Spanish | `es` | 1,918 / 1,918 (100%) | 4,129 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | | Hindi | `hi` | 0 (0%) | – | – | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | none | 20–30 h | | Arabic | `ar` | 0 (0%) | – | – | Arabic shaping and bidi in the text engine, Arabic fallback font; RTL shell layout but not inside panels, and UI labels in LTR word order (DIST-220-4), paragraph direction has no UI (TYPE-218-2), layer names as tofu (#1408, #1693) | no | none | 40–60 h | -| French | `fr` | 1,857 / 1,871 (99.3%) | 3,090 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 1,871 / 1,871 (100%) | 3,890 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 1,857 / 1,871 (99.3%) | 3,088 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 1,871 / 1,871 (100%) | 3,740 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | -| German | `de` | 1,871 / 1,871 (100%) | 3,092 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 1,857 / 1,871 (99.3%) | 3,275 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 1,871 / 1,871 (100%) | 3,534 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | +| French | `fr` | 1,904 / 1,918 (99.3%) | 3,186 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 1,918 / 1,918 (100%) | 3,980 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 1,904 / 1,918 (99.3%) | 3,184 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 1,918 / 1,918 (100%) | 3,832 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 1,918 / 1,918 (100%) | 3,186 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 1,904 / 1,918 (99.3%) | 3,374 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 1,918 / 1,918 (100%) | 3,628 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages -10 more, measured 2026-10-14, status `partial` for the same reason. All cover every measured key -except Polish (1,857 / 1,871): Traditional Chinese `zh-hant` (2,690 rows), Russian `ru` (2,963), -Ukrainian `uk` (3,705), Czech `cs` (3,673), Polish `pl` (3,684), Greek `el` (3,810), Dutch `nl` (3,888), -Hungarian `hu` (4,039), Italian `it` (4,194; also every dynamic label the +11 more, measured 2026-10-21, status `partial` for the same reason. All cover every measured key +except Polish (1,904 / 1,918): Traditional Chinese `zh-hant` (2,796 rows), Russian `ru` (3,061), +Ukrainian `uk` (3,804), Czech `cs` (3,765), Polish `pl` (3,776), Greek `el` (3,900), Dutch `nl` (3,978), +Hungarian `hu` (4,129), Italian `it` (4,280; also every dynamic label the other catalogs translate; reviewed by a native speaker, [notes](localization-it.md)), Turkish `tr` -(3,882 rows). Serbian `sr` (4,127 rows, Latin script, Ekavian, added 2026-10-12) covers every +(3,882 rows). Serbian `sr` (4,217 rows, Latin script, Ekavian, added 2026-10-12) covers every measured key and the union of the other catalogs' dynamic labels; its one/few/many plurals reuse the Russian rule. @@ -89,4 +89,5 @@ engine localization or native review is complete. | 2026-10-12 | minor | Italian native-speaker review: mistranslations (Trap, HDR Toning, Display Text) and phrasing fixed | | 2026-10-12 | minor | Serbian (`sr`, Latin, Ekavian) catalog: every measured key plus the dynamic labels of the other catalogs | | 2026-10-12 | minor | Re-measured with `cargo xtask i18n-coverage`: 1,772 keys; Vietnamese catalog shipped (100%, replaces "none"); Simplified Chinese, French, Indonesian and Korean at 1,758 of 1,772; plug-in menu rows stay in Filter › Plug-ins in every language (#2540, #2627) and installed Japanese fonts are listed on Linux (#2330, #2961) | -| 2026-10-14 | minor | Re-measured with `cargo xtask i18n-coverage` after merging main: 1,871 keys; Simplified Chinese, French, Indonesian and Korean at 1,857, the other key languages at 100%; catalog rows re-counted; other shipped languages refreshed (Hungarian listed, Polish at 1,857) | +| 2026-10-14 | minor | Re-measured with `cargo xtask i18n-coverage` after merging main: 1,871 keys; Simplified Chinese, French, Indonesian and Korean at 1,857, the other key languages at 100%; catalog rows re-counted; other shipped languages refreshed (Hungarian listed, Polish at 1,904) | +| 2026-10-21 | minor | Re-measured current main: 1,918 keys, 1,904 for French, Indonesian, Korean, Polish and Simplified Chinese; catalog rows recounted | From 3be52f998cd2e693a3615f826285864f1f54e6bf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 22 Oct 2026 20:13:10 +0200 Subject: [PATCH 03/63] docs/ui-parity: tools count 67/68 (was the stale 56/68) The Tool enum has 67 variants and the Tools table lists only Art History Brush as missing, so the summary line now says 67/68 (99%). Co-Authored-By: Claude Sonnet 5.5 --- docs/ui-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 63d3907beb3..8805e5e36fd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -12,8 +12,9 @@ Status: **done** (behaves as in Photoshop, with a test), **partial** (exists, di **missing**. Evidence is a file under `crates/ui-egui/src/` unless another path is given, a scorecard id, or an issue. Modifier names are macOS first (⌘ ⌥ ⇧); Windows/Linux use Ctrl and Alt. -**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 56/68 -present (82%, measured). Free Transform modifiers and Crop are close to Photoshop; the gaps are +**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 67/68 +present (99%, measured: the `Tool` enum has 67 variants; only Art History Brush is missing). +Free Transform modifiers and Crop are close to Photoshop; the gaps are in the long tail of modifiers, in-transform UI, spring-loaded tools, panels and preferences. Remaining: 60–110 h for transforms and modifiers (gap G5), 60–100 h for tools (G6), 150–250 h for panels and workspace (G9). From 0cc888efeb2b21613459ca237e617e58115b1e93 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 31 Oct 2026 01:35:59 +0100 Subject: [PATCH 04/63] docs: ui-parity tool count 68/68 (Art History Brush is in the Tool enum) Co-Authored-By: Claude Sonnet 5.5 --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7eb5c7f421f..3b706e46065 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -12,8 +12,8 @@ Status: **done** (behaves as in Photoshop, with a test), **partial** (exists, di **missing**. Evidence is a file under `crates/ui-egui/src/` unless another path is given, a scorecard id, or an issue. Modifier names are macOS first (⌘ ⌥ ⇧); Windows/Linux use Ctrl and Alt. -**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 67/68 -present (99%, measured: the `Tool` enum has 67 variants; only Art History Brush is missing). +**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 68/68 +present (100%, measured: the `Tool` enum has 68 variants; Art History Brush is partial, TOOL-213-20). Free Transform modifiers and Crop are close to Photoshop; the gaps are in the long tail of modifiers, in-transform UI, spring-loaded tools, panels and preferences. Remaining: 60–110 h for transforms and modifiers (gap G5), 60–100 h for tools (G6), 150–250 h From 9aee99b7277ee8c9225e3f8f1e79c9dcda0cfb29 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:37:39 +0100 Subject: [PATCH 05/63] docs/ui-parity: drop a duplicated changelog row Co-Authored-By: Claude Sonnet 5.5 --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e79a7eb2f7c..502c8337e73 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -321,7 +321,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | Selection modifiers at press: evidence now names the marquee, Lasso and Polygonal Lasso tests (still partial: no marquee ⇧⌥ intersect test). ⌥-wheel zoom: missing → partial (works at ×1.1 a notch; #217 asked for ~5 %) | | 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) | | 2026-10-12 | minor | General › Animated Zoom is visible and gates every discrete zoom transition; disabling it snaps all views to their target on the next frame | -| 2026-10-12 | minor | Closed #3632: Distort and Ctrl/Cmd corner drags snap actual corners to guides and intersections; shared guide snapping respects Extras and Canvas Guides visibility, with offset, visibility and constrained-alignment regressions | | 2026-10-12 | minor | Pen Auto Add/Delete on the active path, with its options-bar checkbox, hover feedback and + / − cursor badge (#4144) | | 2026-10-12 | minor | Toolbar tool shortcuts can be reassigned, removed and reset in Keyboard Shortcuts (#4086); capture, restart, group cycling, conflict and text-focus regressions | | 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) | From 457357b752baed47360541661f40f58a6fbca533 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 01:32:28 +0100 Subject: [PATCH 06/63] docs: re-measure localization parity on the merged tree (2,428 keys) Co-Authored-By: Claude Sonnet 5.5 --- docs/localization-parity.md | 51 +++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 2e21d3b4bf9..18f037d7f6d 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-11-07 · **Last updated:** 2026-11-07 · **Change:** minor (coverage re-measured on the merged tree, 2,400 keys; Arabic 93.8%; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-11-07 · **Last updated:** 2026-11-07 · **Change:** minor (coverage re-measured on the merged tree, 2,428 keys; Arabic 92.8%; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,7 +9,7 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (`xtask/src/i18n_coverage.rs`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**2,400 English keys** on 2026-11-07 after merging main (2,389 on this branch before that merge, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) +**2,428 English keys** on 2026-11-07 after merging main (2,400 on this branch before that merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and @@ -23,10 +23,10 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready composer, and its text engine handles RTL, Devanagari and Indic scripts. -**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 93.8–95.3% -(Arabic at 93.8%, 148 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, -German, Korean, Vietnamese at 94.9–95.3%, 114–123 keys each still show in English; status `partial` also -because of the engine messages), Hindi partial (398 of 2,400, 16.6%), plus the other shipped languages below. Weighted by +**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.8–94.4% +(Arabic at 92.8%, 176 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, +German, Korean, Vietnamese at 94.0–94.4%, 137–146 keys each still show in English; status `partial` also +because of the engine messages), Hindi partial (398 of 2,428, 16.4%), plus the other shipped languages below. Weighted by speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, 2026-10-12). @@ -34,27 +34,27 @@ speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorde | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 2,400 / 2,400 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 2,277 / 2,400 (94.9%) | 3,182 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | -| Spanish | `es` | 2,285 / 2,400 (95.2%) | 4,424 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | -| Hindi | `hi` | 398 / 2,400 (16.6%) | 628 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | -| Arabic | `ar` | 2,252 / 2,400 (93.8%) | 3,486 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | -| French | `fr` | 2,284 / 2,400 (95.2%) | 4,511 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 2,286 / 2,400 (95.2%) | 4,405 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 2,280 / 2,400 (95.0%) | 3,518 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 2,283 / 2,400 (95.1%) | 4,135 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | -| German | `de` | 2,279 / 2,400 (95.0%) | 3,526 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 2,283 / 2,400 (95.1%) | 4,064 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 2,283 / 2,400 (95.1%) | 3,954 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | +| English | `en` | 2,428 / 2,428 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 2,282 / 2,428 (94.0%) | 3,187 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| Spanish | `es` | 2,290 / 2,428 (94.3%) | 4,429 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | +| Hindi | `hi` | 398 / 2,428 (16.4%) | 628 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | +| Arabic | `ar` | 2,252 / 2,428 (92.8%) | 3,486 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | +| French | `fr` | 2,289 / 2,428 (94.3%) | 4,516 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 2,291 / 2,428 (94.4%) | 4,410 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 2,285 / 2,428 (94.1%) | 3,523 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 2,288 / 2,428 (94.2%) | 4,140 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 2,284 / 2,428 (94.1%) | 3,531 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 2,288 / 2,428 (94.2%) | 4,069 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 2,288 / 2,428 (94.2%) | 3,959 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages -18 more, measured 2026-11-07, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 132 of the 2,400 measured keys, Bosnian 136, Georgian 129; the other eleven miss 114–123: -Traditional Chinese `zh-hant` (3,137 rows), Russian `ru` (4,574; also every dynamic label the -other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,116), Czech `cs` (4,199), -Polish `pl` (4,102), Greek `el` (4,210), Dutch `nl` (4,284), Hungarian `hu` (4,432), Italian `it` (4,574; +18 more, measured 2026-11-07, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 160 of the 2,428 measured keys, Bosnian 164, Georgian 157; the other eleven miss 137–146: +Traditional Chinese `zh-hant` (3,142 rows), Russian `ru` (4,579; also every dynamic label the +other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,121), Czech `cs` (4,204), +Polish `pl` (4,107), Greek `el` (4,215), Dutch `nl` (4,289), Hungarian `hu` (4,437), Italian `it` (4,579; also every dynamic label the other catalogs translate; reviewed by a native speaker, -[notes](localization-it.md)), Turkish `tr` (4,288 rows). Georgian `ka` (4,642 rows, 2,271 of 2,400 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,521 rows, Latin script, +[notes](localization-it.md)), Turkish `tr` (4,293 rows). Georgian `ka` (4,642 rows, 2,271 of 2,428 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,521 rows, Latin script, Ekavian, added 2026-10-12) covers the union of the other catalogs' dynamic labels; its one/few/many plurals reuse the Russian rule. Swedish `sv` (4,602 rows, added 2026-10-28) covers the other catalogs' dynamic labels; combined from the community catalogs in #5985 and #9536 with one @@ -67,14 +67,14 @@ Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reu rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet. -Azerbaijani `az` (Latin script, 2,267 of 2,400 measured keys) brings the runtime registry to 29 languages including +Azerbaijani `az` (Latin script, 2,267 of 2,428 measured keys) brings the runtime registry to 29 languages including English. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels and 32 plural messages. It uses one/other integer forms, with singular counted nouns. Complete menu keys, regional locale matching and English fallback are covered by tests. Native-speaker review remains pending; validation results and limits are recorded in the [language notes](localization-az.md). Readiness estimates and G13 remain unchanged. -Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,332 of 2,400 keys (97.2%), Thai `th` at 2,209 (92.0%) and Tamil `ta` at 2,131 (88.8%). +Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,332 of 2,428 keys (96.0%), Thai `th` at 2,209 (91.0%) and Tamil `ta` at 2,131 (87.8%). Czech UI follow-up (2026-10-11): status and notice wrappers, hardware labels, brush and transform accessibility names, rasterization prompts, profile mismatch messages and preset @@ -127,3 +127,4 @@ engine localization or native review is complete. | 2026-11-07 | minor | Re-measured current main with `cargo xtask i18n-coverage`: 2,369 keys; Arabic 2,241 (94.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,264–2,272 (97–105 keys still in English); Hindi 387; Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu added to the measurements; catalog rows recounted | | 2026-11-07 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,389 keys; Arabic 2,252 (94.3%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,275–2,284 (105–114 keys still in English); Hindi 398; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | | 2026-11-07 | minor | Re-measured after merging current main (Georgian catalog) with `cargo xtask i18n-coverage`: 2,400 keys; Arabic 2,252 (93.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,277–2,286 (114–123 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | +| 2026-11-07 | minor | Re-measured the merged tree with `cargo xtask i18n-coverage`: 2,428 keys; Arabic 2,252 (92.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (137–146 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | From e21ca07289dc40082f6665cab2a13b3a9cc2801a Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 20:53:34 -0600 Subject: [PATCH 07/63] Color Replacement: the brush cursor always shows its centre + (#11934) With Normal Brush Tip cursors the Color Replacement cursor draws the tip circle with a + in its centre, the pixel it samples, whatever Show Crosshair in Brush Tip says, as in the reference application and as the Background Eraser already does. Other brush tools keep following the preference; Clone Stamp and Healing Brush keep their Alt behaviour. --- crates/ui-egui/src/canvas/cursors.rs | 9 +++-- .../src/color_replacement_cursor_tests.rs | 33 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/color_replacement_cursor_tests.rs diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index e4f0336b1de..6bc48fc59b5 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -37,7 +37,8 @@ pub(crate) fn pencil_tip_is_round(size: f32) -> bool { /// Whether a brush-tip circle draws its centre mark. /// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point /// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in -/// Photoshop; the Background Eraser always shows its sampling hotspot. +/// Photoshop; the Background Eraser and the Color Replacement tool (#11934) always show their +/// sampling hotspot. pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { if tool == Tool::QuickSelection { return false; @@ -45,7 +46,7 @@ pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) - if matches!(tool, Tool::CloneStamp | Tool::Healing) { return option || show_crosshair; } - show_crosshair || tool == Tool::BackgroundEraser + show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::ColorReplacement) } /// The display colour of an RGB triple (0..1 per channel) as an egui colour. @@ -290,6 +291,10 @@ pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { #[path = "../eyedropper_mask_sample_tests.rs"] mod eyedropper_mask_sample_tests; +#[cfg(test)] +#[path = "../color_replacement_cursor_tests.rs"] +mod color_replacement_cursor_tests; + #[cfg(test)] #[path = "../background_eraser_alt_click_tests.rs"] mod background_eraser_alt_click_tests; diff --git a/crates/ui-egui/src/color_replacement_cursor_tests.rs b/crates/ui-egui/src/color_replacement_cursor_tests.rs new file mode 100644 index 00000000000..5a8ad4ebf90 --- /dev/null +++ b/crates/ui-egui/src/color_replacement_cursor_tests.rs @@ -0,0 +1,33 @@ +//! #11934: with Normal Brush Tip cursors the Color Replacement cursor always draws the centre +, +//! its sampling hotspot, whatever Show Crosshair in Brush Tip says. Other brush tools follow the +//! preference, and Clone Stamp / Healing Brush keep their Alt behaviour. + +use super::*; + +#[test] +fn color_replacement_always_shows_its_centre() { + for show_crosshair in [false, true] { + for option in [false, true] { + assert!(brush_tip_centre(Tool::ColorReplacement, option, show_crosshair), "crosshair pref {show_crosshair}, Alt {option}"); + } + } +} + +#[test] +fn other_brush_tools_follow_the_preference() { + for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge, Tool::Pencil, Tool::Smudge] { + assert!(!brush_tip_centre(tool, false, false), "{tool:?} off"); + assert!(brush_tip_centre(tool, false, true), "{tool:?} on"); + } + // The Background Eraser keeps its hotspot, as before. + assert!(brush_tip_centre(Tool::BackgroundEraser, false, false)); +} + +#[test] +fn clone_stamp_and_healing_keep_their_alt_behaviour() { + for tool in [Tool::CloneStamp, Tool::Healing] { + assert!(!brush_tip_centre(tool, false, false), "{tool:?}"); + assert!(brush_tip_centre(tool, true, false), "{tool:?} with Alt"); + assert!(brush_tip_centre(tool, false, true), "{tool:?} with the preference"); + } +} From 9b47c385355e42ba7f424738ac575284136fc7ff Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 13:22:35 +0100 Subject: [PATCH 08/63] Docs: join the tool-inventory changelog row to the ui-parity table Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d85886178ac..4538f9466d5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -378,6 +378,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-03 | minor | Tools › Overscroll off centres an image smaller than the window on that axis, so zooming out around the pointer keeps it in the middle instead of where the zoom left it (#10488, #4799); this overrides #1718's Photoshop 25.4 measurement on the strength of two Photoshop users' reports, and Overscroll on keeps the free view; no percentage changed | | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | - - | 2026-11-08 | minor | Tool inventory: Color Replacement listed in the Brush group, Star (#11377) in Shapes; the `Tool` enum count is now 69; no percentage changed | + + From 0edca67199af3f3472613748f5a595c633215d4d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 13:28:59 +0100 Subject: [PATCH 09/63] Docs: re-measure localization at 2,431 keys, Xwayland tilt/eraser, pen right-click partial Re-ran cargo xtask i18n-coverage on the merged tree: 2,431 keys, per-language counts and catalog rows recounted; 35 registered languages (23 outside the key-language table). Linux Wayland tilt and eraser end work through Xwayland like pressure. The right-click Brush Preset picker row is partial while a pen barrel right-click with Windows Ink on still paints (#5364). Co-Authored-By: Claude Opus 5.5 --- docs/brush-parity.md | 5 +-- docs/hardware-parity.md | 7 +++-- docs/localization-parity.md | 61 +++++++++++++++++++------------------ 3 files changed, 38 insertions(+), 35 deletions(-) diff --git a/docs/brush-parity.md b/docs/brush-parity.md index 0033616e42d..a2058368f85 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Both Axes on Scatter headers, #3825 partial; parity refresh retains the expanded painting-menu limitations; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Both Axes on Scatter headers, #3825 partial; parity refresh retains the expanded painting-menu limitations; right-click Brush Preset picker is partial while a pen barrel right-click with Windows Ink on still often paints a dot (#5364); Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -79,7 +79,7 @@ tablets against Photoshop side by side. | Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 | | Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 | | Shift+right-click opens the painting tool's menu: Edit Brush… and its own Mode list (Brush/Pencil painting modes with Behind and Clear, stamps and History Brush blend modes, Eraser Brush/Pencil/Block, Dodge/Burn Range, Sponge mode, Healing Brush, Gradient and Paint Bucket modes); Behind and Clear greyed on the Background; Alt and Command/Ctrl keep their existing gestures | partial | #4929, `brush_mode_menu.rs`; rows set the options-bar state (`tools.setBrush` or the tool option); kittest and control regressions. Missing because the options bar lacks the setting: Behind for the stamps, History Brush, Gradient and Paint Bucket; the Blur/Sharpen/Smudge modes; the Spot Healing modes (no menu); the Healing Brush's Sampled/Pattern source and Replace; the History Brush source | -| Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980); macOS trackpad taps fixed (#2360, #2772) | +| Right-click opens the Brush Preset picker | partial | [`context-menu-parity.md`](context-menu-parity.md); mouse right-click works; a pen barrel right-click (Wacom, XP-Pen) with Windows Ink on still often paints a dot instead (#5364 open; #1980 closed as a duplicate of #5905); macOS trackpad taps fixed (#2360, #2772) | | Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor done (#2662, #2694), parity request open (#1057) | | Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 | @@ -146,3 +146,4 @@ tablets against Photoshop side by side. | 2026-10-23 | minor | Escape also consumes a held right-button release after a rapid second press, so the Brush Mode picker stays dismissed without painting or changing history (#4929). | | 2026-10-30 | minor | Shift+right-click works for every painting tool as in the reference application: Edit Brush… opens the Brush Preset picker, then the tool's own Mode list from its options bar; Behind and Clear greyed on the Background. Row marked partial for the settings the options bar lacks. No brush-feel estimate changed. | | 2026-10-31 | minor | Merge keeps the expanded Shift+right-click painting-menu limitations alongside the refreshed macOS right-click and Pencil cursor evidence; brush-feel estimates unchanged | +| 2026-11-08 | minor | Right-click Brush Preset picker marked partial: a pen barrel right-click with Windows Ink on still often paints a dot (#5364) | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 65ebb5c730f..2e04ae7139e 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-06 · **Change:** minor (Graphics Adapter choice on Linux, #1885; Camera Raw's preview develops its per-pixel stages on the GPU; GPU, Wayland and monitor-profile rows refreshed against main; Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; previously minor: optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (Graphics Adapter choice on Linux, #1885; Camera Raw's preview develops its per-pixel stages on the GPU; GPU, Wayland (tilt and eraser end via Xwayland) and monitor-profile rows refreshed against main; Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; previously minor: optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR @@ -33,9 +33,9 @@ HDR display to verify. | Feature | Photoshop | macOS | Windows | Linux X11 | Linux Wayland | Web | |---|---|---|---|---|---|---| | Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622); KDE fixed in 0.6.0 (#2297, #1070) | yes | -| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | no | yes | +| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | via Xwayland only (native Wayland: no) | yes | | Barrel rotation | yes | yes (not applied to tip angle, #1301) | no (WinTab: with a twist-reporting pen and driver, opt-in) | partial | no | yes (twist) | -| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | no | partial | +| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | partial, via Xwayland only (native Wayland: no) | partial | | WinTab driver mode | yes | – | yes (opt-in; Windows Ink off) | – | – | – | | Pressure curve | Windows Ink / driver | global curve in Preferences (#2195) | same | same | same | same | @@ -78,3 +78,4 @@ rotation; its eraser end comes from the pointer hooks (#2285). | 2026-10-12 | minor | GPU rows (documents past the texture limit, Rgba32Float panic), Wayland KDE pen and monitor-profile detection refreshed against main | | 2026-10-17 | minor | GPU filters: Camera Raw's preview, per-pixel stages (#6916 step 1) | | 2026-10-19 | minor | Graphics Adapter choice on Linux (#1885) | +| 2026-11-08 | minor | Linux Wayland: tilt and the eraser end work through Xwayland, like pressure; native Wayland still has no pen | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 18f037d7f6d..9aefa0224b6 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-11-07 · **Last updated:** 2026-11-07 · **Change:** minor (coverage re-measured on the merged tree, 2,428 keys; Arabic 92.8%; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-11-08 · **Last updated:** 2026-11-08 · **Change:** minor (coverage re-measured on the merged tree, 2,431 keys; Arabic 92.6%; 35 registered languages; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,11 +9,11 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (`xtask/src/i18n_coverage.rs`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**2,428 English keys** on 2026-11-07 after merging main (2,400 on this branch before that merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) +**2,431 English keys** on 2026-11-08 after merging main (2,428 on 2026-11-07, 2,400 on this branch before that day's merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and -filter parameter help, which are English in every language; so no language is `full`. The report +filter parameter help, which are English in every language; so no translated language is `full`. The report also lists, per language, the keys its catalog lacks; those show in English. `cargo xtask ci` prints it as its last step and never fails on it. @@ -23,10 +23,10 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready composer, and its text engine handles RTL, Devanagari and Indic scripts. -**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.8–94.4% -(Arabic at 92.8%, 176 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, -German, Korean, Vietnamese at 94.0–94.4%, 137–146 keys each still show in English; status `partial` also -because of the engine messages), Hindi partial (398 of 2,428, 16.4%), plus the other shipped languages below. Weighted by +**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.6–94.2% +(Arabic at 92.6%, 179 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, +German, Korean, Vietnamese at 93.9–94.2%, 140–149 keys each still show in English; status `partial` also +because of the engine messages), Hindi partial (399 of 2,431, 16.4%), plus the other shipped languages below. Weighted by speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, 2026-10-12). @@ -34,47 +34,47 @@ speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorde | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 2,428 / 2,428 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 2,282 / 2,428 (94.0%) | 3,187 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | -| Spanish | `es` | 2,290 / 2,428 (94.3%) | 4,429 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | -| Hindi | `hi` | 398 / 2,428 (16.4%) | 628 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | -| Arabic | `ar` | 2,252 / 2,428 (92.8%) | 3,486 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | -| French | `fr` | 2,289 / 2,428 (94.3%) | 4,516 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 2,291 / 2,428 (94.4%) | 4,410 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 2,285 / 2,428 (94.1%) | 3,523 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 2,288 / 2,428 (94.2%) | 4,140 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | -| German | `de` | 2,284 / 2,428 (94.1%) | 3,531 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 2,288 / 2,428 (94.2%) | 4,069 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 2,288 / 2,428 (94.2%) | 3,959 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | +| English | `en` | 2,431 / 2,431 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 2,282 / 2,431 (93.9%) | 3,188 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| Spanish | `es` | 2,290 / 2,431 (94.2%) | 4,430 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | +| Hindi | `hi` | 399 / 2,431 (16.4%) | 629 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | +| Arabic | `ar` | 2,252 / 2,431 (92.6%) | 3,487 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | +| French | `fr` | 2,289 / 2,431 (94.2%) | 4,517 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 2,291 / 2,431 (94.2%) | 4,411 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 2,285 / 2,431 (94.0%) | 3,524 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 2,288 / 2,431 (94.1%) | 4,141 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 2,284 / 2,431 (94.0%) | 3,532 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 2,288 / 2,431 (94.1%) | 4,070 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 2,288 / 2,431 (94.1%) | 3,960 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages -18 more, measured 2026-11-07, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 160 of the 2,428 measured keys, Bosnian 164, Georgian 157; the other eleven miss 137–146: -Traditional Chinese `zh-hant` (3,142 rows), Russian `ru` (4,579; also every dynamic label the -other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,121), Czech `cs` (4,204), -Polish `pl` (4,107), Greek `el` (4,215), Dutch `nl` (4,289), Hungarian `hu` (4,437), Italian `it` (4,579; +23 more registered languages (35 with English), measured 2026-11-08, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 163 of the 2,431 measured keys, Bosnian 168, Georgian 161; the other eleven below miss 140–149: +Traditional Chinese `zh-hant` (3,143 rows), Russian `ru` (4,580; also every dynamic label the +other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,122), Czech `cs` (4,205), +Polish `pl` (4,108), Greek `el` (4,216), Dutch `nl` (4,290), Hungarian `hu` (4,438), Italian `it` (4,580; also every dynamic label the other catalogs translate; reviewed by a native speaker, -[notes](localization-it.md)), Turkish `tr` (4,293 rows). Georgian `ka` (4,642 rows, 2,271 of 2,428 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,521 rows, Latin script, +[notes](localization-it.md)), Turkish `tr` (4,294 rows). Georgian `ka` (4,642 rows, 2,270 of 2,431 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,527 rows, Latin script, Ekavian, added 2026-10-12) covers the union of the other catalogs' dynamic labels; its one/few/many plurals reuse -the Russian rule. Swedish `sv` (4,602 rows, added 2026-10-28) covers the +the Russian rule. Swedish `sv` (4,603 rows, added 2026-10-28) covers the other catalogs' dynamic labels; combined from the community catalogs in #5985 and #9536 with one term per concept; the contested terms follow a native speaker's questionnaire answers. Finnish -`fi` (4,602 rows, combined from #5666 and #6961), Danish `da` (4,602 rows, based on #7267 and -completed for the current UI) and Norwegian Bokmål `nb` (4,602 rows, combined from #8072 and #9025; +`fi` (4,603 rows, combined from #5666 and #6961), Danish `da` (4,603 rows, based on #7267 and +completed for the current UI) and Norwegian Bokmål `nb` (4,603 rows, combined from #8072 and #9025; `no` and `nn` locales resolve to it), all added 2026-10-29, cover the same keys with one term per concept; none has had a native-speaker review yet. Bosnian `bs` (4,622 rows, Latin script, Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reuse the Russian rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet. -Azerbaijani `az` (Latin script, 2,267 of 2,428 measured keys) brings the runtime registry to 29 languages including -English. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels +Azerbaijani `az` (Latin script, 2,266 of 2,431 measured keys) brought the runtime registry to 29 languages including +English when it landed; it now has 35. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels and 32 plural messages. It uses one/other integer forms, with singular counted nouns. Complete menu keys, regional locale matching and English fallback are covered by tests. Native-speaker review remains pending; validation results and limits are recorded in the [language notes](localization-az.md). Readiness estimates and G13 remain unchanged. -Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,332 of 2,428 keys (96.0%), Thai `th` at 2,209 (91.0%) and Tamil `ta` at 2,131 (87.8%). +Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,331 of 2,431 keys (95.9%), Thai `th` at 2,208 (90.8%) and Tamil `ta` at 2,130 (87.6%). Czech UI follow-up (2026-10-11): status and notice wrappers, hardware labels, brush and transform accessibility names, rasterization prompts, profile mismatch messages and preset @@ -128,3 +128,4 @@ engine localization or native review is complete. | 2026-11-07 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,389 keys; Arabic 2,252 (94.3%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,275–2,284 (105–114 keys still in English); Hindi 398; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | | 2026-11-07 | minor | Re-measured after merging current main (Georgian catalog) with `cargo xtask i18n-coverage`: 2,400 keys; Arabic 2,252 (93.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,277–2,286 (114–123 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | | 2026-11-07 | minor | Re-measured the merged tree with `cargo xtask i18n-coverage`: 2,428 keys; Arabic 2,252 (92.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (137–146 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | +| 2026-11-08 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,431 keys; Arabic 2,252 (92.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (140–149 keys still in English); Hindi 399; Georgian 2,270; Azerbaijani 2,266; Hebrew, Romanian and Urdu 2,331, Thai 2,208, Tamil 2,130; 35 registered languages; catalog rows recounted | From dadc5b89276ce11f2c80a45f93d24da35d0daf44 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 8 Nov 2026 09:29:39 -0600 Subject: [PATCH 10/63] Color Replacement cursor: tests cover Alt for every tool and Quick Selection; the docs name Full Size Brush Tip (eliets2 review on crates/ui-egui/src/color_replacement_cursor_tests.rs) --- crates/ui-egui/src/canvas/cursors.rs | 10 ++++----- .../src/color_replacement_cursor_tests.rs | 21 ++++++++++++------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index 6bc48fc59b5..10343e1ae1f 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -34,11 +34,11 @@ pub(crate) fn pencil_tip_is_round(size: f32) -> bool { (h - 0.5) * std::f32::consts::SQRT_2 > h } -/// Whether a brush-tip circle draws its centre mark. -/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point -/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in -/// Photoshop; the Background Eraser and the Color Replacement tool (#11934) always show their -/// sampling hotspot. +/// Whether a brush-tip circle draws its centre mark, for Normal and Full Size Brush Tip cursors +/// alike (both draw through this). Quick Selection never draws one. Clone Stamp and Healing Brush +/// stay an empty circle until Option is held, the source-point cursor. Other brushes follow +/// Preferences › Cursors › Show Crosshair in Brush Tip, as in Photoshop; the Background Eraser +/// and the Color Replacement tool (#11934) always show their sampling hotspot. pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { if tool == Tool::QuickSelection { return false; diff --git a/crates/ui-egui/src/color_replacement_cursor_tests.rs b/crates/ui-egui/src/color_replacement_cursor_tests.rs index 5a8ad4ebf90..e2ed2b1859f 100644 --- a/crates/ui-egui/src/color_replacement_cursor_tests.rs +++ b/crates/ui-egui/src/color_replacement_cursor_tests.rs @@ -1,6 +1,6 @@ -//! #11934: with Normal Brush Tip cursors the Color Replacement cursor always draws the centre +, -//! its sampling hotspot, whatever Show Crosshair in Brush Tip says. Other brush tools follow the -//! preference, and Clone Stamp / Healing Brush keep their Alt behaviour. +//! #11934: with Normal and Full Size Brush Tip cursors the Color Replacement cursor always draws +//! the centre +, its sampling hotspot, whatever Show Crosshair in Brush Tip says. Other brush +//! tools follow the preference, and Clone Stamp / Healing Brush keep their Alt behaviour. use super::*; @@ -16,11 +16,18 @@ fn color_replacement_always_shows_its_centre() { #[test] fn other_brush_tools_follow_the_preference() { for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge, Tool::Pencil, Tool::Smudge] { - assert!(!brush_tip_centre(tool, false, false), "{tool:?} off"); - assert!(brush_tip_centre(tool, false, true), "{tool:?} on"); + for option in [false, true] { + assert!(!brush_tip_centre(tool, option, false), "{tool:?} off, Alt {option}"); + assert!(brush_tip_centre(tool, option, true), "{tool:?} on, Alt {option}"); + } + } + for show_crosshair in [false, true] { + for option in [false, true] { + // The Background Eraser keeps its hotspot, as before; Quick Selection never has one. + assert!(brush_tip_centre(Tool::BackgroundEraser, option, show_crosshair)); + assert!(!brush_tip_centre(Tool::QuickSelection, option, show_crosshair)); + } } - // The Background Eraser keeps its hotspot, as before. - assert!(brush_tip_centre(Tool::BackgroundEraser, false, false)); } #[test] From 9206d181b831e40f5662897884ab6b9fda407dd6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 20:20:00 +0100 Subject: [PATCH 11/63] Docs: re-measure localization coverage after merging main (2,449 keys) Co-Authored-By: Claude Opus 5.5 --- docs/localization-parity.md | 45 +++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 9aefa0224b6..a4df14f86cc 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-11-08 · **Last updated:** 2026-11-08 · **Change:** minor (coverage re-measured on the merged tree, 2,431 keys; Arabic 92.6%; 35 registered languages; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-11-08 · **Last updated:** 2026-11-08 · **Change:** minor (coverage re-measured on the merged tree, 2,449 keys; Arabic 92.1%; 35 registered languages; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,7 +9,7 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (`xtask/src/i18n_coverage.rs`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**2,431 English keys** on 2026-11-08 after merging main (2,428 on 2026-11-07, 2,400 on this branch before that day's merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) +**2,449 English keys** on 2026-11-08 after merging main (2,431 earlier that day, 2,428 on 2026-11-07, 2,400 on this branch before that day's merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`crates/ui-egui/src/i18n/.tsv`) is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and @@ -23,10 +23,10 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready composer, and its text engine handles RTL, Devanagari and Indic scripts. -**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.6–94.2% -(Arabic at 92.6%, 179 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, -German, Korean, Vietnamese at 93.9–94.2%, 140–149 keys each still show in English; status `partial` also -because of the engine messages), Hindi partial (399 of 2,431, 16.4%), plus the other shipped languages below. Weighted by +**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.1–93.7% +(Arabic at 92.1%, 194 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, +German, Korean, Vietnamese at 93.3–93.7%, 155–164 keys each still show in English; status `partial` also +because of the engine messages), Hindi partial (400 of 2,449, 16.3%), plus the other shipped languages below. Weighted by speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, 2026-10-12). @@ -34,27 +34,27 @@ speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorde | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 2,431 / 2,431 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 2,282 / 2,431 (93.9%) | 3,188 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | -| Spanish | `es` | 2,290 / 2,431 (94.2%) | 4,430 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | -| Hindi | `hi` | 399 / 2,431 (16.4%) | 629 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | -| Arabic | `ar` | 2,252 / 2,431 (92.6%) | 3,487 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | -| French | `fr` | 2,289 / 2,431 (94.2%) | 4,517 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 2,291 / 2,431 (94.2%) | 4,411 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 2,285 / 2,431 (94.0%) | 3,524 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 2,288 / 2,431 (94.1%) | 4,141 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | -| German | `de` | 2,284 / 2,431 (94.0%) | 3,532 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 2,288 / 2,431 (94.1%) | 4,070 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 2,288 / 2,431 (94.1%) | 3,960 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | +| English | `en` | 2,449 / 2,449 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 2,285 / 2,449 (93.3%) | 3,188 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| Spanish | `es` | 2,293 / 2,449 (93.6%) | 4,430 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | +| Hindi | `hi` | 400 / 2,449 (16.3%) | 629 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | +| Arabic | `ar` | 2,255 / 2,449 (92.1%) | 3,487 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | +| French | `fr` | 2,292 / 2,449 (93.6%) | 4,517 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 2,294 / 2,449 (93.7%) | 4,411 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 2,288 / 2,449 (93.4%) | 3,524 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 2,291 / 2,449 (93.5%) | 4,141 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 2,287 / 2,449 (93.4%) | 3,532 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 2,291 / 2,449 (93.5%) | 4,070 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 2,291 / 2,449 (93.5%) | 3,960 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages -23 more registered languages (35 with English), measured 2026-11-08, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 163 of the 2,431 measured keys, Bosnian 168, Georgian 161; the other eleven below miss 140–149: +23 more registered languages (35 with English), measured 2026-11-08, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 178 of the 2,449 measured keys, Bosnian 183, Georgian 176; the other eleven below miss 155–164: Traditional Chinese `zh-hant` (3,143 rows), Russian `ru` (4,580; also every dynamic label the other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,122), Czech `cs` (4,205), Polish `pl` (4,108), Greek `el` (4,216), Dutch `nl` (4,290), Hungarian `hu` (4,438), Italian `it` (4,580; also every dynamic label the other catalogs translate; reviewed by a native speaker, -[notes](localization-it.md)), Turkish `tr` (4,294 rows). Georgian `ka` (4,642 rows, 2,270 of 2,431 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,527 rows, Latin script, +[notes](localization-it.md)), Turkish `tr` (4,294 rows). Georgian `ka` (4,642 rows, 2,273 of 2,449 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,527 rows, Latin script, Ekavian, added 2026-10-12) covers the union of the other catalogs' dynamic labels; its one/few/many plurals reuse the Russian rule. Swedish `sv` (4,603 rows, added 2026-10-28) covers the other catalogs' dynamic labels; combined from the community catalogs in #5985 and #9536 with one @@ -67,14 +67,14 @@ Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reu rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet. -Azerbaijani `az` (Latin script, 2,266 of 2,431 measured keys) brought the runtime registry to 29 languages including +Azerbaijani `az` (Latin script, 2,269 of 2,449 measured keys) brought the runtime registry to 29 languages including English when it landed; it now has 35. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels and 32 plural messages. It uses one/other integer forms, with singular counted nouns. Complete menu keys, regional locale matching and English fallback are covered by tests. Native-speaker review remains pending; validation results and limits are recorded in the [language notes](localization-az.md). Readiness estimates and G13 remain unchanged. -Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,331 of 2,431 keys (95.9%), Thai `th` at 2,208 (90.8%) and Tamil `ta` at 2,130 (87.6%). +Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,334 of 2,449 keys (95.3%), Thai `th` at 2,211 (90.3%) and Tamil `ta` at 2,133 (87.1%). Czech UI follow-up (2026-10-11): status and notice wrappers, hardware labels, brush and transform accessibility names, rasterization prompts, profile mismatch messages and preset @@ -129,3 +129,4 @@ engine localization or native review is complete. | 2026-11-07 | minor | Re-measured after merging current main (Georgian catalog) with `cargo xtask i18n-coverage`: 2,400 keys; Arabic 2,252 (93.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,277–2,286 (114–123 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | | 2026-11-07 | minor | Re-measured the merged tree with `cargo xtask i18n-coverage`: 2,428 keys; Arabic 2,252 (92.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (137–146 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | | 2026-11-08 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,431 keys; Arabic 2,252 (92.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (140–149 keys still in English); Hindi 399; Georgian 2,270; Azerbaijani 2,266; Hebrew, Romanian and Urdu 2,331, Thai 2,208, Tamil 2,130; 35 registered languages; catalog rows recounted | +| 2026-11-08 | minor | Re-measured again after merging current main using `cargo xtask i18n-coverage`: 2,449 keys; Arabic 2,255 (92.1%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,285–2,294 (155–164 keys still in English); Hindi 400; Georgian 2,273; Azerbaijani 2,269; Hebrew, Romanian and Urdu 2,334, Thai 2,211, Tamil 2,133; catalog rows unchanged | From 9a15c8e7ee3c40cb72ed4602e892592a572d1f14 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 20:22:08 +0100 Subject: [PATCH 12/63] Docs: align localization hours and tool-count changelog with the tables Co-Authored-By: Claude Opus 5.5 --- docs/localization-parity.md | 4 ++-- docs/ui-parity.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a4df14f86cc..1cd942aee9f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -27,7 +27,7 @@ composer, and its text engine handles RTL, Devanagari and Indic scripts. (Arabic at 92.1%, 194 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean, Vietnamese at 93.3–93.7%, 155–164 keys each still show in English; status `partial` also because of the engine messages), Hindi partial (400 of 2,449, 16.3%), plus the other shipped languages below. Weighted by -speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, +speakers, ~55% ready. Remaining: 90–143 h, plus native-speaker review (recorded only for Italian, 2026-10-12). ## The twelve key languages @@ -63,7 +63,7 @@ term per concept; the contested terms follow a native speaker's questionnaire an completed for the current UI) and Norwegian Bokmål `nb` (4,603 rows, combined from #8072 and #9025; `no` and `nn` locales resolve to it), all added 2026-10-29, cover the same keys with one term per concept; none has had a native-speaker review yet. Bosnian `bs` (4,622 rows, Latin script, -Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reuse the Russian +Ijekavian, added 2026-10-30) covers the same dynamic labels; its one/few/other plurals reuse the Russian rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4538f9466d5..cccd825f0df 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -378,6 +378,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-03 | minor | Tools › Overscroll off centres an image smaller than the window on that axis, so zooming out around the pointer keeps it in the middle instead of where the zoom left it (#10488, #4799); this overrides #1718's Photoshop 25.4 measurement on the strength of two Photoshop users' reports, and Overscroll on keeps the free view; no percentage changed | | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | -| 2026-11-08 | minor | Tool inventory: Color Replacement listed in the Brush group, Star (#11377) in Shapes; the `Tool` enum count is now 69; no percentage changed | +| 2026-11-08 | minor | Tool inventory: Color Replacement listed in the Brush group, Star (#11377) in Shapes; the `Tool` enum count is now 69; tools present 56/68 → 68/68 (Star counted separately) | From f74722b6022e06e774d537041046751409926747 Mon Sep 17 00:00:00 2001 From: "Eng. Mahmoud Bek ElNemer" Date: Mon, 9 Nov 2026 06:43:59 +0200 Subject: [PATCH 13/63] fix(ui): give the Pencil tool a 1 px hard tip on start and Reset Tool Fixes #12200 --- crates/ui-egui/src/canvas/paint_mouse.rs | 14 +- crates/ui-egui/src/control/dispatch.rs | 3 + crates/ui-egui/src/input/hold_keys/tests.rs | 5 +- crates/ui-egui/src/menus/invoke.rs | 6 + .../src/pencil_reset_defaults_tests.rs | 140 ++++++++++++++++++ crates/ui-egui/src/pencil_tests.rs | 5 +- .../tests/it/background_eraser_reset_tip.rs | 2 +- .../ui-egui/tests/it/brush_reset_defaults.rs | 4 +- 8 files changed, 171 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/pencil_reset_defaults_tests.rs diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index fbf4e1ab0d8..b757f3cc9bf 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -43,7 +43,10 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. // The Background Eraser and the Healing Brush start with their own measured tips instead, // as the whole brush Reset Tool gives them (#11911, #12099). + // The Pencil resets its tip to its own 1 px hard round (#12200) regardless of the Brush, + // while preserving `current.opacity`. None if matches!(tool, Tool::BackgroundEraser | Tool::Healing) => fresh_brush(tool, ¤t), + None if tool == Tool::Pencil => BrushSettings { opacity: current.opacity, ..fresh_brush(tool, ¤t) }, None => { let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, ..current } @@ -77,17 +80,22 @@ const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); const BACKGROUND_ERASER_TIP: (f32, f32, f32) = (13.0, 1.0, 0.25); /// The Healing Brush's tip after Reset Tool (#12099): a 19 px hard round at 25 % spacing. const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25); +/// The Pencil tool's starting and Reset Tool tip, as the reference measures it (#12200): size, +/// hardness and spacing of a 1 px hard round at 25 % spacing. +const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's -/// [`HEALING_BRUSH_TIP`]; the other tools keep the default tip. +/// [`HEALING_BRUSH_TIP`], and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the +/// default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; match tool { Tool::Brush => (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP, Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP, Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP, + Tool::Pencil => (brush.size, brush.hardness, brush.spacing) = PENCIL_TOOL_TIP, _ => {} } session_fields(current, &brush) @@ -541,3 +549,7 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "../pencil_reset_defaults_tests.rs"] +mod pencil_reset_defaults_tests; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 6e7e14c87ea..11e3bbdffbc 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1256,6 +1256,9 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { }; if let Some(t) = parsed.tool { crate::tool_memory::select(app, t); + if t == crate::state::Tool::Pencil { + crate::paint_mouse::sync_tool_brush(app); + } } // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 61d78d9ed3d..5bc2164be2a 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -782,7 +782,10 @@ fn tilde_held_with_the_brush_or_pencil_erases_with_its_brush() { drag_with(&mut h, Modifiers::NONE, 110.0, 130.0, 150.0, 130.0); key(&mut h, Key::Backtick, false, Modifiers::NONE); assert_eq!(last_stroke_erases(&h), Some(true), "{tool:?}"); - assert_eq!(rgba(&h, 130, 130)[3], 0.0, "{tool:?}: erased to transparency"); + // `drag_with` bends through `(118, 136)` on the way from `(110, 130)` to `(150, 130)`, + // so the Pencil's 1 px tip (#12200) no longer reaches `(130, 130)`; check `(110, 130)` + // at the stroke start instead. + assert_eq!(rgba(&h, 110, 130)[3], 0.0, "{tool:?}: erased to transparency"); assert_eq!(last_stroke(h.state())["mode"], json!("clear"), "{tool:?}"); assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some(label)); assert_eq!(h.state().ui.tool, tool, "the tool stays"); diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index cbe858eba68..2bd1d868c8b 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -78,6 +78,12 @@ fn frame_convert_dialog(app: &mut PhotocraftApp, id: &str) -> Result Option> { if let Some(tool) = crate::tool_shortcuts::tool(id) { crate::tool_memory::select(app, tool); + // A first pick of the Pencil via shortcut must start from `fresh_brush(Tool::Pencil, ...)` + // (#12200) rather than the outgoing Brush tip, whereas other tools inherit the current + // brush tip on first pick; sync here so an immediate `paint.pencil` uses the 1 px tip. + if tool == crate::state::Tool::Pencil { + crate::paint_mouse::sync_tool_brush(app); + } return Some(Ok(json!({"tool": tool}))); } if id == "layer.frame.convert" && params.as_object().is_none_or(|o| o.is_empty()) { diff --git a/crates/ui-egui/src/pencil_reset_defaults_tests.rs b/crates/ui-egui/src/pencil_reset_defaults_tests.rs new file mode 100644 index 00000000000..59847b42fa0 --- /dev/null +++ b/crates/ui-egui/src/pencil_reset_defaults_tests.rs @@ -0,0 +1,140 @@ +//! #12200: Reset Tool, Reset All Tools and a fresh first pick give the Pencil a 1 px hard round +//! tip (size 1, hardness 100 %, angle 0, roundness 100 %, spacing 25 %, both pressure overrides +//! off, options-bar chip "1"), and a default click at 100.2,100.2 paints only pixel 100,100. + +use egui::{Context, Modifiers, Pos2, RawInput, Rect, Shape, vec2}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::control::{ControlRequest, handle}; +use crate::state::Tool; + +/// Creates a test app with a 200x200 document. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// Dispatches a control request and syncs document views. +fn control(app: &mut PhotocraftApp, method: &str, params: Value) { + let ctx = Context::default(); + let (req, _rx) = ControlRequest::new(method, params); + let _ = handle(app, &ctx, &req); + app.sync_views(); +} + +/// Switches to `tool` and synchronizes its remembered brush. +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +/// Scrambles the active brush tip and pressure overrides away from defaults. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (42.0, 0.3, 0.6, 25.0, 0.5); + (b.pressure_size, b.pressure_opacity) = (true, true); +} + +/// Asserts that `brush.get` reports the Pencil's 1 px hard round default tip. +fn assert_pencil_tip(app: &mut PhotocraftApp) { + let b = app.run("brush.get", json!({})).unwrap(); + let tip = ["size", "hardness", "angle", "roundness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(tip, [1.0, 1.0, 0.0, 1.0, 0.25], "{b}"); + assert_eq!(b["pressureSize"], json!(false), "{b}"); + assert_eq!(b["pressureOpacity"], json!(false), "{b}"); +} + +/// Renders the options bar and returns whether the brush preset chip displays `"1"`. +fn chip_shows_one(app: &mut PhotocraftApp) -> bool { + fn has_one(shape: &Shape, rect: Rect) -> bool { + match shape { + Shape::Text(t) => rect.contains(t.pos) && t.galley.text() == "1", + Shape::Vec(v) => v.iter().any(|s| has_one(s, rect)), + _ => false, + } + } + let ctx = Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 300.0))); + let mut out = ctx.run_ui(RawInput { screen_rect, ..Default::default() }, |ui| crate::panels::options_bar(app, ui)); + out.textures_delta.clear(); + let chip = ctx.read_response(crate::brush_picker::chip_id()).unwrap().rect; + out.shapes.iter().any(|s| has_one(&s.shape, chip)) +} + +/// Verifies that `tool.reset` and `tool.resetAll` give the Pencil its 1 px hard tip and `"1"` chip. +#[test] +fn reset_tool_and_reset_all_give_the_pencil_a_one_pixel_hard_tip() { + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + a.session.tools.brush.opacity = 0.4; + control(&mut a, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_pencil_tip(&mut a); + assert_eq!(a.session.tools.brush.opacity, 1.0); + assert!(chip_shows_one(&mut a)); + + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + assert_pencil_tip(&mut a); + assert!(chip_shows_one(&mut a)); +} + +/// Verifies that first selecting the Pencil (including via `tools.select.pencil` before a UI pass) +/// uses its 1 px hard tip while preserving the outgoing brush opacity. +#[test] +fn pencil_starts_with_its_own_tip_whatever_the_brush_had() { + let mut a = app(); + pick(&mut a, Tool::Brush); + scramble(&mut a); + a.session.tools.brush.opacity = 0.4; + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"})); + assert_pencil_tip(&mut a); + assert!((a.session.tools.brush.opacity - 0.4).abs() < 1e-5); + assert!(chip_shows_one(&mut a)); +} + +/// Verifies that a default Pencil click at `(100.2, 100.2)` paints only pixel `(100, 100)`. +#[test] +fn a_default_click_at_100_2_paints_only_pixel_100_100() { + let mut a = app(); + a.run("layer.new.layer", json!({})).unwrap(); + pick(&mut a, Tool::Pencil); + tool_event(&mut a, ToolEvent::Down { x: 100.2, y: 100.2, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut a, ToolEvent::Up { x: 100.2, y: 100.2 }, Modifiers::NONE); + let st = a.session.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.content_bounds(), photocraft_geom::Rect::new(100, 100, 101, 101)); + assert_eq!(surf.rgba(100, 100)[3], 1.0); +} + +/// Verifies that `tool.resetAll` resets a saved Pencil brush even when invoked from another tool, +/// while preserving the Brush and Eraser reset tips. +#[test] +fn brush_and_other_painting_tools_keep_their_reset_tips() { + let mut a = app(); + pick(&mut a, Tool::Eraser); + scramble(&mut a); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::Brush); + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + let b = a.run("brush.get", json!({})).unwrap(); + let brush_tip = ["size", "hardness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(brush_tip, [13.0, 0.0, 0.25]); + + pick(&mut a, Tool::Pencil); + assert_pencil_tip(&mut a); + assert!(chip_shows_one(&mut a)); + + pick(&mut a, Tool::Eraser); + let e = a.run("brush.get", json!({})).unwrap(); + let eraser_tip = ["size", "hardness", "spacing"].map(|k| (e[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(eraser_tip, [20.0, 1.0, 0.1]); +} diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index 6cc618e8fad..cd5deb8bdbc 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -13,12 +13,11 @@ fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 120, "height": 80, "background": "transparent"})).unwrap(); app.run("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0}})).unwrap(); // Each tool keeps its own brush (#218): switch first, then set the Pencil's options, as the - // options bar does (its first frame takes the Brush's tip at Photoshop's 10 % smoothing). + // options bar does. app.ui.tool = Tool::Pencil; crate::paint_mouse::sync_tool_brush(&mut app); - app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0, "smoothing": {"amount": 0.0}}})).unwrap(); app } diff --git a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs index f971412bc45..8d06ca4447b 100644 --- a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs +++ b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs @@ -96,7 +96,7 @@ fn a_first_use_starts_with_the_tip() { #[test] fn other_tools_and_session_strokes_keep_their_tips() { - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::CloneStamp] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); diff --git a/crates/ui-egui/tests/it/brush_reset_defaults.rs b/crates/ui-egui/tests/it/brush_reset_defaults.rs index 0c596a21025..75d3d6a3561 100644 --- a/crates/ui-egui/tests/it/brush_reset_defaults.rs +++ b/crates/ui-egui/tests/it/brush_reset_defaults.rs @@ -85,7 +85,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { let mut app = app(); pick(&mut app, Tool::Brush); control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::CloneStamp] { pick(&mut app, tool); assert_eq!(tip(&mut app), DEFAULT_TIP, "{tool:?}"); } @@ -93,7 +93,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { #[test] fn other_painting_tools_keep_the_default_reset_tip() { - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::CloneStamp] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); From d8c06f4597281773f654e347b06562723af3ac9c Mon Sep 17 00:00:00 2001 From: x-labb <154824493+x-labb@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:15:31 +0100 Subject: [PATCH 14/63] fix(engine): a gradient's transparency follows the interpolation method (#12010) paint.gradient baked only the colours with `method` and took the nearest stop's alpha for each dense stop, so the transparency never followed the method. Colour and opacity stops are now baked apart, and Smooth gets its own opacity curve (the Oklab easing of the colours, response y^(1/2.2)), fitted to the measured Foreground to Transparent ramp: alpha 255/179/100/35/0 at x 50/250/400/550/750. Opaque gradients and calls without `method` paint as before. --- crates/engine/src/cmd.rs | 2 + .../src/cmd/gradient_alpha_method_tests.rs | 77 +++++++++++++++++++ crates/engine/src/cmd/paint_cmds.rs | 51 +++++++++--- crates/engine/src/presets/gradients.rs | 15 +++- crates/io/src/gradient_bake.rs | 49 ++++++++++-- crates/io/src/lib.rs | 2 +- 6 files changed, 178 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/gradient_alpha_method_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c727a8850d1..9e16929a308 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -93,6 +93,8 @@ pub mod frame_cmds; pub mod fx_view_cmds; pub mod fx_visibility_cmds; pub mod gallery_cmds; +#[cfg(test)] +mod gradient_alpha_method_tests; pub mod gradient_fill_cmds; pub mod group_view_cmds; pub mod history_cmds; diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs new file mode 100644 index 00000000000..2ca1e947631 --- /dev/null +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -0,0 +1,77 @@ +//! #12010: the transparency of a gradient drawn with the Gradient tool follows the interpolation +//! method (Smooth by default) instead of a straight line. Reference: Foreground to Transparent, +//! Smooth, dragged (100, 300) to (700, 300): alpha 255 / 179 / 100 / 35 / 0 at x 50 / 250 / 400 / +//! 550 / 750. + +use serde_json::{Value, json}; + +use crate::Session; + +fn drawn(extra: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let mut p = json!({"gradient": "Foreground to Transparent", "from": [100, 300], "to": [700, 300], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + s +} + +fn alpha_at(s: &Session, x: i32) -> f32 { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!("a pixel layer") }; + surface.pixel(x, 300)[3] * 255.0 +} + +#[test] +fn smooth_transparency_ramp_matches_the_reference() { + let s = drawn(json!({"method": "smooth"})); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn without_a_method_the_ramp_stays_straight() { + let s = drawn(json!({})); + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn opaque_gradients_paint_the_same_with_a_method() { + let paint = |extra: Value| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 8, "background": "white"})).unwrap(); + let mut p = json!({"colors": ["#000000", "#ffffff"], "from": [0, 4], "to": [64, 4], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + (0..64).map(|x| alpha_and_red(&s, x)).collect::>() + }; + fn alpha_and_red(s: &Session, x: i32) -> Vec { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!() }; + surface.pixel(x, 4) + } + // The colours still follow the method; the alpha stays opaque. + let smooth = paint(json!({"method": "smooth"})); + assert!(smooth.iter().all(|p| (p[3] - 1.0).abs() < 1e-3)); + assert_ne!(smooth, paint(json!({}))); +} + +#[test] +fn a_transparent_ramp_with_other_methods_still_paints() { + for m in ["classic", "perceptual", "linear"] { + let s = drawn(json!({"method": m})); + let (a, b) = (alpha_at(&s, 250), alpha_at(&s, 550)); + assert!(a > b && (0.0..=255.0).contains(&a), "{m}: {a} {b}"); + } +} diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 37cac96a23d..e868c3a3334 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -144,15 +144,48 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // where straight stops give 0.0625. let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { Some(m) if stops.len() >= 2 => { - let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); - let mids = vec![0.5; stops.len() - 1]; - photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], c.alpha]) - }) - .collect() + let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); + // With transparency, the colour and opacity stops are baked apart: the colours by the + // method, the opacity by the method's own transparency curve (#12010). Merged stops + // would ease each of their sub-segments again and take the nearest stop's alpha. + let split = match gradients::tool_fill_stops(s, p)? { + Some((cs, os)) => Some((cs, os)), + None => { + // The legacy `colors` list, evenly spaced. + let os = gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default(); + let colors: Vec<[f32; 4]> = + p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); + let n = colors.len(); + let cs = colors + .iter() + .enumerate() + .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) + .collect(); + Some((cs, os)) + } + }; + match split { + Some((cs, os)) if os.iter().any(|o| (o.1 - 1.0).abs() > 1e-6) && cs.len() >= 2 => { + let mids = vec![0.5; cs.len() - 1]; + let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) + .into_iter() + .map(|(t, c)| (t, [c.to_rgb()[0], c.to_rgb()[1], c.to_rgb()[2], 1.0])) + .collect(); + let omids = vec![0.5; os.len().saturating_sub(1)]; + gradients::apply_opacity(colours, &photocraft_io::bake_gradient_opacity(os, &omids, smoothness, m)) + } + _ => { + let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); + let mids = vec![0.5; stops.len() - 1]; + photocraft_io::bake_gradient(colors, &mids, smoothness, m) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], c.alpha]) + }) + .collect() + } + } } _ => stops, }; diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 20cb95d95bb..d9f5c6bf25d 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -401,19 +401,28 @@ pub const STOP: &str = "gradient.presets.stop"; /// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient` /// handles itself). pub fn tool_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.resolve(s.tools.foreground, s.tools.background))) +} + +/// The same gradient as [`tool_stops`] with its colour and opacity stops kept apart, for the +/// interpolation `method`, which treats the two differently. +pub fn tool_fill_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.fill_stops(s.tools.foreground, s.tools.background))) +} + +fn tool_preset(s: &Session, p: &Value) -> Result> { const CMD: &str = "paint.gradient"; if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) { return Ok(None); } - let g = if let Some(name) = str_param(p, "gradient") { + Ok(Some(if let Some(name) = str_param(p, "gradient") { let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)? } else if p.get("stops").is_some() { GradientPreset::from_params("Custom", p, CMD)? } else { s.presets.gradient.clone().with_transparency(p, CMD)? - }; - Ok(Some(g.resolve(s.tools.foreground, s.tools.background))) + })) } /// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`. diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index 6c7aaf32f43..c8d521a3e75 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -195,10 +195,11 @@ const OPACITY_RESPONSE: f32 = 0.65; /// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency /// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input -/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve: it was -/// not measured (the Photoshop build it was fitted on has no Smooth method). +/// unchanged when it already interpolates linearly. Smooth follows [`bake_smooth_opacity`]. pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> { - let method = if method == Method::Smooth { Method::Classic } else { method }; + if method == Method::Smooth { + return bake_smooth_opacity(stops, midpoints); + } let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3); let smoothness = if smoothness.is_finite() { smoothness.clamp(0.0, 1.0) } else { 0.0 }; if stops.len() < 2 || (smoothness <= 0.0 && method == Method::Classic && plain_mids) { @@ -236,6 +237,43 @@ pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, baked } +/// Gamma of Smooth's opacity response: the opacity of a fully transparent gradient ramp is the +/// Oklab lightness curve's linear value `y` raised to `1 / 2.2`. Photoshop 27.11, "Foreground to +/// Transparent" dragged over 600 px: alpha 255 / 179 / 100 / 35 / 0 at 50 / 250 / 400 / 550 / 750 +/// (#12010). The same ramp as an sRGB grey (`y` encoded with the sRGB curve) gives 30 at the dark +/// end, 5 levels off, where the 2.2 power gives 35. +const SMOOTH_OPACITY_GAMMA: f32 = 2.2; + +/// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is +/// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses +/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Smoothness +/// doesn't change Smooth; opacity midpoints still move each segment's centre. Constant opacity +/// comes back unchanged. +fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { + return stops; + } + let mut s = stops; + s.sort_by(|a, b| a.0.total_cmp(&b.0)); + let pts: Vec<(f32, [f32; 3])> = s + .iter() + .map(|(t, o)| { + let o = if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; + (*t, [o.powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3]) + }) + .collect(); + const N: usize = 96; + let mut baked: Vec<(f32, f32)> = (0..=N) + .map(|k| { + let t = k as f32 / N as f32; + let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0]; + (t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 }) + }) + .collect(); + baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + baked +} + #[cfg(test)] mod tests { use super::*; @@ -280,10 +318,11 @@ mod tests { } #[test] - fn plain_classic_and_smooth_opacity_stay_as_stored() { + fn plain_classic_and_constant_smooth_opacity_stay_as_stored() { let stops = vec![(1.0, 0.0), (0.0, 1.0)]; assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Classic), stops); - assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Smooth), stops); + let flat = vec![(0.0, 0.4), (1.0, 0.4)]; + assert_eq!(bake_opacity(flat.clone(), &[0.5], 0.0, Method::Smooth), flat); assert_eq!(bake_opacity(vec![(0.5, 0.3)], &[], 1.0, Method::Linear), vec![(0.5, 0.3)]); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index c796b7cffa1..b7c0b7bf9ac 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -53,7 +53,7 @@ mod flat; mod gradient_bake; pub mod guides_map; mod png_steps; -pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient}; +pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_opacity as bake_gradient_opacity}; mod duotone_map; mod kra; pub mod linked; From 0f76df26c42b19ae43a67e60437566f4aacf15ee Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 02:16:17 +0100 Subject: [PATCH 15/63] PR #12644: keep the new transparency curve to the measured case Smooth's opacity curve was measured only in the Gradient tool at 100 % Smoothness. The split path also changed Classic, Perceptual and Linear, Smooth below 100 %, and (through bake_opacity) Gradient Overlay and PSD Smooth gradients; #12010 says unmeasured cases keep today's behaviour. - paint.gradient bakes the opacity apart only for Smooth at 100 % Smoothness; everything else keeps the merged stops. - bake_opacity maps Smooth to Classic again; the measured curve is the separate bake_smooth_opacity, used only by the Gradient tool. - A single colour stop with a transparency ramp now follows the curve; legacy `colors` with their own alpha keep the merged stops. - bake_smooth_opacity clamps constant stops. Tests pin today's ramp for the other methods and Smoothness 50, and cover the single-colour, RGBA-colour and constant-stop cases. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/gradient_alpha_method_tests.rs | 40 +++++++++-- crates/engine/src/cmd/paint_cmds.rs | 67 ++++++++++++------- crates/io/src/gradient_bake.rs | 39 +++++------ crates/io/src/lib.rs | 2 +- 4 files changed, 99 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index 2ca1e947631..b8327cb8cba 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -67,11 +67,41 @@ fn opaque_gradients_paint_the_same_with_a_method() { assert_ne!(smooth, paint(json!({}))); } +// Not measured in the Gradient tool: the other methods, and Smooth below 100 % Smoothness, keep +// today's merged stops (each dense stop takes the nearest stop's alpha). #[test] -fn a_transparent_ramp_with_other_methods_still_paints() { - for m in ["classic", "perceptual", "linear"] { - let s = drawn(json!({"method": m})); - let (a, b) = (alpha_at(&s, 250), alpha_at(&s, 550)); - assert!(a > b && (0.0..=255.0).contains(&a), "{m}: {a} {b}"); +fn unmeasured_methods_and_smoothness_keep_todays_ramp() { + for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] { + let s = drawn(extra.clone()); + for (x, want) in [(175, 250.0), (250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}"); + } + } +} + +fn drawn_colors(colors: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let p = json!({"colors": colors, "transparency": [[0, 100], [1, 0]], "method": "smooth", "from": [100, 300], "to": [700, 300], "dither": false}); + s.execute("paint.gradient", p).unwrap(); + s +} + +#[test] +fn one_colour_with_a_transparency_ramp_follows_smooth() { + let s = drawn_colors(json!(["#ff0000"])); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn legacy_colours_keep_their_own_alpha() { + let s = drawn_colors(json!(["#ff000080", "#ff000080"])); + for (x, want) in [(50, 128.0), (400, 64.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}"); } } diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index e868c3a3334..498ec7aa546 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -145,36 +145,25 @@ fn gradient(s: &mut Session, p: &Value) -> Result { let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { Some(m) if stops.len() >= 2 => { let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); - // With transparency, the colour and opacity stops are baked apart: the colours by the - // method, the opacity by the method's own transparency curve (#12010). Merged stops - // would ease each of their sub-segments again and take the nearest stop's alpha. - let split = match gradients::tool_fill_stops(s, p)? { - Some((cs, os)) => Some((cs, os)), - None => { - // The legacy `colors` list, evenly spaced. - let os = gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default(); - let colors: Vec<[f32; 4]> = - p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); - let n = colors.len(); - let cs = colors - .iter() - .enumerate() - .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) - .collect(); - Some((cs, os)) - } - }; + // Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by + // the method, the opacity by Smooth's measured transparency curve (#12010). Merged + // stops would take the nearest stop's alpha. The other methods and Smoothness values + // were not measured in the Gradient tool and keep the merged stops. + let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; match split { - Some((cs, os)) if os.iter().any(|o| (o.1 - 1.0).abs() > 1e-6) && cs.len() >= 2 => { - let mids = vec![0.5; cs.len() - 1]; + Some((cs, os)) => { + let mids = vec![0.5; cs.len().saturating_sub(1)]; let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) .into_iter() - .map(|(t, c)| (t, [c.to_rgb()[0], c.to_rgb()[1], c.to_rgb()[2], 1.0])) + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], 1.0]) + }) .collect(); let omids = vec![0.5; os.len().saturating_sub(1)]; - gradients::apply_opacity(colours, &photocraft_io::bake_gradient_opacity(os, &omids, smoothness, m)) + gradients::apply_opacity(colours, &photocraft_io::bake_gradient_smooth_opacity(os, &omids)) } - _ => { + None => { let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); let mids = vec![0.5; stops.len() - 1]; photocraft_io::bake_gradient(colors, &mids, smoothness, m) @@ -204,6 +193,36 @@ fn gradient(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own +/// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their +/// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient. +fn split_stops(s: &Session, p: &Value, fg: [f32; 4]) -> Result> { + let (mut cs, os) = match gradients::tool_fill_stops(s, p)? { + Some(split) => split, + None => { + // The legacy `colors` list, evenly spaced. + let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); + if colors.iter().any(|c| c[3] < 1.0) { + return Ok(None); + } + let n = colors.len(); + let cs = colors + .iter() + .enumerate() + .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) + .collect(); + (cs, gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) + } + }; + if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) { + return Ok(None); + } + if let [(_, c)] = cs.as_slice() { + cs = vec![(0.0, *c), (1.0, *c)]; + } + Ok(if cs.is_empty() { None } else { Some((cs, os)) }) +} + /// Paint helper command specs. pub fn specs() -> Vec { vec![ diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index c8d521a3e75..954dfdd48a9 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -195,11 +195,10 @@ const OPACITY_RESPONSE: f32 = 0.65; /// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency /// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input -/// unchanged when it already interpolates linearly. Smooth follows [`bake_smooth_opacity`]. +/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve here: it +/// was measured only in the Gradient tool at 100 % Smoothness ([`bake_smooth_opacity`]). pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> { - if method == Method::Smooth { - return bake_smooth_opacity(stops, midpoints); - } + let method = if method == Method::Smooth { Method::Classic } else { method }; let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3); let smoothness = if smoothness.is_finite() { smoothness.clamp(0.0, 1.0) } else { 0.0 }; if stops.len() < 2 || (smoothness <= 0.0 && method == Method::Classic && plain_mids) { @@ -246,22 +245,17 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2; /// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is /// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses -/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Smoothness -/// doesn't change Smooth; opacity midpoints still move each segment's centre. Constant opacity -/// comes back unchanged. -fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { +/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Measured +/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it. +/// Constant opacity comes back as it is, clamped to 0..=1. +pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { - return stops; + return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect(); } let mut s = stops; s.sort_by(|a, b| a.0.total_cmp(&b.0)); - let pts: Vec<(f32, [f32; 3])> = s - .iter() - .map(|(t, o)| { - let o = if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; - (*t, [o.powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3]) - }) - .collect(); + let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect(); const N: usize = 96; let mut baked: Vec<(f32, f32)> = (0..=N) .map(|k| { @@ -318,11 +312,10 @@ mod tests { } #[test] - fn plain_classic_and_constant_smooth_opacity_stay_as_stored() { + fn plain_classic_and_smooth_opacity_stay_as_stored() { let stops = vec![(1.0, 0.0), (0.0, 1.0)]; assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Classic), stops); - let flat = vec![(0.0, 0.4), (1.0, 0.4)]; - assert_eq!(bake_opacity(flat.clone(), &[0.5], 0.0, Method::Smooth), flat); + assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Smooth), stops); assert_eq!(bake_opacity(vec![(0.5, 0.3)], &[], 1.0, Method::Linear), vec![(0.5, 0.3)]); } @@ -431,6 +424,14 @@ mod tests { } /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. + #[test] + fn smooth_opacity_clamps_constant_stops() { + let flat = vec![(0.0, 0.4), (1.0, 0.4)]; + assert_eq!(bake_smooth_opacity(flat.clone(), &[0.5]), flat); + assert_eq!(bake_smooth_opacity(vec![(0.0, 2.0), (1.0, 2.0)], &[0.5]), vec![(0.0, 1.0), (1.0, 1.0)]); + assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]); + } + #[test] fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() { assert_eq!(eval(&[], &[], 1.0, 0.5, Method::Smooth), [0.0; 3]); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b7c0b7bf9ac..6cee2d1c453 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -53,7 +53,7 @@ mod flat; mod gradient_bake; pub mod guides_map; mod png_steps; -pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_opacity as bake_gradient_opacity}; +pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_smooth_opacity as bake_gradient_smooth_opacity}; mod duotone_map; mod kra; pub mod linked; From 597b220cf008a6d9034f1f3ff76e259c2da1dfec Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:33:34 +0100 Subject: [PATCH 16/63] PR #12644: the eval doc comment back on its own test Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- crates/io/src/gradient_bake.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index c2666211d3a..6dee3dfd930 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -458,7 +458,6 @@ mod tests { assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01); } - /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. #[test] fn smooth_opacity_clamps_constant_stops() { let flat = vec![(0.0, 0.4), (1.0, 0.4)]; @@ -467,6 +466,7 @@ mod tests { assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]); } + /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. #[test] fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() { assert_eq!(eval(&[], &[], 1.0, 0.5, Method::Smooth), [0.0; 3]); From a65bea764be6d40cb6d83291ed341884bcf1cfbe Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 14:10:18 +0100 Subject: [PATCH 17/63] PR #12644: pin today's ramp only at the reviewed points The x=175 value was a guess; main paints 255 there for the other methods. The 191/128/64 points from the review stay pinned. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/gradient_alpha_method_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index b8327cb8cba..5b62b4778c2 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -73,7 +73,7 @@ fn opaque_gradients_paint_the_same_with_a_method() { fn unmeasured_methods_and_smoothness_keep_todays_ramp() { for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] { let s = drawn(extra.clone()); - for (x, want) in [(175, 250.0), (250, 191.0), (400, 128.0), (550, 64.0)] { + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { let got = alpha_at(&s, x); assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}"); } From 9ddef6cf7cbba5ac385e1ebe5799cbf70d7c212f Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 14:56:40 +0100 Subject: [PATCH 18/63] #12243: sync every selected tool's brush at once; tests follow main's Clone Stamp tip ui.pointer and tools.select.* now load the selected tool's own brush right away for any tool, not only the Pencil, so a brush command before the next frame never uses the outgoing tool's tip. The tilde-erase test checks the whole drag erases, the reset-tip tests use the Sponge as the default-tip tool (main gave the Clone Stamp its own tip), and the Shift-click test expects the Pencil's pixel-centre points. Co-Authored-By: ElNeMeR70 Co-Authored-By: Claude Opus 5.5 --- .../src/canvas/art_history_shift_click_tests.rs | 4 +++- crates/ui-egui/src/control/dispatch.rs | 6 +++--- crates/ui-egui/src/input/hold_keys/tests.rs | 4 ++++ crates/ui-egui/src/menus/invoke.rs | 9 +++------ crates/ui-egui/src/pencil_reset_defaults_tests.rs | 14 ++++++++++++++ .../tests/it/background_eraser_reset_tip.rs | 2 +- crates/ui-egui/tests/it/brush_reset_defaults.rs | 4 ++-- 7 files changed, 30 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs b/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs index 011e4a4cd2b..22caf243433 100644 --- a/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs +++ b/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs @@ -105,7 +105,9 @@ fn shift_click_still_connects_brush_pencil_history_brush_and_other_painting_tool tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 40.0 }, none); tool_event(&mut app, ToolEvent::Down { x: 120.0, y: 40.0, pressure: 1.0 }, shift); tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 40.0 }, shift); - assert_eq!(last_points(&app, cmd), vec![[20.0, 40.0], [120.0, 40.0]], "{tool:?}"); + // The Pencil's 1 px tip paints whole pixels, so its points sit on pixel centres (#12200). + let want = if tool == Tool::Pencil { vec![[20.5, 40.5], [120.5, 40.5]] } else { vec![[20.0, 40.0], [120.0, 40.0]] }; + assert_eq!(last_points(&app, cmd), want, "{tool:?}"); assert!(red(&app, 70, 40) > 0.9, "{tool:?} painted the connecting line midpoint"); } } diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index ee28eaa50c8..2aa71a69156 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1273,9 +1273,9 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { }; if let Some(t) = parsed.tool { crate::tool_memory::select(app, t); - if t == crate::state::Tool::Pencil { - crate::paint_mouse::sync_tool_brush(app); - } + // The tool's own brush now, not at the next frame, so a paint command right after uses + // it (the Pencil's 1 px tip, #12200; any tool's remembered brush). + crate::paint_mouse::sync_tool_brush(app); } // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 70000aaabbe..109405eb729 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -786,6 +786,10 @@ fn tilde_held_with_the_brush_or_pencil_erases_with_its_brush() { // so the Pencil's 1 px tip (#12200) no longer reaches `(130, 130)`; check `(110, 130)` // at the stroke start instead. assert_eq!(rgba(&h, 110, 130)[3], 0.0, "{tool:?}: erased to transparency"); + // The whole drag erases, not only its first dab: a 1 px Pencil line along the 40 px drag + // clears far more pixels than one dab. + let cleared = (100..160).flat_map(|x| (120..146).map(move |y| (x, y))).filter(|&(x, y)| rgba(&h, x, y)[3] == 0.0).count(); + assert!(cleared >= 20, "{tool:?}: erased along the drag, {cleared} pixels"); assert_eq!(last_stroke(h.state())["mode"], json!("clear"), "{tool:?}"); assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some(label)); assert_eq!(h.state().ui.tool, tool, "the tool stays"); diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 102ee34cebc..5987a221c90 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -106,12 +106,9 @@ fn frame_convert_dialog(app: &mut PhotocraftApp, id: &str) -> Result Option> { if let Some(tool) = crate::tool_shortcuts::tool(id) { crate::tool_memory::select(app, tool); - // A first pick of the Pencil via shortcut must start from `fresh_brush(Tool::Pencil, ...)` - // (#12200) rather than the outgoing Brush tip, whereas other tools inherit the current - // brush tip on first pick; sync here so an immediate `paint.pencil` uses the 1 px tip. - if tool == crate::state::Tool::Pencil { - crate::paint_mouse::sync_tool_brush(app); - } + // The tool's own brush now, not at the next frame, so a paint command right after uses + // it: a first Pencil pick its 1 px tip (#12200), any other tool its remembered brush. + crate::paint_mouse::sync_tool_brush(app); return Some(Ok(json!({"tool": tool}))); } if id == "layer.frame.convert" && params.as_object().is_none_or(|o| o.is_empty()) { diff --git a/crates/ui-egui/src/pencil_reset_defaults_tests.rs b/crates/ui-egui/src/pencil_reset_defaults_tests.rs index 59847b42fa0..37ebd78b4e5 100644 --- a/crates/ui-egui/src/pencil_reset_defaults_tests.rs +++ b/crates/ui-egui/src/pencil_reset_defaults_tests.rs @@ -99,6 +99,20 @@ fn pencil_starts_with_its_own_tip_whatever_the_brush_had() { assert!(chip_shows_one(&mut a)); } +/// Selecting the Brush again by command, before a UI pass, gives back the Brush's own tip: the +/// Pencil's 1 px tip is not left for the next brush command, and the Brush's edit is not saved to +/// the Pencil. +#[test] +fn selecting_back_to_the_brush_by_command_restores_its_tip_at_once() { + let mut a = app(); + pick(&mut a, Tool::Brush); + a.session.tools.brush.size = 42.0; + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"})); + assert_pencil_tip(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.brush"})); + assert_eq!(a.session.tools.brush.size, 42.0, "the Brush's own size, before any frame"); +} + /// Verifies that a default Pencil click at `(100.2, 100.2)` paints only pixel `(100, 100)`. #[test] fn a_default_click_at_100_2_paints_only_pixel_100_100() { diff --git a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs index 8d06ca4447b..877dc1dd4f0 100644 --- a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs +++ b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs @@ -96,7 +96,7 @@ fn a_first_use_starts_with_the_tip() { #[test] fn other_tools_and_session_strokes_keep_their_tips() { - for tool in [Tool::Eraser, Tool::CloneStamp] { + for tool in [Tool::Eraser, Tool::Sponge] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); diff --git a/crates/ui-egui/tests/it/brush_reset_defaults.rs b/crates/ui-egui/tests/it/brush_reset_defaults.rs index 75d3d6a3561..ab641cd6d16 100644 --- a/crates/ui-egui/tests/it/brush_reset_defaults.rs +++ b/crates/ui-egui/tests/it/brush_reset_defaults.rs @@ -85,7 +85,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { let mut app = app(); pick(&mut app, Tool::Brush); control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); - for tool in [Tool::Eraser, Tool::CloneStamp] { + for tool in [Tool::Eraser, Tool::Sponge] { pick(&mut app, tool); assert_eq!(tip(&mut app), DEFAULT_TIP, "{tool:?}"); } @@ -93,7 +93,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { #[test] fn other_painting_tools_keep_the_default_reset_tip() { - for tool in [Tool::Eraser, Tool::CloneStamp] { + for tool in [Tool::Eraser, Tool::Sponge] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); From 6146287edaa942813c514e04d0c9df7f55103bbb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 09:13:42 -0500 Subject: [PATCH 19/63] Space-Hand view menu: a plain Esc or Enter only closes the menu; pasteboard tests (#11271) Follow-up to #11323 as asked there, on top of main's Space-Hand view menu (#11292). With the view menu open under Space, a plain Esc or Enter no longer reaches a pending crop (Esc only closes the menu); modified keys dispatch as before. Space + right-click on the pasteboard now keeps its menu open after Space is released (the menu records the tool underneath, as the view menu does). Tests for both, plus the context-menu and UI parity rows. 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/canvas_tool_menu.rs | 4 +- crates/ui-egui/src/input/hold_keys/tests.rs | 103 ++++++++++++++++++ crates/ui-egui/src/input/shortcuts.rs | 14 +++ docs/context-menu-parity.md | 2 +- docs/ui-parity.md | 1 + 5 files changed, 122 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 8917596e4b6..1d08d7ecf2b 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -979,7 +979,9 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: transform: false, pasteboard: true, anchor: None, - under: None, + // Space's Hand keeps the menu over the selected tool (#11271); a held zoom key's goes with + // the key, as before. + under: (tool == Tool::Hand && tool != app.ui.tool).then_some(app.ui.tool), text: false, type_layer: false, type_shape: None, diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 3fc3e2e0309..2609083506b 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -1152,3 +1152,106 @@ fn command_or_alt_space_right_click_opens_no_view_menu() { } } } + +/// A right-click at `p` with Space already held (the Hand over the selected tool). +fn right_click_at(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// A pending crop frame on the Crop tool, as the held-key test above sets one up. +fn with_pending_crop(h: &mut Harness<'static, PhotocraftApp>) -> [f64; 4] { + let frame = [100.0, 50.0, 300.0, 200.0]; + h.state_mut().ui.crop_rect = Some(frame); + h.state_mut().crop.default_frame = false; + h.run_steps(2); + assert!(crate::crop_ui::pending(h.state())); + frame +} + +/// The Space-Hand view menu over a pending crop (#11271): Esc closes only the menu and Enter +/// commits nothing, as under the crop's own menu; with the menu closed Esc discards the crop. +#[test] +fn space_hand_view_menu_keeps_escape_and_enter_from_the_pending_crop() { + let mut h = harness(Tool::Crop); + let frame = with_pending_crop(&mut h); + let size = h.state().session.active().map(|s| s.doc.size); + let steps = h.state().session.active().map(|s| s.history.past_len()); + let p = screen(&h, 200.0, 125.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, p); + assert!( + h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_none() && crate::canvas_tool_menu::is_view_tool(m.tool)), + "Space's Hand opens the view menu" + ); + tap(&mut h, Key::Escape, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not discarded"); + assert!(crate::crop_ui::pending(h.state())); + right_click_at(&mut h, p); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the view menu opens again"); + tap(&mut h, Key::Enter, Modifiers::NONE); + h.run_steps(2); + assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "Enter under the menu doesn't crop"); + assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "no history step"); + assert_eq!(h.state().ui.crop_rect, Some(frame)); + // Close the menu and let Space go: Esc discards the pending crop as ever. + h.state_mut().ui.canvas_tool_menu = None; + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(3); + tap(&mut h, Key::Escape, Modifiers::NONE); + h.run_steps(2); + assert!(!crate::crop_ui::pending(h.state()), "with no menu open Esc discards the crop"); +} + +/// Only a plain Esc and Enter are the view menu's (#11271): Ctrl+Alt+Enter dispatches with the menu +/// open (it leaves the menu open), and Esc with a tool key in one pass closes the menu and picks +/// the tool. +#[test] +fn space_hand_view_menu_reserves_only_plain_escape_and_enter() { + let mut h = harness(Tool::Move); + let p = screen(&h, 200.0, 125.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, p); + assert!(h.state().ui.canvas_tool_menu.is_some(), "Space's Hand opens the view menu"); + let mods = platform(Modifiers::COMMAND | Modifiers::ALT); + let steps = h.state().session.active().map(|s| s.history.past_len()); + h.input_mut() + .events + .extend([Event::ModifiersChanged(mods), Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: mods }]); + h.run_steps(2); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_some(), "a modified Enter leaves the menu open"); + assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "and changes nothing"); + h.input_mut().events.extend([ + Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + ]); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.tool, Tool::Brush, "and B in the same pass still picks the Brush"); +} + +/// Space's Hand outside the image opens the pasteboard menu, which outlives the held Space and +/// closes when the tool underneath changes (#11271). +#[test] +fn space_hand_pasteboard_menu_opens_outside_the_image_and_outlives_space() { + let mut h = harness(Tool::Move); + let outside = screen(&h, -60.0, -60.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, outside); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "Space's Hand opens the pasteboard menu outside"); + assert_eq!(h.state().ui.tool, Tool::Move, "the Move tool stays selected"); + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(3); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard menu outlives the held Space"); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "another tool selected closes it"); +} diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 158079ddf0a..4a1c72b73c2 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -534,6 +534,20 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text || m.crop.is_some()) { return false; } + // The Space-Hand view menu (the menu of a view tool opened over another tool, #11271) takes a + // plain Esc and ↵ too: they don't cancel or commit a pending crop under it. Esc closes the + // menu here and both keys are withheld from the dispatch below; every other key, modified ↵ + // and tool keys included, dispatches as usual. + if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.under.is_some() && crate::canvas_tool_menu::is_view_tool(m.tool)) { + let plain = |e: &egui::Event, k: egui::Key| matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none()); + let (esc, enter) = ctx.input(|i| (i.events.iter().any(|e| plain(e, egui::Key::Escape)), i.events.iter().any(|e| plain(e, egui::Key::Enter)))); + if esc { + app.ui.canvas_tool_menu = None; + } + if esc || enter { + ctx.input_mut(|i| i.events.retain(|e| !plain(e, egui::Key::Escape) && !plain(e, egui::Key::Enter))); + } + } let symmetry_editing = app.ui.symmetry_transform.is_some(); crate::symmetry_ui::track(app, ctx); if symmetry_editing && (app.ui.symmetry_transform.is_none() || egui::Popup::is_any_open(ctx)) { diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 1ef971ef338..6e023dd75c5 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -28,7 +28,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | | Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 | | Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | -| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | +| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022); a held zoom key does not. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | | Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas | | Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 | | Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d22ea9d20d5..d60082bfd87 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -386,5 +386,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | | 2026-11-04 | minor | Unsaved-changes prompt on macOS: ⌘D presses Don't Save, as in Photoshop (#11282); no percentage changed | +| 2026-11-11 | minor | Space's Hand: a right-click opens the view menu over any tool, as in Photoshop (#11271), and a plain Esc or Enter under it only closes the menu, leaving a pending crop alone; a held zoom key still opens none; no percentage changed | From 44b175ef7a6d5b52aa0e58065996d8d6cf90c316 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 09:14:37 -0500 Subject: [PATCH 20/63] Docs: the Space-Hand rows name only what this follow-up adds (#11271) The menu itself came with #11292; these rows now describe the Esc/Enter guard and the pasteboard menu under Space. Co-Authored-By: Claude Opus 5.5 --- docs/context-menu-parity.md | 2 +- docs/ui-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 6e023dd75c5..ca11e21ace2 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -28,7 +28,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | | Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 | | Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | -| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022); a held zoom key does not. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | +| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022), and outside the image the pasteboard menu; a plain Esc or Enter under it only closes the menu. A held zoom key opens none. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | | Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas | | Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 | | Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d60082bfd87..16d5ac270f8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -386,6 +386,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | | 2026-11-04 | minor | Unsaved-changes prompt on macOS: ⌘D presses Don't Save, as in Photoshop (#11282); no percentage changed | -| 2026-11-11 | minor | Space's Hand: a right-click opens the view menu over any tool, as in Photoshop (#11271), and a plain Esc or Enter under it only closes the menu, leaving a pending crop alone; a held zoom key still opens none; no percentage changed | +| 2026-11-11 | minor | Space's Hand view menu (#11271, after #11292): a plain Esc or Enter under it only closes the menu and leaves a pending crop alone, as a context menu does in Photoshop; outside the image Space's Hand opens the pasteboard menu over the selected tool, which stays open after Space is released; no percentage changed | From 0eafc3b674aa2574ab612e72c023cb0a6fde45fc Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 09:38:40 -0500 Subject: [PATCH 21/63] Docs: under the Space-Hand view menu Esc closes it and Enter does nothing (#11271) A plain Enter is only withheld from the dispatch; it doesn't close the menu. Both rows said "Esc or Enter only closes the menu". Co-Authored-By: Claude Opus 5.5 --- docs/context-menu-parity.md | 2 +- docs/ui-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index ca11e21ace2..f441a2bc81f 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -28,7 +28,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | | Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 | | Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | -| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022), and outside the image the pasteboard menu; a plain Esc or Enter under it only closes the menu. A held zoom key opens none. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | +| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022), and outside the image the pasteboard menu. Under it a plain Esc closes only the menu and a plain Enter does nothing, so neither reaches a pending crop. A held zoom key opens none. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | | Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas | | Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 | | Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 16d5ac270f8..487d737c6fd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -386,6 +386,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | | 2026-11-04 | minor | Unsaved-changes prompt on macOS: ⌘D presses Don't Save, as in Photoshop (#11282); no percentage changed | -| 2026-11-11 | minor | Space's Hand view menu (#11271, after #11292): a plain Esc or Enter under it only closes the menu and leaves a pending crop alone, as a context menu does in Photoshop; outside the image Space's Hand opens the pasteboard menu over the selected tool, which stays open after Space is released; no percentage changed | +| 2026-11-11 | minor | Space's Hand view menu (#11271, after #11292): a plain Esc under it closes only the menu and a plain Enter does nothing, so neither reaches a pending crop (in Photoshop, Esc with a context menu open only closes the menu); outside the image Space's Hand opens the pasteboard menu over the selected tool, which stays open after Space is released; no percentage changed | From fcd3c2966c55122f1497fbeafb64bde69a41fbf2 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:55:28 +0100 Subject: [PATCH 22/63] Shape tools: Shift draws the square or circle from the shorter side of the drag (#13222) Shift-dragging with the Ellipse tool took the longer side of the drag, so a 200 x 100 drag made a 200 x 200 circle; Photoshop makes a 100 x 100 one, and Shift+Alt centres that circle on the press. `shape_geometry` now takes the shorter side. The rule is shared by every box-drawn shape tool (the issue measured the Rectangle tool to follow the same rule), so the Rectangle and Star tests that pinned the longer side now expect the shorter one. The drag preview and Space repositioning go through `shape_bounds`, which calls the same function, so they show the same box as the result. --- crates/ui-egui/src/star_tool_tests.rs | 2 +- crates/ui-egui/src/tools/vector_ui.rs | 3 + .../vector_ui/ellipse_shift_circle_tests.rs | 76 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/shapes.rs | 3 +- crates/ui-egui/src/tools/vector_ui/tests.rs | 8 +- 5 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs diff --git a/crates/ui-egui/src/star_tool_tests.rs b/crates/ui-egui/src/star_tool_tests.rs index b83bb15d833..8a476690c87 100644 --- a/crates/ui-egui/src/star_tool_tests.rs +++ b/crates/ui-egui/src/star_tool_tests.rs @@ -109,7 +109,7 @@ fn shift_and_alt_constrain_and_centre_the_star_like_the_polygon_tool() { app.ui.tool = Tool::Star; drag(&mut app, [100.0, 100.0], [140.0, 120.0], Modifiers::SHIFT | Modifiers::ALT); match live_shape(&app) { - Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [60.0, 60.0, 80.0, 80.0], "a square box drawn from the centre"), + Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [80.0, 80.0, 40.0, 40.0], "a square box of the shorter side drawn from the centre (#13222)"), other => panic!("a live star shape, got {other:?}"), } } diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 54fe6527ce4..382947e5de5 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -231,6 +231,9 @@ mod delete_anchor_options_bar_tests; #[cfg(test)] mod pen_enter_deselects_tests; +#[cfg(test)] +mod ellipse_shift_circle_tests; + pub(crate) use pen::freeform_locked_shape; /// Where a Pen draft goes, captured at its first anchor. diff --git a/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs new file mode 100644 index 00000000000..d57cb42eea5 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs @@ -0,0 +1,76 @@ +//! #13222: ⇧ while dragging with the Ellipse tool makes a circle from the shorter side of the +//! drag, as in Photoshop, not the longer one; ⇧⌥ centres that circle on the press. The drag +//! preview (`shape_bounds`) shows the same box as the layer the drag makes. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use super::shape_bounds; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::EllipseShape; + app +} + +/// A drag pressed without modifiers, with `mods` pressed after the start (so the press picks no +/// path operation or eyedropper). +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + 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); +} + +/// The active layer's live ellipse `[x, y, w, h]`. +fn ellipse_rect(app: &PhotocraftApp) -> [f64; 4] { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(s) => match &s.live { + Some(LiveShape::Ellipse { rect }) => *rect, + other => panic!("a live ellipse, got {other:?}"), + }, + _ => panic!("a shape layer"), + } +} + +fn preview(app: &PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) -> [f64; 4] { + shape_bounds(&app.ui.tool_options, Tool::EllipseShape, from, to, mods).expect("a box") +} + +#[test] +fn shift_makes_a_circle_from_the_shorter_side() { + let mut app = app(); + drag(&mut app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT); + assert_eq!(ellipse_rect(&app), [400.0, 300.0, 100.0, 100.0]); + assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT), [400.0, 300.0, 500.0, 400.0]); +} + +#[test] +fn shift_uses_the_shorter_side_when_the_drag_is_taller_than_wide() { + let mut app = app(); + drag(&mut app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT); + assert_eq!(ellipse_rect(&app), [400.0, 300.0, 50.0, 50.0]); + assert_eq!(preview(&app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT), [400.0, 300.0, 450.0, 350.0]); +} + +#[test] +fn shift_alt_centres_the_shorter_side_circle_on_the_press() { + let mut app = app(); + let mods = Modifiers::SHIFT | Modifiers::ALT; + drag(&mut app, [400.0, 300.0], [600.0, 400.0], mods); + assert_eq!(ellipse_rect(&app), [300.0, 200.0, 200.0, 200.0]); + assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], mods), [300.0, 200.0, 500.0, 400.0]); +} + +#[test] +fn shift_keeps_the_drag_direction_up_and_left() { + let app = app(); + assert_eq!(preview(&app, [400.0, 300.0], [200.0, 200.0], Modifiers::SHIFT), [300.0, 200.0, 400.0, 300.0]); +} diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 0776227d04b..83fc490ee33 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -103,7 +103,8 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { - let m = w.abs().max(h.abs()); + // The shorter side of the drag sets the square, as in Photoshop (#13222). + let m = w.abs().min(h.abs()); (w, h) = (m * w.signum(), m * h.signum()); } let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) }; diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index b7d19a4d5fc..3b85a4757e1 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -491,7 +491,7 @@ fn shape_drag_creates_layers_with_modifiers() { finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT); let st = app.session.active().unwrap(); let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert_eq!((b.width(), b.height()), (50, 50), "shift = square"); + assert_eq!((b.width(), b.height()), (20, 20), "shift = square of the shorter side (#13222)"); finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT); let st = app.session.active().unwrap(); let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); @@ -693,9 +693,9 @@ fn shift_pressed_during_a_shape_drag_constrains_it() { let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); assert!(matches!(l.content, LayerContent::Shape(_)), "{tool:?} ({sides} sides): a shape layer"); let b = l.surface().unwrap().content_bounds(); - // The drag is 60 × 30; constrained, the shape's box is 60 × 60 (a hexagon is narrower - // than its box, so the height tells). - assert!(b.height().abs_diff(60) <= 1 && b.width() <= 61, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); + // The drag is 60 × 30; constrained, the shape's box is 30 × 30, the shorter side (#13222) + // (a hexagon is narrower than its box, so the height tells). + assert!(b.height().abs_diff(30) <= 1 && b.width() <= 31, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); } } From 7132f38cbe91ac619cfa186a3b4d25a6b15843a0 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:57:55 +0100 Subject: [PATCH 23/63] fix(ui): Polygon Sides alerts when a typed value is past 3-100 (#13304) The Sides field in the Polygon tool's options bar clamped a typed 0, 2 or 101 silently. It now uses the whole-number alerting field: a value typed past 3..100 inserts the closest one and, once the field is left, shows "An integer between 3 and 100 is required. Closest value inserted." with OK. A scrub past either end still stops there without an alert. --- .../src/tools/polygon_sides_alert_tests.rs | 116 ++++++++++++++++++ crates/ui-egui/src/tools/shape_options.rs | 39 +++++- 2 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/tools/polygon_sides_alert_tests.rs diff --git a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs new file mode 100644 index 00000000000..ffeac2092ca --- /dev/null +++ b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs @@ -0,0 +1,116 @@ +//! #13304: the Polygon tool's Sides takes whole numbers 3..100; a value typed past the range becomes +//! the closest one and, once the field is left, the reference's "Closest value inserted" alert with +//! OK says so. A scrub past either end stops there without one. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::SIDES_RANGE_ALERT; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// The options bar with the Polygon tool active. +fn bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::Polygon; + 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 +} + +/// Clicks into Sides and gives back where it sits. +fn click_sides(h: &mut Harness<'static, PhotocraftApp>) -> egui::Rect { + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Sides:")).expect("the Sides field"); + let rect = field.rect(); + field.click(); + h.run_steps(1); + rect +} + +/// Types `text` into Sides, then Tabs out of it. +fn type_sides(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + click_sides(h); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// OK on the alert, as `ui.dialog.confirm` presses it (this harness draws only the bar). +fn ok(h: &mut Harness<'static, PhotocraftApp>) { + let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); +} + +fn sides(h: &Harness<'static, PhotocraftApp>) -> u32 { + h.state().ui.tool_options.polygon_sides +} + +#[test] +fn sides_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("0", 3), ("2", 3), ("-5", 3), ("101", 100), ("1000", 100)] { + let mut h = bar(); + type_sides(&mut h, typed); + assert_eq!(sides(&h), want, "{typed}"); + assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{typed}: one alert"); + ok(&mut h); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert_eq!(sides(&h), want, "{typed}: the closest value is kept"); + } +} + +#[test] +fn sides_in_range_are_stored_without_an_alert() { + for (typed, want) in [("3", 3), ("7", 7), ("100", 100)] { + let mut h = bar(); + type_sides(&mut h, typed); + assert_eq!(sides(&h), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn sides_that_are_no_number_keep_the_value_without_an_alert() { + let mut h = bar(); + type_sides(&mut h, "abc"); + assert_eq!(sides(&h), 5, "the previous value stays"); + assert!(alerts(&h).is_empty(), "no number, no alert"); +} + +#[test] +fn a_caption_scrub_past_either_end_does_not_alert() { + for (start, dx, want) in [("95", 50.0, 100), ("8", -50.0, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + // The field keeps the keyboard while its caption is scrubbed past the end. + let rect = click_sides(&mut h); + // The caption sits just left of the field. + let from = egui::pos2(rect.left() - 20.0, rect.center().y); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(from + vec2(dx * k as f32, 0.0))); + h.run_steps(1); + } + let to = from + vec2(dx * 6.0, 0.0); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the scrub reached the end"); + assert!(alerts(&h).is_empty(), "{start}: a scrub stops at the end without an alert"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index 8aabe459229..848ed0316e9 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -101,6 +101,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool o.stroke_width = enabled_stroke_width(o.stroke_width); } } + let mut sides_alert = false; match tool { Tool::Rectangle => { crate::widgets::vline(ui, 22.0); @@ -117,11 +118,9 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool } Tool::Polygon => { crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Sides:")); - let mut s = o.polygon_sides as f32; - if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() { - o.polygon_sides = s.round().clamp(3.0, 100.0) as u32; - } + let label = tl!("Sides:"); + lbl(ui, label); + sides_alert = sides_field(ui, label, &mut o.polygon_sides); } Tool::Line => { crate::widgets::vline(ui, 22.0); @@ -196,8 +195,38 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool if let Some(rgb) = recent { crate::paint_picker::remember(app, rgb); } + if sides_alert { + sides_range_alert(app); + } } +/// The Polygon tool's Sides: whole numbers 3..100. Returns true once the field is left with a +/// value typed past them, so the caller shows [`SIDES_RANGE_ALERT`] (#13304). +fn sides_field(ui: &mut egui::Ui, label: &str, sides: &mut u32) -> bool { + let mut s = *sides as f32; + let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut s, 3.0..=100.0, "", 48.0); + if r.changed() { + *sides = s.round().clamp(3.0, 100.0) as u32; + } + out_of_range +} + +/// The reference's alert for a Polygon Sides value typed past 3..100 (#13304). +pub(crate) const SIDES_RANGE_ALERT: &str = "An integer between 3 and 100 is required. Closest value inserted."; + +/// Shows [`SIDES_RANGE_ALERT`] as a modal with OK, once even if more than one pass asks. +fn sides_range_alert(app: &mut PhotocraftApp) { + let message = tl!(SIDES_RANGE_ALERT).to_owned(); + let shown = app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} + +#[cfg(test)] +#[path = "polygon_sides_alert_tests.rs"] +mod polygon_sides_alert_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 bc5ee33abdbdcd73d859e0581417d06af81e3511 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:30:19 +0300 Subject: [PATCH 24/63] Remove tool: reorder options bar checkboxes and add their tooltips The Remove tool's options bar now reads Sample all layers, Remove after each stroke, Create new layer, left to right, each with the reference tooltip. Defaults, the greyed Create new layer on a mask or channel target, and the options sent with a removal are unchanged. --- crates/ui-egui/src/tools/retouch_ui.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 68abe3dfae2..144161dfe29 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -914,11 +914,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::checkbox(ui, &mut o.sample_all.spot_healing, tl!("Sample All Layers")); } Tool::Remove => { - // Photoshop's options bar: Sample All Layers, Create a new layer, Remove after each - // stroke; with strokes waiting, ✓ applies them and ⊘ drops them. - crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample All Layers")); - ui.add_enabled_ui(composite, |ui| crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create a new layer"))); - crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke")); + // Photoshop's options bar (#12546): Sample all layers, Remove after each stroke, Create + // new layer; with strokes waiting, ✓ applies them and ⊘ drops them. + crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample all layers")).on_hover_text(tl!("Sample content from all visible layers")); + crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke")) + .on_hover_text(tl!("Remove area after a single stroke")); + ui.add_enabled_ui(composite, |ui| { + crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create new layer")).on_hover_text(tl!("Create new layer with results")); + }); if !app.remove_pending.is_empty() { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::primary_button(ui, "✓", 32.0) From 75316d2bd402d06ad80ff529228609625f5c8791 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:30:19 +0300 Subject: [PATCH 25/63] Test the Remove tool options bar labels, order and tooltips Reuse the Burn bar test's harness helpers rather than copying them. --- crates/ui-egui/src/burn_bar_tooltips_tests.rs | 6 +- .../tools/remove_options_bar_labels_tests.rs | 104 ++++++++++++++++++ crates/ui-egui/src/tools/retouch_ui.rs | 4 + 3 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs diff --git a/crates/ui-egui/src/burn_bar_tooltips_tests.rs b/crates/ui-egui/src/burn_bar_tooltips_tests.rs index b000418ab3f..3bc893fdb2b 100644 --- a/crates/ui-egui/src/burn_bar_tooltips_tests.rs +++ b/crates/ui-egui/src/burn_bar_tooltips_tests.rs @@ -17,7 +17,7 @@ const CONTROLS: [(Role, &str, &str); 3] = [ ]; /// Build a settled options-bar fixture with the requested tool, locale, viewport and scale. -fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> { +pub(super) fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); app.run("prefs.set", json!({"path": "workspace.enableNarrowOptionsBar", "value": narrow})).unwrap(); @@ -39,7 +39,7 @@ fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness< } /// Find the named control by its accessibility role without matching tooltip labels. -fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> { +pub(super) fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> { h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("missing {role:?} {label:?}")) } @@ -54,7 +54,7 @@ fn control_name(h: &Harness<'static, PhotocraftApp>, lang: Lang, role: Role, lab } /// Scroll a control into view, wait for its hover delay and assert the visible tooltip text. -fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) { +pub(super) fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) { control(h, role, label).scroll_to_me(); h.run_steps(4); let rect = control(h, role, label).rect(); diff --git a/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs b/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs new file mode 100644 index 00000000000..9a7587a6918 --- /dev/null +++ b/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs @@ -0,0 +1,104 @@ +//! #12546: the Remove tool's checkboxes read "Sample all layers", "Remove after each stroke", +//! "Create new layer", left to right, each with the reference tooltip. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::burn_bar_tooltips_tests::{bar, control, hover}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::i18n::Lang; +use crate::state::Tool; + +const BOXES: [(&str, &str); 3] = [ + ("Sample all layers", "Sample content from all visible layers"), + ("Remove after each stroke", "Remove area after a single stroke"), + ("Create new layer", "Create new layer with results"), +]; + +fn remove_bar() -> Harness<'static, PhotocraftApp> { + bar(Tool::Remove, Lang::EN, 1600.0, 1.0, false) +} + +fn checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + control(h, Role::CheckBox, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn the_checkboxes_read_the_reference_labels_left_to_right() { + let h = remove_bar(); + let mut boxes: Vec<(f32, String)> = + h.query_all_by_role(Role::CheckBox).map(|n| (n.rect().left(), n.accesskit_node().label().unwrap_or_default())).collect(); + boxes.sort_by(|a, b| a.0.total_cmp(&b.0)); + let labels: Vec<&str> = boxes.iter().map(|(_, l)| l.as_str()).collect(); + assert_eq!(labels, BOXES.map(|(label, _)| label)); +} + +#[test] +fn hovering_each_checkbox_shows_its_tooltip() { + for (label, tip) in BOXES { + let mut h = remove_bar(); + assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover"); + let before = h.state().ui.tool_options.clone(); + hover(&mut h, Role::CheckBox, label, tip); + let o = &h.state().ui.tool_options; + assert_eq!( + (o.sample_all.remove, o.remove_after_each_stroke, o.remove_new_layer), + (before.sample_all.remove, before.remove_after_each_stroke, before.remove_new_layer) + ); + } +} + +#[test] +fn defaults_show_only_remove_after_each_stroke_on_and_reset_tool_restores_them() { + let mut h = remove_bar(); + let defaults = [false, true, false]; + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults); + for (label, _) in BOXES { + control(&h, Role::CheckBox, label).click(); + h.run_steps(2); + } + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults.map(|on| !on), "each click toggles its own box"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults); +} + +#[test] +fn create_new_layer_greys_when_a_mask_or_colour_subset_is_targeted() { + let mut h = remove_bar(); + assert!(!control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled()); + let app = h.state_mut(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + h.run_steps(2); + assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a targeted mask greys it"); + let app = h.state_mut(); + app.ui.mask_target = false; + app.run("channel.target", json!({"colors": [0, 2]})).unwrap(); + h.run_steps(2); + assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a colour subset greys it"); + for (label, _) in &BOXES[..2] { + assert!(!control(&h, Role::CheckBox, label).accesskit_node().is_disabled(), "{label} stays enabled"); + } +} + +#[test] +fn the_boxes_ticked_on_the_bar_reach_the_removal_options() { + let mut h = remove_bar(); + for label in ["Sample all layers", "Create new layer"] { + control(&h, Role::CheckBox, label).click(); + h.run_steps(2); + } + let app = h.state_mut(); + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().cloned().unwrap(); + assert_eq!((id.as_str(), p["sampleAllLayers"].as_bool(), p["newLayer"].as_bool()), ("paint.remove", Some(true), Some(true))); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 144161dfe29..aa8b594cd52 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -1233,3 +1233,7 @@ mod healing_indexed_alert_tests; #[cfg(test)] #[path = "../clone_stamp_no_source_alert_tests.rs"] mod clone_stamp_no_source_alert_tests; + +#[cfg(test)] +#[path = "remove_options_bar_labels_tests.rs"] +mod remove_options_bar_labels_tests; From 82b5d853fd35473e2fae161251a12384d01b4d1d Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:26:01 +0300 Subject: [PATCH 26/63] Paint Bucket cursor: arrow at the bucket's top left, hotspot on its tip With Standard Other Cursors the bucket now carries a small arrow whose tip is the hotspot, as in the reference application, instead of a crosshair at its lower right. Precise Other Cursors, Caps Lock, Alt and Ctrl keep their cursors. --- crates/ui-egui/src/canvas/tool_cursor.rs | 2 +- .../ui-egui/src/canvas/tool_cursor/bucket.rs | 91 ++++++++++++++----- .../ui-egui/src/canvas/tool_cursor/tests.rs | 36 ++------ crates/ui-egui/src/input_tests.rs | 6 +- 4 files changed, 80 insertions(+), 55 deletions(-) diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 42b3e622dfb..f69e2c61a53 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -149,7 +149,7 @@ pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorI CursorIcon::Default } -/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image. +/// The bucket artwork and the arrow on its fill target move as one native cursor or painted image. pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result { bucket::show(painter, at) } diff --git a/crates/ui-egui/src/canvas/tool_cursor/bucket.rs b/crates/ui-egui/src/canvas/tool_cursor/bucket.rs index 41d37ea1f34..091326303b7 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/bucket.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/bucket.rs @@ -1,11 +1,23 @@ -//! One image owns the bucket artwork and its lower-right fill target. Splitting those between -//! the frame and the OS pointer lets them drift apart whenever a frame arrives after the pointer. +//! One image owns the bucket artwork and the arrow at its top left whose tip is the fill target +//! (#12539). Splitting those between the frame and the OS pointer lets them drift apart whenever a +//! frame arrives after the pointer. use super::{CursorIcon, CustomCursorImage, Painter, Pos2, native, native_scale}; use std::sync::Arc; const SIZE: f32 = 22.0; -const HOT: egui::Vec2 = egui::vec2(26.0 / 24.0 * SIZE, 25.0 / 24.0 * SIZE); +/// The bucket icon's top-left corner, in points from the arrow tip. +const ICON: egui::Vec2 = egui::vec2(6.0, 6.0); +/// Our own small arrow, in points from its tip: the hotspot, so a click fills the pixel under it. +const ARROW: [egui::Vec2; 7] = [ + egui::vec2(0.0, 0.0), + egui::vec2(0.0, 10.5), + egui::vec2(2.6, 8.2), + egui::vec2(4.3, 11.8), + egui::vec2(5.9, 11.1), + egui::vec2(4.2, 7.5), + egui::vec2(7.5, 7.5), +]; #[derive(Clone)] struct Cached { @@ -58,40 +70,75 @@ pub(super) fn rasterize(scale: f32) -> Result { if !scale.is_finite() || scale <= 0.0 { return Err(format!("Invalid Paint Bucket cursor scale: {scale}")); } - // Round the hotspot itself, rather than the box, so it always lands on an exact bitmap pixel. - // Keep one logical pixel of the existing icon halo and its antialiasing fringe inside the box. - let margin = (scale + 1.0).ceil(); - let hot = [(HOT.x * scale).round() + margin, (HOT.y * scale).round() + margin]; - let cross = super::rasterize(&super::STANDARD_CROSSHAIR, scale).ok_or_else(|| format!("Paint Bucket crosshair does not fit a cursor at scale {scale}"))?; - let size = [hot[0] + f32::from(cross.size[0] - cross.hotspot[0]), hot[1] + f32::from(cross.size[1] - cross.hotspot[1])]; + // The arrow's halo reaches one halo width above and left of its tip, so the tip lands on + // (1, 1) at 1x, as in the reference cursor. The bucket's halo and fringe get room below right. + let halo = scale.round(); + let side = (SIZE * scale).round(); + let icon_at = (ICON * scale).round() + egui::Vec2::splat(halo); + let size = [icon_at.x + side + halo + 1.0, icon_at.y + side + halo + 1.0]; if size.iter().any(|side| !side.is_finite() || *side > f32::from(super::MAX_SIDE)) { return Err(format!("Paint Bucket cursor does not fit the platform bitmap limit at scale {scale}")); } let size = size.map(|side| side as u16); - let hotspot = hot.map(|coord| coord as u16); + let hotspot = [halo as u16; 2]; let mut pixels = vec![egui::Color32::TRANSPARENT; usize::from(size[0]) * usize::from(size[1])]; - let icon = crate::icons::rasterize("paint-bucket", (SIZE * scale).round() as u32)?; - let margin = margin as i32; - let halo = scale.round() as i32; - // The same eight dark halo offsets and white SVG as icons::cursor, now in the image that - // also owns the crosshair. Color32 keeps composition premultiplied until the final upload. - for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)] { + let icon = crate::icons::rasterize("paint-bucket", side as u32)?; + let halo = halo as i32; + let (arrow_width, arrow) = arrow_mask(scale); + // The same eight dark halo offsets and white SVG as icons::cursor, then the arrow on top of + // the bucket: black on a white halo. Color32 keeps composition premultiplied until the upload. + const OFFSETS: [(i32, i32); 9] = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)]; + for (dx, dy) in OFFSETS { for (i, pixel) in icon.pixels.iter().enumerate() { - let x = (i % icon.size[0]) as i32 + margin + dx * halo; - let y = (i / icon.size[0]) as i32 + margin + dy * halo; + let x = (i % icon.size[0]) as i32 + icon_at.x as i32 + dx * halo; + let y = (i / icon.size[0]) as i32 + icon_at.y as i32 + dy * halo; let color = if dx == 0 && dy == 0 { *pixel } else { egui::Color32::from_black_alpha((f32::from(pixel.a()) * 200.0 / 255.0).round() as u8) }; over(&mut pixels, size, x, y, color); } } - for (i, pixel) in cross.rgba.as_chunks::<4>().0.iter().enumerate() { - let x = (i % usize::from(cross.size[0])) as i32 + i32::from(hotspot[0]) - i32::from(cross.hotspot[0]); - let y = (i / usize::from(cross.size[0])) as i32 + i32::from(hotspot[1]) - i32::from(cross.hotspot[1]); - over(&mut pixels, size, x, y, egui::Color32::from_rgba_unmultiplied(pixel[0], pixel[1], pixel[2], pixel[3])); + for (dx, dy) in OFFSETS { + for (i, alpha) in arrow.iter().enumerate() { + let x = (i % arrow_width) as i32 + i32::from(hotspot[0]) + dx * halo; + let y = (i / arrow_width) as i32 + i32::from(hotspot[1]) + dy * halo; + let color = if dx == 0 && dy == 0 { egui::Color32::from_black_alpha(*alpha) } else { egui::Color32::from_white_alpha(*alpha) }; + over(&mut pixels, size, x, y, color); + } } let rgba = pixels.into_iter().flat_map(|pixel| pixel.to_srgba_unmultiplied()).collect::>(); Ok(CustomCursorImage { rgba: Arc::from(rgba), size, hotspot }) } +/// The arrow's coverage per physical pixel, its tip at the centre of pixel (0, 0), the texel +/// centre the painted fallback puts on the pointer: the mask's width and its alpha values, row by row. +fn arrow_mask(scale: f32) -> (usize, Vec) { + const SAMPLES: u16 = 4; + let extent = ARROW.iter().fold(egui::Vec2::ZERO, |extent, point| extent.max(*point)) * scale + egui::Vec2::splat(0.5); + let (width, height) = (extent.x.ceil() as usize, extent.y.ceil() as usize); + let mut mask = Vec::with_capacity(width * height); + for y in 0..height { + for x in 0..width { + let mut hits = 0_u16; + for sy in 0..SAMPLES { + for sx in 0..SAMPLES { + let sample = egui::vec2(x as f32 + (f32::from(sx) + 0.5) / f32::from(SAMPLES), y as f32 + (f32::from(sy) + 0.5) / f32::from(SAMPLES)); + hits += u16::from(inside((sample - egui::Vec2::splat(0.5)) / scale, &ARROW)); + } + } + mask.push((f32::from(hits) * 255.0 / f32::from(SAMPLES * SAMPLES)).round() as u8); + } + } + (width, mask) +} + +/// Even-odd point in polygon. +fn inside(point: egui::Vec2, polygon: &[egui::Vec2]) -> bool { + let next = polygon.iter().skip(1).chain(polygon.first()); + polygon.iter().zip(next).fold(false, |inside, (a, b)| { + let crosses = (a.y > point.y) != (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x; + inside != crosses + }) +} + fn over(pixels: &mut [egui::Color32], size: [u16; 2], x: i32, y: i32, foreground: egui::Color32) { if x < 0 || y < 0 || x >= i32::from(size[0]) || y >= i32::from(size[1]) { return; diff --git a/crates/ui-egui/src/canvas/tool_cursor/tests.rs b/crates/ui-egui/src/canvas/tool_cursor/tests.rs index e9f469c858d..5246cbe1bc1 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/tests.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/tests.rs @@ -10,11 +10,6 @@ fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 { image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3] } -fn rgba_at(image: &CustomCursorImage, x: u16, y: u16) -> [u8; 4] { - let offset = (usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4; - image.rgba[offset..offset + 4].try_into().unwrap() -} - fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { let mut output = ctx.run_ui(Default::default(), draw); // These tests inspect cursor output without a renderer. @@ -67,36 +62,19 @@ fn precise_and_tip_centre_crosshairs_have_distinct_hotspots() { } #[test] -fn bucket_bitmap_keeps_the_svg_above_left_of_its_exact_crosshair_hotspot() { - for scale in [1.0, 1.25, 2.0] { +fn bucket_bitmap_keeps_the_svg_below_right_of_its_arrow_tip_hotspot() { + for (scale, hotspot) in [(1.0, [1, 1]), (1.25, [1, 1]), (2.0, [2, 2])] { let image = super::bucket::rasterize(scale).unwrap(); - let expected_x = (26.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil(); - let expected_y = (25.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil(); - assert_eq!(image.hotspot, [expected_x as u16, expected_y as u16], "bucket box target at {scale}x"); - let gradient_cross = rasterize(&STANDARD_CROSSHAIR, scale).unwrap(); - assert_eq!(alpha(&image, image.hotspot[0], image.hotspot[1]), 0, "Gradient-style open center at {scale}x"); + assert_eq!(image.hotspot, hotspot, "the arrow tip sits one halo in from the top left at {scale}x"); + assert!(alpha(&image, image.hotspot[0], image.hotspot[1]) > 128, "the antialiased tip itself is drawn at {scale}x"); let side = usize::from(image.size[0]); let has_bucket_art = image.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, p)| { let x = (i % side) as u16; let y = (i / side) as u16; - p[3] > 200 && x + 2 < image.hotspot[0] && y + 2 < image.hotspot[1] + p[0] > 200 && p[3] > 200 && x > image.hotspot[0] + 10 && y > image.hotspot[1] + 10 }); - assert!(has_bucket_art, "opaque bucket art remains above-left of the hotspot at {scale}x"); - - for arm in [1, 5, 8] { - let arm = (arm as f32 * scale).round() as u16; - assert_eq!( - rgba_at(&image, image.hotspot[0] + arm, image.hotspot[1]), - rgba_at(&gradient_cross, gradient_cross.hotspot[0] + arm, gradient_cross.hotspot[1]), - "right arm matches the Gradient crosshair at {scale}x" - ); - assert_eq!( - rgba_at(&image, image.hotspot[0], image.hotspot[1] + arm), - rgba_at(&gradient_cross, gradient_cross.hotspot[0], gradient_cross.hotspot[1] + arm), - "lower arm matches the Gradient crosshair at {scale}x" - ); - } + assert!(has_bucket_art, "opaque white bucket art below-right of the hotspot at {scale}x"); } } @@ -196,7 +174,7 @@ fn scaled_wayland_bucket_uses_one_cached_image_area_without_a_split_crosshair() let (first, first_images) = run(1.25, first_at); assert!(first.platform_output.cursor_image.is_none(), "scaled Wayland does not send a bitmap to winit"); assert_eq!(first.platform_output.cursor_icon, CursorIcon::None, "the image replaces the system arrow"); - assert_eq!(first_images.len(), 1, "bucket and fill crosshair are one Image primitive"); + assert_eq!(first_images.len(), 1, "bucket and arrow are one Image primitive"); let image = super::bucket::rasterize(1.25).unwrap(); let image_bounds = first_images[0].1; let image_hotspot = image_bounds.min + egui::vec2((f32::from(image.hotspot[0]) + 0.5) / 1.25, (f32::from(image.hotspot[1]) + 0.5) / 1.25); diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 54719f1c143..dd9ed44cde0 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -1113,15 +1113,15 @@ fn paint_bucket_shows_a_bucket_cursor() { let cursor = output.platform_output.cursor_image.as_ref().expect("native root viewport uses the unified bucket bitmap"); let [hot_x, hot_y] = cursor.hotspot; let hot_pixel = (usize::from(hot_y) * usize::from(cursor.size[0]) + usize::from(hot_x)) * 4 + 3; - assert_eq!(cursor.rgba[hot_pixel], 0, "the Gradient-style crosshair leaves its exact bitmap hotspot open"); + assert!(cursor.rgba[hot_pixel] > 128, "the arrow tip is drawn on the exact bitmap hotspot"); let side = usize::from(cursor.size[0]); assert!( cursor.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, pixel)| { let x = (i % side) as u16; let y = (i / side) as u16; - pixel[3] > 200 && x + 2 < hot_x && y + 2 < hot_y + pixel[3] > 200 && x > hot_x + 2 && y > hot_y + 2 }), - "the bucket artwork is opaque above-left of the same hotspot" + "the bucket artwork is opaque below-right of the same hotspot" ); assert!(!cursor_area_visible(&h, "pc-icon-cursor"), "native cursor has no frame-painted icon overlay"); assert!(!cursor_area_visible(&h, "pc-tool-cursor"), "native cursor does not create a painted cursor Area"); From c7988223403b636be5dbaf041c13731d00ee1ff3 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:26:01 +0300 Subject: [PATCH 27/63] Test the Paint Bucket cursor through the canvas --- crates/ui-egui/src/canvas/cursors.rs | 4 + .../src/canvas/paint_bucket_cursor_tests.rs | 103 ++++++++++++++++++ .../ui-egui/src/canvas/remove_cursor_tests.rs | 8 +- 3 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index 5d1934039c8..886b53a8915 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -424,3 +424,7 @@ mod background_eraser_alt_click_tests; #[cfg(test)] #[path = "remove_cursor_tests.rs"] mod remove_cursor_tests; + +#[cfg(test)] +#[path = "paint_bucket_cursor_tests.rs"] +mod paint_bucket_cursor_tests; diff --git a/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs b/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs new file mode 100644 index 00000000000..cff285afc2c --- /dev/null +++ b/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs @@ -0,0 +1,103 @@ +//! The Paint Bucket cursor (#12539): with Standard Other Cursors it is the bucket with a small +//! arrow at its top left, the hotspot on the arrow tip, and a click fills the pixel under that tip. +//! Precise Other Cursors and Caps Lock keep the crosshair; ⌥ and ⌘ keep the Eyedropper and Move +//! cursors. Tests drive the real canvas (`document_area`) and read the OS cursor bitmap it sets. + +use egui::{CursorIcon, Modifiers}; +use egui_kittest::Harness; +use serde_json::json; + +use super::remove_cursor_tests::{Cursor, cursor, harness, set_pref}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The cursor with `mods` held over the canvas centre. +fn cursor_with(h: &mut Harness<'_, PhotocraftApp>, mods: Modifiers) -> Cursor { + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(3); + cursor(h) +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_standard_cursor_is_the_bucket_with_the_arrow_tip_on_the_hotspot() { + let h = harness(Tool::PaintBucket); + let (icon, image) = cursor(&h); + assert_eq!(icon, CursorIcon::Crosshair, "the OS bitmap keeps its visible fallback"); + let (size, [x, y], rgba) = image.expect("the Paint Bucket's OS cursor bitmap"); + assert_eq!([x, y], [1, 1], "the hotspot is the arrow tip at the bitmap's top left"); + let at = |x: u16, y: u16| { + let i = (usize::from(y) * usize::from(size[0]) + usize::from(x)) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + // The tip sits on the hotspot texel's centre, so that pixel is antialiased, not solid. + assert!(at(x, y)[3] > 128, "the tip itself is drawn: no open crosshair centre under the pointer"); + let body = at(x + 1, y + 4); + assert!(body[3] > 230 && body[0] < 40, "a black arrow runs down from the tip: {body:?}"); + let bucket = (0..size[1]).flat_map(|row| (0..size[0]).map(move |col| (col, row))).any(|(col, row)| { + let p = at(col, row); + col > x + 10 && row > y + 10 && p[0] > 200 && p[3] > 200 + }); + assert!(bucket, "the white bucket art sits below right of the arrow"); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_click_fills_the_pixel_under_the_arrow_tip() { + let mut h = harness(Tool::PaintBucket); + let p = h.state().last_canvas_rect.center(); + let (x, y) = crate::panels::info::hover_pixel(h.state()).expect("the pointer is over the image"); + // Black left of and above the pointer's pixel: a fill there stops at the edges, a fill one + // pixel off to the left or up would turn the black red. + let app = h.state_mut(); + for rect in [[0, 0, x, 300], [0, 0, 400, y]] { + app.run("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + h.run_steps(2); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + assert_eq!(pixel(h.state(), x, y), [255, 0, 0], "the pixel under the tip is filled"); + assert_eq!(pixel(h.state(), x - 1, y), [0, 0, 0], "the pixel left of it is not"); + assert_eq!(pixel(h.state(), x, y - 1), [0, 0, 0], "the pixel above it is not"); +} + +#[test] +fn precise_other_cursors_and_caps_lock_keep_the_crosshair() { + let mut h = harness(Tool::PaintBucket); + let standard = cursor(&h); + set_pref(&mut h, "cursors.other", json!("precise")); + let precise = cursor(&h); + assert_eq!(precise.0, CursorIcon::Crosshair, "Precise: the crosshair"); + assert_ne!(precise, standard, "Precise: not the bucket"); + set_pref(&mut h, "cursors.other", json!("standard")); + h.state_mut().caps_lock = true; + h.run_steps(2); + assert_eq!(cursor(&h), precise, "Caps Lock: the same crosshair"); +} + +#[test] +fn alt_and_command_keep_the_eyedropper_and_move_cursors() { + let mut bucket = harness(Tool::PaintBucket); + let standard = cursor(&bucket); + let eyedropper = cursor(&harness(Tool::Eyedropper)); + let alt = cursor_with(&mut bucket, Modifiers::ALT); + assert_eq!(alt, eyedropper, "⌥: the Eyedropper cursor"); + assert_ne!(alt, standard); + let mv = cursor_with(&mut harness(Tool::Move), Modifiers::NONE); + let command = cursor_with(&mut bucket, Modifiers::COMMAND); + assert_eq!(command, mv, "⌘: the Move cursor"); + assert_ne!(command, standard); +} diff --git a/crates/ui-egui/src/canvas/remove_cursor_tests.rs b/crates/ui-egui/src/canvas/remove_cursor_tests.rs index cc4670e5904..8373d7fadec 100644 --- a/crates/ui-egui/src/canvas/remove_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/remove_cursor_tests.rs @@ -11,7 +11,7 @@ use crate::PhotocraftApp; use crate::state::Tool; /// The canvas at 100 % with `tool` and a 40 px tip, the pointer over its centre. -fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { +pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.ui.tool = tool; @@ -40,7 +40,7 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { h } -fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) { +pub(super) fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) { h.state_mut().run("prefs.set", json!({"path": path, "value": value})).unwrap(); h.run_steps(2); } @@ -65,10 +65,10 @@ fn circle_drawn(h: &Harness<'_, PhotocraftApp>) -> bool { } /// A cursor icon, and its bitmap's size, hotspot and pixels. -type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec)>); +pub(super) type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec)>); /// The cursor the canvas asks for this frame. -fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor { +pub(super) fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor { let out = h.output(); let image = out.platform_output.cursor_image.as_ref().map(|i| (i.size, i.hotspot, i.rgba.to_vec())); (out.platform_output.cursor_icon, image) From 65a27c2a5f0d992e00c17e01659b50340b4a1e9b Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:07:23 +0300 Subject: [PATCH 28/63] Paint Bucket: a plain right-click on the image opens its Mode list As in the reference application, the list opens at the pointer with no entry checked; Shift+right-click keeps checking the current mode and the pasteboard keeps its colour menu. ui.inspect reports the same check marks. --- crates/ui-egui/src/brush_mode_menu.rs | 38 +++++++++++++++++------- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/paint_mouse.rs | 19 +++++++----- crates/ui-egui/src/control/inspect.rs | 3 +- 4 files changed, 42 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 6cb79575087..24fd114fb2e 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -189,15 +189,19 @@ pub(crate) fn is_gesture(tool: Tool, mods: egui::Modifiers) -> bool { mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd && !items(tool).is_empty() } -/// Does a right-click with `mods` open the menu? The Shift gesture for every tool that has one, -/// and a plain right-click with the Eraser in Block mode, where the Brush Preset picker's Size and -/// Hardness mean nothing (#11937, as in the reference application). -/// A plain right-click opens it only where it would otherwise open the picker: with the Erase -/// preference it still erases. -pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers) -> bool { +/// Does a right-click with `mods` at document point `doc` open the menu? The Shift gesture for +/// every tool that has one, and a plain right-click with the Eraser in Block mode, where the Brush +/// Preset picker's Size and Hardness mean nothing (#11937), or with the Paint Bucket (#12530), as +/// in the reference application. +/// A plain right-click opens it only where it would otherwise open the picker or nothing: with the +/// Erase preference it still erases, and on the pasteboard its colour menu opens. +pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers, doc: Option<[f64; 2]>) -> bool { let plain = !mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd; let block = tool == Tool::Eraser && app.ui.tool_options.eraser_mode == "block"; - is_gesture(tool, mods) || (plain && block && !crate::paint_mouse::right_erases(app, tool)) + let pasteboard = doc.is_some_and(|d| crate::canvas_tool_menu::pasteboard_at(app, tool, d)); + // An open Free Transform box owns the plain right-click: its transform menu opens instead. + let bucket = tool == Tool::PaintBucket && app.ui.transform.is_none(); + is_gesture(tool, mods) || (plain && (block || bucket) && !crate::paint_mouse::right_erases(app, tool) && !pasteboard) } /// The modifiers that decide a right-button gesture: the ones held when the button went down. @@ -228,11 +232,25 @@ pub(crate) fn menu_id() -> Id { Id::unique("canvas-brush-mode-menu") } -/// Opens the active tool's menu at screen point `pos`. -pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) { +/// Temp data: was the open menu opened by a plain right-click (not the Shift gesture)? +fn plain_id() -> Id { + menu_id().with("plain") +} + +/// The row drawn checked. The Paint Bucket's plain right-click menu checks none, as in the +/// reference application; its Shift+right-click menu checks the current mode. +pub(crate) fn checked(app: &PhotocraftApp, ctx: &Context, tool: Tool) -> Option { + let plain = ctx.data(|d| d.get_temp::(plain_id())).unwrap_or(false); + if plain && tool == Tool::PaintBucket { None } else { current(app, tool) } +} + +/// Opens the active tool's menu at screen point `pos`, for a right-click with `mods`. +pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2], mods: egui::Modifiers) { if !pos.iter().all(|v| v.is_finite()) || items(app.ui.tool).is_empty() { return; } + let plain = !is_gesture(app.ui.tool, mods); + ctx.data_mut(|d| d.insert_temp(plain_id(), plain)); // The checked row reads the tool's own brush. crate::paint_mouse::sync_tool_brush(app); app.ui.brush_picker = None; @@ -378,7 +396,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &Context) { crate::paint_mouse::sync_tool_brush(app); let tool = app.ui.tool; let rows: Vec<(Item, bool)> = items(tool).into_iter().map(|i| (i, enabled(app, i))).collect(); - let current = current(app, tool); + let current = checked(app, ctx, tool); let screen = crate::work_area::visible_rect(ctx); let id = menu_id(); let margin = ctx.global_style().spacing.menu_margin.sum() + egui::Vec2::splat(2.0); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dbe4bca522c..3045ba3837c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1019,7 +1019,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: // Tools follow the left button; the right one opens the Brush Preset picker or erases // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); - let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool); + let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool, xf); if input.menu_dismiss_press { // Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View): // starve them. The release click stays armed, so the click handling below consumes diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 835f76ae46e..63268933aa7 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -343,8 +343,9 @@ pub fn track_right_press_view(response: &Response, view: &crate::state::View, fl /// Route the canvas response's buttons: the left one drives the tool; the right one resizes the /// brush with Alt held (#297), erases (Erase preference) or opens the Brush Preset picker. Arms -/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. -pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) -> Buttons { +/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. `xf` is this canvas's view, +/// one cell of a Window › Arrange layout: it places a right-click on the image or the pasteboard. +pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool, xf: &crate::canvas::ViewXform) -> Buttons { if crate::brush_mode_menu::blocks_canvas(app, &response.ctx) { app.secondary_erase = false; return Buttons::default(); @@ -373,12 +374,13 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) // ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307). let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods); // Decided by the modifiers held when the button went down, not by those of the release frame that reports the click. - let mode_menu = - crate::brush_mode_menu::opens_on(app, tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods))); + let menu_mods = crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods)); + let menu_at = right_click_at(response); + let mode_menu = crate::brush_mode_menu::opens_on(app, tool, menu_mods, menu_at.map(|p| xf.to_doc(p))); if mode_menu && !resizing && app.drag.is_none() { app.secondary_erase = false; - if let Some(p) = right_click_at(response) { - crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y]); + if let Some(p) = menu_at { + crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y], menu_mods); } return Buttons { started: response.drag_started_by(PointerButton::Primary), @@ -451,10 +453,11 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: boo app.brush_resize_armed = down && app.drag.is_none(); return true; } - if crate::brush_mode_menu::opens_on(app, tool, mods) && app.drag.is_none() && app.brush_resize.is_none() { + // The control channel opens the pasteboard menu before it gets here (`secondary_canvas_menu_took`). + if crate::brush_mode_menu::opens_on(app, tool, mods, None) && app.drag.is_none() && app.brush_resize.is_none() { app.secondary_erase = false; if down { - crate::brush_mode_menu::open(app, ctx, at); + crate::brush_mode_menu::open(app, ctx, at, mods); } return false; } diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 5d73b0018d0..1bf77b7600f 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -57,13 +57,14 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { use crate::brush_mode_menu as m; let tool = app.ui.tool; let current = m::current(app, tool); + let checked = m::checked(app, ctx, tool); json!({ "pos": pos, "tool": tool, "mode": current.and_then(m::Item::label), "choices": m::labels(tool), "items": m::items(tool).into_iter().map(|i| match i.label() { - Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == current}), + Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == checked}), None => json!({"separator": true}), }).collect::>(), }) From 6b58afb6244bc7bcf45e8bec8424a91425b663e3 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:07:23 +0300 Subject: [PATCH 29/63] Test the Paint Bucket's plain right-click Mode list --- crates/ui-egui/src/brush_mode_menu.rs | 4 + .../src/eraser_block_right_click_tests.rs | 38 ++-- .../paint_bucket_right_click_menu_tests.rs | 184 ++++++++++++++++++ 3 files changed, 210 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 24fd114fb2e..528928e8c3a 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -442,3 +442,7 @@ mod eraser_block_right_click_tests; #[cfg(test)] #[path = "pattern_stamp_behind_tests.rs"] mod pattern_stamp_behind_tests; + +#[cfg(test)] +#[path = "paint_bucket_right_click_menu_tests.rs"] +mod paint_bucket_right_click_menu_tests; diff --git a/crates/ui-egui/src/eraser_block_right_click_tests.rs b/crates/ui-egui/src/eraser_block_right_click_tests.rs index 73be8c87508..720865444d0 100644 --- a/crates/ui-egui/src/eraser_block_right_click_tests.rs +++ b/crates/ui-egui/src/eraser_block_right_click_tests.rs @@ -10,7 +10,7 @@ use crate::PhotocraftApp; use crate::control::{ControlRequest, Outcome, handle}; use crate::state::Tool; -fn app(mode: &str) -> PhotocraftApp { +pub(super) fn app(mode: &str) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); @@ -21,7 +21,7 @@ fn app(mode: &str) -> PhotocraftApp { app } -fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { +pub(super) fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { let (req, _rx) = ControlRequest::new(method, params); match handle(app, ctx, &req) { Outcome::Done(v) => v, @@ -29,7 +29,7 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu } } -fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { +pub(super) fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { call( app, ctx, @@ -38,7 +38,7 @@ fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { ); } -fn steps(app: &PhotocraftApp) -> usize { +pub(super) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.past_len() } @@ -94,18 +94,7 @@ fn with_the_erase_preference_block_mode_still_erases() { /// nothing is erased. #[test] fn a_real_right_click_opens_the_menu_and_escape_closes_it() { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app("block"), - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(4); + let mut h = harness(app("block")); let n = steps(h.state()); let c = h.state().last_canvas_rect.center(); h.event(egui::Event::PointerMoved(c)); @@ -121,3 +110,20 @@ fn a_real_right_click_opens_the_menu_and_escape_closes_it() { assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it"); assert_eq!(steps(h.state()), n, "nothing erased"); } + +/// The canvas alone, drawn by the real mouse path. +pub(super) fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} diff --git a/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs new file mode 100644 index 00000000000..eff0ec017fb --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs @@ -0,0 +1,184 @@ +//! #12530: with the Paint Bucket a plain right-click on the image opens its Mode list at the +//! pointer, the options bar's entries with none checked; picking one sets the Mode, adds no history +//! and fills nothing. The pasteboard keeps its colour menu, Shift+right-click keeps its checked +//! menu and other tools keep their right-click. + +use egui::{Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::BlendMode; +use serde_json::{Value, json}; + +use super::eraser_block_right_click_tests::{app, call, harness, right_click, steps}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn bucket() -> PhotocraftApp { + let mut app = app("brush"); + app.ui.tool = Tool::PaintBucket; + app +} + +/// The options bar's Mode list for the Paint Bucket, Clear included. +fn options_bar_modes() -> Vec<&'static str> { + crate::blend_keys::tool_modes(Tool::PaintBucket).unwrap().into_iter().map(|m| m.map_or("Clear", BlendMode::label)).collect() +} + +fn checked_rows(inspect: &Value) -> Vec { + let items = inspect["result"]["brushModeMenu"]["items"].as_array().unwrap(); + items.iter().filter(|i| i["checked"] == true).map(|i| i["label"].clone()).collect() +} + +#[test] +fn a_plain_right_click_lists_the_options_bar_modes_with_none_checked() { + let ctx = egui::Context::default(); + let mut app = bucket(); + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_mode_menu.is_some(), "the Mode list opens"); + assert!(app.ui.brush_picker.is_none() && app.ui.canvas_tool_menu.is_none()); + let inspect = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(inspect["result"]["brushModeMenu"]["choices"], json!(options_bar_modes()), "{inspect}"); + assert_eq!(checked_rows(&inspect), Vec::::new(), "no entry is checked"); + assert_eq!(inspect["result"]["brushModeMenu"]["mode"], "Normal", "the tool's mode is still reported"); +} + +#[test] +fn picking_an_entry_sets_the_mode_and_adds_no_history() { + let ctx = egui::Context::default(); + let mut app = bucket(); + let (n, journal) = (steps(&app), app.session.journal.len()); + right_click(&mut app, &ctx, json!({})); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "Multiply"}))["ok"], true); + assert_eq!(app.ui.tool_options.bucket_blend_mode, BlendMode::Multiply); + assert!(!app.ui.tool_options.bucket_clear); + assert!(app.ui.brush_mode_menu.is_none()); + assert_eq!((steps(&app), app.session.journal.len()), (n, journal), "nothing is filled"); +} + +#[test] +fn shift_right_click_still_checks_the_current_mode() { + let ctx = egui::Context::default(); + let mut app = bucket(); + app.ui.tool_options.bucket_blend_mode = BlendMode::Screen; + right_click(&mut app, &ctx, json!({"shift": true})); + let inspect = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(checked_rows(&inspect), vec![json!("Screen")], "{inspect}"); +} + +#[test] +fn other_tools_keep_their_plain_right_click() { + let ctx = egui::Context::default(); + for tool in [Tool::Brush, Tool::Pencil, Tool::CloneStamp, Tool::Gradient, Tool::Eraser] { + let mut app = bucket(); + app.ui.tool = tool; + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_mode_menu.is_none(), "{tool:?}"); + } +} + +/// A real right-click at `at` with `mods` held. +fn mouse_right_click(h: &mut Harness<'static, PhotocraftApp>, at: Pos2, mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: mods }); + h.run_steps(2); + } + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +fn row_checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// The real mouse: the menu opens at the pointer with no row checked; Escape and a click outside +/// close it without a change; a row sets the Mode. Nothing is filled. +#[test] +fn a_real_right_click_opens_the_unchecked_menu_at_the_pointer() { + let mut h = harness(bucket()); + let (n, journal) = (steps(h.state()), h.state().session.journal.len()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::NONE); + assert_eq!(h.state().ui.brush_mode_menu, Some([c.x, c.y]), "the menu at the pointer"); + assert!(!row_checked(&h, "Normal"), "the current mode is not checked"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it"); + mouse_right_click(&mut h, c, Modifiers::NONE); + let outside = c - egui::vec2(20.0, 0.0); + h.event(egui::Event::PointerMoved(outside)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + assert!(h.state().ui.brush_mode_menu.is_none(), "a click outside closes it"); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Normal); + mouse_right_click(&mut h, c, Modifiers::NONE); + h.get_by_label("Multiply").click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Multiply); + assert!(h.state().ui.brush_mode_menu.is_none()); + assert_eq!((steps(h.state()), h.state().session.journal.len()), (n, journal), "nothing is filled"); +} + +#[test] +fn a_real_shift_right_click_checks_the_current_mode() { + let mut h = harness(bucket()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::SHIFT); + assert!(h.state().ui.brush_mode_menu.is_some()); + assert!(row_checked(&h, "Normal")); +} + +#[test] +fn a_real_right_click_on_the_pasteboard_opens_its_colour_menu() { + let mut h = harness(bucket()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c + egui::vec2(300.0, 0.0), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} + +/// An open Free Transform box keeps its transform menu: the Mode list does not open over it. +#[test] +fn a_real_right_click_on_a_free_transform_box_opens_only_the_transform_menu() { + let mut app = bucket(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = harness(app); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.transform), "the transform menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} + +/// Window › Arrange: each document's canvas is a cell, and a right-click is placed on the image or +/// the pasteboard by that cell's view, not by the whole work area's. +#[test] +fn arranged_cells_place_the_right_click_by_their_own_view() { + let mut h = harness(bucket()); + h.state_mut().run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + h.state_mut().ui.view.arrange = "twoUpVertical".into(); + h.run_steps(4); + let full = h.state().last_canvas_rect; + let active = h.state().session.active_index().unwrap(); + let cell = crate::canvas::arranged_cells(h.state(), full).unwrap().into_iter().find(|(i, _)| *i == active).unwrap().1; + mouse_right_click(&mut h, cell.center(), Modifiers::NONE); + assert!(h.state().ui.brush_mode_menu.is_some(), "the image in the active cell: the Mode list"); + assert!(h.state().ui.canvas_tool_menu.is_none()); + h.key_press(egui::Key::Escape); + h.run_steps(2); + // The pasteboard at the cell's inner edge, where the whole work area's view has the image. + let edge = cell.clamp(full.center()); + let pasteboard = edge + (cell.center() - edge).normalized() * 10.0; + mouse_right_click(&mut h, pasteboard, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} From d6b92af09152c15832f0650facf623e3169ee51b Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:14:39 +0300 Subject: [PATCH 30/63] Refuse every pattern with the Pattern Stamp in Indexed Color paint.patternStamp and its live strokes return the reference application's message in an Indexed Color document, whatever the pattern's colour mode, and paint nothing; a press with the Pattern Stamp shows it as a modal alert. The options bar's Mode reads Threshold there. Other documents keep painting. --- crates/engine/src/cmd/retouch_cmds.rs | 4 +++- .../src/cmd/retouch_cmds/pattern_stamp.rs | 24 +++++++++++++++++-- crates/ui-egui/src/panels/brush_controls.rs | 7 ++++-- crates/ui-egui/src/panels/options_bar.rs | 5 +++- crates/ui-egui/src/tools/brush_refusal.rs | 9 ++++++- 5 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index b4fcdd90222..4a9bf1c4c22 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -29,7 +29,9 @@ mod art_history; mod content_aware_move; mod patch; mod pattern_stamp; -pub use pattern_stamp::live_impressionist as live_pattern_impressionist; +pub use pattern_stamp::{ + INDEXED_REFUSAL as PATTERN_STAMP_INDEXED_REFUSAL, live_impressionist as live_pattern_impressionist, press_refusal as pattern_stamp_press_refusal, +}; mod periodic; mod remove; pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 8c05c99085c..f5e4cb1e65e 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -9,7 +9,7 @@ //! Impressionist was not measured: those strokes lay their dabs over the pixels in Normal, as //! they did before Behind existed. -use photocraft_color::{BlendMode, PixelFormat}; +use photocraft_color::{BlendMode, ColorMode, PixelFormat}; use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_doc::{LayerId, Pattern}; use photocraft_geom::Rect; @@ -19,11 +19,30 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke}; -use crate::{Result, Session}; +use crate::{EngineError, Result, Session}; const STREAM_PHASE_X: u64 = 101; const STREAM_PHASE_Y: u64 = 102; +/// The reference's alert for a Pattern Stamp stroke in an Indexed Color document (#12887). +pub const INDEXED_REFUSAL: &str = "Could not fill because the pattern and image have different color modes."; + +/// The reference refuses every pattern in an Indexed Color document before painting: RGB, +/// Grayscale, CMYK, Lab and Indexed ones from another image. It paints only a pattern with the +/// document's own colour table, which PhotoCraft can't tell apart, so that one is refused too. +/// Bitmap, Duotone and Multichannel documents weren't measured and paint as before. +fn mode_refusal(s: &Session) -> Result<()> { + if s.active().is_some_and(|st| st.doc.mode == ColorMode::Indexed) { Err(EngineError::Other(INDEXED_REFUSAL.into())) } else { Ok(()) } +} + +/// [`mode_refusal`] for a press with the stroke's `p`, so the canvas can alert before the stroke +/// starts: `None` when the pattern paints, or when `p` names no pattern (the stroke reports that). +pub fn press_refusal(s: &Session, p: &Value) -> Option { + mode_refusal(s).err()?; + crate::pattern_cmds::resolve_param(s, "paint.patternStamp", p).ok()?; + Some(INDEXED_REFUSAL.into()) +} + pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { has_pixel_layer(s)?; if crate::pattern_cmds::resolve_id(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) } @@ -58,6 +77,7 @@ impl Setup { let aligned = flag(p, "aligned", true); let impressionist = flag(p, "impressionist", false); let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?; + mode_refusal(s)?; if pat.is_empty() { return Err(bad(CMD, "the pattern is empty")); } diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 4f30ac1bdf6..481b56b8292 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -40,8 +40,11 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf /// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns. /// Without `behind_enabled` (the Background is the active layer) Behind is greyed, as in the /// Shift+right-click menu, and the wheel and the keys step past it. -pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool) { - let opts = crate::brush_mode_menu::pattern_stamp_choices(); +pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool, threshold: bool) { + let mut opts = crate::brush_mode_menu::pattern_stamp_choices(); + if threshold && let Some(normal) = opts.iter_mut().find(|o| o.0 == (Some(BlendMode::Normal), false)) { + normal.1 = tl!("Threshold"); + } let before = if b.behind { (None, true) } else { (Some(b.mode), false) }; let mut mode = before; let groups = |m: &(Option, bool)| m.0.is_some_and(starts_blend_group); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 895e6b0a02f..3f8ab2f4465 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -148,7 +148,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Its list has Behind, greyed on the Background (#12879). opt_label(ui, tl!("Mode")); let behind = crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind); - super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind); + // An Indexed Color document names Normal "Threshold" (#12887); the other + // entries weren't measured there. + let threshold = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed); + super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind, threshold); } else if let Some(modes) = crate::blend_keys::tool_modes(tool) { opt_label(ui, tl!("Mode")); if let Some(Some(m)) = diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index e75c60794de..25490cefa43 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -46,8 +46,15 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { /// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal /// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock /// transparent pixels is no refusal, and a group's targeted mask paints. A tool with a -/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document. +/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document; the +/// Pattern Stamp only the engine's, for any pattern in an Indexed Color document. pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { + // The Pattern Stamp's colour-mode alert depends on its pattern too (#12887). + if tool == Tool::PatternStamp { + use photocraft_engine::retouch_cmds::{PATTERN_STAMP_INDEXED_REFUSAL, pattern_stamp_press_refusal}; + let p = crate::retouch_ui::pattern_stamp_params(app, &[]); + return pattern_stamp_press_refusal(&app.session, &p).is_some().then(|| tl!(PATTERN_STAMP_INDEXED_REFUSAL).to_owned()); + } if let Some(name) = mode_tool_name(tool) && let Some(template) = match app.session.active()?.doc.mode { photocraft_doc::ColorMode::Indexed => Some(INDEXED), From 5d49a2c7d64a9d2881a79fd7082a9328bc248614 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:58:49 +0100 Subject: [PATCH 31/63] fix(ui): an arrow or wheel step past a whole-number field's end does not alert value_field_whole_alerting treated an arrow-key or wheel step on a focused field as a typed value, so Up at 100 or Down at 3 in the Polygon Sides field showed the "Closest value inserted" alert when the field was left. A step now stops at the end silently, as a scrub does and as the Background Eraser's Angle field already does. The issue keeps arrow keys and the wheel at today's behaviour (#13304). --- .../src/tools/polygon_sides_alert_tests.rs | 19 ++++++++++++++++++- crates/ui-egui/src/widgets/fields.rs | 7 +++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs index ffeac2092ca..399dcc86add 100644 --- a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs +++ b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs @@ -1,6 +1,6 @@ //! #13304: the Polygon tool's Sides takes whole numbers 3..100; a value typed past the range becomes //! the closest one and, once the field is left, the reference's "Closest value inserted" alert with -//! OK says so. A scrub past either end stops there without one. +//! OK says so. A scrub or an arrow-key step past either end stops there without one. use egui::accesskit::Role; use egui::vec2; @@ -88,6 +88,23 @@ fn sides_that_are_no_number_keep_the_value_without_an_alert() { assert!(alerts(&h).is_empty(), "no number, no alert"); } +#[test] +fn arrow_steps_past_either_end_stop_there_without_an_alert() { + for (start, key, want) in [("99", egui::Key::ArrowUp, 100), ("4", egui::Key::ArrowDown, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + click_sides(&mut h); + for _ in 0..3 { + h.key_press(key); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the steps reached the end"); + assert!(alerts(&h).is_empty(), "{start}: an arrow step stops at the end without an alert"); + } +} + #[test] fn a_caption_scrub_past_either_end_does_not_alert() { for (start, dx, want) in [("95", 50.0, 100), ("8", -50.0, 3)] { diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index 078d4ef003b..bbd7d387722 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -16,7 +16,7 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive /// (Photoshop's "Closest value inserted" alerts, #11938): it stores the closest whole number in /// range, and returns true once the field is left after such a value was typed, so the caller /// shows its alert. While the field has the keyboard it keeps the typed text (a `0` on the way to -/// `05` stays). A scrub past the ends just stops there and says nothing. +/// `05` stays). A scrub, arrow-key or wheel step past the ends just stops there and says nothing. pub fn value_field_whole_alerting( ui: &mut Ui, name: &str, @@ -34,6 +34,9 @@ pub fn value_field_whole_alerting( let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32, Option)>(draft_id)); let draft = draft.filter(|(_, stored, field)| *stored == *value && field.is_some_and(|f| ui.ctx().memory(|m| m.has_focus(f)))); let mut typed = draft.map_or(*value, |(typed, _, _)| typed); + // Read before the field: it consumes the arrow keys it steps with, and the wheel it steps + // with while focused never shows in the scroll delta. A step is no typed value (#13304). + let stepped = ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx()); // The field's own range is wide, so the typed value reaches here unclamped. let r = value_field_named(ui, name, &mut typed, -1.0e9..=1.0e9, suffix, width); let out_id = r.id.with("out-of-range"); @@ -42,7 +45,7 @@ pub fn value_field_whole_alerting( } if r.changed() && typed.is_finite() { *value = fit(typed); - let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); + let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none() && !stepped; let out = typing && !(lo..=hi).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); if typing && r.has_focus() { From 64c730e8a8aefc423ced183e4cb9f4bd5bb16c03 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:17:50 -0800 Subject: [PATCH 32/63] Free Transform: follow the pointer from the press and build mip levels off the UI thread --- .../ui-egui/examples/free_transform_bench.rs | 167 ++++++++++++ crates/ui-egui/src/canvas.rs | 83 ++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/tools/transform_tex.rs | 143 ++++++++-- .../ui-egui/src/transform_drag_start_tests.rs | 256 ++++++++++++++++++ perf/budgets.toml | 26 ++ 6 files changed, 660 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/examples/free_transform_bench.rs create mode 100644 crates/ui-egui/src/transform_drag_start_tests.rs diff --git a/crates/ui-egui/examples/free_transform_bench.rs b/crates/ui-egui/examples/free_transform_bench.rs new file mode 100644 index 00000000000..bc13925f3a9 --- /dev/null +++ b/crates/ui-egui/examples/free_transform_bench.rs @@ -0,0 +1,167 @@ +//! Free Transform stalls (#11103): two selected raster layers on a 24 MP document, one box. +//! +//! ```sh +//! cargo run --release -p photocraft-ui-egui --example free_transform_bench -- [--size 6000x4000] [--reps 9] [--steps 60] +//! ``` +//! +//! - begin: Ctrl+T (`transform_tool::begin`) and the first preview frame, then Esc. +//! - drag update: one pointer move and the preview frame it draws. "scale" drags the bottom-right +//! handle towards the top-left corner, shrinking the box from 100 % to 20 % at 100 % view zoom, +//! so the scale crosses ½ and ¼ (new mip levels) mid-drag; "move" drags the box by its middle. +//! +//! CPU side only: the egui frame and the texture preparation it does, not GPU upload or +//! presentation. A helper thread's work (a mip level built off the UI thread) isn't counted. + +use std::time::Instant; + +use photocraft_ui_egui::canvas::{ToolEvent, ViewXform}; +use photocraft_ui_egui::{PhotocraftApp, Services, transform_tool}; +use serde_json::json; + +fn arg(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +fn median(v: &[f64]) -> f64 { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.0) +} + +fn worst(v: &[f64]) -> f64 { + v.iter().copied().fold(0.0, f64::max) +} + +/// The view the frames draw through: 100 %, the document centred in a 1600 × 1000 canvas. +fn view(w: u32, h: u32) -> ViewXform { + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)), + zoom: 1.0, + center: [w as f32 / 2.0, h as f32 / 2.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// One frame drawing the open box's preview, in milliseconds. +fn frame(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> f64 { + let input = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; + let start = Instant::now(); + let output = ctx.run_ui(input, |ui| transform_tool::draw_content(app, ui.painter(), xf)); + let ms = start.elapsed().as_secs_f64() * 1e3; + drop(output); + ms +} + +fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) { + transform_tool::pointer(app, ev, egui::Modifiers::NONE); +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (w, h) = + arg(&args, "--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse::().ok()?, b.parse::().ok()?)))).unwrap_or((6000, 4000)); + let reps: usize = arg(&args, "--reps").and_then(|s| s.parse().ok()).unwrap_or(9).max(1); + let steps: usize = arg(&args, "--steps").and_then(|s| s.parse().ok()).unwrap_or(60).max(2); + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": w, "height": h, "background": "white"})).expect("new document"); + // Two overlapping layers, each covering most of the canvas. + let (fw, fh) = (w * 2 / 3, h * 3 / 4); + let mut ids = Vec::new(); + for (name, x, y, color) in [("A", 0, 0, "#c03020"), ("B", w - fw, h - fh, "#2050c0")] { + let id = app.run("layer.new.layer", json!({"name": name})).expect("new layer")["layer"].as_u64().unwrap_or(0); + app.run("layer.select", json!({"layer": id})).expect("select"); + app.run("select.rect", json!({"x": x, "y": y, "width": fw, "height": fh})).expect("select.rect"); + app.run("edit.fill", json!({"contents": "color", "color": color})).expect("fill"); + app.run("select.deselect", json!({})).expect("deselect"); + ids.push(id); + } + if let (Some(a), Some(b)) = (ids.first(), ids.get(1)) { + app.run("layer.select", json!({"layer": a})).expect("select A"); + app.run("layer.select", json!({"layer": b, "mode": "add"})).expect("add B"); + } + app.sync_views(); + if let Some(v) = app.ui.views.first_mut() { + v.zoom = 1.0; + v.center = [w as f32 / 2.0, h as f32 / 2.0]; + v.fit_pending = false; + } + let xf = view(w, h); + let ctx = egui::Context::default(); + let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); + + // Ctrl+T and its first preview frame. + let (mut begin, mut first, mut begin_total) = (Vec::new(), Vec::new(), Vec::new()); + for _ in 0..reps { + let t0 = Instant::now(); + transform_tool::begin(&mut app, &ctx).expect("Free Transform"); + let opened = t0.elapsed().as_secs_f64() * 1e3; + let drawn = frame(&app, &ctx, &xf); + begin.push(opened); + first.push(drawn); + begin_total.push(opened + drawn); + transform_tool::cancel(&mut app); + } + + // Drags: one pointer move + its frame per update. + let mut drag = |kind: &str| -> Vec { + transform_tool::begin(&mut app, &ctx).expect("Free Transform"); + let _ = frame(&app, &ctx, &xf); + let q = app.ui.transform.as_ref().map(|t| t.quad).unwrap_or_default(); + let (from, to) = if kind == "scale" { + // The bottom-right handle towards the top-left corner: 100 % → 20 %. + let (a, c) = (q[0], q[2]); + (c, [a[0] + 0.2 * (c[0] - a[0]), a[1] + 0.2 * (c[1] - a[1])]) + } else { + let m = [(q[0][0] + q[2][0]) / 2.0, (q[0][1] + q[2][1]) / 2.0]; + (m, [m[0] + 400.0, m[1] + 250.0]) + }; + pointer(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }); + let mut times = Vec::with_capacity(steps); + for s in 1..=steps { + let k = s as f64 / steps as f64; + let p = [from[0] + k * (to[0] - from[0]), from[1] + k * (to[1] - from[1])]; + let t0 = Instant::now(); + pointer(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }); + let moved = t0.elapsed().as_secs_f64() * 1e3; + times.push(moved + frame(&app, &ctx, &xf)); + } + pointer(&mut app, ToolEvent::Up { x: to[0], y: to[1] }); + transform_tool::cancel(&mut app); + times + }; + let mut scale = Vec::new(); + let mut moving = Vec::new(); + for _ in 0..reps.min(3) { + scale.extend(drag("scale")); + moving.extend(drag("move")); + } + + if let Some(out) = arg(&args, "--json") { + use photocraft_testkit::perf::{process_peak_rss_bytes, report, row, write_report}; + let rss = photocraft_testkit::perf::current_rss_bytes().max(process_peak_rss_bytes()); + let rows = vec![ + row("Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame", &begin_total, rss, None), + row("Free Transform begin, 2 layers on 24 MP: Ctrl+T", &begin, rss, None), + row("Free Transform begin, 2 layers on 24 MP: first frame", &first, rss, None), + row("Free Transform drag update, 2 layers on 24 MP: scale through mip levels", &scale, rss, None), + row("Free Transform drag update, 2 layers on 24 MP: move", &moving, rss, None), + ]; + let rep = report("free_transform_bench", json!({"width": w, "height": h, "layers": 2, "reps": reps, "steps": steps}), rows, None); + if let Err(e) = write_report(&out, &rep) { + eprintln!("{e}"); + } + } + println!("{w}×{h}, 2 layers, {reps} reps, {steps} steps per drag"); + println!( + "begin: Ctrl+T {:.1} ms + first frame {:.1} ms = {:.1} ms (median; worst {:.1} ms)", + median(&begin), + median(&first), + median(&begin_total), + worst(&begin_total) + ); + println!("drag update, scale 100 % → 20 %: median {:.2} ms, worst {:.2} ms", median(&scale), worst(&scale)); + println!("drag update, move: median {:.2} ms, worst {:.2} ms", median(&moving), worst(&moving)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c38f6c8d32d..e01e82bbca0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1274,6 +1274,7 @@ fn handle_canvas_tool_stroke( if press_stroke || (strokes_live(tool) && (app.alt_sampling || app.mixer_sampling)) { buttons.started = false; } + let transform_press = transform_press_moves(app, ui, input, mods, buttons); if buttons.started && !input.menu_dismiss_press && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) @@ -1411,6 +1412,88 @@ fn handle_canvas_tool_stroke( if press_stroke && (app.drag.is_none() || !ui.input(|i| i.pointer.primary_down())) { app.press_stroke = false; } + if transform_press { + transform_press_release(app, ui, input, mods, buttons); + } +} + +/// Marks a Free Transform drag started on the press (`transform_press_moves`). +fn transform_press_id(ctx: &egui::Context) -> egui::Id { + egui::Id::new("free-transform-press").with(ctx.viewport_id()) +} + +/// An open Free Transform box follows the pointer from the press (#11103): the press goes to the +/// box at once and every move before egui recognises a drag (past its click distance) moves it, +/// so the box doesn't sit still and then jump to catch up. Warp keeps its own gesture. Returns +/// whether the current press started this way; the drag egui recognises later continues it. +fn transform_press_moves( + app: &mut PhotocraftApp, + ui: &egui::Ui, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + buttons: &mut crate::paint_mouse::Buttons, +) -> bool { + let ctx = input.ctx; + let id = transform_press_id(ctx); + let view = Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id()))); + let open = input.transform_owns_pointer && app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()); + if open + && !input.menu_dismiss_press + && !input.under_dialog + && input.response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_pressed()) + && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| input.rect.contains(*p)) + { + let d = input.xf.to_doc(p); + let press_mods = ui.input(|i| pointer_button_modifiers(&i.events, PointerButton::Primary)).unwrap_or(mods); + tool_input::tool_event_with_view(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods, view); + ctx.data_mut(|m| m.insert_temp(id, true)); + } + let pressed = ctx.data(|m| m.get_temp::(id)).unwrap_or(false); + if !pressed { + return false; + } + // The press already went to the box: the recognised drag continues it, it doesn't start over. + buttons.started = false; + let moved = ui.input(|i| i.pointer.primary_down() && i.pointer.delta() != egui::Vec2::ZERO); + if moved + && !buttons.dragged + && !buttons.stopped + && let Some(p) = ui.input(|i| i.pointer.latest_pos()) + { + let d = input.xf.to_doc(p); + tool_input::tool_event_with_view(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods, view); + } + true +} + +/// Ends a Free Transform press that egui never recognised as a drag: its release is the gesture's +/// `Up` (a click outside the box still accepts or keeps it), not a second click-sized `Down`/`Up`. +fn transform_press_release( + app: &mut PhotocraftApp, + ui: &egui::Ui, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + buttons: &mut crate::paint_mouse::Buttons, +) { + let ctx = input.ctx; + if !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { + buttons.clicked = false; + if app.ui.transform.is_some() + && let Some(p) = input.response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos())) + { + let d = input.xf.to_doc(p); + tool_input::tool_event_with_view( + app, + ToolEvent::Up { x: d[0], y: d[1] }, + mods, + Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id()))), + ); + } + } + if app.ui.transform.is_none() || !ui.input(|i| i.pointer.primary_down()) { + ctx.data_mut(|m| m.remove::(transform_press_id(ctx))); + } } /// Dispatches discrete pointer click and release events to active tools with view transform context. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7a56e9b703d..4e4289acfa8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -879,6 +879,8 @@ mod transform_fx_tests; #[cfg(test)] mod transform_commit_click_tests; +#[cfg(test)] +mod transform_drag_start_tests; #[cfg(test)] mod layer_props_ui_tests; diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index ae67b2e2c5e..56872f28882 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -11,7 +11,10 @@ //! enlarged by the transform: the full-resolution level with nearest filtering, so pixels stay //! crisp like the canvas around them. //! -//! Levels and filter variants are uploaded on first use and cached for the session. +//! Levels and filter variants are uploaded on first use and cached for the session. A mip level +//! first needed mid-drag (the scale crossing ½, ¼…) is built, colour-converted and uploaded on a +//! helper thread, and the closest finer level already uploaded is shown until it is ready +//! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread. use std::sync::{Arc, Mutex, PoisonError}; @@ -30,12 +33,20 @@ struct Level { pub struct PreviewTextures { name: String, /// CPU copies of the levels built so far (level 0 = full resolution), premultiplied. - images: Mutex>>, + images: Arc>>>, /// uv extent of level 0 that covers the source exactly (< 1 when level 0 was padded). base_uv: [f32; 2], - uploaded: Mutex>, + uploaded: Arc>>, + /// Mip levels being built off the UI thread, as `(level, display key)`. + building: Arc>>, + /// Whether a mip level that has a finer level to stand in for it is built off the UI thread. + background: bool, } +/// Off the UI thread on native builds; the web build has no threads to spare. Unit tests build +/// synchronously unless they ask (`set_background_builds`), so frames stay deterministic. +const BUILD_IN_BACKGROUND: bool = cfg!(not(any(test, target_arch = "wasm32"))); + /// A source pixel shown at this many screen pixels or more counts as "zoomed in" (nearest). const CRISP_ZOOM: f32 = 2.0; @@ -47,12 +58,26 @@ impl PreviewTextures { let base_uv = [base_uv[0].clamp(0.0, 1.0), base_uv[1].clamp(0.0, 1.0)]; Self { name, - images: Mutex::new(vec![image]), + images: Arc::new(Mutex::new(vec![image])), base_uv, - uploaded: Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }]), + uploaded: Arc::new(Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }])), + building: Arc::new(Mutex::new(Vec::new())), + background: BUILD_IN_BACKGROUND, } } + /// Build mip levels off the UI thread (`true`) or in the frame that first needs them. + #[cfg(test)] + pub(crate) fn set_background_builds(&mut self, on: bool) { + self.background = on; + } + + /// Whether a mip level is still being built off the UI thread. + #[cfg(test)] + pub(crate) fn is_building(&self) -> bool { + !self.building.lock().unwrap_or_else(PoisonError::into_inner).is_empty() + } + /// Size of the full-resolution level in texels. pub fn size(&self) -> [usize; 2] { self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |i| i.size) @@ -100,6 +125,19 @@ impl PreviewTextures { if let Some(l) = up.iter().find(|l| l.level == level && l.nearest == nearest && l.display_key == display_key) { return (l.tex.id(), l.uv); } + // A level first needed mid-drag: show the closest finer level already uploaded for this + // display while a helper thread builds it (#11103). + if self.background + && level > 0 + && let Some(finer) = up.iter().filter(|l| l.display_key == display_key && l.level < level).max_by_key(|l| (l.level, !l.nearest)) + { + let shown = (finer.tex.id(), finer.uv); + drop(up); + if self.build_in_background(ctx, level, display, display_key) { + return shown; + } + up = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner); + } let Some((img, uv)) = self.level_image(level) else { // Can't build it (shouldn't happen): fall back to the first upload. return up.first().map_or((TextureId::default(), [1.0, 1.0]), |l| (l.tex.id(), l.uv)); @@ -114,24 +152,86 @@ impl PreviewTextures { (id, uv) } + /// Builds level `level` on a helper thread, uploads it and asks for a frame. False when no + /// thread could be started (the caller builds it in this frame instead). + fn build_in_background(&self, ctx: &egui::Context, level: u32, display: Option<&CanvasDisplay>, display_key: u64) -> bool { + { + let mut building = self.building.lock().unwrap_or_else(PoisonError::into_inner); + if building.contains(&(level, display_key)) { + return true; + } + building.push((level, display_key)); + } + let (images, uploaded, building) = (Arc::clone(&self.images), Arc::clone(&self.uploaded), Arc::clone(&self.building)); + let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name)); + let display = display.map(share_display); + let job = move || { + let built = level_of(&images, base_uv, level); + // Nobody left to show it (the box closed meanwhile): don't upload. + if let Some((img, uv)) = built.filter(|_| Arc::strong_count(&uploaded) > 1) { + let img = display.as_ref().map_or_else(|| Arc::clone(&img), |d| Arc::new(display_image(&img, d))); + let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); + let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); + // A monitor profile change meanwhile released this display's uploads: drop it. + if up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { + up.push(Level { level, display_key, nearest: false, tex, uv }); + } + } + building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); + ctx.request_repaint(); + }; + let started = std::thread::Builder::new().name("transform-mip".into()).spawn(job).is_ok(); + if !started { + self.building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); + } + started + } + /// Level `n` of the mip chain (built on demand by 2×2 box filtering) and its uv extent. pub(crate) fn level_image(&self, n: u32) -> Option<(Arc, [f32; 2])> { - let mut imgs = self.images.lock().unwrap_or_else(PoisonError::into_inner); - while imgs.len() <= n as usize { + level_of(&self.images, self.base_uv, n) + } +} + +/// Level `n` of `images` (built on demand by 2×2 box filtering) and its uv extent. Each level is +/// filtered with the lock released, so a helper thread building one doesn't stall the frame +/// reading another (the layer-style preview reads them too). +fn level_of(images: &Mutex>>, base_uv: [f32; 2], n: u32) -> Option<(Arc, [f32; 2])> { + loop { + let (prev, len) = { + let imgs = images.lock().unwrap_or_else(PoisonError::into_inner); let prev = imgs.last()?; - if prev.size[0] <= 1 && prev.size[1] <= 1 { + if imgs.len() > n as usize || (prev.size[0] <= 1 && prev.size[1] <= 1) { break; } - let next = Arc::new(halve(prev)); + (Arc::clone(prev), imgs.len()) + }; + let next = Arc::new(halve(&prev)); + let mut imgs = images.lock().unwrap_or_else(PoisonError::into_inner); + // Another thread may have added this level meanwhile: keep the first. + if imgs.len() == len { imgs.push(next); } - let k = (imgs.len() - 1).min(n as usize); - let img = imgs.get(k)?.clone(); - let base = imgs.first()?.size; - // Level k covers size·2^k base texels (the last row/column may be padding). - let f = (1u64 << k) as f32; - let uv = [self.base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), self.base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)]; - Some((img, [uv[0].min(1.0), uv[1].min(1.0)])) + } + let imgs = images.lock().unwrap_or_else(PoisonError::into_inner); + let k = (imgs.len() - 1).min(n as usize); + let img = imgs.get(k)?.clone(); + let base = imgs.first()?.size; + // Level k covers size·2^k base texels (the last row/column may be padding). + let f = (1u64 << k) as f32; + let uv = [base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)]; + Some((img, [uv[0].min(1.0), uv[1].min(1.0)])) +} + +/// A copy of `d` for a helper thread (its profiles and transform are shared, not copied). +fn share_display(d: &CanvasDisplay) -> CanvasDisplay { + CanvasDisplay { + encode_srgb: d.encode_srgb, + source: Arc::clone(&d.source), + monitor: Arc::clone(&d.monitor), + transform: d.transform.clone(), + key: d.key, + texture_key: d.texture_key, } } @@ -163,12 +263,21 @@ fn halve(img: &ColorImage) -> ColorImage { let (nw, nh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1)); let mut out = vec![Color32::TRANSPARENT; nw * nh]; let px = |x: usize, y: usize| img.pixels.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or_default(); - for (y, row) in out.chunks_mut(nw).enumerate() { + let row = |y: usize, row: &mut [Color32]| { for (x, o) in row.iter_mut().enumerate() { let q = [px(2 * x, 2 * y), px(2 * x + 1, 2 * y), px(2 * x, 2 * y + 1), px(2 * x + 1, 2 * y + 1)]; let avg = |c: fn(&Color32) -> u8| ((q.iter().map(|p| u32::from(c(p))).sum::() + 2) / 4) as u8; *o = Color32::from_rgba_premultiplied(avg(Color32::r), avg(Color32::g), avg(Color32::b), avg(Color32::a)); } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(nw).enumerate().for_each(|(y, r)| row(y, r)); + } + #[cfg(target_arch = "wasm32")] + for (y, r) in out.chunks_mut(nw).enumerate() { + row(y, r); } ColorImage::new([nw, nh], out) } diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs new file mode 100644 index 00000000000..8768d7c3c50 --- /dev/null +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -0,0 +1,256 @@ +//! Free Transform drag stalls (#11103). +//! +//! - Start: an open box moves from the first pointer move after the press, not once egui +//! recognises a drag (past its click distance), so it never jumps to catch up. Clicks keep their +//! rules: a click on the box moves nothing, a jittery click outside it on the image leaves it as +//! it was, a double-click on it commits. +//! - Mip levels: a level first needed mid-drag is built off the UI thread while the closest finer +//! level already uploaded stands in for it. + +use std::time::{Duration, Instant}; + +use egui::{Color32, ColorImage, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; +use crate::transform_tex::PreviewTextures; + +/// An 800 × 600 document at 100 % with a red block (x 100..300, y 100..300) on layer "Paint" and +/// Free Transform open on it. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.extras.snap = false; + app.ui.tool = Tool::Move; + let paint = LayerId(app.run("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": paint.0})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + // Frames 1/60 s apart, so two clicks make a double-click. + let mut h = Harness::builder().with_size(vec2(1100.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + 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 = [400.0, 300.0]; + v.fit_pending = false; + h.run_steps(2); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.transform.is_some(), "Free Transform is open"); + h +} + +fn view_xform(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + let app = h.state(); + let v = &app.ui.views[0]; + ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } +} + +fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { + view_xform(h).to_screen(x, y) +} + +fn quad(h: &Harness<'static, PhotocraftApp>) -> [[f64; 2]; 4] { + h.state().ui.transform.as_ref().expect("the box is open").quad +} + +fn steps(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, down: bool) { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +/// Hover document point `(x, y)`, then press there. +fn press(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + button(h, p, true); +} + +/// One frame with the pointer at document point `(x, y)`. +fn move_to(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); +} + +fn release(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + button(h, p, false); + h.run_steps(1); +} + +/// How far the box's top-left corner is from `from`. +fn offset(h: &Harness<'static, PhotocraftApp>, from: [[f64; 2]; 4]) -> [f64; 2] { + let q = quad(h); + [q[0][0] - from[0][0], q[0][1] - from[0][1]] +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3 +} + +#[test] +fn the_box_moves_from_the_first_pointer_move_after_the_press() { + let mut h = harness(); + let start = quad(&h); + press(&mut h, 200.0, 200.0); + assert!(near(offset(&h, start), [0.0, 0.0]), "the press alone moves nothing: {:?}", offset(&h, start)); + // 3 px: inside egui's click distance, so no drag is recognised yet. + move_to(&mut h, 203.0, 200.0); + assert!(near(offset(&h, start), [3.0, 0.0]), "the first move moves the box: {:?}", offset(&h, start)); + move_to(&mut h, 240.0, 220.0); + assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start)); + release(&mut h, 240.0, 220.0); + assert!(h.state().ui.transform.is_some(), "a drag doesn't close the box"); + assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start)); +} + +#[test] +fn the_box_keeps_up_with_every_move_with_no_jump_when_the_drag_is_recognised() { + let mut h = harness(); + let start = quad(&h); + press(&mut h, 200.0, 200.0); + // One pixel a frame, through egui's click distance and past it. + for dx in 1..=16 { + move_to(&mut h, 200.0 + dx as f32, 200.0); + let got = offset(&h, start); + assert!(near(got, [f64::from(dx), 0.0]), "after a {dx} px move the box is {got:?} off"); + } + release(&mut h, 216.0, 200.0); + assert!(near(offset(&h, start), [16.0, 0.0]), "{:?}", offset(&h, start)); +} + +#[test] +fn a_click_on_the_box_moves_nothing_and_keeps_it_open() { + let mut h = harness(); + let (start, before) = (quad(&h), steps(&h)); + press(&mut h, 200.0, 200.0); + release(&mut h, 200.0, 200.0); + assert!(h.state().ui.transform.is_some()); + assert_eq!(quad(&h), start); + assert_eq!(steps(&h), before); +} + +#[test] +fn a_jittery_click_outside_the_box_on_the_image_leaves_it_as_it_was() { + let mut h = harness(); + let (start, pivot) = (quad(&h), h.state().ui.transform.as_ref().unwrap().pivot); + // Only the Background has pixels here (#11100): the box stays open. + press(&mut h, 600.0, 450.0); + move_to(&mut h, 601.0, 450.0); + release(&mut h, 601.0, 450.0); + let t = h.state().ui.transform.as_ref().expect("the box stays open"); + assert_eq!((t.quad, t.pivot), (start, pivot), "the jitter's turn is put back"); +} + +#[test] +fn a_double_click_on_the_box_still_commits() { + let mut h = harness(); + let before = steps(&h); + press(&mut h, 200.0, 200.0); + button(&mut h, screen(&h, 200.0, 200.0), false); + button(&mut h, screen(&h, 200.0, 200.0), true); + button(&mut h, screen(&h, 200.0, 200.0), false); + h.run_steps(2); + assert!(h.state().ui.transform.is_none(), "committed"); + assert_eq!(steps(&h), before + 1); +} + +/// Waits until `t` has no mip level building off the UI thread. +fn wait_for_builds(t: &PreviewTextures) { + let start = Instant::now(); + while t.is_building() { + assert!(start.elapsed() < Duration::from_secs(10), "a mip level never finished building"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +/// A 5 × 3 white image with background builds on: level 1 is 3 × 2 texels covering 6 × 4 base +/// texels, level 3 is 1 × 1 covering 8 × 8. +fn textures(ctx: &egui::Context) -> PreviewTextures { + let mut t = PreviewTextures::new(ctx, "drag-mips".into(), ColorImage::new([5, 3], vec![Color32::WHITE; 15]), [1.0, 1.0]); + t.set_background_builds(true); + t +} + +#[test] +fn a_mip_level_first_needed_mid_drag_is_built_off_the_ui_thread() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let (full, full_uv) = t.pick(&ctx, 1.0, 1.0, false); + // Shrunk past ½: level 1 is wanted, level 0 shows until it is ready. + let (shown, uv) = t.pick(&ctx, 0.3, 1.0, false); + assert_eq!((shown, uv), (full, full_uv), "the full-resolution level stands in"); + wait_for_builds(&t); + let (built, uv) = t.pick(&ctx, 0.3, 1.0, false); + assert_ne!(built, full, "level 1 has its own texture once built"); + assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}"); + assert_eq!(t.pick(&ctx, 0.3, 1.0, false).0, built, "cached"); + ctx.tex_manager().write().take_delta().clear(); +} + +#[test] +fn the_closest_finer_level_stands_in_while_a_level_builds() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let full = t.pick(&ctx, 1.0, 1.0, false).0; + let _ = t.pick(&ctx, 0.3, 1.0, false); + wait_for_builds(&t); + let level1 = t.pick(&ctx, 0.3, 1.0, false).0; + // log2(1 / 0.1) = 3.3: level 3 is wanted; level 1 is the closest one uploaded. + assert_eq!(t.pick(&ctx, 0.1, 1.0, false).0, level1); + wait_for_builds(&t); + let level3 = t.pick(&ctx, 0.1, 1.0, false).0; + assert!(level3 != level1 && level3 != full, "level 3 has its own texture once built"); + ctx.tex_manager().write().take_delta().clear(); +} + +#[test] +fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + let doc = session.active().unwrap().doc.clone(); + session.color.settings.monitor_profile = "display-p3".into(); + let p3 = session.color.canvas_display(&doc).unwrap(); + assert!(!p3.is_identity()); + let ctx = egui::Context::default(); + let t = textures(&ctx); + let full = t.pick(&ctx, 1.0, 1.0, false).0; + // Only the unconverted level 0 is uploaded: nothing can stand in for this monitor. + let (shown, uv) = t.pick_display(&ctx, 0.3, 1.0, false, Some(&p3)); + assert!(!t.is_building(), "built in this frame"); + assert_ne!(shown, full); + assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}"); + ctx.tex_manager().write().take_delta().clear(); +} diff --git a/perf/budgets.toml b/perf/budgets.toml index 0d3d665e2db..8035b5ef365 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -882,3 +882,29 @@ issue = 9329 bench = "perf_scenarios" row = "app frame after Paste Into on 24 MP (CPU canvas)" enforce = false # new; no baseline yet + +# ---- #11103: Free Transform drag stalls ------------------------------------------------------- + +[[bench]] +name = "free_transform_bench" +package = "photocraft-ui-egui" +args = ["--reps", "9"] +quick_args = ["--size", "1200x800", "--reps", "3", "--steps", "20"] +note = "two selected layers on 24 MP: Ctrl+T + first preview frame, and drag updates (pointer move + preview frame) scaling through new mip levels or moving; CPU side, no GPU upload/present" + +[[scenario]] +id = "P90" +title = "Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame)" +issue = 11103 +bench = "free_transform_bench" +row = "Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame" +enforce = false # new; budget set from the #11103 measurements + +[[scenario]] +id = "P91" +title = "Free Transform drag update, 2 layers on 24 MP (scale through new mip levels)" +issue = 11103 +bench = "free_transform_bench" +row = "Free Transform drag update, 2 layers on 24 MP: scale through mip levels" +metric = "max" +enforce = false # new; budget set from the #11103 measurements From 11cc1c128717e80d87213ed2e7c77661af734f0a Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:20:10 -0800 Subject: [PATCH 33/63] Free Transform: use a unique egui id for the press marker --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e01e82bbca0..072ffce15b4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1419,7 +1419,7 @@ fn handle_canvas_tool_stroke( /// Marks a Free Transform drag started on the press (`transform_press_moves`). fn transform_press_id(ctx: &egui::Context) -> egui::Id { - egui::Id::new("free-transform-press").with(ctx.viewport_id()) + egui::Id::unique(("free-transform-press", ctx.viewport_id())) } /// An open Free Transform box follows the pointer from the press (#11103): the press goes to the From f61800a518fb99552181c31f17ce555ffdff7934 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:24:04 -0800 Subject: [PATCH 34/63] Free Transform tests: take the click point before the double-click --- crates/ui-egui/src/transform_drag_start_tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs index 8768d7c3c50..96f87a0a9c5 100644 --- a/crates/ui-egui/src/transform_drag_start_tests.rs +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -179,9 +179,10 @@ fn a_double_click_on_the_box_still_commits() { let mut h = harness(); let before = steps(&h); press(&mut h, 200.0, 200.0); - button(&mut h, screen(&h, 200.0, 200.0), false); - button(&mut h, screen(&h, 200.0, 200.0), true); - button(&mut h, screen(&h, 200.0, 200.0), false); + let p = screen(&h, 200.0, 200.0); + button(&mut h, p, false); + button(&mut h, p, true); + button(&mut h, p, false); h.run_steps(2); assert!(h.state().ui.transform.is_none(), "committed"); assert_eq!(steps(&h), before + 1); From 758b3abfc3133e5b581f8f37fe84e0545f62fc27 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:27:20 -0800 Subject: [PATCH 35/63] Free Transform: take the press marker's id before locking egui's data --- crates/ui-egui/src/canvas.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 072ffce15b4..52e9570f8b1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1492,7 +1492,9 @@ fn transform_press_release( } } if app.ui.transform.is_none() || !ui.input(|i| i.pointer.primary_down()) { - ctx.data_mut(|m| m.remove::(transform_press_id(ctx))); + // The id first: reading the viewport inside `data_mut` would wait on its own lock. + let id = transform_press_id(ctx); + ctx.data_mut(|m| m.remove::(id)); } } From 3d4040b0232dea3ee33fac3ce76f216f9ef22870 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:31:28 -0800 Subject: [PATCH 36/63] Free Transform tests: move the box before the double-click commit --- crates/ui-egui/src/transform_drag_start_tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs index 96f87a0a9c5..af146f504df 100644 --- a/crates/ui-egui/src/transform_drag_start_tests.rs +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -177,6 +177,11 @@ fn a_jittery_click_outside_the_box_on_the_image_leaves_it_as_it_was() { #[test] fn a_double_click_on_the_box_still_commits() { let mut h = harness(); + // Moved 10 px first: committing an unchanged box adds no History step. + let t = h.state_mut().ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 10.0, y]); + t.pivot[0] += 10.0; + h.run_steps(1); let before = steps(&h); press(&mut h, 200.0, 200.0); let p = screen(&h, 200.0, 200.0); From fdd7fee472a1211ca196c9ffb4377ac7e05b18aa Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:20:12 +0300 Subject: [PATCH 37/63] Clone Stamp: grey Sample at Current Layer and read Mode as Threshold in Indexed Color In an Indexed Color document the reference greys the Clone Stamp's Sample at Current Layer, a stroke samples the current layer whatever Sample held, and the Normal Mode reads "Threshold". Other modes keep today's list, and the stored Sample choice comes back in other documents. --- crates/ui-egui/src/panels/brush_controls.rs | 15 +++++++++-- crates/ui-egui/src/panels/options_bar.rs | 9 ++++--- crates/ui-egui/src/tools/retouch_ui.rs | 28 +++++++++++++++------ 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 4f30ac1bdf6..c14985f6f41 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -3,8 +3,19 @@ use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, Stro /// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the /// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's /// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none. -pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option], current: Option) -> Option> { - let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect(); +/// `threshold` names Normal "Threshold", as the reference does in an Indexed Color document. +pub(super) fn tool_mode_dropdown( + ui: &mut egui::Ui, + id: &str, + modes: &[Option], + current: Option, + threshold: bool, +) -> Option> { + let label = |m: &Option| match m { + Some(BlendMode::Normal) if threshold => tl!("Threshold"), + _ => m.map_or("Clear", BlendMode::label), + }; + let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, label(m))).collect(); let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m))); let mut mode = current; let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0; diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 895e6b0a02f..14be4368d48 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -151,9 +151,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind); } else if let Some(modes) = crate::blend_keys::tool_modes(tool) { opt_label(ui, tl!("Mode")); - if let Some(Some(m)) = - tool_mode_dropdown(ui, "retouch-mode", &modes, Some(crate::blend_keys::brush_tool_mode(tool, brush.mode))) - { + let mode = crate::blend_keys::brush_tool_mode(tool, brush.mode); + // Indexed Color names Normal "Threshold"; the other modes weren't measured. + let threshold = crate::retouch_ui::clone_stamp_indexed(app); + if let Some(Some(m)) = tool_mode_dropdown(ui, "retouch-mode", &modes, Some(mode), threshold) { brush.mode = m; } } @@ -518,7 +519,7 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: if let Some(modes) = crate::blend_keys::tool_modes(tool) { let o = &mut app.ui.tool_options; let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; - if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { + if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current, false) { o.bucket_clear = m.is_none(); if let Some(m) = m { o.bucket_blend_mode = m; diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 68abe3dfae2..6d047148511 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -35,7 +35,8 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { // The options bar's Mode is the tool's own brush's. let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode); // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). - let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); + let sample = if clone_stamp_indexed(app) { "current" } else { o.clone_sample.as_str() }; + let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); if app.ui.tool == Tool::CloneStamp { p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); @@ -52,6 +53,12 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { Some(p) } +/// The Clone Stamp in an Indexed Color document, where the reference greys Sample at Current Layer +/// and names the Normal Mode "Threshold" (#12613). +pub(crate) fn clone_stamp_indexed(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::CloneStamp && app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed) +} + /// History Brush params for the live preview and the commit (without `points` and `target`): the /// options bar's Mode and the tool's own brush. For an Eraser with Erase to History they also /// carry `eraseToHistory` and the Eraser's Pencil or Block tip. @@ -888,6 +895,17 @@ fn protect_tones_checkbox(ui: &mut egui::Ui, on: &mut bool) -> (egui::Response, (resp, label_resp.id) } +/// The Clone Stamp's and Healing Brush's Sample. `indexed` ([`clone_stamp_indexed`]) greys it at +/// Current Layer and leaves the stored choice for other documents. +fn clone_sample_dropdown(ui: &mut egui::Ui, stored: &mut String, indexed: bool) { + let opts = [("current", tl!("Current Layer")), ("currentAndBelow", tl!("Current & Below")), ("all", tl!("All Layers"))]; + let mut sample = if indexed { "current" } else { stored.as_str() }; + let changed = ui.add_enabled_ui(!indexed, |ui| crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut sample, &opts, 130.0)).inner; + if changed && !indexed { + *stored = sample.to_owned(); + } +} + /// Options bar for the retouching and smart-selection tools. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye) @@ -900,6 +918,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo return true; } let composite = crate::canvas::paint_target(app).as_str() == Some("pixels"); + let indexed = clone_stamp_indexed(app); let o = &mut app.ui.tool_options; match tool { Tool::SpotHealing => { @@ -965,12 +984,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo Tool::Healing | Tool::CloneStamp => { crate::widgets::checkbox(ui, &mut o.clone_aligned, tl!("Aligned")); opt(ui, tl!("Sample:")); - let opts = [ - ("current".to_string(), tl!("Current Layer")), - ("currentAndBelow".to_string(), tl!("Current & Below")), - ("all".to_string(), tl!("All Layers")), - ]; - crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut o.clone_sample, &opts, 130.0); + clone_sample_dropdown(ui, &mut o.clone_sample, indexed); if app.ui.clone_source.is_none() { crate::widgets::vline(ui, 22.0); opt(ui, &crate::i18n::fmt(tl!("{key}-click to set the source"), &[("key", &crate::shortcuts::pretty("Alt"))])); From 4252a5df58f1d0e364a3f84689b936aa18eb64ad Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:20:12 +0300 Subject: [PATCH 38/63] Test the Clone Stamp's options bar in an Indexed Color document --- .../src/clone_stamp_indexed_bar_tests.rs | 129 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + .../src/options_bar_mode_wheel_tests.rs | 8 +- 3 files changed, 136 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs diff --git a/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs b/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs new file mode 100644 index 00000000000..22d9591b898 --- /dev/null +++ b/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs @@ -0,0 +1,129 @@ +//! In an Indexed Color document the Clone Stamp's Sample is greyed at Current Layer and a stroke +//! samples the current layer, whatever Sample held; the Normal Mode reads "Threshold". Opacity, +//! Flow and Aligned stay enabled, and RGB documents keep the list, the label and the Sample choice. + +use egui::Modifiers; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::{Harness, Node}; +use photocraft_doc::BlendMode; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::options_bar_mode_wheel_tests::{brush_mode, harness, mode_dropdown, wheel}; +use crate::state::Tool; + +/// The Clone Stamp in a new document, Sample set to All Layers; `indexed` converts it first. +fn bar(indexed: bool) -> Harness<'static, PhotocraftApp> { + let mut h = harness(Tool::CloneStamp); + let app = h.state_mut(); + if indexed { + app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + } + app.ui.tool_options.clone_sample = "all".into(); + h.run_steps(4); + h +} + +/// The Sample dropdown: the one showing one of its choices. +fn sample<'a>(h: &'a Harness<'_, PhotocraftApp>) -> Node<'a> { + let choices = ["Current Layer", "Current & Below", "All Layers"]; + h.query_all_by_role(Role::ComboBox).find(|n| n.value().is_some_and(|v| choices.contains(&v.as_str()))).expect("the Sample dropdown") +} + +/// The options bar's field or checkbox named `name` ("Opacity:" in the Photoshop-look themes). +fn control<'a>(h: &'a Harness<'_, PhotocraftApp>, role: Role, name: &str) -> Node<'a> { + h.query_all_by_role(role).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == name)).unwrap_or_else(|| panic!("{name}")) +} + +/// An Alt-click for the source, then a drag, through the canvas: the committed stroke's params. +fn clone_stroke(h: &mut Harness<'_, PhotocraftApp>) -> Value { + let app = h.state_mut(); + tool_event(app, ToolEvent::Down { x: 40.0, y: 20.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(app, ToolEvent::Up { x: 40.0, y: 20.0 }, Modifiers::ALT); + tool_event(app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE); + let (id, params) = app.session.journal.last().unwrap(); + assert_eq!(id, "paint.cloneStamp", "{}", app.ui.status); + params.clone() +} + +#[test] +fn in_an_indexed_document_sample_is_greyed_at_current_layer() { + let h = bar(true); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("Current Layer")); + assert!(node.accesskit_node().is_disabled()); + assert_eq!(h.state().ui.tool_options.clone_sample, "all", "the stored choice is kept"); +} + +#[test] +fn a_stroke_in_an_indexed_document_samples_the_current_layer() { + let mut h = bar(true); + let steps = h.state().session.active().unwrap().history.past_len(); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "current"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one Clone Stamp state"); +} + +fn shows(h: &Harness<'_, PhotocraftApp>, value: &str) -> bool { + h.query_all_by_role(Role::ComboBox).any(|n| n.value().as_deref() == Some(value)) +} + +#[test] +fn in_an_indexed_document_normal_reads_threshold_in_the_same_list() { + let mut h = bar(true); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(shows(&h, "Threshold")); + // The list itself is today's: the wheel steps on to Dissolve and back. + let at = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Threshold")).unwrap().rect().center(); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert!(shows(&h, "Dissolve")); + wheel(&mut h, at, 1.0); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(shows(&h, "Threshold")); +} + +/// Other modes in Indexed Color weren't measured: they keep today's list. +#[test] +fn in_an_indexed_document_another_mode_keeps_the_list() { + let mut h = bar(true); + h.state_mut().session.tools.brush.mode = BlendMode::Dissolve; + h.run_steps(4); + assert!(shows(&h, "Dissolve")); + assert!(!shows(&h, "Threshold")); +} + +#[test] +fn back_in_rgb_sample_shows_and_sends_the_stored_choice() { + let mut h = bar(true); + h.state_mut().run("image.mode.rgb", json!({})).unwrap(); + h.run_steps(4); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("All Layers")); + assert!(!node.accesskit_node().is_disabled()); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all"); +} + +#[test] +fn opacity_flow_and_aligned_stay_enabled_in_an_indexed_document() { + let h = bar(true); + for (role, name) in [(Role::SpinButton, "Opacity"), (Role::SpinButton, "Flow"), (Role::CheckBox, "Aligned")] { + assert!(!control(&h, role, name).accesskit_node().is_disabled(), "{name}"); + } +} + +#[test] +fn rgb_documents_keep_the_mode_list_and_the_sample_choice() { + let mut h = bar(false); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("All Layers")); + assert!(!node.accesskit_node().is_disabled()); + assert!(!shows(&h, "Threshold")); + let at = mode_dropdown(&h).center(); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a816a79b871..22e5a82af50 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1100,3 +1100,6 @@ mod sponge_default_tip_tests; #[cfg(test)] mod red_eye_context_menu_tests; + +#[cfg(test)] +mod clone_stamp_indexed_bar_tests; diff --git a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs index 7870917ded5..84f8e55b87f 100644 --- a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs +++ b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs @@ -13,7 +13,7 @@ use crate::PhotocraftApp; use crate::state::Tool; /// The app with a new document and `tool` chosen. -fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { +pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -26,12 +26,12 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { } /// The options bar's Mode dropdown: the highest one showing `Normal` (the Layers panel's is lower). -fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect { +pub(super) fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect { h.query_all_by_role(Role::ComboBox).filter(|n| n.value().as_deref() == Some("Normal")).map(|n| n.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap() } /// `lines` wheel lines at `at` in one event: negative is down. -fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { +pub(super) fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { h.hover_at(at); h.run_steps(1); h.event(egui::Event::MouseWheel { @@ -44,7 +44,7 @@ fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { h.run_steps(3); } -fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode { +pub(super) fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode { h.state().session.tools.brush.mode } From 0926cf9663bdb3cf37ed34ad663cc60aa1aec45e Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:34:53 -0800 Subject: [PATCH 39/63] Scorecard: list the Free Transform scenarios --- docs/scorecard.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index b7fb8babd47..cc934308acd 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -6,7 +6,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| -| [Performance](#performance) | 3 | 22 | 54 | 88 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 50 not run, 4 not measurable yet (baseline 2026-10-05) | +| [Performance](#performance) | 3 | 22 | 56 | 90 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 52 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 8 of 199 (target 0) | @@ -110,6 +110,8 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl | P87 | Toggle a masked adjustment mid-stack in the layered document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P88 | Bring forward / send backward a small layer in the many-layer document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P89 | App frame after Paste Into on 24 MP (CPU canvas) | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | +| P90 | Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame) | track only | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | +| P91 | Free Transform drag update, 2 layers on 24 MP (scale through new mip levels) | track only | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | **Not measurable yet** (the code can't do it yet; no number is recorded): From be5778c4f87fb62b7df3b0ef3e43b34add7001df Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:14:39 +0300 Subject: [PATCH 40/63] Test the Pattern Stamp's Indexed Color refusal --- .../src/cmd/retouch_cmds/pattern_stamp.rs | 4 + .../pattern_stamp_indexed_tests.rs | 96 +++++++++++++++++++ .../src/options_bar_mode_wheel_tests.rs | 21 ++++ 3 files changed, 121 insertions(+) create mode 100644 crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index f5e4cb1e65e..c01ca41a9be 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -386,3 +386,7 @@ mod tests { assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err()); } } + +#[cfg(test)] +#[path = "pattern_stamp_indexed_tests.rs"] +mod pattern_stamp_indexed_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs new file mode 100644 index 00000000000..6fb7adc4c04 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs @@ -0,0 +1,96 @@ +//! #12887: in an Indexed Color document the Pattern Stamp refuses every pattern (RGB, Grayscale, +//! CMYK, Lab, or one defined from an Indexed image) with the reference application's message, +//! painting nothing and adding no history; the live strokes are refused the same way. RGB, +//! Grayscale, CMYK and Lab documents at every depth keep painting with it. + +use super::super::LiveRetouch; +use super::*; + +/// A new `mode` document of `depth` bits, 64 × 64, white. +fn new_doc(s: &mut Session, mode: &str, depth: u64) { + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap(); +} + +/// The reference's test pattern: 20 × 20 with red, green, blue and white quadrants, defined from a +/// `mode` document. Returns its id. +fn quadrants(s: &mut Session, mode: &str) -> String { + s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": mode})).unwrap(); + for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff")] { + s.execute("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + let r = s.execute("edit.definePattern", json!({"name": format!("Quadrants {mode}")})).unwrap(); + r["pattern"].as_str().unwrap().to_string() +} + +fn to_indexed(s: &mut Session) { + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); +} + +fn stroke(pattern: &str, impressionist: bool) -> Value { + json!({"points": [[12, 32], [52, 32]], "size": 30, "hardness": 100, "pattern": pattern, "impressionist": impressionist}) +} + +/// The active layer's pixels and the History length. +fn state(s: &Session) -> (Vec<[f32; 4]>, usize) { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + ((0..64).flat_map(|y| (0..64).map(move |x| surf.rgba(x, y))).collect(), st.history.past_len()) +} + +#[test] +fn an_rgb_pattern_is_refused_in_an_indexed_document_with_the_reference_words() { + let mut s = Session::new(); + let pat = quadrants(&mut s, "rgb"); + new_doc(&mut s, "rgb", 8); + to_indexed(&mut s); + let before = state(&s); + for impressionist in [false, true] { + let err = s.execute("paint.patternStamp", stroke(&pat, impressionist)).unwrap_err().to_string(); + assert_eq!(err, INDEXED_REFUSAL, "impressionist {impressionist}"); + assert_eq!(state(&s), before, "impressionist {impressionist}: nothing painted, no history"); + } + // The press check the canvas alerts with, and the live strokes, which preview nothing. + assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL)); + let live = LiveRetouch::begin(&s, "paint.patternStamp", &stroke(&pat, false)).err().map(|e| e.to_string()); + assert_eq!(live.as_deref(), Some(INDEXED_REFUSAL), "live"); + let dabs = live_impressionist(&s, &stroke(&pat, true)).err().map(|e| e.to_string()); + assert_eq!(dabs.as_deref(), Some(INDEXED_REFUSAL), "live Impressionist"); +} + +#[test] +fn other_documents_keep_painting_with_the_rgb_pattern() { + let mut s = Session::new(); + let pat = quadrants(&mut s, "rgb"); + for mode in ["rgb", "grayscale", "cmyk", "lab"] { + for depth in [8, 16, 32] { + new_doc(&mut s, mode, depth); + let (pixels, steps) = state(&s); + assert_eq!(press_refusal(&s, &stroke(&pat, false)), None, "{mode}/{depth}"); + s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + let after = state(&s); + assert_ne!(after.0, pixels, "{mode}/{depth}: painted"); + assert_eq!(after.1, steps + 1, "{mode}/{depth}: one history step"); + } + } +} + +#[test] +fn grayscale_cmyk_lab_and_indexed_patterns_are_refused_in_an_indexed_document_too() { + let mut s = Session::new(); + let mut patterns = ["grayscale", "cmyk", "lab"].map(|mode| quadrants(&mut s, mode)).to_vec(); + // A pattern defined from an Indexed Color image. + s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": "rgb"})).unwrap(); + to_indexed(&mut s); + patterns.push(s.execute("edit.definePattern", json!({"name": "Indexed"})).unwrap()["pattern"].as_str().unwrap().to_string()); + new_doc(&mut s, "rgb", 8); + to_indexed(&mut s); + let before = state(&s); + for pat in patterns { + let err = s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_err().to_string(); + assert_eq!(err, INDEXED_REFUSAL, "{pat}"); + assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL), "{pat}"); + assert_eq!(state(&s), before, "{pat}: nothing painted, no history"); + } +} diff --git a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs index 7870917ded5..cb72244fadf 100644 --- a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs +++ b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs @@ -127,6 +127,27 @@ fn the_pattern_stamp_mode_dropdown_has_behind() { assert_eq!(h.state().ui.tool, Tool::PatternStamp); } +/// The centre of a dropdown showing `value`. +fn combo(h: &Harness<'_, PhotocraftApp>, value: &str) -> Option { + h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some(value)).map(|n| n.rect().center()) +} + +/// In an Indexed Color document the Pattern Stamp's Mode reads "Threshold" for Normal (#12887); the +/// other entries weren't measured there, so the list and the wheel stay as today. +#[test] +fn the_pattern_stamp_mode_reads_threshold_in_an_indexed_document() { + let mut h = harness(Tool::PatternStamp); + h.state_mut().run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + h.run_steps(4); + let at = combo(&h, "Threshold").expect("Mode reads Threshold"); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert!(combo(&h, "Dissolve").is_some() && combo(&h, "Threshold").is_none(), "Dissolve reads as itself"); + wheel(&mut h, at, 1.0); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(combo(&h, "Threshold").is_some()); +} + /// The Paint Bucket's Mode dropdown has Clear after Dissolve, as the Brush's does. #[test] fn the_paint_bucket_mode_dropdown_has_clear() { From 48ebb1e2fd79d6aa3a1a58a508ca7c414cef551c Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:55:48 -0800 Subject: [PATCH 41/63] Free Transform bench: use a desktop GPU's texture limit --- crates/ui-egui/examples/free_transform_bench.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/examples/free_transform_bench.rs b/crates/ui-egui/examples/free_transform_bench.rs index bc13925f3a9..c0fc35f36f5 100644 --- a/crates/ui-egui/examples/free_transform_bench.rs +++ b/crates/ui-egui/examples/free_transform_bench.rs @@ -44,9 +44,13 @@ fn view(w: u32, h: u32) -> ViewXform { } } +/// The texture size limit a desktop GPU reports (egui's default without a renderer is 2048, +/// which would shrink the preview to a fraction of the layer and hide the cost being measured). +const MAX_TEXTURE_SIDE: usize = 16384; + /// One frame drawing the open box's preview, in milliseconds. fn frame(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> f64 { - let input = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; + let input = egui::RawInput { screen_rect: Some(xf.rect), max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() }; let start = Instant::now(); let output = ctx.run_ui(input, |ui| transform_tool::draw_content(app, ui.painter(), xf)); let ms = start.elapsed().as_secs_f64() * 1e3; @@ -90,7 +94,7 @@ fn main() { } let xf = view(w, h); let ctx = egui::Context::default(); - let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); + let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() }, |_| {}); // Ctrl+T and its first preview frame. let (mut begin, mut first, mut begin_total) = (Vec::new(), Vec::new(), Vec::new()); From b6643e30e8eb613908edd00755f404fd65d31145 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:17:50 -0800 Subject: [PATCH 42/63] Free Transform perf: set the begin and drag-update budgets from the measurements --- perf/budgets.toml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/perf/budgets.toml b/perf/budgets.toml index 8035b5ef365..67e69d0d5b8 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -898,7 +898,8 @@ title = "Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame)" issue = 11103 bench = "free_transform_bench" row = "Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame" -enforce = false # new; budget set from the #11103 measurements +budget_ms = 300 +enforce = true # #11103: 166 ms p50, 173 ms max (2026-11-11); a regression guard until the press frame is reworked [[scenario]] id = "P91" @@ -907,4 +908,5 @@ issue = 11103 bench = "free_transform_bench" row = "Free Transform drag update, 2 layers on 24 MP: scale through mip levels" metric = "max" -enforce = false # new; budget set from the #11103 measurements +budget_ms = 16 +enforce = true # #11103: max 43.2 ms before (a mip level built in the frame), 0.09 ms after (2026-11-11) From e459bcc824a3fa98fbf11b489a726ff2f779408a Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:19:19 -0800 Subject: [PATCH 43/63] Scorecard: Free Transform budgets --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index cc934308acd..c012feffd04 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -110,8 +110,8 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl | P87 | Toggle a masked adjustment mid-stack in the layered document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P88 | Bring forward / send backward a small layer in the many-layer document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P89 | App frame after Paste Into on 24 MP (CPU canvas) | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | -| P90 | Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame) | track only | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | -| P91 | Free Transform drag update, 2 layers on 24 MP (scale through new mip levels) | track only | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | +| P90 | Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame) | ≤ 300 ms p95 | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | +| P91 | Free Transform drag update, 2 layers on 24 MP (scale through new mip levels) | ≤ 16 ms max | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | **Not measurable yet** (the code can't do it yet; no number is recorded): From 4926f46604fd6403f6edefecaf19e13da7c13bb3 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:20:00 +0100 Subject: [PATCH 44/63] fix(ui): only a step the field took hides a typed whole-number value A wheel event that moves less than a notch, or not at all (a trackpad's zero-delta start), in the pass a value is typed counted as a step: the typed draft was dropped and leaving the field did not alert. The field now records the pass an arrow key or wheel notch stepped it, and the alerting wrapper reads that instead of guessing from the input. --- .../src/tools/polygon_sides_alert_tests.rs | 57 ++++++++++++++++++- crates/ui-egui/src/widgets/fields.rs | 19 ++++++- 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs index 399dcc86add..5d94f034b46 100644 --- a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs +++ b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs @@ -1,6 +1,6 @@ //! #13304: the Polygon tool's Sides takes whole numbers 3..100; a value typed past the range becomes //! the closest one and, once the field is left, the reference's "Closest value inserted" alert with -//! OK says so. A scrub or an arrow-key step past either end stops there without one. +//! OK says so. A scrub, arrow-key or wheel step past either end stops there without one. use egui::accesskit::Role; use egui::vec2; @@ -17,7 +17,14 @@ fn bar() -> Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); app.ui.tool = Tool::Polygon; - let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state( + |ui, app| { + // As the app's frame does: the wheel goes to the focused field. + crate::field_wheel::begin_frame(ui.ctx()); + crate::panels::options_bar(app, ui); + }, + app, + ); PhotocraftApp::setup_context(&h.ctx, Default::default()); h.run_steps(4); h @@ -131,3 +138,49 @@ fn a_caption_scrub_past_either_end_does_not_alert() { assert!(alerts(&h).is_empty(), "{start}: a scrub stops at the end without an alert"); } } + +fn wheel_event(unit: egui::MouseWheelUnit, dy: f32) -> egui::Event { + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + } +} + +#[test] +fn wheel_steps_past_either_end_stop_there_without_an_alert() { + for (start, lines, want) in [("99", 1.0, 100), ("4", -1.0, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + click_sides(&mut h); + for _ in 0..3 { + h.event(wheel_event(egui::MouseWheelUnit::Line, lines)); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the wheel reached the end"); + assert!(alerts(&h).is_empty(), "{start}: a wheel step stops at the end without an alert"); + } +} + +/// A wheel event that steps nothing (a trackpad's zero-delta start, or less than a notch) in the +/// frame a value is typed leaves it typed: it still alerts on the way out. +#[test] +fn a_wheel_event_that_steps_nothing_does_not_hide_a_typed_value() { + for (unit, dy) in [(egui::MouseWheelUnit::Point, 0.0), (egui::MouseWheelUnit::Point, 2.0)] { + let mut h = bar(); + click_sides(&mut h); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + // Both in one pass, as a trackpad can deliver them (`event` hands the app one per pass). + h.input_mut().events.extend([egui::Event::Text("101".into()), wheel_event(unit, dy)]); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), 100, "{dy} pt"); + assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{dy} pt: the typed 101 alerts"); + } +} diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index bbd7d387722..6d7615b3608 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -34,11 +34,11 @@ pub fn value_field_whole_alerting( let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32, Option)>(draft_id)); let draft = draft.filter(|(_, stored, field)| *stored == *value && field.is_some_and(|f| ui.ctx().memory(|m| m.has_focus(f)))); let mut typed = draft.map_or(*value, |(typed, _, _)| typed); - // Read before the field: it consumes the arrow keys it steps with, and the wheel it steps - // with while focused never shows in the scroll delta. A step is no typed value (#13304). - let stepped = ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx()); // The field's own range is wide, so the typed value reaches here unclamped. let r = value_field_named(ui, name, &mut typed, -1.0e9..=1.0e9, suffix, width); + // A step is no typed value (#13304). Only a step the field took counts: a wheel event that + // moves less than a notch (or not at all) steps nothing, and must not drop what was typed. + let stepped = stepped_this_pass(ui.ctx(), r.id); let out_id = r.id.with("out-of-range"); if r.gained_focus() { ui.ctx().data_mut(|d| d.remove_temp::(out_id)); @@ -316,6 +316,8 @@ fn value_field_box( // The text stays selected, as in Photoshop: typing after a step replaces the value. crate::field_tab::select_all(ui.ctx(), resp.id, &if fine { fmt_num2(f64::from(*value)) } else { fmt_num(f64::from(*value)) }); } + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(stepped_id(resp.id), pass)); resp.mark_changed(); } if ui.memory(|m| m.has_focus(resp.id)) { @@ -324,6 +326,17 @@ fn value_field_box( (resp, rect) } +/// Where a value field records the pass in which an arrow key or wheel notch last stepped it. +fn stepped_id(field: egui::Id) -> egui::Id { + field.with("stepped-pass") +} + +/// Whether the value field `field` was stepped this pass by an arrow key or a wheel notch. +fn stepped_this_pass(ctx: &egui::Context, field: egui::Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(stepped_id(field))) == Some(pass) +} + /// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box. pub const POPUP_ARROW_W: f32 = 14.0; From ea009ae189ecee0bcbdbb8ebe09a56d35f9fe09c Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:50:15 +0300 Subject: [PATCH 45/63] Pattern Stamp: Opacity and Flow on the options bar and in its strokes The bar showed them only for the Clone Stamp and the History Brush, and pattern_stamp_params sent neither, so paint.patternStamp always painted at 100 %. The Pattern Stamp's fields are whole percents 1..100 with the Brush's tooltips, as in the reference (#12616). A first pick starts it at 100 / 100 instead of taking the previous tool's Opacity and Flow. --- crates/ui-egui/src/canvas/paint_mouse.rs | 12 +++++++++--- crates/ui-egui/src/panels/options_bar.rs | 13 ++++++++++--- crates/ui-egui/src/tools/retouch_ui.rs | 2 ++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index b5cfab7f2ba..d906c4e22c3 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -40,7 +40,8 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). - // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. + // The Art History Brush also starts at full opacity (#10263), and the Pattern Stamp at full + // opacity and flow (#12616): those fields are their own. // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools and the Clone // Stamp start with their own measured tips instead, as the whole brush Reset Tool gives // them (#11911, #12099, #12671, #12684, #13029, #12601). @@ -48,10 +49,15 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { fresh_brush(tool, ¤t) } None => { - let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; + let fresh = BrushSettings::default(); + let (opacity, flow) = match tool { + Tool::ArtHistoryBrush => (fresh.opacity, current.flow), + Tool::PatternStamp => (fresh.opacity, fresh.flow), + _ => (current.opacity, current.flow), + }; // The Remove tool starts at its measured 19 px; the rest is the current brush (#12548). let size = if tool == Tool::Remove { REMOVE_TOOL_SIZE } else { current.size }; - BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, size, ..current } + BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, flow, size, ..current } } }; // The picked preset was the outgoing tool's brush: forget it, so Update Brush can't overwrite diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 895e6b0a02f..c252f61986a 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -157,10 +157,17 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { brush.mode = m; } } - if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { + if matches!(tool, Tool::CloneStamp | Tool::PatternStamp | Tool::HistoryBrush) { let width = if t.pro { 62.0 } else { 66.0 }; - percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); - percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); + // The Pattern Stamp's are whole percents as measured; the Brush's tooltips (#12616). + let pattern = tool == Tool::PatternStamp; + let field = if pattern { whole_percent_field } else { percent_field }; + let opacity = field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); + let flow = field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); + if pattern { + opacity.on_hover_text(tl!("Set opacity for stroke")); + flow.on_hover_text(tl!("Set flow rate for stroke")); + } } // Art History has no Mode (the engine paints Normal) and no Flow. if tool == Tool::ArtHistoryBrush { diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 68abe3dfae2..e7fbd62b54c 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -177,6 +177,8 @@ pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> "seed": stroke_seed(points), // The options bar's Mode is the tool's own brush's; Behind is a mode of that list. "mode": if app.session.tools.brush.behind { "Behind" } else { app.session.tools.brush.mode.label() }, + "opacity": app.session.tools.brush.opacity * 100.0, + "flow": app.session.tools.brush.flow * 100.0, }); if o.pattern_stamp_aligned && let Some(ph) = app.ui.pattern_stamp_phase From 23d2574798f3a88cf1e08c6d83b12fff9b9df653 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:50:15 +0300 Subject: [PATCH 46/63] Test the Pattern Stamp's Opacity and Flow --- crates/ui-egui/src/panels/options_bar.rs | 4 + .../src/pattern_stamp_opacity_flow_tests.rs | 177 ++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index c252f61986a..3af616cbc50 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1055,3 +1055,7 @@ mod sharpen_strength_alert_tests; #[cfg(test)] #[path = "../smudge_strength_alert_tests.rs"] mod smudge_strength_alert_tests; + +#[cfg(test)] +#[path = "../pattern_stamp_opacity_flow_tests.rs"] +mod pattern_stamp_opacity_flow_tests; diff --git a/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs b/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs new file mode 100644 index 00000000000..13cfa738005 --- /dev/null +++ b/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs @@ -0,0 +1,177 @@ +//! #12616: the Pattern Stamp's options bar has Opacity and Flow after Mode (whole percents 1..100, +//! default 100, the reference's tooltips, the Brush's silent clamp for a typed value past the +//! range), its strokes paint with them, live and committed alike, and Reset Tool puts both back +//! to 100. + +use std::collections::BTreeSet; + +use egui::accesskit::Role; +use egui::{Modifiers, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::eraser_range_alert_tests::{alerts, bar, type_into}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, display_doc, tool_event}; +use crate::state::Tool; + +/// The field named `label` ("Opacity", "Flow"), by its caption's name. +fn field<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> { + let label = format!("{label}:"); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label.as_str())).unwrap_or_else(|| panic!("the {label} field")) +} + +/// The live brush's Opacity and Flow in percent. +fn opacity_flow(app: &PhotocraftApp) -> (f32, f32) { + let b = &app.session.tools.brush; + ((b.opacity * 100.0).round(), (b.flow * 100.0).round()) +} + +#[test] +fn the_bar_shows_opacity_and_flow_after_mode_at_100() { + let h = bar(Tool::PatternStamp); + let mode = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Normal")).expect("the Mode dropdown").rect(); + let (opacity, flow) = (field(&h, "Opacity"), field(&h, "Flow")); + assert_eq!((opacity.accesskit_node().numeric_value(), flow.accesskit_node().numeric_value()), (Some(100.0), Some(100.0))); + assert_eq!(opacity.accesskit_node().description().as_deref(), Some("Set opacity for stroke")); + assert_eq!(flow.accesskit_node().description().as_deref(), Some("Set flow rate for stroke")); + let (opacity, flow) = (opacity.rect(), flow.rect()); + assert!(mode.right() <= opacity.left() && opacity.right() <= flow.left(), "Mode, Opacity, Flow: {mode:?} {opacity:?} {flow:?}"); +} + +#[test] +fn typed_values_are_whole_percents_clamped_to_1_100_without_an_alert() { + let mut h = bar(Tool::PatternStamp); + for (opacity, flow, want) in [("50", "10", (50.0, 10.0)), ("37.6", "12.4", (38.0, 12.0)), ("150", "0", (100.0, 1.0))] { + type_into(&mut h, "Opacity", opacity); + type_into(&mut h, "Flow", flow); + assert_eq!(opacity_flow(h.state()), want, "typed {opacity} / {flow}"); + assert!(alerts(&h).is_empty(), "the Brush's fields clamp silently"); + } + let b = &h.state().session.tools.brush; + assert_eq!((b.opacity, b.flow), (1.0, 0.01), "stored as whole percents"); +} + +#[test] +fn reset_tool_puts_opacity_and_flow_back_to_100() { + let mut h = bar(Tool::PatternStamp); + type_into(&mut h, "Opacity", "40"); + type_into(&mut h, "Flow", "25"); + assert_eq!(opacity_flow(h.state()), (40.0, 25.0)); + crate::burn_default_tip_tests::invoke(h.state_mut(), "tool.reset", json!({})); + h.run_steps(3); + assert_eq!(opacity_flow(h.state()), (100.0, 100.0)); + assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0)); + assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0)); +} + +/// The issue's test document: 800 × 600 RGB 8 bit, white with its right half green (40,160,60), +/// a 20 × 20 pattern of 10 px quadrants (red, green / blue, white) and the Pattern Stamp with a +/// 40 px hard tip, Aligned on, at `opacity` and `flow` (fractions). +fn document(opacity: f32, flow: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 20})).unwrap(); + for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff"), (10, 10, "#ffffff")] { + app.run("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + let pattern = app.run("edit.definePattern", json!({"name": "Quadrants", "rect": [0, 0, 20, 20]})).unwrap()["pattern"].clone(); + app.run("pattern.presets.select", json!({"pattern": pattern})).unwrap(); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 400, "y": 0, "width": 400, "height": 600})).unwrap(); + app.run("edit.fill", json!({"color": "#28a03c"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::PatternStamp; + app.ui.tool_options.pattern_stamp_aligned = true; + crate::paint_mouse::sync_tool_brush(&mut app); + let brush = json!({"size": 40, "hardness": 1.0, "opacity": opacity, "flow": flow, "pressureSize": false, "smoothing": {"amount": 0.0}}); + app.run("tools.setBrush", json!({"brush": brush})).unwrap(); + app +} + +/// The distinct 8-bit colours inside the tip of a click at (600, 300), in `doc`. +fn colours(doc: &photocraft_doc::Document, app: &PhotocraftApp) -> BTreeSet<[u8; 3]> { + let surf = doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap(); + let inside = Rect::from_center_size(egui::pos2(600.0, 300.0), egui::vec2(24.0, 24.0)); + let (x0, y0, x1, y1) = (inside.left() as i32, inside.top() as i32, inside.right() as i32, inside.bottom() as i32); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).map(|c| [c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8)).collect() +} + +/// One click at (600, 300) on the green half: what the canvas showed before the release, and what +/// the release committed. +fn click(app: &mut PhotocraftApp) -> (BTreeSet<[u8; 3]>, BTreeSet<[u8; 3]>) { + tool_event(app, ToolEvent::Down { x: 600.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.live_stroke.is_some(), "the stroke draws live"); + // The canvas shows the second document; the first holds the pattern. + let idx = app.session.active_index().unwrap(); + let shown = colours(&display_doc(app, idx).0, app); + tool_event(app, ToolEvent::Up { x: 600.0, y: 300.0 }, Modifiers::NONE); + assert!(!app.ui.status_error, "{}", app.ui.status); + let committed = colours(&app.session.active().unwrap().doc, app); + (shown, committed) +} + +/// The reference's values for Opacity 50, and for Flow 50 (the same): half the pattern over green. +const HALF: [[u8; 3]; 4] = [[148, 80, 30], [20, 208, 30], [20, 80, 158], [148, 208, 158]]; + +#[test] +fn opacity_50_paints_the_reference_values_live_and_committed() { + let mut app = document(0.5, 1.0); + let (shown, committed) = click(&mut app); + assert_eq!(committed, BTreeSet::from(HALF)); + assert_eq!(shown, committed, "the live preview and the commit agree"); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(50.0), Some(100.0)), "{params}"); +} + +#[test] +fn flow_50_paints_the_same_values_as_opacity_50() { + let mut app = document(1.0, 0.5); + let (shown, committed) = click(&mut app); + assert_eq!(committed, BTreeSet::from(HALF)); + assert_eq!(shown, committed); +} + +#[test] +fn flow_10_paints_about_10_percent() { + let mut app = document(1.0, 0.1); + let (shown, committed) = click(&mut app); + assert_eq!(shown, committed); + // Red over green: the reference's 62,144,54. + let red = committed.iter().find(|c| c[0] > c[2] && c[1] < 150).copied().expect("the red cells"); + assert!(red.iter().zip([62u8, 144, 54]).all(|(a, b)| a.abs_diff(b) <= 1), "{red:?} in {committed:?}"); +} + +/// A first pick doesn't carry the Brush's Opacity and Flow over: the Pattern Stamp starts at 100. +#[test] +fn a_first_pick_after_a_30_percent_brush_starts_at_100() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"opacity": 0.3, "flow": 0.4}})).unwrap(); + h.run_steps(3); + h.state_mut().ui.tool = Tool::PatternStamp; + h.run_steps(4); + assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0)); + assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0)); + let app = h.state_mut(); + assert!(crate::retouch_ui::finish_stroke(app, Tool::PatternStamp, &[[40.0, 40.0, 1.0]], Modifiers::NONE, false)); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(100.0), Some(100.0)), "{params}"); +} + +/// Impressionist strokes take Opacity too (not measured: only that they paint with it, live and +/// committed alike). +#[test] +fn an_impressionist_stroke_paints_with_opacity_live_and_committed() { + let painted = |opacity: f32| { + let mut app = document(opacity, 1.0); + app.ui.tool_options.pattern_stamp_impressionist = true; + let (shown, committed) = click(&mut app); + assert_eq!(shown, committed, "opacity {opacity}: the live preview and the commit agree"); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!(params["opacity"].as_f64(), Some(f64::from(opacity) * 100.0), "{params}"); + committed + }; + assert_ne!(painted(0.5), painted(1.0), "Opacity 50 paints differently from 100"); +} From af627c0314e0da0344bbafa902c563c9539c6873 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:15:23 -0800 Subject: [PATCH 47/63] Free Transform: count only the preview as the owner of a mip level being built --- crates/ui-egui/src/tools/transform_tex.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index 56872f28882..e9af47aee7f 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -162,19 +162,23 @@ impl PreviewTextures { } building.push((level, display_key)); } - let (images, uploaded, building) = (Arc::clone(&self.images), Arc::clone(&self.uploaded), Arc::clone(&self.building)); + // Only the preview owns `uploaded`: workers hold it weakly, so another level still building + // doesn't count as a preview to upload for. + let (images, uploaded, building) = (Arc::clone(&self.images), Arc::downgrade(&self.uploaded), Arc::clone(&self.building)); let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name)); let display = display.map(share_display); let job = move || { let built = level_of(&images, base_uv, level); - // Nobody left to show it (the box closed meanwhile): don't upload. - if let Some((img, uv)) = built.filter(|_| Arc::strong_count(&uploaded) > 1) { + // Nobody left to show it (the box closed meanwhile): neither convert nor upload. + if let Some((img, uv)) = built.filter(|_| uploaded.strong_count() > 0) { let img = display.as_ref().map_or_else(|| Arc::clone(&img), |d| Arc::new(display_image(&img, d))); - let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); - let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); - // A monitor profile change meanwhile released this display's uploads: drop it. - if up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { - up.push(Level { level, display_key, nearest: false, tex, uv }); + if let Some(uploaded) = uploaded.upgrade() { + let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); + let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); + // A monitor profile change meanwhile released this display's uploads: drop it. + if up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { + up.push(Level { level, display_key, nearest: false, tex, uv }); + } } } building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); From e344c8fe1107e3a5f01be392ca42aabd1fbc601e Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:43:20 -0800 Subject: [PATCH 48/63] Free Transform: a closed preview's flag, not its references, stops mip uploads --- crates/ui-egui/src/tools/transform_tex.rs | 48 ++++++++++++++----- .../ui-egui/src/transform_drag_start_tests.rs | 24 ++++++++++ 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index e9af47aee7f..2f5d6ed2338 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -16,6 +16,7 @@ //! helper thread, and the closest finer level already uploaded is shown until it is ready //! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use egui::{Color32, ColorImage, TextureHandle, TextureId, TextureOptions}; @@ -41,6 +42,19 @@ pub struct PreviewTextures { building: Arc>>, /// Whether a mip level that has a finer level to stand in for it is built off the UI thread. background: bool, + /// Cleared when the preview closes (under the `uploaded` lock): a level finishing after that is + /// neither converted nor uploaded. Workers only read it, so they never keep the preview alive. + alive: Arc, + /// Held by a test to pause the workers just before they check `alive`. + #[cfg(test)] + gate: Arc>, +} + +impl Drop for PreviewTextures { + fn drop(&mut self) { + let _uploads = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner); + self.alive.store(false, Ordering::Release); + } } /// Off the UI thread on native builds; the web build has no threads to spare. Unit tests build @@ -63,6 +77,9 @@ impl PreviewTextures { uploaded: Arc::new(Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }])), building: Arc::new(Mutex::new(Vec::new())), background: BUILD_IN_BACKGROUND, + alive: Arc::new(AtomicBool::new(true)), + #[cfg(test)] + gate: Arc::new(Mutex::new(())), } } @@ -78,6 +95,14 @@ impl PreviewTextures { !self.building.lock().unwrap_or_else(PoisonError::into_inner).is_empty() } + /// What a test locks to pause the workers just before they check that the preview is open, + /// and what tells it they are all done, which still works once the preview is gone. + #[cfg(test)] + pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>) { + let building = Arc::clone(&self.building); + (Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty()) + } + /// Size of the full-resolution level in texels. pub fn size(&self) -> [usize; 2] { self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |i| i.size) @@ -162,23 +187,24 @@ impl PreviewTextures { } building.push((level, display_key)); } - // Only the preview owns `uploaded`: workers hold it weakly, so another level still building - // doesn't count as a preview to upload for. - let (images, uploaded, building) = (Arc::clone(&self.images), Arc::downgrade(&self.uploaded), Arc::clone(&self.building)); + let (images, uploaded, building, alive) = (Arc::clone(&self.images), Arc::clone(&self.uploaded), Arc::clone(&self.building), Arc::clone(&self.alive)); let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name)); let display = display.map(share_display); + #[cfg(test)] + let gate = Arc::clone(&self.gate); let job = move || { let built = level_of(&images, base_uv, level); - // Nobody left to show it (the box closed meanwhile): neither convert nor upload. - if let Some((img, uv)) = built.filter(|_| uploaded.strong_count() > 0) { + #[cfg(test)] + drop(gate.lock().unwrap_or_else(PoisonError::into_inner)); + // The box closed meanwhile: neither convert nor upload. + if let Some((img, uv)) = built.filter(|_| alive.load(Ordering::Acquire)) { let img = display.as_ref().map_or_else(|| Arc::clone(&img), |d| Arc::new(display_image(&img, d))); - if let Some(uploaded) = uploaded.upgrade() { + let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); + // Checked again under the lock the preview takes as it closes. A monitor profile + // change meanwhile released this display's uploads: drop it then too. + if alive.load(Ordering::Acquire) && up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); - let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); - // A monitor profile change meanwhile released this display's uploads: drop it. - if up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { - up.push(Level { level, display_key, nearest: false, tex, uv }); - } + up.push(Level { level, display_key, nearest: false, tex, uv }); } } building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs index af146f504df..f4150c25334 100644 --- a/crates/ui-egui/src/transform_drag_start_tests.rs +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -260,3 +260,27 @@ fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() { assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}"); ctx.tex_manager().write().take_delta().clear(); } + +/// A box closed while two levels were still building: neither worker converts or uploads its +/// level, though each still holds the preview's shared state (#13382 review). +#[test] +fn levels_finishing_after_the_box_closed_are_not_uploaded() { + let ctx = egui::Context::default(); + let before = ctx.tex_manager().read().num_allocated(); + let t = textures(&ctx); + let _ = t.pick(&ctx, 1.0, 1.0, false); + let (gate, done) = t.worker_hooks(); + let held = gate.lock().unwrap(); + // Levels 1 and 3, each on its own worker, both paused before they check the box is open. + let _ = t.pick(&ctx, 0.3, 1.0, false); + let _ = t.pick(&ctx, 0.1, 1.0, false); + drop(t); + drop(held); + let start = Instant::now(); + while !done() { + assert!(start.elapsed() < Duration::from_secs(10), "the workers finish"); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(ctx.tex_manager().read().num_allocated(), before, "nothing uploaded for the closed box"); + ctx.tex_manager().write().take_delta().clear(); +} From 6eeaf31f7567a29080cd5f2dec82f08fefa8f477 Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:58:27 -0800 Subject: [PATCH 49/63] Free Transform tests: count mip uploads, not textures left --- crates/ui-egui/src/tools/transform_tex.rs | 18 +++++++++---- .../ui-egui/src/transform_drag_start_tests.rs | 26 ++++++++++++++++--- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index 2f5d6ed2338..00ad295b4f5 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -16,7 +16,7 @@ //! helper thread, and the closest finer level already uploaded is shown until it is ready //! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread. -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use egui::{Color32, ColorImage, TextureHandle, TextureId, TextureOptions}; @@ -48,6 +48,9 @@ pub struct PreviewTextures { /// Held by a test to pause the workers just before they check `alive`. #[cfg(test)] gate: Arc>, + /// How many levels the workers have uploaded, for tests. + #[cfg(test)] + uploads: Arc, } impl Drop for PreviewTextures { @@ -80,6 +83,8 @@ impl PreviewTextures { alive: Arc::new(AtomicBool::new(true)), #[cfg(test)] gate: Arc::new(Mutex::new(())), + #[cfg(test)] + uploads: Arc::new(AtomicUsize::new(0)), } } @@ -96,11 +101,12 @@ impl PreviewTextures { } /// What a test locks to pause the workers just before they check that the preview is open, - /// and what tells it they are all done, which still works once the preview is gone. + /// what tells it they are all done, and how many levels they uploaded; the last two still work + /// once the preview is gone. #[cfg(test)] - pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>) { + pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>, Arc) { let building = Arc::clone(&self.building); - (Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty()) + (Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty(), Arc::clone(&self.uploads)) } /// Size of the full-resolution level in texels. @@ -191,7 +197,7 @@ impl PreviewTextures { let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name)); let display = display.map(share_display); #[cfg(test)] - let gate = Arc::clone(&self.gate); + let (gate, uploads) = (Arc::clone(&self.gate), Arc::clone(&self.uploads)); let job = move || { let built = level_of(&images, base_uv, level); #[cfg(test)] @@ -204,6 +210,8 @@ impl PreviewTextures { // change meanwhile released this display's uploads: drop it then too. if alive.load(Ordering::Acquire) && up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); + #[cfg(test)] + uploads.fetch_add(1, Ordering::Relaxed); up.push(Level { level, display_key, nearest: false, tex, uv }); } } diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs index f4150c25334..0892e81ccfb 100644 --- a/crates/ui-egui/src/transform_drag_start_tests.rs +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -262,14 +262,14 @@ fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() { } /// A box closed while two levels were still building: neither worker converts or uploads its -/// level, though each still holds the preview's shared state (#13382 review). +/// level, though each still holds the preview's shared state (#13382 review). Counted as uploads, +/// not as textures left, which an upload freed again at once would also pass. #[test] fn levels_finishing_after_the_box_closed_are_not_uploaded() { let ctx = egui::Context::default(); - let before = ctx.tex_manager().read().num_allocated(); let t = textures(&ctx); let _ = t.pick(&ctx, 1.0, 1.0, false); - let (gate, done) = t.worker_hooks(); + let (gate, done, uploads) = t.worker_hooks(); let held = gate.lock().unwrap(); // Levels 1 and 3, each on its own worker, both paused before they check the box is open. let _ = t.pick(&ctx, 0.3, 1.0, false); @@ -281,6 +281,24 @@ fn levels_finishing_after_the_box_closed_are_not_uploaded() { assert!(start.elapsed() < Duration::from_secs(10), "the workers finish"); std::thread::sleep(Duration::from_millis(2)); } - assert_eq!(ctx.tex_manager().read().num_allocated(), before, "nothing uploaded for the closed box"); + assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 0, "nothing uploaded for the closed box"); + ctx.tex_manager().write().take_delta().clear(); +} + +/// The same two workers with the box still open: both upload, so the count above means something. +#[test] +fn levels_finishing_while_the_box_is_open_are_uploaded() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let _ = t.pick(&ctx, 1.0, 1.0, false); + let (_, done, uploads) = t.worker_hooks(); + let _ = t.pick(&ctx, 0.3, 1.0, false); + let _ = t.pick(&ctx, 0.1, 1.0, false); + let start = Instant::now(); + while !done() { + assert!(start.elapsed() < Duration::from_secs(10), "the workers finish"); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 2); ctx.tex_manager().write().take_delta().clear(); } From c699bfeed4f0a66c16d7b925c0a3d060aaa9efcd Mon Sep 17 00:00:00 2001 From: tjbbjt <102318757+tjbbjt@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:05:03 -0800 Subject: [PATCH 50/63] Free Transform: name the test-only upload counter in full --- crates/ui-egui/src/tools/transform_tex.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index 00ad295b4f5..77dbfbd79a3 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -16,7 +16,7 @@ //! helper thread, and the closest finer level already uploaded is shown until it is ready //! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread. -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use egui::{Color32, ColorImage, TextureHandle, TextureId, TextureOptions}; @@ -50,7 +50,7 @@ pub struct PreviewTextures { gate: Arc>, /// How many levels the workers have uploaded, for tests. #[cfg(test)] - uploads: Arc, + uploads: Arc, } impl Drop for PreviewTextures { @@ -84,7 +84,7 @@ impl PreviewTextures { #[cfg(test)] gate: Arc::new(Mutex::new(())), #[cfg(test)] - uploads: Arc::new(AtomicUsize::new(0)), + uploads: Arc::new(std::sync::atomic::AtomicUsize::new(0)), } } @@ -104,7 +104,7 @@ impl PreviewTextures { /// what tells it they are all done, and how many levels they uploaded; the last two still work /// once the preview is gone. #[cfg(test)] - pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>, Arc) { + pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>, Arc) { let building = Arc::clone(&self.building); (Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty(), Arc::clone(&self.uploads)) } From 18c9fec23c2d16701edcb49299d5707ff77cd500 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 12 Nov 2026 19:02:15 +0530 Subject: [PATCH 51/63] Path Selection: Enter deselects the components and untargets the path, Escape deselects them (#13287) With components of the targeted saved path selected, Escape clears the component selection and keeps the path targeted and drawn; Enter also untargets the path. Neither adds a History step. Free Transform Path and Cmd+Enter keep their keys, and every unmeasured case keeps today's behaviour. --- crates/ui-egui/src/input/shortcuts.rs | 25 +++ crates/ui-egui/src/tools/path_components.rs | 10 ++ .../path_selection_enter_escape_tests.rs | 144 ++++++++++++++++++ 3 files changed, 179 insertions(+) create mode 100644 crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 51970cbe3b5..13c9e2d8b6f 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -955,6 +955,31 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } } + // Path Selection (#13287): with components of the saved path targeted in the Paths panel + // selected, Esc deselects the components and keeps the path targeted and drawn, while a plain + // Enter deselects the components and also untargets the path (its Paths panel row and outline + // go). Neither adds a History step. Free Transform Path and ⌘↩ (Make Selection) took their + // keys earlier; with no component selected both keys keep today's behaviour. Not while the + // path's name is typed in the panel. + if !esc_taken + && app.ui.tool == Tool::PathSelection + && !crate::vector_ui::path_renaming(app, ctx) + && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) + && let Some((crate::direct_select::PathRef::Saved(i), ..)) = crate::path_components::selected(app) + && i == index + { + if pressed(Key::Escape) { + crate::path_components::deselect_components(app); + return; + } + if pressed(Key::Enter) { + crate::path_components::deselect_components(app); + if let Some(name) = app.ui.selected_path.clone() { + crate::vector_ui::deselect_loaded_path(app, &name); + } + return; + } + } // + / − pick a Path Operation with the Pen tools and Path Selection (`path_components`)… crate::path_components::handle_keys(app, ctx); // … and otherwise ⇧+ / ⇧− step the blend mode and ⇧⌥ letters pick one (`blend_keys`). Before the diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 041279b748c..b6caeebe1e0 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -52,6 +52,12 @@ pub(crate) fn selected(app: &PhotocraftApp) -> Option<(PathRef, Path, Vec (!heads.is_empty()).then_some((r, path, heads)) } +/// Deselects every component (and anchor), leaving the path itself as it is. Shared with Direct +/// Selection's Enter (#13208). +pub(crate) fn deselect_components(app: &mut PhotocraftApp) { + app.ui.direct_selection = DirectSelection::default(); +} + /// The operation every selected component has, for the menu's icon; `None` when they differ. pub(crate) fn selected_op(app: &PhotocraftApp) -> Option<&'static str> { let (_, path, heads) = selected(app)?; @@ -272,3 +278,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "path_selection_enter_escape_tests.rs"] +mod path_selection_enter_escape_tests; diff --git a/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs new file mode 100644 index 00000000000..92df008031f --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs @@ -0,0 +1,144 @@ +//! #13287: with Path Selection and components of the saved path targeted in the Paths panel +//! selected, Esc deselects the components and keeps the path targeted, and Enter deselects them and +//! untargets the path. Neither adds a History step or moves a point. + +use egui::{Key, Modifiers}; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::direct_select::{DirectSelection, PathRef, active_paths}; +use crate::state::Tool; + +/// 800 x 600 with the saved path "Path 1" (a square and a triangle) targeted, and the square +/// selected as a component. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": true, "knots": [[400, 300], [600, 300], [500, 500]]} + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PathSelection; + app.ui.selected_path = Some("Path 1".into()); + crate::path_components::press(&mut app, [300.0, 300.0], false); + let (target, ..) = crate::path_components::selected(&app).expect("the square is selected"); + assert_eq!(target, PathRef::Saved(0)); + app +} + +fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + ctx.begin_pass(egui::RawInput { events: vec![ev], ..Default::default() }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn path_1(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +fn nothing_selected(app: &PhotocraftApp) { + assert!(crate::path_components::selected(app).is_none(), "no component is selected"); + assert_eq!(app.ui.direct_selection, DirectSelection::default()); +} + +/// Until Path Selection has its own arrow-key nudge (#10920), an arrow key must move nothing once +/// the components are deselected. +fn arrow_moves_nothing(app: &mut PhotocraftApp) { + let (before, n) = (path_1(app), steps(app)); + press(app, Key::ArrowRight, Modifiers::NONE); + assert_eq!(path_1(app), before, "the arrow key moves no point"); + assert_eq!(steps(app), n, "and adds no History step"); +} + +#[test] +fn enter_deselects_the_components_and_untargets_the_path() { + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + press(&mut app, Key::Enter, Modifiers::NONE); + nothing_selected(&app); + assert_eq!(app.ui.selected_path, None, "Path 1 is no longer targeted"); + assert!(!active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline is gone"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "Enter adds no History step"); + arrow_moves_nothing(&mut app); +} + +#[test] +fn escape_deselects_the_components_and_keeps_the_path_targeted() { + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + press(&mut app, Key::Escape, Modifiers::NONE); + nothing_selected(&app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1")); + assert!(active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline stays"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "Esc adds no History step"); + arrow_moves_nothing(&mut app); +} + +#[test] +fn enter_with_a_work_path_present_does_not_make_the_work_path_the_drawn_path() { + let mut app = app(); + let line = json!({"subpaths": [{"knots": [[100, 100], [200, 100]]}]}); + app.run("path.set", json!({"name": "work", "path": line})).unwrap(); + // `path.set` of the Work Path changes the panel's target: target Path 1 and its component again. + app.ui.selected_path = Some("Path 1".into()); + crate::path_components::press(&mut app, [300.0, 300.0], false); + assert!(crate::path_components::selected(&app).is_some()); + press(&mut app, Key::Enter, Modifiers::NONE); + assert_eq!(app.ui.selected_path, None); + assert!(!crate::vector_ui::work_path_shown(&app), "the Work Path stays hidden"); + assert!(active_paths(&app).is_empty(), "no path is drawn"); +} + +#[test] +fn escape_with_a_pixel_selection_deselects_the_pixels_and_keeps_the_components() { + let mut app = app(); + app.run("select.all", json!({})).unwrap(); + press(&mut app, Key::Escape, Modifiers::NONE); + assert!(app.session.active().unwrap().doc.selection.is_none(), "Esc deselects the pixels"); + assert!(crate::path_components::selected(&app).is_some(), "the components stay selected"); +} + +#[test] +fn enter_and_escape_with_no_component_selected_keep_the_path_targeted() { + for key in [Key::Enter, Key::Escape] { + let mut app = app(); + crate::path_components::deselect_components(&mut app); + press(&mut app, key, Modifiers::NONE); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?}"); + } +} + +#[test] +fn free_transform_path_still_owns_enter_and_escape() { + let ctx = egui::Context::default(); + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(app.ui.transform.is_some()); + press(&mut app, Key::Escape, Modifiers::NONE); + assert!(app.ui.transform.is_none(), "Esc cancels the transform"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "cancelling adds no History step"); + + let mut app = self::app(); + let n = steps(&app); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + // 5 px down: an unchanged box commits nothing. + let t = app.ui.transform.as_mut().unwrap(); + let [x0, y0, x1, y1] = t.rect; + t.quad = [[x0, y0 + 5.0], [x1, y0 + 5.0], [x1, y1 + 5.0], [x0, y1 + 5.0]]; + press(&mut app, Key::Enter, Modifiers::NONE); + assert!(app.ui.transform.is_none(), "Enter commits the transform"); + assert_eq!(steps(&app), n + 1, "one History step"); +} From 19c623c00cab14b194a8579a66c87a2273a65c3f Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 12 Nov 2026 21:47:43 +0530 Subject: [PATCH 52/63] Path Selection: only bare Enter / Escape deselect the components (#13287) consume_key also matches the keys with Shift or Alt held; those cases were not measured, so they keep today's behaviour. --- crates/ui-egui/src/input/shortcuts.rs | 14 +++++++++++--- .../src/tools/path_selection_enter_escape_tests.rs | 12 ++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 13c9e2d8b6f..cac770fb8e8 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -960,7 +960,15 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // Enter deselects the components and also untargets the path (its Paths panel row and outline // go). Neither adds a History step. Free Transform Path and ⌘↩ (Make Selection) took their // keys earlier; with no component selected both keys keep today's behaviour. Not while the - // path's name is typed in the panel. + // path's name is typed in the panel. Only the bare keys: `consume_key` would also take them with + // ⇧ or ⌥, which were not measured. + let bare = |k: Key| { + ctx.input_mut(|i| { + let n = i.events.len(); + i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none())); + i.events.len() != n + }) + }; if !esc_taken && app.ui.tool == Tool::PathSelection && !crate::vector_ui::path_renaming(app, ctx) @@ -968,11 +976,11 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { && let Some((crate::direct_select::PathRef::Saved(i), ..)) = crate::path_components::selected(app) && i == index { - if pressed(Key::Escape) { + if bare(Key::Escape) { crate::path_components::deselect_components(app); return; } - if pressed(Key::Enter) { + if bare(Key::Enter) { crate::path_components::deselect_components(app); if let Some(name) = app.ui.selected_path.clone() { crate::vector_ui::deselect_loaded_path(app, &name); diff --git a/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs index 92df008031f..9a3b174af54 100644 --- a/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs +++ b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs @@ -109,6 +109,18 @@ fn escape_with_a_pixel_selection_deselects_the_pixels_and_keeps_the_components() assert!(crate::path_components::selected(&app).is_some(), "the components stay selected"); } +#[test] +fn shift_or_alt_with_enter_or_escape_keeps_the_components_and_the_path() { + for key in [Key::Enter, Key::Escape] { + for modifiers in [Modifiers::SHIFT, Modifiers::ALT] { + let mut app = app(); + press(&mut app, key, modifiers); + assert!(crate::path_components::selected(&app).is_some(), "{key:?} {modifiers:?}"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?} {modifiers:?}"); + } + } +} + #[test] fn enter_and_escape_with_no_component_selected_keep_the_path_targeted() { for key in [Key::Enter, Key::Escape] { From 69ad84d9fbee119bde5d7b3a4dbc0ad9829f3f27 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 02:43:21 +0100 Subject: [PATCH 53/63] PR #12644: keep Smooth's transparency gradient at 97 stops The colour and opacity bakes sample the same 97 positions, but apply_opacity cut every interval into four (385 stops), and paint_gradient scans the stops for every pixel. Multiply the alpha in at each shared position instead; other positions still go through apply_opacity. Raised by CodeRabbit. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/gradient_alpha_method_tests.rs | 11 +++++ crates/engine/src/cmd/paint_cmds.rs | 41 +++++++++++++------ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index 5b62b4778c2..26030610259 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -105,3 +105,14 @@ fn legacy_colours_keep_their_own_alpha() { assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}"); } } + +// paint_gradient scans the stops for every pixel: Smooth's colour and opacity bakes share their +// 97 positions and must not be cut into four per interval (385 stops). +#[test] +fn smooth_transparency_keeps_one_stop_per_sampled_position() { + use photocraft_color::Color; + let black = Color::rgb(0.0, 0.0, 0.0); + let stops = super::paint_cmds::smooth_split_stops((vec![(0.0, black), (1.0, black)], vec![(0.0, 1.0), (1.0, 0.0)])); + assert_eq!(stops.len(), 97); + assert!((stops[0].1[3] - 1.0).abs() < 1e-6 && stops[96].1[3].abs() < 1e-6); +} diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 00fdaf4c881..e4e0c2265ad 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -168,18 +168,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // were not measured in the Gradient tool and keep the merged stops. let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; match split { - Some((cs, os)) => { - let mids = vec![0.5; cs.len().saturating_sub(1)]; - let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], 1.0]) - }) - .collect(); - let omids = vec![0.5; os.len().saturating_sub(1)]; - gradients::apply_opacity(colours, &photocraft_io::bake_gradient_smooth_opacity(os, &omids)) - } + Some(split) => smooth_split_stops(split), None => { let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); let mids = vec![0.5; stops.len() - 1]; @@ -210,6 +199,34 @@ fn gradient(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Smooth's colour and opacity stops baked apart, then joined. Both bakes sample the same +/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut +/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for +/// every pixel. Positions that differ still go through `apply_opacity`. +pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops { + let mids = vec![0.5; cs.len().saturating_sub(1)]; + let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], 1.0]) + }) + .collect(); + let omids = vec![0.5; os.len().saturating_sub(1)]; + let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids); + if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) { + return gradients::apply_opacity(colours, &opacity); + } + colours + .into_iter() + .zip(opacity) + .map(|((t, mut c), (_, a))| { + c[3] = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }; + (t, c) + }) + .collect() +} + /// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own /// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their /// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient. From 2124972069052354f53b8ee65c83aece547ab196 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 02:50:13 +0100 Subject: [PATCH 54/63] PR #13248: name the reference application in the new comments The two comments the PR adds named the reference product by its trademark; public text says "reference application". Co-Authored-By: RickiNano <81099017+RickiNano@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs | 4 ++-- crates/ui-egui/src/tools/vector_ui/shapes.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs index d57cb42eea5..0d134ece1ae 100644 --- a/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs @@ -1,6 +1,6 @@ //! #13222: ⇧ while dragging with the Ellipse tool makes a circle from the shorter side of the -//! drag, as in Photoshop, not the longer one; ⇧⌥ centres that circle on the press. The drag -//! preview (`shape_bounds`) shows the same box as the layer the drag makes. +//! drag, as in the reference application, not the longer one; ⇧⌥ centres that circle on the +//! press. The drag preview (`shape_bounds`) shows the same box as the layer the drag makes. use egui::Modifiers; use photocraft_doc::{LayerContent, LiveShape}; diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 3adcecc2de3..cd05a260363 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -116,7 +116,7 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { - // The shorter side of the drag sets the square, as in Photoshop (#13222). + // The drag's shorter side sets the square, as in the reference application (#13222). let m = w.abs().min(h.abs()); (w, h) = (m * w.signum(), m * h.signum()); } From ae51bd1a5dc6219e450c9e9252e11ab402ccccc6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 03:09:25 +0100 Subject: [PATCH 55/63] #12243: main's Remove-tool reset test expects the Pencil's 1 px tip Main's other_tools_keep_their_reset_sizes (#12548) still listed the Pencil at the old 20 px reset size; with #12200 the Pencil resets to its 1 px hard round. Co-Authored-By: ElNeMeR70 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/remove_default_size_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/remove_default_size_tests.rs b/crates/ui-egui/src/tools/remove_default_size_tests.rs index ddc5af2bc01..5bcd0b5dc08 100644 --- a/crates/ui-egui/src/tools/remove_default_size_tests.rs +++ b/crates/ui-egui/src/tools/remove_default_size_tests.rs @@ -66,10 +66,11 @@ fn reset_all_tools_gives_it_19_px_active_or_picked_later() { assert_eq!(tip(&mut app), REMOVE_TIP, "picked after the reset"); } +/// The Pencil resets to its 1 px hard round (#12200). #[test] fn other_tools_keep_their_reset_sizes() { for (tool, want) in - [(Tool::Brush, 13.0), (Tool::Pencil, 20.0), (Tool::Eraser, 20.0), (Tool::SpotHealing, 20.0), (Tool::Healing, 19.0), (Tool::CloneStamp, 21.0)] + [(Tool::Brush, 13.0), (Tool::Pencil, 1.0), (Tool::Eraser, 20.0), (Tool::SpotHealing, 20.0), (Tool::Healing, 19.0), (Tool::CloneStamp, 21.0)] { let mut a = app(); pick(&mut a, tool); From a7990ee1f208fa011f80186dba5004ce9e181fd6 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:13:04 +0100 Subject: [PATCH 56/63] Line tool: arrowhead Concavity takes -50..50 % (#13258) Concavity is a whole number from -50 % to 50 % of the head's length, as in Photoshop. A negative value bends the head's base away from the tip, and the shaft now ends where the bent base crosses the shaft's edge. Values outside the range (documents, PSDs and settings saved with the old 0..100 range) are clamped to the nearest end instead of failing. - vector: arrow_line bends the base by concavity x length, both directions - engine: shape.create / shape.edit take arrowConcavity in -50..=50 - io: PSD import keeps negative concavity, clamped to -50..50 - ui: gear and Properties Concavity are whole-number fields with the "Closest value inserted" alert; the gear menu stays open on clicks inside so a value can be typed --- crates/engine/src/cmd/vector_cmds.rs | 4 +- crates/engine/src/cmd/vector_cmds/params.rs | 4 +- crates/engine/src/cmd/vector_cmds/tests.rs | 28 +++- crates/io/src/vector_map.rs | 18 ++- crates/ui-egui/src/panels/layer_props_ui.rs | 4 +- crates/ui-egui/src/panels/options_bar.rs | 2 +- crates/ui-egui/src/tools/vector_ui.rs | 2 +- .../line_arrow_concavity_field_tests.rs | 121 ++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/options.rs | 41 +++++- crates/ui-egui/src/tools/vector_ui/shapes.rs | 3 +- .../vector/src/line_arrow_concavity_tests.rs | 99 ++++++++++++++ crates/vector/src/shapes.rs | 25 ++-- 12 files changed, 325 insertions(+), 26 deletions(-) create mode 100644 crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs create mode 100644 crates/vector/src/line_arrow_concavity_tests.rs diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 7d781257fab..ad6daa4f89e 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "New Shape Layer", ["Layer", "New"], leak(format!( - r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## + r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":-50..50=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## )), has_doc, shape_create @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Edit Shape", [], leak(format!( - r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## + r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":-50..50? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## )), has_layer, shape_edit diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index bab083c1620..bd13af9977d 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -398,7 +398,9 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L end: flag("arrowEnd", pe)?, width: dim("arrowWidth", pwidth, 1.0, 4096.0)?, length: dim("arrowLength", plen, 1.0, 4096.0)?, - concavity: dim("arrowConcavity", pc, 0.0, 100.0)?, + // -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100 range + // keeps working when another property is edited. + concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?, } } else { LiveShape::Line { from, to, weight } diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 3cd399d0961..9ba81ece109 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -1464,7 +1464,7 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { for (key, invalids) in [ ("arrowWidth", [json!("52"), json!(null), json!([]), json!(0), json!(4097)]), ("arrowLength", [json!("50"), json!(null), json!([]), json!(0), json!(4097)]), - ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-1), json!(101)]), + ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-51), json!(51)]), ] { for invalid in invalids { let mut create = json!({ @@ -1486,6 +1486,32 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { } } +/// Concavity takes -50..50 % (#13258); a shape saved with the old 0..100 range still edits. +#[test] +fn arrow_concavity_takes_minus_fifty_to_fifty() { + let mut s = session(160, 120, 8); + let concavity = |s: &Session, id: u64| match s.active().unwrap().doc.layer(LayerId(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + }; + let created = s.execute("shape.create", json!({"kind": "line", "from": [10, 20], "to": [120, 20], "arrowEnd": true, "arrowConcavity": -50})).unwrap(); + let id = created["layer"].as_u64().unwrap(); + assert_eq!(concavity(&s, id), -50.0); + s.execute("shape.edit", json!({"layer": id, "arrowConcavity": 50})).unwrap(); + assert_eq!(concavity(&s, id), 50.0); + + if let Some(LayerContent::Shape(sh)) = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(LayerId(id)).map(|l| &mut l.content) + && let Some(LiveShape::ArrowLine { concavity, .. }) = &mut sh.live + { + *concavity = 80.0; + } + s.execute("shape.edit", json!({"layer": id, "arrowWidth": 12})).unwrap(); + assert_eq!(concavity(&s, id), 50.0, "an old 0..100 value is clamped, not refused"); +} + #[test] fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() { let mut s = session(400, 400, 8); diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs index 331d3edda77..006f8926255 100644 --- a/crates/io/src/vector_map.rs +++ b/crates/io/src/vector_map.rs @@ -420,7 +420,8 @@ pub fn live_from_vogk(data: &[u8]) -> Option { // Missing or invalid PSD arrow sizes must not prevent later edits. let width = if width.is_finite() && width >= 1.0 { width } else { 52.0 }; let length = if length.is_finite() && length >= 1.0 { length } else { 50.0 }; - let concavity = if concavity.is_finite() { concavity.clamp(0.0, 100.0) } else { 0.0 }; + // Photoshop's range is -50..50 % (#13258): keep a negative value. + let concavity = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) } else { 0.0 }; Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) } else { Some(LiveShape::Line { from, to, weight }) @@ -747,6 +748,21 @@ mod tests { assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }, 72.0).is_none()); } + /// A PSD arrow keeps a negative concavity, and one past 50 % opens clamped to 50 (#13258). + #[test] + fn vogk_arrow_concavity_keeps_negatives_and_clamps_to_fifty() { + let arrow = + |concavity| LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: true, width: 5.0, length: 10.0, concavity }; + let read = |c| match live_from_vogk(&vogk_bytes(&arrow(c), 72.0).unwrap()) { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + other => panic!("{other:?}"), + }; + assert_eq!(read(-50.0), -50.0); + assert_eq!(read(-20.0), -20.0); + assert_eq!(read(80.0), 50.0); + assert_eq!(read(-90.0), -50.0); + } + #[test] fn shape_blocks_keep_unchanged_and_regenerate_changed() { let sh = ShapeLayer { diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index 9bba0ebf7e4..677b332503c 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -933,10 +933,10 @@ mod tests { ); // The next live-property edit must still be accepted after resizing. - s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 60.0})).unwrap(); + s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 40.0})).unwrap(); let layer = s.active().unwrap().doc.layer(id).unwrap(); let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") }; - assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 60.0).abs() < 1e-9)); + assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 40.0).abs() < 1e-9)); } /// A stroked shape's Transform fields show its path, not the stroke's pixels, and a W edit diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 3e9034715e3..111816d2978 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1014,7 +1014,7 @@ fn eraser_percent(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool { } /// Shows one of the range alerts as a modal with OK, once even if more than one pass asks. -fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { +pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { let message = tl!(text).to_owned(); let shown = ui_state.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 01ff55fce07..4d6053fecf6 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -114,7 +114,7 @@ fn copy_arrow_to_tool_defaults(app: &mut PhotocraftApp, id: photocraft_doc::Laye *end, bounded(*width, 1.0, 4096.0), bounded(*length, 1.0, 4096.0), - bounded(*concavity, 0.0, 100.0), + bounded(*concavity, -50.0, 50.0), bounded(*weight, 1.0, 10000.0), )) } diff --git a/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs new file mode 100644 index 00000000000..716ec56173f --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs @@ -0,0 +1,121 @@ +//! #13258: arrowhead Concavity takes whole numbers from -50 % to 50 % in the Properties panel and +//! the Line tool's gear menu; a value typed past the range becomes the closest end and, once the +//! field is left, the reference's "Closest value inserted" alert with OK says so. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::json; + +use super::{CONCAVITY_RANGE_ALERT, shape_properties}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// An 800 x 600 document with a weight 4 End arrow (5 x 10 px head) from 400,300 to 600,300. +fn app_with_arrow() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let made = app + .run("shape.create", json!({"kind": "line", "from": [400, 300], "to": [600, 300], "weight": 4, "arrowEnd": true, "arrowWidth": 5, "arrowLength": 10})) + .unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + (app, id) +} + +/// True once `setup_context` installed the app's fonts (the first frame runs before it). +fn fonts_ready(ui: &egui::Ui) -> bool { + ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +fn properties() -> (Harness<'static, PhotocraftApp>, LayerId) { + let (app, id) = app_with_arrow(); + let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + if fonts_ready(ui) { + shape_properties(app, ui, id); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + (h, id) +} + +/// The options bar with the Line tool active, its arrowhead gear menu open. +fn gear() -> Harness<'static, PhotocraftApp> { + let (mut app, _) = app_with_arrow(); + app.ui.tool = Tool::Line; + let mut h = Harness::builder().with_size(vec2(1800.0, 400.0)).build_ui_state( + |ui, app| { + if fonts_ready(ui) { + crate::panels::options_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h.query_by_label("Arrowhead options").expect("the arrowhead gear").click(); + h.run_steps(3); + h +} + +/// Types `text` into the Concavity field, then Tabs out of it. +fn type_concavity(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Concavity")).expect("the Concavity field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +fn concavity(h: &Harness<'static, PhotocraftApp>, id: LayerId) -> f64 { + match h.state().session.active().and_then(|st| st.doc.layer(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + } +} + +#[test] +fn properties_concavity_in_range_is_applied_without_an_alert() { + for (typed, want) in [("-50", -50.0), ("-12", -12.0), ("25", 25.0), ("50", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn properties_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert_eq!(alerts(&h), vec![CONCAVITY_RANGE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn gear_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0), ("-20", -20.0)] { + let mut h = gear(); + assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().label().as_deref() == Some("Concavity")), "the gear menu is open"); + type_concavity(&mut h, typed); + assert_eq!(h.state().ui.tool_options.arrow_concavity, want, "{typed}"); + let expected: Vec = if typed == "-20" { vec![] } else { vec![CONCAVITY_RANGE_ALERT.to_string()] }; + assert_eq!(alerts(&h), expected, "{typed}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 28772ea0f95..b9fa61248b1 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -147,7 +147,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // Photoshop-style arrowhead settings at the right of Line options. if tool == Tool::Line { crate::widgets::vline(ui, 22.0); - ui.menu_image_button(crate::icons::image("settings", 18.0, t.icon), |ui| { + let mut concavity_alert = false; + // Stays open on clicks inside, like the Pen's gear: a click into a field to type a value + // would otherwise close the menu before the value was entered (#13258). + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let gear = egui::Button::image(crate::icons::image("settings", 18.0, t.icon)); + let menu = egui::containers::menu::MenuButton::from_button(gear).config(config); + let (gear, _) = menu.ui(ui, |ui| { let o = &mut app.ui.tool_options; ui.set_min_width(170.0); ui.label(tl!("Arrowheads")); @@ -165,16 +171,25 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo ui.add(egui::DragValue::new(&mut o.arrow_length).range(1.0..=4096.0).suffix(" px")); }); ui.horizontal(|ui| { - ui.label(tl!("Concavity")); - ui.add(egui::DragValue::new(&mut o.arrow_concavity).range(0.0..=100.0).suffix(" %")); + let label = tl!("Concavity"); + ui.label(label); + concavity_alert = crate::widgets::value_field_whole_alerting(ui, label, &mut o.arrow_concavity, CONCAVITY_RANGE, "%", 52.0).1; }); - }) - .response - .on_hover_text(tl!("Arrowhead options")); + }); + gear.on_hover_text(tl!("Arrowhead options")); + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } true } +/// Arrowhead Concavity in percent of the head's length, as the reference takes it (#13258). +pub(crate) const CONCAVITY_RANGE: std::ops::RangeInclusive = -50.0..=50.0; + +/// The reference's alert for a Concavity typed past [`CONCAVITY_RANGE`] (#13258). +pub(crate) const CONCAVITY_RANGE_ALERT: &str = "An integer between -50% and 50% is required. Closest value inserted."; + /// Path mode's "Make:" row, as in Photoshop's options bar: Selection… (#5703), Mask (#12904) and /// Shape (#10934), from the path being drawn or the active path; all greyed without one. fn make_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -281,6 +296,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }; let t = Tokens::get(ui.ctx()); let mut edit: Option = None; + let mut concavity_alert = false; // A swatch picked in a Fill/Stroke popover joins the Recently Used Colors once the edit took it. let mut recent: Option<[f32; 3]> = None; let doc_id = app.session.active().map(|st| st.doc.id); @@ -459,8 +475,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } }); ui.horizontal(|ui| { + let label = tl!("Concavity"); + ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0)); let mut v = *concavity as f32; - if num(ui, "Concavity", &mut v, 0.0..=100.0, "%") { + let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut v, CONCAVITY_RANGE, "%", 64.0); + concavity_alert |= out_of_range; + if r.changed() { edit = Some(json!({"arrowConcavity": v, "coalesce": key("arrow-concavity")})); } }); @@ -527,8 +547,15 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }); } } + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } +#[cfg(test)] +#[path = "line_arrow_concavity_field_tests.rs"] +mod line_arrow_concavity_field_tests; + #[cfg(test)] #[path = "pen_make_mask_tests.rs"] mod pen_make_mask_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 958c35fe07b..42ee1056049 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -112,7 +112,8 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: json!({"kind": "line", "from": from, "to": to, "weight": weight, "arrowStart": o.arrow_start, "arrowEnd": o.arrow_end, "arrowWidth": o.arrow_width, "arrowLength": o.arrow_length, - "arrowConcavity": o.arrow_concavity}) + // Settings saved with the old 0..100 range draw at the nearest value (#13258). + "arrowConcavity": if o.arrow_concavity.is_finite() { o.arrow_concavity.round().clamp(-50.0, 50.0) } else { 0.0 }}) } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { diff --git a/crates/vector/src/line_arrow_concavity_tests.rs b/crates/vector/src/line_arrow_concavity_tests.rs new file mode 100644 index 00000000000..9e35d5ff1cc --- /dev/null +++ b/crates/vector/src/line_arrow_concavity_tests.rs @@ -0,0 +1,99 @@ +//! Arrowhead Concavity is -50..50 % of the head's length, as in Photoshop (#13258): the middle of +//! the head's rear edge bends toward the tip for a positive value and away from it for a negative +//! one, and the shaft ends where that bent edge crosses the shaft's edge. Joining the shaft and +//! the heads into one outline is #13260; these tests check the anchors the reference outline has. + +use super::*; + +/// The measured setup: weight 4, head width 5 and length 10, drag 400,300 to 600,300. +fn arrow(start: bool, end: bool, concavity: f64) -> Path { + arrow_line((400.0, 300.0), (600.0, 300.0), 4.0, start, end, 5.0, 10.0, concavity) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn close(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 +} + +fn same(sp: &Subpath, want: &[[f64; 2]], what: &str) { + let got = anchors(sp); + assert!(got.len() == want.len() && got.iter().zip(want).all(|(g, w)| close(*g, *w)), "{what}: {got:?} != {want:?}"); +} + +/// Every anchor of the reference's one-outline result is an anchor of `p`. +fn has_reference_anchors(p: &Path, reference: &[[f64; 2]]) { + let all: Vec<[f64; 2]> = p.subpaths.iter().flat_map(anchors).collect(); + for r in reference { + assert!(all.iter().any(|a| close(*a, *r)), "reference anchor {r:?} missing from {all:?}"); + } +} + +#[test] +fn minus_fifty_bends_the_base_away_from_the_tip_and_the_shaft_ends_where_it_crosses() { + let p = arrow(false, true, -50.0); + assert_eq!(p.subpaths.len(), 2); + same(&p.subpaths[0], &[[400.0, 302.0], [589.0, 302.0], [589.0, 298.0], [400.0, 298.0]], "shaft to 589"); + // Tip, outer corners, and the base's middle 5 px (50 % of 10) behind the base at 590. + same(&p.subpaths[1], &[[600.0, 300.0], [590.0, 302.5], [585.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors(&p, &[[400.0, 302.0], [400.0, 298.0], [589.0, 298.0], [590.0, 297.5], [600.0, 300.0], [590.0, 302.5], [589.0, 302.0]]); +} + +#[test] +fn fifty_bends_both_bases_toward_their_tips_by_five_px() { + let p = arrow(true, true, 50.0); + assert_eq!(p.subpaths.len(), 3); + same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [591.0, 298.0], [409.0, 298.0]], "shaft 409..591"); + same(&p.subpaths[1], &[[400.0, 300.0], [410.0, 302.5], [405.0, 300.0], [410.0, 297.5]], "start head"); + same(&p.subpaths[2], &[[600.0, 300.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors( + &p, + &[ + [409.0, 302.0], + [410.0, 302.5], + [400.0, 300.0], + [410.0, 297.5], + [409.0, 298.0], + [591.0, 298.0], + [590.0, 297.5], + [600.0, 300.0], + [590.0, 302.5], + [591.0, 302.0], + ], + ); +} + +#[test] +fn zero_keeps_a_flat_base_and_the_shaft_ends_at_it() { + let p = arrow(false, true, 0.0); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 302.0])); + assert!(close(anchors(&p.subpaths[1])[2], [590.0, 300.0])); +} + +#[test] +fn values_past_fifty_draw_as_fifty_so_older_documents_still_open() { + assert_eq!(arrow(true, true, 80.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, 100.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, -90.0), arrow(true, true, -50.0)); + assert_eq!(arrow(true, true, f64::NAN), arrow(true, true, 0.0)); +} + +#[test] +fn a_head_no_wider_than_the_shaft_meets_it_at_the_base_whatever_the_concavity() { + for c in [-50.0, 0.0, 50.0] { + let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, c); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 303.0]), "concavity {c}"); + } +} + +#[test] +fn long_heads_bent_away_never_turn_the_shaft_inside_out() { + for (start, end) in [(true, true), (false, true), (true, false)] { + let p = arrow_line((0.0, 0.0), (20.0, 0.0), 4.0, start, end, 30.0, 50.0, -50.0); + let shaft = anchors(&p.subpaths[0]); + assert!(shaft[0][0] <= shaft[1][0], "{start} {end}: {shaft:?}"); + assert!(p.subpaths.iter().flat_map(anchors).all(|a| a[0].is_finite() && a[1].is_finite())); + } +} diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index 607531d5b32..0140f75e7d7 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -235,8 +235,10 @@ pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path { /// A filled vector line with optional arrowheads at its endpoints (#6408). /// `width` and `length` measure the head in document pixels, independently of the shaft weight. -/// `concavity` is 0..100 percent: 0 has a flat rear edge, 100 a deep V-shaped notch. -/// The shaft stops at the notch, so a concave head remains concave after filling. +/// `concavity` is -50..50 percent of `length`: the middle of the head's rear edge bends that far +/// toward the tip (positive) or away from it (negative); 0 is flat. Values outside are clamped, so +/// documents saved with the old 0..100 range still open (#13258). The shaft stops where the bent +/// rear edge crosses the shaft's edge, so a concave head stays open after filling. // The arguments correspond to the stored LiveShape::ArrowLine parameters. #[allow(clippy::too_many_arguments)] pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: bool, width: f64, length: f64, concavity: f64) -> Path { @@ -256,15 +258,16 @@ pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: b let (vx, vy) = (-uy, ux); let size = (if length.is_finite() { length.max(1.0) } else { 1.0 }).min(distance * if start && end { 0.49 } else { 0.9 }); let half = (if width.is_finite() { width.max(1.0) } else { 1.0 }) / 2.0; - let requested_notch = concavity.clamp(0.0, 100.0) / 100.0; - // Preserve 0..50%. Beyond that compress the usable range so the head never collapses. - let max_notch = 0.75; - let notch = if requested_notch <= 0.5 { requested_notch } else { 0.5 + (requested_notch - 0.5) * (max_notch - 0.5) / 0.5 }; - // Put the shaft up to the notch, leaving the head's concave edges visible. - let inner = size * (1.0 - notch); + // The rear edge's bend toward the tip as a fraction of `size` (negative: away from the tip). + let notch = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) / 100.0 } else { 0.0 }; + let hw = weight.max(0.1) / 2.0; + // The rear edge runs straight from each outer corner to its bent middle, so where it crosses + // the shaft's edge it is bent by `notch` times how far that edge is from the corner; a head no + // wider than the shaft meets it at its base. A head bent away from its tip reaches past its + // base, so the shaft is capped to never turn inside out. + let inner = (size * (1.0 - notch * (1.0 - (hw / half).min(1.0)))).min(if start && end { distance / 2.0 } else { distance }); let shaft_a = if start { (a.0 + ux * inner, a.1 + uy * inner) } else { a }; let shaft_b = if end { (b.0 - ux * inner, b.1 - uy * inner) } else { b }; - let hw = weight.max(0.1) / 2.0; let mut pieces = vec![Subpath::polygon(&[ (shaft_a.0 + vx * hw, shaft_a.1 + vy * hw), (shaft_b.0 + vx * hw, shaft_b.1 + vy * hw), @@ -429,6 +432,10 @@ mod tests { #[path = "star_outer_corner_radius_tests.rs"] mod star_outer_corner_radius_tests; +#[cfg(test)] +#[path = "line_arrow_concavity_tests.rs"] +mod line_arrow_concavity_tests; + #[cfg(test)] mod line_arrow_6408_tests { use super::*; From 675bd970f383c6eda08f6c0d7db659715c53869e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:17:47 +0100 Subject: [PATCH 57/63] Line tool: fill the wedge a concave arrowhead leaves; whole-percent concavity (#13258) With a base bent toward the tip, the shaft stopped where the bent base crosses its edge and left the wedge up to the base's middle unfilled. The shaft's end now follows the bent base to its middle, which fills the wedge without reaching past the head's flanks, matching the reference outline. shape.create / shape.edit round arrowConcavity to a whole percent, as the gear and Properties fields do. --- crates/engine/src/cmd/vector_cmds.rs | 2 +- crates/engine/src/cmd/vector_cmds/params.rs | 6 +-- crates/engine/src/cmd/vector_cmds/tests.rs | 3 ++ .../vector/src/line_arrow_concavity_tests.rs | 43 ++++++++++++++++++- crates/vector/src/shapes.rs | 38 +++++++++------- 5 files changed, 70 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index ad6daa4f89e..656b9813927 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "New Shape Layer", ["Layer", "New"], leak(format!( - r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":-50..50=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## + r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":-50..50=0 (line; rounded to a whole percent),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## )), has_doc, shape_create diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index bd13af9977d..34f009415a2 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -398,9 +398,9 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L end: flag("arrowEnd", pe)?, width: dim("arrowWidth", pwidth, 1.0, 4096.0)?, length: dim("arrowLength", plen, 1.0, 4096.0)?, - // -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100 range - // keeps working when another property is edited. - concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?, + // A whole -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100 + // range keeps working when another property is edited. + concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?.round(), } } else { LiveShape::Line { from, to, weight } diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 9ba81ece109..707d6c1a49d 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -1502,6 +1502,9 @@ fn arrow_concavity_takes_minus_fifty_to_fifty() { assert_eq!(concavity(&s, id), -50.0); s.execute("shape.edit", json!({"layer": id, "arrowConcavity": 50})).unwrap(); assert_eq!(concavity(&s, id), 50.0); + // Whole percents only, as the fields take them. + s.execute("shape.edit", json!({"layer": id, "arrowConcavity": -20.6})).unwrap(); + assert_eq!(concavity(&s, id), -21.0); if let Some(LayerContent::Shape(sh)) = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(LayerId(id)).map(|l| &mut l.content) && let Some(LiveShape::ArrowLine { concavity, .. }) = &mut sh.live diff --git a/crates/vector/src/line_arrow_concavity_tests.rs b/crates/vector/src/line_arrow_concavity_tests.rs index 9e35d5ff1cc..a860af64809 100644 --- a/crates/vector/src/line_arrow_concavity_tests.rs +++ b/crates/vector/src/line_arrow_concavity_tests.rs @@ -1,7 +1,8 @@ //! Arrowhead Concavity is -50..50 % of the head's length, as in Photoshop (#13258): the middle of //! the head's rear edge bends toward the tip for a positive value and away from it for a negative //! one, and the shaft ends where that bent edge crosses the shaft's edge. Joining the shaft and -//! the heads into one outline is #13260; these tests check the anchors the reference outline has. +//! the heads into one outline is #13260; these tests check the anchors the reference outline has +//! and that the subpaths (each filled and combined, as the rasterizer does) cover what it covers. use super::*; @@ -23,6 +24,21 @@ fn same(sp: &Subpath, want: &[[f64; 2]], what: &str) { assert!(got.len() == want.len() && got.iter().zip(want).all(|(g, w)| close(*g, *w)), "{what}: {got:?} != {want:?}"); } +/// Whether `pt` is inside any subpath of `p` (each a polygon, combined as a union). +fn covers(p: &Path, pt: [f64; 2]) -> bool { + p.subpaths.iter().any(|sp| { + let a = anchors(sp); + let mut inside = false; + for i in 0..a.len() { + let (p0, p1) = (a[i], a[(i + 1) % a.len()]); + if (p0[1] > pt[1]) != (p1[1] > pt[1]) && pt[0] < p0[0] + (pt[1] - p0[1]) / (p1[1] - p0[1]) * (p1[0] - p0[0]) { + inside = !inside; + } + } + inside + }) +} + /// Every anchor of the reference's one-outline result is an anchor of `p`. fn has_reference_anchors(p: &Path, reference: &[[f64; 2]]) { let all: Vec<[f64; 2]> = p.subpaths.iter().flat_map(anchors).collect(); @@ -45,7 +61,8 @@ fn minus_fifty_bends_the_base_away_from_the_tip_and_the_shaft_ends_where_it_cros fn fifty_bends_both_bases_toward_their_tips_by_five_px() { let p = arrow(true, true, 50.0); assert_eq!(p.subpaths.len(), 3); - same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [591.0, 298.0], [409.0, 298.0]], "shaft 409..591"); + // The shaft's ends follow the bent bases to their middles, filling the wedge in front of them. + same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [595.0, 300.0], [591.0, 298.0], [409.0, 298.0], [405.0, 300.0]], "shaft 409..591"); same(&p.subpaths[1], &[[400.0, 300.0], [410.0, 302.5], [405.0, 300.0], [410.0, 297.5]], "start head"); same(&p.subpaths[2], &[[600.0, 300.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5]], "end head"); has_reference_anchors( @@ -97,3 +114,25 @@ fn long_heads_bent_away_never_turn_the_shaft_inside_out() { assert!(p.subpaths.iter().flat_map(anchors).all(|a| a[0].is_finite() && a[1].is_finite())); } } + +#[test] +fn a_base_bent_toward_the_tip_leaves_no_hole_and_nothing_past_the_flanks() { + let p = arrow(true, true, 50.0); + // The reference outline has no edge between the shaft's end and the bent base's middle. + for pt in [[593.0, 300.0], [594.5, 300.0], [592.0, 299.0], [407.0, 300.0], [405.5, 300.0], [408.0, 301.0]] { + assert!(covers(&p, pt), "{pt:?} is inside the reference outline"); + } + // Between x 591 and 600 the flanks are inside the shaft's width (298.25 at x 593). + for pt in [[593.0, 298.1], [593.0, 301.9], [407.0, 298.1], [407.0, 301.9]] { + assert!(!covers(&p, pt), "{pt:?} is outside the reference outline"); + } + // Outside the shaft's width, the notch stays open between the base and the flank's corner. + assert!(!covers(&p, [590.6, 297.9])); +} + +#[test] +fn a_head_no_wider_than_the_shaft_still_fills_the_wedge_its_bent_base_leaves() { + let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, 50.0); + same(&p.subpaths[0], &[[400.0, 303.0], [590.0, 303.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5], [590.0, 297.0], [400.0, 297.0]], "shaft"); + assert!(covers(&p, [592.0, 300.0])); +} diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index 0140f75e7d7..90ff388a328 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -268,25 +268,31 @@ pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: b let inner = (size * (1.0 - notch * (1.0 - (hw / half).min(1.0)))).min(if start && end { distance / 2.0 } else { distance }); let shaft_a = if start { (a.0 + ux * inner, a.1 + uy * inner) } else { a }; let shaft_b = if end { (b.0 - ux * inner, b.1 - uy * inner) } else { b }; - let mut pieces = vec![Subpath::polygon(&[ - (shaft_a.0 + vx * hw, shaft_a.1 + vy * hw), - (shaft_b.0 + vx * hw, shaft_b.1 + vy * hw), - (shaft_b.0 - vx * hw, shaft_b.1 - vy * hw), - (shaft_a.0 - vx * hw, shaft_a.1 - vy * hw), - ])]; - // The tip, both outer corners of the head and the recessed midpoint. - // Positive `sign` points towards the tail of the head (away from its tip). - let mut head = |tip: (f64, f64), sign: f64| { + let side = |p: (f64, f64), d: f64| (p.0 + vx * d, p.1 + vy * d); + // A head's tip, both outer corners and its rear edge's bent middle. Positive `sign` points + // toward the tail of the head (away from its tip). + let head = |tip: (f64, f64), sign: f64| { let base = (tip.0 + ux * sign * size, tip.1 + uy * sign * size); let rear_middle = (base.0 - ux * sign * size * notch, base.1 - uy * sign * size * notch); - pieces.push(Subpath::polygon(&[tip, (base.0 + vx * half, base.1 + vy * half), rear_middle, (base.0 - vx * half, base.1 - vy * half)])); + [tip, side(base, half), rear_middle, side(base, -half)] }; - if start { - head(a, 1.0); - } - if end { - head(b, -1.0); - } + let (start_head, end_head) = (start.then(|| head(a, 1.0)), end.then(|| head(b, -1.0))); + // A base bent toward the tip leaves a wedge between the shaft's end and the head that the + // reference fills: the shaft's end follows the bent base to its middle, so it fills the wedge + // without reaching past the head's flanks. A base bent away lies under the head already. + let wedge = |h: [(f64, f64); 4], from: usize, to: usize| -> Vec<(f64, f64)> { + if notch <= 0.0 { + return Vec::new(); + } + let corners = hw > half; + [(corners, h[from]), (true, h[2]), (corners, h[to])].into_iter().filter_map(|(keep, p)| keep.then_some(p)).collect() + }; + let mut shaft = vec![side(shaft_a, hw), side(shaft_b, hw)]; + shaft.extend(end_head.map_or_else(Vec::new, |h| wedge(h, 1, 3))); + shaft.extend([side(shaft_b, -hw), side(shaft_a, -hw)]); + shaft.extend(start_head.map_or_else(Vec::new, |h| wedge(h, 3, 1))); + let mut pieces = vec![Subpath::polygon(&shaft)]; + pieces.extend([start_head, end_head].into_iter().flatten().map(|h| Subpath::polygon(&h))); // Never return non-finite arrow geometry. // Large but valid scaled arrowheads remain unchanged. if pieces.iter().flat_map(|sp| &sp.knots).any(|k| !k.anchor.x.is_finite() || !k.anchor.y.is_finite()) { From c5558f6644b175c24ef5e9b7f7e7962c44ab3188 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:47:56 -0600 Subject: [PATCH 58/63] algo: Paint Bucket gets its own match rule for transparent and semi-transparent seeds --- crates/algo/src/lib.rs | 3 + crates/algo/src/paint.rs | 2 +- .../paint_bucket_transparent_seed_tests.rs | 170 ++++++++++++++++++ crates/algo/src/selection.rs | 52 +++++- 4 files changed, 225 insertions(+), 2 deletions(-) create mode 100644 crates/algo/src/paint_bucket_transparent_seed_tests.rs diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index a673c15b698..4b8506ca1e9 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1771,3 +1771,6 @@ mod selected_alpha_tests { } } } + +#[cfg(test)] +mod paint_bucket_transparent_seed_tests; diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index a7f57c337d5..01944f7830b 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -227,7 +227,7 @@ pub fn bucket_fill_inks( return false; } let img = crate::selection::rgba8_image(s, area); - let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; + let Some(region) = crate::selection::wand_region_bucket(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; drop(img); bucket_fill_region_inks(s, ®ion, opacity, selection, lock_transparency, src, inks, mode); true diff --git a/crates/algo/src/paint_bucket_transparent_seed_tests.rs b/crates/algo/src/paint_bucket_transparent_seed_tests.rs new file mode 100644 index 00000000000..461226d700c --- /dev/null +++ b/crates/algo/src/paint_bucket_transparent_seed_tests.rs @@ -0,0 +1,170 @@ +//! Paint Bucket match rule for transparent and semi-transparent seeds (#12529), Anti-alias off. +//! +//! The issue's document is 800 x 600 with a red square, a grey ramp and an anti-aliased black +//! disc on a transparent layer. These tests shrink the geometry (see `NOTES.md`) but keep every +//! measured relationship: the ramp is its own 256 x 1 strip so seeds 127 / 128 and the tolerances +//! 0 / 1 / 32 / 100 give the issue's exact grey ranges. + +use photocraft_color::{PixelFormat, blend::BlendMode}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; + +use crate::paint::{FillMode, bucket_fill_inks}; +use crate::selection::{rgba8_image, wand_region}; + +const W: i32 = 100; +const H: i32 = 80; +const AREA: Rect = Rect { x0: 0, y0: 0, x1: W, y1: H }; +const GREEN: [u8; 4] = [0, 255, 0, 255]; +/// Row of the black disc's edge; x 10..14 hold alpha 40, 112, 197, 253 like (690..700, 400). +const EDGE_Y: i32 = 70; +/// Alphas of the edge row from x = 10: the 40 / 112 / 197 / 253 ladder, then solid 253 inside. +const LADDER: [u8; 4] = [40, 112, 197, 253]; + +fn idx(x: i32, y: i32) -> usize { + (y * W + x) as usize +} + +/// Red square (40..60 x 10..30), grey ramp strip (value = x, x 0..64, y 40..43), and a black +/// edge row at `EDGE_Y` (x 10..14 the alpha ladder, x 14..30 alpha 253); the rest transparent. +fn document() -> Vec<[u8; 4]> { + let mut img = vec![[0u8; 4]; (W * H) as usize]; + for y in 10..30 { + for x in 40..60 { + img[idx(x, y)] = [220, 30, 30, 255]; + } + } + for y in 40..43 { + for x in 0..64 { + img[idx(x, y)] = [x as u8, x as u8, x as u8, 255]; + } + } + for (i, a) in LADDER.iter().enumerate() { + img[idx(10 + i as i32, EDGE_Y)] = [0, 0, 0, *a]; + } + for x in 14..30 { + img[idx(x, EDGE_Y)] = [0, 0, 0, 253]; + } + img +} + +fn surface(img: &[[u8; 4]], area: Rect) -> Surface { + let bytes: Vec = img.iter().flatten().copied().collect(); + Surface::from_interleaved(PixelFormat::RGBA8, area, &bytes) +} + +/// Bucket-fills green at `seed` and returns the layer afterwards. +fn fill(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tol: f32, contiguous: bool) -> Vec<[u8; 4]> { + let mut s = surface(img, area); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + assert!(bucket_fill_inks(&mut s, area, seed, tol, contiguous, false, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal))); + rgba8_image(&s, area) +} + +/// Pixels the fill changed, as indices. +fn changed(before: &[[u8; 4]], after: &[[u8; 4]]) -> Vec { + (0..before.len()).filter(|&i| before[i] != after[i]).collect() +} + +fn assert_only_alpha_zero_filled(before: &[[u8; 4]], after: &[[u8; 4]], label: &str) { + for (i, (b, a)) in before.iter().zip(after).enumerate() { + if b[3] == 0 { + assert_eq!(*a, GREEN, "{label}: transparent pixel {i} should fill"); + } else { + assert_eq!(a, b, "{label}: pixel {i} with alpha {} must not change", b[3]); + } + } +} + +#[test] +fn transparent_seed_fills_only_alpha_zero_at_any_tolerance() { + let img = document(); + for tol in [0.0, 32.0, 255.0] { + let after = fill(&img, AREA, (49, 49), tol, true); + // The transparent background is one connected region here, so contiguous reaches all of it. + assert_only_alpha_zero_filled(&img, &after, &format!("tolerance {tol}")); + for (i, a) in LADDER.iter().enumerate() { + assert_eq!(after[idx(10 + i as i32, EDGE_Y)], [0, 0, 0, *a], "edge alpha {a} survives at tolerance {tol}"); + } + assert_eq!(after[idx(9, EDGE_Y)], GREEN, "transparent pixel next to the edge fills"); + assert_eq!(after[idx(50, 20)], [220, 30, 30, 255], "red square untouched at tolerance {tol}"); + assert_eq!(after[idx(30, 41)], [30, 30, 30, 255], "ramp untouched at tolerance {tol}"); + } +} + +#[test] +fn transparent_seed_not_contiguous_fills_every_alpha_zero_pixel_only() { + let mut img = document(); + // An enclosed transparent hole that contiguous fill cannot reach. + for y in 12..16 { + for x in 44..48 { + img[idx(x, y)] = [0, 0, 0, 0]; + } + } + for tol in [0.0, 255.0] { + let after = fill(&img, AREA, (49, 49), tol, false); + assert_only_alpha_zero_filled(&img, &after, &format!("global, tolerance {tol}")); + assert_eq!(after[idx(45, 13)], GREEN, "the enclosed transparent hole fills"); + assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253]); + } +} + +#[test] +fn semi_transparent_seed_takes_same_colour_pixels_of_any_nonzero_alpha() { + let img = document(); + let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true); + // The 40 / 112 / 197 / 253 ladder and the solid 253 run all fill: no alpha band applies. + for x in 10..30 { + assert_eq!(after[idx(x, EDGE_Y)], GREEN, "black alpha pixel at x {x} fills"); + } + assert_eq!(after[idx(9, EDGE_Y)], [0, 0, 0, 0], "the transparent neighbour is never taken"); + let n = changed(&img, &after).len(); + assert_eq!(n, 20, "only the black edge row changes"); +} + +#[test] +fn semi_transparent_seed_respects_colour_tolerance() { + let mut img = document(); + img[idx(12, EDGE_Y)] = [100, 100, 100, 112]; + let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true); + assert_eq!(after[idx(11, EDGE_Y)], GREEN); + assert_eq!(after[idx(12, EDGE_Y)], [100, 100, 100, 112], "a colour outside Tolerance stays"); + assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253], "and it cuts the contiguous run"); +} + +fn ramp_strip() -> Vec<[u8; 4]> { + (0..=255u8).map(|v| [v, v, v, 255]).collect() +} + +fn filled_range(after: &[[u8; 4]]) -> Option<(usize, usize)> { + let hits: Vec = (0..after.len()).filter(|&i| after[i] == GREEN).collect(); + Some((*hits.first()?, *hits.last()?)) +} + +#[test] +fn opaque_seed_keeps_todays_ranges() { + let img = ramp_strip(); + let area = Rect::new(0, 0, 256, 1); + for (seed, tol, contiguous, lo, hi) in + [(127, 0.0, true, 127, 127), (127, 1.0, true, 126, 128), (127, 32.0, true, 95, 159), (127, 100.0, true, 27, 227), (128, 32.0, false, 96, 160)] + { + let after = fill(&img, area, (seed, 0), tol, contiguous); + assert_eq!(filled_range(&after), Some((lo, hi)), "seed {seed} tolerance {tol} contiguous {contiguous}"); + let count = after.iter().filter(|p| **p == GREEN).count(); + assert_eq!(count, hi - lo + 1, "the filled range is solid"); + } +} + +/// The wand rule did not move: a transparent seed at Tolerance 255 still matches every pixel +/// (alpha within 255 of 0), which is what the Magic Wand and Magic Eraser keep. +#[test] +fn wand_region_still_uses_the_alpha_band() { + let img = document(); + let r = wand_region(&img, AREA, (49, 49), 255.0, true, false).expect("seed is inside"); + assert_eq!(r.at(50, 20), 1.0, "red square is inside the wand region"); + assert_eq!(r.at(30, 41), 1.0, "ramp is inside the wand region"); + assert_eq!(r.at(13, EDGE_Y), 1.0, "disc edge is inside the wand region"); + let r32 = wand_region(&img, AREA, (49, 49), 32.0, true, false).expect("seed is inside"); + assert_eq!(r32.at(10, EDGE_Y), 0.0, "alpha 40 is outside a Tolerance 32 alpha band"); + assert_eq!(r32.at(9, EDGE_Y), 1.0, "alpha 0 is inside it"); +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index c91a2611de5..a2fa420fca2 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -354,6 +354,49 @@ pub fn wand_region_by( anti_alias: bool, within: Option<&[f32]>, distance: ColorDistance, +) -> Option { + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, within, distance, MatchRule::Wand) +} + +/// Which pixels count as "similar" to the clicked one. +#[derive(Clone, Copy)] +enum MatchRule { + /// The Magic Wand / Magic Eraser rule: colour and alpha each within Tolerance, except that + /// two fully transparent pixels always match. + Wand, + /// The Paint Bucket rule, see [`wand_region_bucket`]. + Bucket, +} + +/// [`wand_region`] with the Paint Bucket's match rule (measured on the reference, #12529). +/// +/// It differs from the wand rule only when the clicked pixel is not opaque. The wand lets any +/// pixel whose alpha is within Tolerance of the seed's match, so a bucket click on transparent +/// pixels leaked into the anti-aliased edge of a shape and, at Tolerance 255, filled the whole +/// layer (#6183). The bucket rule is: +/// - seed alpha 0: only pixels with alpha 0 match; Tolerance plays no role; +/// - seed alpha 255: unchanged (colour and alpha each within Tolerance); +/// - seed alpha in between: a pixel matches when its alpha is above 0 and its colour is +/// within Tolerance of the seed's colour. There is no alpha band (alpha 40, 197 and 253 of +/// one colour were measured to fill together) and alpha-0 pixels are never taken. +/// +/// Only that one semi-transparent case was measured; other cases follow this rule until +/// measured. [`wand_region`] and [`wand_region_within`] are unchanged. +pub fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, None, ColorDistance::LargestChannel, MatchRule::Bucket) +} + +#[allow(clippy::too_many_arguments)] +fn region_by_rule( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, + distance: ColorDistance, + rule: MatchRule, ) -> Option { if !area.contains(seed.0, seed.1) { return None; @@ -371,7 +414,14 @@ pub fn wand_region_by( let tol = (tolerance + 1e-3).floor().max(0.0) as i32; // Copying a selection can leave RGB under zero alpha. Those invisible colours must not // split a transparent region into pieces, as if the copied source were still visible. - let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol); + let similar = |p: [u8; 4]| match rule { + MatchRule::Wand => (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol), + MatchRule::Bucket => match target[3] { + 0 => p[3] == 0, + 255 => distance.rgb(p, target) <= tol && (p[3] as i32 - 255).abs() <= tol, + _ => p[3] != 0 && distance.rgb(p, target) <= tol, + }, + }; let mut marks = vec![0u8; w * h]; let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); if contiguous { From 0264b4dde90a0d3124b3ebd4d8254c93f186ad78 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 13 Nov 2026 12:19:21 +0530 Subject: [PATCH 59/63] Path Selection: Ctrl/Cmd acts as Direct Selection (#13284) With Path Selection and Ctrl/Cmd held alone, a press on an anchor, handle or segment goes through Direct Selection, so a Ctrl-drag on one anchor moves only that anchor in one History step. Releasing Ctrl goes back to Path Selection. Ctrl with Alt or Shift keeps today's behaviour (not measured in the reference application). --- crates/ui-egui/src/tools.rs | 2 + crates/ui-egui/src/tools/direct_select.rs | 9 +- .../tools/path_selection_ctrl_direct_tests.rs | 92 +++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 721057faacd..f7f7893015d 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -77,6 +77,8 @@ mod gradient_refusal_messages_tests; #[cfg(test)] mod line_tool_defaults_tests; #[cfg(test)] +mod path_selection_ctrl_direct_tests; +#[cfg(test)] mod path_selection_shape_over_saved_path_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index abda6368c6a..ded2a17946b 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -319,9 +319,11 @@ impl Edit { } /// Is Direct Selection what the pointer does now: its own tool, or a Pen (the Pen, Freeform Pen -/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held. +/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held, or Path Selection +/// with ⌘/Ctrl alone (#13284; with ⌥ or ⇧ too, the reference was not measured, so as today). fn direct(tool: Tool, mods: Modifiers) -> bool { tool == Tool::DirectSelection + || (tool == Tool::PathSelection && mods.command && !mods.alt && !mods.shift) || (matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint) && mods.command) } @@ -654,6 +656,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - let _ = app.run("layer.select", json!({"layer": id})); } let owner = Owner::current(app); + let tool_is_path_selection = app.ui.tool == Tool::PathSelection; let ds = &mut app.ui.direct_selection; if ds.target.as_ref() != Some(&target) { *ds = DirectSelection { target: Some(target), ..Default::default() }; @@ -700,7 +703,9 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - return true; } ds.anchors.push(k); - } else if !ds.anchors.contains(&k) { + } else if !ds.anchors.contains(&k) || tool_is_path_selection { + // Path Selection's ⌘/Ctrl moves the anchor pressed alone, not the selected + // component it belongs to (#13284). ds.anchors = vec![k]; } Edit::Anchors(ds.anchors.clone()) diff --git a/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs b/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs new file mode 100644 index 00000000000..3803b84fd31 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs @@ -0,0 +1,92 @@ +//! #13284: with Path Selection and ⌘/Ctrl held, a press on an anchor acts as Direct Selection, as in +//! the reference application: only that anchor moves, in one History step. Without ⌘/Ctrl the tool +//! drags the whole component, and releasing ⌘/Ctrl goes back to that. + +use egui::Modifiers; +use photocraft_doc::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; +const SQUARE: [[f64; 2]; 4] = [[100.0, 300.0], [300.0, 300.0], [300.0, 500.0], [100.0, 500.0]]; + +/// The closed square 100,300–300,500 saved as "Path 1", targeted, with Path Selection. +fn setup() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": SQUARE}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(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]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], 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); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn anchors(app: &PhotocraftApp) -> Vec<[f64; 2]> { + saved(app).subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn undo_label(app: &PhotocraftApp) -> Option { + app.session.active()?.history.undo_label().map(str::to_string) +} + +fn moved_by(d: [f64; 2]) -> Vec<[f64; 2]> { + SQUARE.iter().map(|p| [p[0] + d[0], p[1] + d[1]]).collect() +} + +/// "Drag Anchor Points" today; PR #13541 renames a one-anchor drag to the singular. +fn is_anchor_drag_label(label: Option<&str>) -> bool { + matches!(label, Some("Drag Anchor Points" | "Drag Anchor Point")) +} + +#[test] +fn ctrl_drag_on_an_anchor_moves_only_that_anchor_in_one_step() { + let mut app = setup(); + let before = undo_label(&app); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]], "only the pressed anchor moved"); + assert!(is_anchor_drag_label(undo_label(&app).as_deref()), "one anchor-drag step: {:?}", undo_label(&app)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(anchors(&app), SQUARE.to_vec(), "one undo restores the square"); + assert_eq!(undo_label(&app), before, "the drag was a single History step"); +} + +#[test] +fn ctrl_drag_on_an_anchor_of_a_selected_component_moves_only_that_anchor() { + let mut app = setup(); + // A plain click selects the whole component first. + drag(&mut app, [200.0, 300.0], [200.0, 300.0], Modifiers::NONE); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]]); +} + +#[test] +fn a_drag_without_ctrl_still_moves_every_anchor() { + let mut app = setup(); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::NONE); + assert_eq!(anchors(&app), moved_by([-20.0, -20.0]), "the whole component moved"); +} + +#[test] +fn releasing_ctrl_returns_to_moving_the_whole_component() { + let mut app = setup(); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + let after_ctrl = anchors(&app); + drag(&mut app, [200.0, 400.0], [210.0, 410.0], Modifiers::NONE); + let expected: Vec<[f64; 2]> = after_ctrl.iter().map(|p| [p[0] + 10.0, p[1] + 10.0]).collect(); + assert_eq!(anchors(&app), expected, "a plain drag moves the whole component again"); +} From 80bd726158c289e10c908f92cf7f7e5f74a45fc7 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:11:41 -0600 Subject: [PATCH 60/63] algo: keep the bucket wrapper crate-private; unmeasured semi-transparent colours keep the alpha band --- .../src/paint_bucket_transparent_seed_tests.rs | 15 +++++++++++++++ crates/algo/src/selection.rs | 16 +++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/algo/src/paint_bucket_transparent_seed_tests.rs b/crates/algo/src/paint_bucket_transparent_seed_tests.rs index 461226d700c..a47c26f888a 100644 --- a/crates/algo/src/paint_bucket_transparent_seed_tests.rs +++ b/crates/algo/src/paint_bucket_transparent_seed_tests.rs @@ -168,3 +168,18 @@ fn wand_region_still_uses_the_alpha_band() { assert_eq!(r32.at(10, EDGE_Y), 0.0, "alpha 40 is outside a Tolerance 32 alpha band"); assert_eq!(r32.at(9, EDGE_Y), 1.0, "alpha 0 is inside it"); } + +/// The measured semi-transparent case is one colour at several alphas; a pixel of another +/// colour keeps the alpha band the shared rule always had (the issue leaves unmeasured +/// cases at today's behaviour). Seed [0, 0, 0, 40] at x = 1: x = 0 is the same-colour +/// control [0, 0, 0, 253]; x = 2 is [20, 20, 20, 197] — its RGB distance of 20 passes +/// Tolerance 32, but its alpha sits 157 from the seed's, so it is not filled. +#[test] +fn semi_transparent_seed_keeps_the_alpha_band_for_other_colours() { + let img: Vec<[u8; 4]> = vec![[0, 0, 0, 253], [0, 0, 0, 40], [20, 20, 20, 197]]; + let area = Rect::new(0, 0, 3, 1); + let after = fill(&img, area, (1, 0), 32.0, true); + let ch = changed(&img, &after); + assert!(ch.contains(&0), "same-colour pixel of alpha 253 fills"); + assert!(!ch.contains(&2), "different-colour pixel of alpha 197 keeps the alpha band"); +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index a2fa420fca2..b0dec119566 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -376,13 +376,15 @@ enum MatchRule { /// layer (#6183). The bucket rule is: /// - seed alpha 0: only pixels with alpha 0 match; Tolerance plays no role; /// - seed alpha 255: unchanged (colour and alpha each within Tolerance); -/// - seed alpha in between: a pixel matches when its alpha is above 0 and its colour is -/// within Tolerance of the seed's colour. There is no alpha band (alpha 40, 197 and 253 of -/// one colour were measured to fill together) and alpha-0 pixels are never taken. +/// - seed alpha in between: a pixel of the seed's own colour matches when its alpha is +/// above 0 — there is no alpha band for that case (alpha 40, 197 and 253 of one colour +/// were measured to fill together). A pixel of any other colour must also sit within +/// Tolerance of the seed's alpha, as before: that case was not measured, and unmeasured +/// cases keep today's behaviour. Alpha-0 pixels are never taken. /// -/// Only that one semi-transparent case was measured; other cases follow this rule until -/// measured. [`wand_region`] and [`wand_region_within`] are unchanged. -pub fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { +/// Only that one semi-transparent case was measured; unmeasured cases keep the previous +/// behaviour. [`wand_region`] and [`wand_region_within`] are unchanged. +pub(crate) fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, None, ColorDistance::LargestChannel, MatchRule::Bucket) } @@ -419,7 +421,7 @@ fn region_by_rule( MatchRule::Bucket => match target[3] { 0 => p[3] == 0, 255 => distance.rgb(p, target) <= tol && (p[3] as i32 - 255).abs() <= tol, - _ => p[3] != 0 && distance.rgb(p, target) <= tol, + _ => p[3] != 0 && distance.rgb(p, target) <= tol && (p[..3] == target[..3] || (p[3] as i32 - target[3] as i32).abs() <= tol), }, }; let mut marks = vec![0u8; w * h]; From 7dc578de3b26805ac9b7524b1023ab28eb8cc8b2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:08:12 +0100 Subject: [PATCH 61/63] Fix modified lasso clicks clearing selections (#13612) Co-authored-by: FredApps --- crates/ui-egui/src/canvas/gesture.rs | 2 +- crates/ui-egui/src/tools/lasso_ui/tests.rs | 32 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index c30bcf1694f..155ae25ac88 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -173,7 +173,7 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { if made.is_ok() && d.tool != Tool::Lasso { crate::retouch_ui::patch_hint(app); } - } else if app.session.is_enabled("select.deselect") { + } else if (d.tool != Tool::Lasso || selection_mode(app, d.modifiers) == "replace") && app.session.is_enabled("select.deselect") { let _ = app.run("select.deselect", json!({})); } } diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index a568d102ae2..a96c0c89c6e 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -170,6 +170,38 @@ fn mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f h.run_steps(2); } +#[test] +fn pasteboard_click_deselects_only_in_new_mode_and_is_undoable() { + for mods in [Modifiers::NONE, Modifiers::SHIFT, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + let mut h = harness(); + h.state_mut().run("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap(); + let history = h.state().session.active().unwrap().history.past_len(); + mouse(&mut h, "down", -20.0, 100.0, mods); + mouse(&mut h, "up", -20.0, 100.0, mods); + let state = h.state().session.active().unwrap(); + if mods == Modifiers::NONE { + assert!(state.doc.selection.is_none(), "New-mode click deselects"); + assert_eq!(state.history.past_len(), history + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "undo restores the selection"); + } else { + assert!(state.doc.selection.is_some(), "modified selection mode keeps the selection"); + assert_eq!(state.history.past_len(), history); + } + } +} + +#[test] +fn lasso_drag_from_pasteboard_still_creates_a_selection() { + let mut h = harness(); + mouse(&mut h, "down", -20.0, 80.0, Modifiers::NONE); + mouse(&mut h, "move", 100.0, 80.0, Modifiers::NONE); + mouse(&mut h, "move", 100.0, 160.0, Modifiers::NONE); + mouse(&mut h, "up", -20.0, 160.0, Modifiers::NONE); + let selection = h.state().session.active().unwrap().doc.selection.as_ref().expect("a drag still selects"); + assert!(selection.sample_channel(50, 120, 0) > 0.5); +} + fn freeform_harness() -> egui_kittest::Harness<'static, PhotocraftApp> { let mut h = harness(); let app = h.state_mut(); From ff6431628bfeb5ae1c826b703474e75cbf52e81c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:14:28 +0100 Subject: [PATCH 62/63] Reset rotated canvas with idle Escape (#13607) Co-authored-by: FredApps --- crates/ui-egui/src/input/shortcuts.rs | 11 +++++++++++ crates/ui-egui/src/input_tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 51970cbe3b5..89fb4745fdf 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -910,6 +910,17 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { || ctx.any_popup_open() || ctx.data(|d| d.get_temp::<(egui::Id, egui::Rect)>(egui::Id::unique("tool-flyout")).is_some()) || crate::panels::toolbar::more_flyout_open(ctx); + // Active operations and popups have already had priority. Reset a rotated view before + // idle Escape actions such as leaving full screen or deselecting; Rotate View handles its + // own Escape later, where it also clears an in-progress rotation drag. + if !esc_taken + && let Some(view) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) + && view.rotation != 0.0 + && pressed(Key::Escape) + { + view.rotation = 0.0; + return; + } // Both full screen modes (with and without the menu bar) return to Standard, as in Photoshop // (#4116), through the menu command so the window and the Screen Mode check follow. if !esc_taken && app.ui.view.screen_mode != "standard" && pressed(Key::Escape) { diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 54719f1c143..18fa7acbe85 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -1251,12 +1251,14 @@ fn hand_pointer_over_the_canvas_under_a_dialog() { fn esc_ends_a_pen_path_and_keeps_it() { let mut h = harness(); h.state_mut().ui.tool = crate::state::Tool::Pen; + h.state_mut().ui.views[0].rotation = 40.0; let owner = crate::vector_ui::capture_pen_owner(h.state()); h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], owner, ..Default::default() }); h.key_press(Key::Escape); h.run_steps(2); assert!(h.state().ui.pen.is_none(), "the Pen leaves drawing state"); + assert_eq!(h.state().ui.views[0].rotation, 40.0, "the active path owns Escape"); let doc = &h.state().session.active().unwrap().doc; let path = doc.work_path.as_ref().expect("the path is kept as the work path"); assert_eq!(path.subpaths.len(), 1); @@ -1295,6 +1297,27 @@ fn pen_shows_the_close_path_pointer_over_the_first_anchor() { assert_eq!(pointer(&mut h, 50.0, 50.0), close, "back on the first anchor"); } +/// A rotated view takes the first idle Esc; the next retains normal deselection. +#[test] +fn escape_resets_rotation_before_idle_deselection_for_paint_tools() { + for tool in [crate::state::Tool::Brush, crate::state::Tool::Pencil] { + let mut h = harness(); + h.state_mut().ui.tool = tool; + h.state_mut().ui.views[0].rotation = 40.0; + h.state_mut().run("select.all", json!({})).unwrap(); + h.run_steps(1); + let history = h.state().session.active().unwrap().history.entries().len(); + h.key_press(Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].rotation, 0.0, "{tool:?}"); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "first Esc keeps the selection"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), history, "view reset is not an edit"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.selection.is_none(), "second Esc deselects normally"); + } +} + /// Esc with no active operation deselects (#2674), like ⌘D. #[test] fn escape_deselects_when_nothing_else_needs_cancelling() { @@ -1318,11 +1341,13 @@ fn escape_deselects_when_nothing_else_needs_cancelling() { fn escape_with_a_dialog_open_cancels_the_dialog_not_the_selection() { let mut h = harness(); h.state_mut().run("select.all", json!({})).unwrap(); + h.state_mut().ui.views[0].rotation = 40.0; open_dialog(&mut h); h.key_press(Key::Escape); h.run_steps(2); assert!(h.state().ui.dialogs.is_empty(), "Esc cancelled the dialog"); assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the selection stays"); + assert_eq!(h.state().ui.views[0].rotation, 40.0, "the dialog owns the first Esc"); } /// The command palette owns Esc: it closes the palette and the selection stays. From bf0377c28d52a00225b48887ed3dbcac712d745e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:30:45 +0100 Subject: [PATCH 63/63] Live stroke canvas test: wait for the stroke to settle before the drawing picture (#13477) (#13514) * Live stroke canvas test: wait for the stroke to settle before the drawing picture (#13477) The live stroke paints on its own thread and a frame waits only 6 ms for it. A step that finishes later is collected only by the next pointer event, so on a slow runner the "drawing" picture could show the stroke one step behind and release painted the rest (76/255 on CI). The test now holds the pointer still (repeats its last move) and takes pictures with short real waits until three in a row match, bounded so it can't hang. Test-only change. * Live stroke canvas test: also wait for the stroke to go idle (#13477) Matching pictures alone don't prove a slow step has finished, so the settle loop now also requires the live stroke to be idle. PhotocraftApp::live_stroke_busy exposes the existing internal check read-only for that. * Fail the live stroke test if settling times out --------- Co-authored-by: FredApps --- crates/ui-egui/src/canvas/strokes.rs | 8 +++++ crates/ui-egui/tests/it/live_stroke_canvas.rs | 30 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 621f97dd0e2..6ccd55cc042 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -547,6 +547,14 @@ pub(super) fn live_stroke_busy(app: &PhotocraftApp) -> bool { app.live_stroke.as_ref().is_some_and(|l| l.paint.busy()) } +impl PhotocraftApp { + /// Is the live stroke still painting, or holding steps the canvas hasn't shown yet? Lets a + /// test read the canvas only once what it shows is the whole stroke so far (#13477). + pub fn live_stroke_busy(&self) -> bool { + live_stroke_busy(self) + } +} + /// The points the live retouching stroke has rendered. #[cfg(test)] pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option> { diff --git a/crates/ui-egui/tests/it/live_stroke_canvas.rs b/crates/ui-egui/tests/it/live_stroke_canvas.rs index 6942dba8a45..1a6a5560951 100644 --- a/crates/ui-egui/tests/it/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/live_stroke_canvas.rs @@ -158,13 +158,41 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { times.sort_by(f64::total_cmp); // Pointer move → stroke rendered → frame built (canvas refresh and upload included). eprintln!("{c:?}: move-to-frame median {:.2} ms, max {:.2} ms", times[times.len() / 2], times[times.len() - 1]); - let drawing = canvas(h); + // The pointer stays held at its last point, as a mouse held still repeats its position. + let held = |h: &mut Harness| { + control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]})); + canvas(h) + }; + let drawing = settled(h, held); let gpu = h.state().perf.gpu && !c.flip; control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]})); let done = canvas(h); (before, drawing, done, gpu) } +/// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own +/// thread and a frame waits only a few real ms for it, so on a slow machine its newest step +/// arrives late, and only a later pointer event shows it; release would then paint the rest. +/// `picture` holds the pointer still and takes a picture, with short real waits between them, +/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove +/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails +/// instead of hanging or comparing an unsettled picture. +fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { + const TRIES: usize = 80; + let mut last = picture(h); + let mut unchanged = 0; + for _ in 0..TRIES { + std::thread::sleep(std::time::Duration::from_millis(25)); + let next = picture(h); + unchanged = if next == last { unchanged + 1 } else { 0 }; + last = next; + if unchanged >= 2 && !h.state().live_stroke_busy() { + return last; + } + } + panic!("the live stroke did not settle before release"); +} + fn max_diff(a: &[[u8; 4]], b: &[[u8; 4]]) -> u8 { assert_eq!(a.len(), b.len()); a.iter().zip(b).flat_map(|(p, q)| (0..3).map(move |i| p[i].abs_diff(q[i]))).max().unwrap_or(0)