A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
v1.1.0
sora8fb01b0e847b
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.ymlindex dba752a..d43b277 100644--- a/.github/workflows/pages.yml+++ b/.github/workflows/pages.yml@@ -69,7 +69,7 @@ jobs:published_at: String(r.published_at || ""),prerelease: Boolean(r.prerelease),html_url: String(r.html_url || ""),- body: String(r.body || "").slice(0, 4000),+ body: String(r.body || "").slice(0, 16000),assets: (Array.isArray(r.assets) ? r.assets : []).map((a) => ({name: String(a.name || ""),size: Number(a.size || 0),diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac703e7..26aaa7a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,53 @@# Changelog+## v1.1.0++### New+- Added an Interface Size setting (60%–200%) in Preferences -> Appearance to make menus and panels smaller or larger+- Added a Reset Zoom to 100% command (`Ctrl+1`) to quickly reset the canvas zoom back to 100%+- Added basic 3D shapes in 3D mode: Cube, Sphere, Capsule, Cylinder, and Pyramid+- Added drag-and-drop import for 3D models (`.glb`, `.gltf`, `.obj`) directly onto the canvas+- Added a floating Quick-Access Brush Panel (`Shift+B`) that stays visible even when you hide all other panels (`Tab`), keeping your favorite brushes always within reach+- Added one-click star buttons and drag-and-drop in the Brush list to add or remove any built-in or custom brush from the panel+- Added built-in panel settings to switch between vertical and horizontal layouts, resize tiles, change opacity, reorder brushes, and lock the panel in place+- Brush outlines now rotate smoothly as you move and draw with rake brushes and other rotating brushes (including Natural Paint, directional, pen tilt, and barrel twist brushes)+- Added a "This brush rotates" checkbox in Brush Tip settings and Brush Studio so you can easily turn cursor rotation on or off for any brush+- Added full rotation for Gradient Meshes. Rotate all mesh points at once using the on-canvas rotate handle (hold `Shift` to snap every 15°) or the Rotate slider and quick buttons (`-45°`, `+45°`, `+90°`, `0°`)+- Added multi-point selection for Gradient Meshes+- Added transparency support to Lasso Fill with an Opacity slider (`1%–100%`) and a Transparent (Erase) toggle+- Added a live shape preview while drawing with Lasso Fill so you can see the shape, color, and opacity in real time (press `Esc` to cancel)+- Added custom Sub Tool groups (like in Clip Studio Paint)+- Added full drag-and-drop organizing across all Sub Tool groups+- Added keyboard shortcuts to step through your tools: `,` and `.` for Previous / Next Sub Tool, `Shift+,` and `Shift+.` for Previous / Next Tool, and `Alt+,` and `Alt+.` for Previous / Next Sub Tool Group+- Added direct keyboard shortcuts for individual brushes, custom sub tools, and custom Sub Tool groups+- Added `Win` (Windows / OS) key support for custom hotkeys across the entire app+- Added a dedicated Decoration tool group in the toolbar with 26 built-in Clip Studio Paint–style brushes+- Added separate preset memory for Brush and Decoration, so switching between them always brings back your last-used brush in each group+- Added full support for Decoration brushes in Quick Brushes, Quick Access, Brush Studio and `.inkb` export+- Added QuickShape (off by default in Preferences -> Brush & Stylus)+- Added Enclose and Fill under the Fill tool+- Added Paint Unfilled Area under the Fill tool+- Added Smart Line Fill controls (`Refer Source`, `Target Area`, `Brush Size`, `Close Gap` up to `40px`, `Area Scaling`, `Opacity`, `Tolerance`, and `Anti-Alias`) with live on-canvas previews, brush cursor sizing (`[` / `]` and `Ctrl+Alt+Drag`), Reference Folder support, and Transparent Ink erasing (`C`)+- Added Puppet Warp (`Ctrl+Shift+T` or `Edit` -> `Puppet Warp`)+- Added Cage Transform (`Edit` -> `Cage Transform` or via the transform bar)+- Both Puppet Warp and Cage Transform work on single layers, active selections, and entire multi-layer folders in a single undoable step, and switch seamlessly with Free, Perspective, and Mesh modes+- Added 1-Click Value Check (`Shift+Y`) to instantly switch the main canvas to live black-and-white tones so you can check light and dark contrast while painting+- Added quick Value Check toggle buttons in the top bar, Navigator, Command Bar, Quick Access, and View menu, along with a clear `Value B/W` indicator badge when active+- Added a live B/W preview mode right inside the Navigator panel+- Added an interactive Color | B/W Split View in the Navigator (`Alt+Shift+Y`)++### Improvements+- Switching between Free, Perspective, and Mesh transform modes now keeps your current changes (moving, resizing, rotating, flipping, or warping), so you can continue editing seamlessly without starting over+- Flip Horizontal and Flip Vertical buttons now also work in Perspective and Mesh transform modes+- Time-lapse recordings are now saved directly inside `.ink` files and automatically resume right where you left off when you reopen your artwork+- Paused time-lapses also keep all their saved frames inside `.ink` files so you can preview, export, or resume recording anytime+- Turning time-lapse recording on, off, or clearing frames now marks the file as having unsaved changes so you won't accidentally lose them on exit+- Time-lapse recordings are now preserved if the app crashes and you restore your session+- Made the inside of regular Lasso selections completely transparent instead of tinted blue so your colors stay clear while drawing++### Bug Fixes+- Fixed Natural Paint brushes not drawing properly inside regular Lasso and other active selections+## v1.0.4### Newdiff --git a/package-lock.json b/package-lock.jsonindex fb0ae3c..1d74ed4 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "ink-studio",- "version": "1.0.4",+ "version": "1.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "ink-studio",- "version": "1.0.4",+ "version": "1.1.0","license": "GPL-3.0","dependencies": {"@tailwindcss/vite": "^4.3.3",diff --git a/package.json b/package.jsonindex 68e9c56..65355d2 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "ink-studio","private": true,- "version": "1.0.4",+ "version": "1.1.0","description": "Collaborative Drawing Studio","author": "Sora","license": "GPL-3.0",diff --git a/public/brushes/decoration/background/building_0.png b/public/brushes/decoration/background/building_0.pngnew file mode 100644index 0000000..f83ae38Binary files /dev/null and b/public/brushes/decoration/background/building_0.png differdiff --git a/public/brushes/decoration/background/building_1.png b/public/brushes/decoration/background/building_1.pngnew file mode 100644index 0000000..d9487f6Binary files /dev/null and b/public/brushes/decoration/background/building_1.png differdiff --git a/public/brushes/decoration/background/building_10.png b/public/brushes/decoration/background/building_10.pngnew file mode 100644index 0000000..7f52781Binary files /dev/null and b/public/brushes/decoration/background/building_10.png differdiff --git a/public/brushes/decoration/background/building_11.png b/public/brushes/decoration/background/building_11.pngnew file mode 100644index 0000000..fba2431Binary files /dev/null and b/public/brushes/decoration/background/building_11.png differdiff --git a/public/brushes/decoration/background/building_12.png b/public/brushes/decoration/background/building_12.pngnew file mode 100644index 0000000..9c374b8Binary files /dev/null and b/public/brushes/decoration/background/building_12.png differdiff --git a/public/brushes/decoration/background/building_2.png b/public/brushes/decoration/background/building_2.pngnew file mode 100644index 0000000..e4c6ffaBinary files /dev/null and b/public/brushes/decoration/background/building_2.png differdiff --git a/public/brushes/decoration/background/building_3.png b/public/brushes/decoration/background/building_3.pngnew file mode 100644index 0000000..0a6de0bBinary files /dev/null and b/public/brushes/decoration/background/building_3.png differdiff --git a/public/brushes/decoration/background/building_4.png b/public/brushes/decoration/background/building_4.pngnew file mode 100644index 0000000..777d341Binary files /dev/null and b/public/brushes/decoration/background/building_4.png differdiff --git a/public/brushes/decoration/background/building_5.png b/public/brushes/decoration/background/building_5.pngnew file mode 100644index 0000000..dc0635dBinary files /dev/null and b/public/brushes/decoration/background/building_5.png differdiff --git a/public/brushes/decoration/background/building_6.png b/public/brushes/decoration/background/building_6.pngnew file mode 100644index 0000000..8f7ce88Binary files /dev/null and b/public/brushes/decoration/background/building_6.png differdiff --git a/public/brushes/decoration/background/building_7.png b/public/brushes/decoration/background/building_7.pngnew file mode 100644index 0000000..a0a4a91Binary files /dev/null and b/public/brushes/decoration/background/building_7.png differdiff --git a/public/brushes/decoration/background/building_8.png b/public/brushes/decoration/background/building_8.pngnew file mode 100644index 0000000..4f39343Binary files /dev/null and b/public/brushes/decoration/background/building_8.png differdiff --git a/public/brushes/decoration/background/building_9.png b/public/brushes/decoration/background/building_9.pngnew file mode 100644index 0000000..32b43a0Binary files /dev/null and b/public/brushes/decoration/background/building_9.png differdiff --git a/public/brushes/decoration/background/cloud_0.png b/public/brushes/decoration/background/cloud_0.pngnew file mode 100644index 0000000..3befb3fBinary files /dev/null and b/public/brushes/decoration/background/cloud_0.png differdiff --git a/public/brushes/decoration/background/grass_0.png b/public/brushes/decoration/background/grass_0.pngnew file mode 100644index 0000000..5c29278Binary files /dev/null and b/public/brushes/decoration/background/grass_0.png differdiff --git a/public/brushes/decoration/background/grass_1.png b/public/brushes/decoration/background/grass_1.pngnew file mode 100644index 0000000..c4dc4dcBinary files /dev/null and b/public/brushes/decoration/background/grass_1.png differdiff --git a/public/brushes/decoration/background/trees_0.png b/public/brushes/decoration/background/trees_0.pngnew file mode 100644index 0000000..27f273bBinary files /dev/null and b/public/brushes/decoration/background/trees_0.png differdiff --git a/public/brushes/decoration/background/trees_1.png b/public/brushes/decoration/background/trees_1.pngnew file mode 100644index 0000000..2b4d27aBinary files /dev/null and b/public/brushes/decoration/background/trees_1.png differdiff --git a/public/brushes/decoration/background/trees_2.png b/public/brushes/decoration/background/trees_2.pngnew file mode 100644index 0000000..2b4bc76Binary files /dev/null and b/public/brushes/decoration/background/trees_2.png differdiff --git a/public/brushes/decoration/background/trees_3.png b/public/brushes/decoration/background/trees_3.pngnew file mode 100644index 0000000..cdb9587Binary files /dev/null and b/public/brushes/decoration/background/trees_3.png differdiff --git a/public/brushes/decoration/background/trees_4.png b/public/brushes/decoration/background/trees_4.pngnew file mode 100644index 0000000..f62a2f2Binary files /dev/null and b/public/brushes/decoration/background/trees_4.png differdiff --git a/public/brushes/decoration/clothing/classic-lace_0.png b/public/brushes/decoration/clothing/classic-lace_0.pngnew file mode 100644index 0000000..8d67c88Binary files /dev/null and b/public/brushes/decoration/clothing/classic-lace_0.png differdiff --git a/public/brushes/decoration/clothing/cross-lace_0.png b/public/brushes/decoration/clothing/cross-lace_0.pngnew file mode 100644index 0000000..6aa43d3Binary files /dev/null and b/public/brushes/decoration/clothing/cross-lace_0.png differdiff --git a/public/brushes/decoration/clothing/decorative-rope_0.png b/public/brushes/decoration/clothing/decorative-rope_0.pngnew file mode 100644index 0000000..1baf078Binary files /dev/null and b/public/brushes/decoration/clothing/decorative-rope_0.png differdiff --git a/public/brushes/decoration/clothing/ornate-scallop_0.png b/public/brushes/decoration/clothing/ornate-scallop_0.pngnew file mode 100644index 0000000..c89e081Binary files /dev/null and b/public/brushes/decoration/clothing/ornate-scallop_0.png differdiff --git a/public/brushes/decoration/clothing/rope-ribbon_0.png b/public/brushes/decoration/clothing/rope-ribbon_0.pngnew file mode 100644index 0000000..7c99b8bBinary files /dev/null and b/public/brushes/decoration/clothing/rope-ribbon_0.png differdiff --git a/public/brushes/decoration/clothing/rose-trim_0.png b/public/brushes/decoration/clothing/rose-trim_0.pngnew file mode 100644index 0000000..54e55a0Binary files /dev/null and b/public/brushes/decoration/clothing/rose-trim_0.png differdiff --git a/public/brushes/decoration/clothing/sakura-lace_0.png b/public/brushes/decoration/clothing/sakura-lace_0.pngnew file mode 100644index 0000000..93377c6Binary files /dev/null and b/public/brushes/decoration/clothing/sakura-lace_0.png differdiff --git a/public/brushes/decoration/clothing/scallop-lace_0.png b/public/brushes/decoration/clothing/scallop-lace_0.pngnew file mode 100644index 0000000..15681e8Binary files /dev/null and b/public/brushes/decoration/clothing/scallop-lace_0.png differdiff --git a/public/brushes/decoration/clothing/scallop-trim-lace_0.png b/public/brushes/decoration/clothing/scallop-trim-lace_0.pngnew file mode 100644index 0000000..bcd0239Binary files /dev/null and b/public/brushes/decoration/clothing/scallop-trim-lace_0.png differdiff --git a/public/brushes/decoration/clothing/sheer-scallop_0.png b/public/brushes/decoration/clothing/sheer-scallop_0.pngnew file mode 100644index 0000000..d51b6d4Binary files /dev/null and b/public/brushes/decoration/clothing/sheer-scallop_0.png differdiff --git a/public/brushes/decoration/clothing/simple-lace_0.png b/public/brushes/decoration/clothing/simple-lace_0.pngnew file mode 100644index 0000000..14b7364Binary files /dev/null and b/public/brushes/decoration/clothing/simple-lace_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-1_0.png b/public/brushes/decoration/clothing/standard-lace-1_0.pngnew file mode 100644index 0000000..71ab968Binary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-1_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-2_0.png b/public/brushes/decoration/clothing/standard-lace-2_0.pngnew file mode 100644index 0000000..0be98e4Binary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-2_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-3_0.png b/public/brushes/decoration/clothing/standard-lace-3_0.pngnew file mode 100644index 0000000..8dba62bBinary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-3_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-4_0.png b/public/brushes/decoration/clothing/standard-lace-4_0.pngnew file mode 100644index 0000000..8a97224Binary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-4_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-5_0.png b/public/brushes/decoration/clothing/standard-lace-5_0.pngnew file mode 100644index 0000000..126ff14Binary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-5_0.png differdiff --git a/public/brushes/decoration/clothing/standard-lace-6_0.png b/public/brushes/decoration/clothing/standard-lace-6_0.pngnew file mode 100644index 0000000..fe460a3Binary files /dev/null and b/public/brushes/decoration/clothing/standard-lace-6_0.png differdiff --git a/public/brushes/decoration/clothing/star-lace_0.png b/public/brushes/decoration/clothing/star-lace_0.pngnew file mode 100644index 0000000..7cabcdeBinary files /dev/null and b/public/brushes/decoration/clothing/star-lace_0.png differdiff --git a/public/brushes/decoration/effect/bloodstain_0.png b/public/brushes/decoration/effect/bloodstain_0.pngnew file mode 100644index 0000000..1fb1bc9Binary files /dev/null and b/public/brushes/decoration/effect/bloodstain_0.png differdiff --git a/public/brushes/decoration/effect/bloodstain_1.png b/public/brushes/decoration/effect/bloodstain_1.pngnew file mode 100644index 0000000..b598021Binary files /dev/null and b/public/brushes/decoration/effect/bloodstain_1.png differdiff --git a/public/brushes/decoration/effect/bloodstain_2.png b/public/brushes/decoration/effect/bloodstain_2.pngnew file mode 100644index 0000000..8c3030eBinary files /dev/null and b/public/brushes/decoration/effect/bloodstain_2.png differdiff --git a/public/brushes/decoration/effect/bloodstain_3.png b/public/brushes/decoration/effect/bloodstain_3.pngnew file mode 100644index 0000000..6789e49Binary files /dev/null and b/public/brushes/decoration/effect/bloodstain_3.png differdiff --git a/public/brushes/decoration/effect/bloodstain_4.png b/public/brushes/decoration/effect/bloodstain_4.pngnew file mode 100644index 0000000..66c4e15Binary files /dev/null and b/public/brushes/decoration/effect/bloodstain_4.png differdiff --git a/public/brushes/decoration/effect/bloodstain_5.png b/public/brushes/decoration/effect/bloodstain_5.pngnew file mode 100644index 0000000..b5f843eBinary files /dev/null and b/public/brushes/decoration/effect/bloodstain_5.png differdiff --git a/public/brushes/decoration/effect/bloodstain_6.png b/public/brushes/decoration/effect/bloodstain_6.pngnew file mode 100644index 0000000..ec32e12Binary files /dev/null and b/public/brushes/decoration/effect/bloodstain_6.png differdiff --git a/public/brushes/decoration/effect/cherry_0.png b/public/brushes/decoration/effect/cherry_0.pngnew file mode 100644index 0000000..2808cfaBinary files /dev/null and b/public/brushes/decoration/effect/cherry_0.png differdiff --git a/public/brushes/decoration/effect/cherry_1.png b/public/brushes/decoration/effect/cherry_1.pngnew file mode 100644index 0000000..7b60207Binary files /dev/null and b/public/brushes/decoration/effect/cherry_1.png differdiff --git a/public/brushes/decoration/effect/cherry_2.png b/public/brushes/decoration/effect/cherry_2.pngnew file mode 100644index 0000000..6ec19c1Binary files /dev/null and b/public/brushes/decoration/effect/cherry_2.png differdiff --git a/public/brushes/decoration/effect/feather_0.png b/public/brushes/decoration/effect/feather_0.pngnew file mode 100644index 0000000..9318521Binary files /dev/null and b/public/brushes/decoration/effect/feather_0.png differdiff --git a/public/brushes/decoration/effect/feather_1.png b/public/brushes/decoration/effect/feather_1.pngnew file mode 100644index 0000000..54e8aa2Binary files /dev/null and b/public/brushes/decoration/effect/feather_1.png differdiff --git a/public/brushes/decoration/effect/feather_2.png b/public/brushes/decoration/effect/feather_2.pngnew file mode 100644index 0000000..0299b8fBinary files /dev/null and b/public/brushes/decoration/effect/feather_2.png differdiff --git a/public/brushes/decoration/effect/feather_3.png b/public/brushes/decoration/effect/feather_3.pngnew file mode 100644index 0000000..271519cBinary files /dev/null and b/public/brushes/decoration/effect/feather_3.png differdiff --git a/public/brushes/decoration/effect/roses_0.png b/public/brushes/decoration/effect/roses_0.pngnew file mode 100644index 0000000..2f41f61Binary files /dev/null and b/public/brushes/decoration/effect/roses_0.png differdiff --git a/public/brushes/decoration/effect/roses_1.png b/public/brushes/decoration/effect/roses_1.pngnew file mode 100644index 0000000..af7b7adBinary files /dev/null and b/public/brushes/decoration/effect/roses_1.png differdiff --git a/public/brushes/decoration/effect/roses_2.png b/public/brushes/decoration/effect/roses_2.pngnew file mode 100644index 0000000..bf36d20Binary files /dev/null and b/public/brushes/decoration/effect/roses_2.png differdiff --git a/public/brushes/decoration/effect/roses_3.png b/public/brushes/decoration/effect/roses_3.pngnew file mode 100644index 0000000..218fd5eBinary files /dev/null and b/public/brushes/decoration/effect/roses_3.png differdiff --git a/public/brushes/decoration/effect/roses_4.png b/public/brushes/decoration/effect/roses_4.pngnew file mode 100644index 0000000..417939fBinary files /dev/null and b/public/brushes/decoration/effect/roses_4.png differdiff --git a/public/brushes/decoration/effect/roses_5.png b/public/brushes/decoration/effect/roses_5.pngnew file mode 100644index 0000000..b6de1c5Binary files /dev/null and b/public/brushes/decoration/effect/roses_5.png differdiff --git a/public/brushes/decoration/effect/roses_6.png b/public/brushes/decoration/effect/roses_6.pngnew file mode 100644index 0000000..6225ce9Binary files /dev/null and b/public/brushes/decoration/effect/roses_6.png differdiff --git a/public/brushes/decoration/effect/roses_7.png b/public/brushes/decoration/effect/roses_7.pngnew file mode 100644index 0000000..fb79527Binary files /dev/null and b/public/brushes/decoration/effect/roses_7.png differdiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex bd30a0e..6733e57 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2021,7 +2021,7 @@ dependencies = [[[package]]name = "ink-studio"-version = "1.0.4"+version = "1.1.0"dependencies = ["axum","flate2",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0839ef1..2994238 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "ink-studio"-version = "1.0.4"+version = "1.1.0"description = "Collaborative Drawing Studio"authors = ["Sora"]license = "GPL-3.0"@@ -50,6 +50,7 @@ windows-sys = { version = "0.59", features = ["Win32_System_SystemInformation","Win32_System_Threading","Win32_UI_HiDpi",+ "Win32_UI_Input_KeyboardAndMouse","Win32_UI_Input_Pointer","Win32_UI_Shell","Win32_UI_WindowsAndMessaging",diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 7020463..6930361 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -15,6 +15,7 @@"core:window:allow-start-dragging","core:window:allow-is-maximized","core:window:allow-is-fullscreen",- "core:window:allow-set-fullscreen"+ "core:window:allow-set-fullscreen",+ "core:webview:allow-set-webview-zoom"]}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5750245..c31b96c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,5 +1,6 @@pub mod clip_parser;mod doc_wire;+mod os_hotkeys;mod psd_parser;mod raster_ops;mod recovery;@@ -501,6 +502,19 @@ async fn timelapse_write_frame(request: tauri::ipc::Request<'_>) -> Result<(), Stimelapse::write_frame(&session_id, frame_index, &ext, data).await}+#[tauri::command]+async fn timelapse_write_frames_batch(request: tauri::ipc::Request<'_>) -> Result<usize, String> {+ let session_id = header_str(&request, "x-session-id")?;+ let body = raw_body(&request)?;+ let entries = timelapse::unpack_frame_batch(body)?;+ timelapse::write_frames_batch(&session_id, entries).await+}++#[tauri::command]+async fn timelapse_list_frames(session_id: String) -> Result<Vec<(u32, String)>, String> {+ timelapse::list_frames(&session_id).await+}+#[tauri::command]async fn timelapse_read_frame(request: tauri::ipc::Request<'_>,@@ -845,6 +859,21 @@ fn tablet_get_status() -> tablet_input::TabletStatus {tablet_input::get_tablet_status()}+#[tauri::command]+fn os_hotkeys_sync(+ window: tauri::WebviewWindow,+ bindings: Vec<os_hotkeys::NativeOsHotkeyBinding>,+ recording: bool,+ on_event: tauri::ipc::Channel<os_hotkeys::NativeOsHotkeyEvent>,+) -> Result<os_hotkeys::OsHotkeyStatus, String> {+ os_hotkeys::sync_os_hotkeys(&window, bindings, recording, on_event)+}++#[tauri::command]+fn os_hotkeys_stop() {+ os_hotkeys::stop_os_hotkeys();+}+#[tauri::command]async fn get_system_hardware_info() -> Result<system_perf::SystemHardwareInfo, String> {tokio::task::spawn_blocking(system_perf::collect_system_hardware_info)@@ -1015,6 +1044,8 @@ pub fn run() {scratch_disk_read_tile,scratch_disk_clear,timelapse_write_frame,+ timelapse_write_frames_batch,+ timelapse_list_frames,timelapse_read_frame,timelapse_clear,timelapse_check_ffmpeg,@@ -1032,6 +1063,8 @@ pub fn run() {tablet_start_input,tablet_stop_input,tablet_get_status,+ os_hotkeys_sync,+ os_hotkeys_stop,get_system_hardware_info,get_scratch_disk_usage,apply_performance_config,@@ -1042,6 +1075,7 @@ pub fn run() {app.run(|_app_handle, event| {if let tauri::RunEvent::Exit = event {+ os_hotkeys::stop_os_hotkeys();tablet_input::stop_tablet_input();server::shutdown_sync();}diff --git a/src-tauri/src/os_hotkeys.rs b/src-tauri/src/os_hotkeys.rsnew file mode 100644index 0000000..2db58c8--- /dev/null+++ b/src-tauri/src/os_hotkeys.rs@@ -0,0 +1,723 @@+use serde::{Deserialize, Serialize};+use tauri::ipc::Channel;++#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash)]+#[serde(rename_all = "camelCase")]+pub struct NativeOsHotkeyBinding {+ pub code: String,+ pub ctrl: bool,+ pub shift: bool,+ pub alt: bool,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeOsHotkeyEvent {+ pub phase: String, // "keydown" | "keyup"+ pub code: String,+ pub key: String,+ pub ctrl_key: bool,+ pub meta_key: bool,+ pub shift_key: bool,+ pub alt_key: bool,+ pub repeat: bool,+ pub is_recording: bool,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OsHotkeyStatus {+ pub supported: bool,+ pub active: bool,+ pub registered_count: usize,+ pub recording: bool,+}++/// Converts a standard DOM KeyboardEvent.code into one or more Windows Virtual-Key codes.+pub fn dom_code_to_vks(code: &str) -> Vec<u32> {+ if let Some(ch) = code.strip_prefix("Key") {+ if ch.len() == 1 {+ let b = ch.as_bytes()[0];+ if b.is_ascii_uppercase() {+ return vec![b as u32];+ }+ }+ }+ if let Some(d) = code.strip_prefix("Digit") {+ if d.len() == 1 {+ let b = d.as_bytes()[0];+ if b.is_ascii_digit() {+ return vec![b as u32];+ }+ }+ }+ if let Some(d) = code.strip_prefix("Numpad") {+ if d.len() == 1 {+ let b = d.as_bytes()[0];+ if b.is_ascii_digit() {+ return vec![0x60 + (b - b'0') as u32];+ }+ }+ return match d {+ "Add" => vec![0x6B],+ "Subtract" => vec![0x6D],+ "Enter" => vec![0x0D],+ _ => vec![],+ };+ }+ if let Some(fn_num) = code.strip_prefix('F') {+ if let Ok(n) = fn_num.parse::<u32>() {+ if (1..=12).contains(&n) {+ return vec![0x70 + (n - 1)];+ }+ }+ }++ match code {+ "BracketLeft" => vec![0xDB],+ "BracketRight" => vec![0xDD],+ "Comma" => vec![0xBC],+ "Period" => vec![0xBE],+ "Slash" => vec![0xBF],+ "Backslash" => vec![0xDC],+ "Semicolon" => vec![0xBA],+ "Quote" => vec![0xDE],+ "Backquote" => vec![0xC0],+ "Equal" => vec![0xBB],+ "Minus" => vec![0xBD],+ "Tab" => vec![0x09],+ "Space" => vec![0x20],+ "Enter" => vec![0x0D],+ "Escape" => vec![0x1B],+ "Delete" => vec![0x2E],+ "Backspace" => vec![0x08],+ "ArrowUp" => vec![0x26],+ "ArrowDown" => vec![0x28],+ "ArrowLeft" => vec![0x25],+ "ArrowRight" => vec![0x27],+ "Home" => vec![0x24],+ "End" => vec![0x23],+ "PageUp" => vec![0x21],+ "PageDown" => vec![0x22],+ _ => vec![],+ }+}++/// Converts a Windows Virtual-Key code into canonical DOM (code, key) pair.+pub fn vk_to_dom_code_and_key(vk: u32, is_extended: bool) -> Option<(&'static str, &'static str)> {+ match vk {+ 0x41 => Some(("KeyA", "a")),+ 0x42 => Some(("KeyB", "b")),+ 0x43 => Some(("KeyC", "c")),+ 0x44 => Some(("KeyD", "d")),+ 0x45 => Some(("KeyE", "e")),+ 0x46 => Some(("KeyF", "f")),+ 0x47 => Some(("KeyG", "g")),+ 0x48 => Some(("KeyH", "h")),+ 0x49 => Some(("KeyI", "i")),+ 0x4A => Some(("KeyJ", "j")),+ 0x4B => Some(("KeyK", "k")),+ 0x4C => Some(("KeyL", "l")),+ 0x4D => Some(("KeyM", "m")),+ 0x4E => Some(("KeyN", "n")),+ 0x4F => Some(("KeyO", "o")),+ 0x50 => Some(("KeyP", "p")),+ 0x51 => Some(("KeyQ", "q")),+ 0x52 => Some(("KeyR", "r")),+ 0x53 => Some(("KeyS", "s")),+ 0x54 => Some(("KeyT", "t")),+ 0x55 => Some(("KeyU", "u")),+ 0x56 => Some(("KeyV", "v")),+ 0x57 => Some(("KeyW", "w")),+ 0x58 => Some(("KeyX", "x")),+ 0x59 => Some(("KeyY", "y")),+ 0x5A => Some(("KeyZ", "z")),+ 0x30 => Some(("Digit0", "0")),+ 0x31 => Some(("Digit1", "1")),+ 0x32 => Some(("Digit2", "2")),+ 0x33 => Some(("Digit3", "3")),+ 0x34 => Some(("Digit4", "4")),+ 0x35 => Some(("Digit5", "5")),+ 0x36 => Some(("Digit6", "6")),+ 0x37 => Some(("Digit7", "7")),+ 0x38 => Some(("Digit8", "8")),+ 0x39 => Some(("Digit9", "9")),+ 0x60 => Some(("Numpad0", "0")),+ 0x61 => Some(("Numpad1", "1")),+ 0x62 => Some(("Numpad2", "2")),+ 0x63 => Some(("Numpad3", "3")),+ 0x64 => Some(("Numpad4", "4")),+ 0x65 => Some(("Numpad5", "5")),+ 0x66 => Some(("Numpad6", "6")),+ 0x67 => Some(("Numpad7", "7")),+ 0x68 => Some(("Numpad8", "8")),+ 0x69 => Some(("Numpad9", "9")),+ 0x6B => Some(("NumpadAdd", "+")),+ 0x6D => Some(("NumpadSubtract", "-")),+ 0x70 => Some(("F1", "F1")),+ 0x71 => Some(("F2", "F2")),+ 0x72 => Some(("F3", "F3")),+ 0x73 => Some(("F4", "F4")),+ 0x74 => Some(("F5", "F5")),+ 0x75 => Some(("F6", "F6")),+ 0x76 => Some(("F7", "F7")),+ 0x77 => Some(("F8", "F8")),+ 0x78 => Some(("F9", "F9")),+ 0x79 => Some(("F10", "F10")),+ 0x7A => Some(("F11", "F11")),+ 0x7B => Some(("F12", "F12")),+ 0xDB => Some(("BracketLeft", "[")),+ 0xDD => Some(("BracketRight", "]")),+ 0xBC => Some(("Comma", ",")),+ 0xBE => Some(("Period", ".")),+ 0xBF => Some(("Slash", "/")),+ 0xDC => Some(("Backslash", "\\")),+ 0xBA => Some(("Semicolon", ";")),+ 0xDE => Some(("Quote", "'")),+ 0xC0 => Some(("Backquote", "`")),+ 0xBB => Some(("Equal", "=")),+ 0xBD => Some(("Minus", "-")),+ 0x09 => Some(("Tab", "Tab")),+ 0x20 => Some(("Space", " ")),+ 0x0D => Some((if is_extended { "NumpadEnter" } else { "Enter" }, "Enter")),+ 0x1B => Some(("Escape", "Escape")),+ 0x2E => Some(("Delete", "Delete")),+ 0x08 => Some(("Backspace", "Backspace")),+ 0x26 => Some(("ArrowUp", "ArrowUp")),+ 0x28 => Some(("ArrowDown", "ArrowDown")),+ 0x25 => Some(("ArrowLeft", "ArrowLeft")),+ 0x27 => Some(("ArrowRight", "ArrowRight")),+ 0x24 => Some(("Home", "Home")),+ 0x23 => Some(("End", "End")),+ 0x21 => Some(("PageUp", "PageUp")),+ 0x22 => Some(("PageDown", "PageDown")),+ _ => None,+ }+}++#[cfg(target_os = "windows")]+mod win_impl {+ use super::*;+ use std::collections::HashSet;+ use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};+ use std::sync::{mpsc, LazyLock, Mutex, RwLock};+ use std::thread::JoinHandle;+ use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};+ use windows_sys::Win32::System::Threading::GetCurrentThreadId;+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{+ GetAsyncKeyState, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP,+ VK_CONTROL, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_RCONTROL, VK_RMENU,+ VK_RSHIFT, VK_RWIN, VK_SHIFT,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ CallNextHookEx, DispatchMessageW, GetAncestor, GetForegroundWindow, GetMessageW,+ PostThreadMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, GA_ROOT,+ HHOOK, KBDLLHOOKSTRUCT, LLKHF_EXTENDED, LLKHF_INJECTED, MSG, WH_KEYBOARD_LL, WM_KEYDOWN,+ WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP,+ };++ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ struct VkBinding {+ vk: u32,+ ctrl: bool,+ shift: bool,+ alt: bool,+ }++ static MAIN_HWND: AtomicIsize = AtomicIsize::new(0);+ static RECORDING_MODE: AtomicBool = AtomicBool::new(false);+ static HOOK_RUNNING: AtomicBool = AtomicBool::new(false);+ static HOOK_THREAD_ID: AtomicU32 = AtomicU32::new(0);+ static WIN_DOWN: AtomicBool = AtomicBool::new(false);+ static WIN_COMBO_CONSUMED: AtomicBool = AtomicBool::new(false);++ static BINDINGS: LazyLock<RwLock<HashSet<VkBinding>>> =+ LazyLock::new(|| RwLock::new(HashSet::new()));+ static CONSUMED_VKS: LazyLock<Mutex<HashSet<u32>>> =+ LazyLock::new(|| Mutex::new(HashSet::new()));+ static EVENT_TX: LazyLock<Mutex<Option<mpsc::Sender<NativeOsHotkeyEvent>>>> =+ LazyLock::new(|| Mutex::new(None));+ static CHANNEL_SINK: LazyLock<Mutex<Option<Channel<NativeOsHotkeyEvent>>>> =+ LazyLock::new(|| Mutex::new(None));+ static HOOK_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =+ LazyLock::new(|| Mutex::new(None));+ static DISPATCH_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =+ LazyLock::new(|| Mutex::new(None));++ fn is_pure_modifier_vk(vk: u32) -> bool {+ matches!(+ vk as u16,+ VK_LWIN+ | VK_RWIN+ | VK_CONTROL+ | VK_LCONTROL+ | VK_RCONTROL+ | VK_SHIFT+ | VK_LSHIFT+ | VK_RSHIFT+ | VK_MENU+ | VK_LMENU+ | VK_RMENU+ )+ }++ fn is_our_window_foreground() -> bool {+ let main_raw = MAIN_HWND.load(Ordering::Relaxed);+ if main_raw == 0 {+ return false;+ }+ let main_hwnd = main_raw as HWND;+ unsafe {+ let fg = GetForegroundWindow();+ if fg.is_null() {+ return false;+ }+ if fg == main_hwnd {+ return true;+ }+ GetAncestor(fg, GA_ROOT) == main_hwnd+ }+ }++ fn is_vk_pressed(vk: u16) -> bool {+ unsafe { (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0 }+ }++ /// Injects a harmless unassigned virtual key (0xE8) so Windows Shell treats the Win hold+ /// as a completed key chord rather than a lone Win tap (preventing the Start Menu popup).+ fn suppress_start_menu_tap() {+ unsafe {+ let inputs: [INPUT; 2] = [+ INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: 0xE8,+ wScan: 0,+ dwFlags: 0,+ time: 0,+ dwExtraInfo: 0,+ },+ },+ },+ INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: 0xE8,+ wScan: 0,+ dwFlags: KEYEVENTF_KEYUP,+ time: 0,+ dwExtraInfo: 0,+ },+ },+ },+ ];+ let _ = SendInput(+ inputs.len() as u32,+ inputs.as_ptr(),+ std::mem::size_of::<INPUT>() as i32,+ );+ }+ }++ fn emit_async(event: NativeOsHotkeyEvent) {+ if let Ok(guard) = EVENT_TX.try_lock() {+ if let Some(tx) = guard.as_ref() {+ let _ = tx.send(event);+ }+ }+ }++ unsafe extern "system" fn ll_keyboard_proc(+ n_code: i32,+ w_param: WPARAM,+ l_param: LPARAM,+ ) -> LRESULT {+ if n_code < 0 {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let kb = &*(l_param as *const KBDLLHOOKSTRUCT);+ // Never intercept injected keys (including our own 0xE8 Start Menu suppressor)+ if (kb.flags & LLKHF_INJECTED) != 0 {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let msg = w_param as u32;+ let is_down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;+ let is_up = msg == WM_KEYUP || msg == WM_SYSKEYUP;+ if !is_down && !is_up {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let vk = kb.vkCode;+ let is_extended = (kb.flags & LLKHF_EXTENDED) != 0;++ // Track Win key physical press/release cleanly without ever swallowing Win keyup+ if vk == VK_LWIN as u32 || vk == VK_RWIN as u32 {+ if is_down {+ if !WIN_DOWN.swap(true, Ordering::SeqCst) {+ WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);+ }+ } else {+ WIN_DOWN.store(false, Ordering::SeqCst);+ WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);+ }+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ // Release previously consumed key cleanly even if focus changed mid-hold+ if is_up {+ let was_consumed = CONSUMED_VKS+ .try_lock()+ .map(|mut set| set.remove(&vk))+ .unwrap_or(false);+ if was_consumed {+ if let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) {+ emit_async(NativeOsHotkeyEvent {+ phase: "keyup".to_string(),+ code: code.to_string(),+ key: key.to_string(),+ ctrl_key: is_vk_pressed(VK_CONTROL),+ meta_key: WIN_DOWN.load(Ordering::Relaxed)+ || is_vk_pressed(VK_LWIN)+ || is_vk_pressed(VK_RWIN),+ shift_key: is_vk_pressed(VK_SHIFT),+ alt_key: is_vk_pressed(VK_MENU),+ repeat: false,+ is_recording: RECORDING_MODE.load(Ordering::Relaxed),+ });+ }+ return 1;+ }+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ // Only evaluate keydowns when Win key is actively held AND Ink Studio is foreground+ let win_held =+ WIN_DOWN.load(Ordering::Relaxed) || is_vk_pressed(VK_LWIN) || is_vk_pressed(VK_RWIN);+ if !win_held || is_pure_modifier_vk(vk) || !is_our_window_foreground() {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let ctrl = is_vk_pressed(VK_CONTROL);+ let shift = is_vk_pressed(VK_SHIFT);+ let alt = is_vk_pressed(VK_MENU);++ // Never fight Windows Lock Screen (Win+L without extra modifiers)+ if vk == 0x4C && !ctrl && !shift && !alt {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) else {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ };++ let is_recording = RECORDING_MODE.load(Ordering::Relaxed);+ let matched = if is_recording {+ // Do not capture bare Escape when recording; let user cancel+ vk != 0x1B+ } else {+ BINDINGS+ .try_read()+ .map(|set| set.contains(&VkBinding { vk, ctrl, shift, alt }))+ .unwrap_or(false)+ };++ if !matched {+ return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);+ }++ let is_repeat = CONSUMED_VKS+ .try_lock()+ .map(|mut set| !set.insert(vk))+ .unwrap_or(false);++ if !WIN_COMBO_CONSUMED.swap(true, Ordering::SeqCst) {+ suppress_start_menu_tap();+ }++ emit_async(NativeOsHotkeyEvent {+ phase: "keydown".to_string(),+ code: code.to_string(),+ key: key.to_string(),+ ctrl_key: ctrl,+ meta_key: true,+ shift_key: shift,+ alt_key: alt,+ repeat: is_repeat,+ is_recording,+ });++ 1+ }++ fn ensure_hook_running() -> Result<(), String> {+ if HOOK_RUNNING.load(Ordering::SeqCst) {+ return Ok(());+ }++ let (tx, rx) = mpsc::channel::<NativeOsHotkeyEvent>();+ if let Ok(mut guard) = EVENT_TX.lock() {+ *guard = Some(tx);+ }++ let dispatch_handle = std::thread::Builder::new()+ .name("inkstudio-os-hotkey-dispatch".to_string())+ .spawn(move || {+ while let Ok(ev) = rx.recv() {+ if let Ok(sink) = CHANNEL_SINK.lock() {+ if let Some(ch) = sink.as_ref() {+ let _ = ch.send(ev);+ }+ }+ }+ })+ .map_err(|e| format!("Failed to spawn OS hotkey dispatch thread: {}", e))?;++ if let Ok(mut guard) = DISPATCH_THREAD.lock() {+ *guard = Some(dispatch_handle);+ }++ let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();+ let hook_handle = std::thread::Builder::new()+ .name("inkstudio-os-hotkeys".to_string())+ .spawn(move || unsafe {+ let tid = GetCurrentThreadId();+ HOOK_THREAD_ID.store(tid, Ordering::SeqCst);++ let hook: HHOOK =+ SetWindowsHookExW(WH_KEYBOARD_LL, Some(ll_keyboard_proc), std::ptr::null_mut(), 0);+ if hook.is_null() {+ HOOK_THREAD_ID.store(0, Ordering::SeqCst);+ let _ = ready_tx.send(Err("Failed to install WH_KEYBOARD_LL hook".to_string()));+ return;+ }++ HOOK_RUNNING.store(true, Ordering::SeqCst);+ let _ = ready_tx.send(Ok(()));++ let mut msg: MSG = std::mem::zeroed();+ while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }++ UnhookWindowsHookEx(hook);+ HOOK_RUNNING.store(false, Ordering::SeqCst);+ HOOK_THREAD_ID.store(0, Ordering::SeqCst);+ WIN_DOWN.store(false, Ordering::SeqCst);+ WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);+ if let Ok(mut consumed) = CONSUMED_VKS.lock() {+ consumed.clear();+ }+ })+ .map_err(|e| format!("Failed to spawn OS hotkey hook thread: {}", e))?;++ match ready_rx.recv() {+ Ok(Ok(())) => {+ if let Ok(mut guard) = HOOK_THREAD.lock() {+ *guard = Some(hook_handle);+ }+ Ok(())+ }+ Ok(Err(err)) => {+ let _ = hook_handle.join();+ stop();+ Err(err)+ }+ Err(_) => {+ let _ = hook_handle.join();+ stop();+ Err("OS hotkey hook thread exited unexpectedly".to_string())+ }+ }+ }++ pub fn sync(+ window: &tauri::WebviewWindow,+ bindings: Vec<NativeOsHotkeyBinding>,+ recording: bool,+ channel: Channel<NativeOsHotkeyEvent>,+ ) -> Result<OsHotkeyStatus, String> {+ let hwnd = window+ .hwnd()+ .map_err(|e| format!("Failed to acquire main HWND: {}", e))?;+ MAIN_HWND.store(hwnd.0 as isize, Ordering::SeqCst);++ if let Ok(mut sink) = CHANNEL_SINK.lock() {+ *sink = Some(channel);+ }++ let mut vk_set = HashSet::new();+ for b in &bindings {+ for vk in dom_code_to_vks(&b.code) {+ vk_set.insert(VkBinding {+ vk,+ ctrl: b.ctrl,+ shift: b.shift,+ alt: b.alt,+ });+ }+ }+ let count = vk_set.len();++ if let Ok(mut guard) = BINDINGS.write() {+ *guard = vk_set;+ }+ RECORDING_MODE.store(recording, Ordering::SeqCst);++ if count == 0 && !recording {+ stop_hook_only();+ return Ok(OsHotkeyStatus {+ supported: true,+ active: false,+ registered_count: 0,+ recording: false,+ });+ }++ ensure_hook_running()?;++ Ok(OsHotkeyStatus {+ supported: true,+ active: HOOK_RUNNING.load(Ordering::SeqCst),+ registered_count: count,+ recording,+ })+ }++ fn stop_hook_only() {+ RECORDING_MODE.store(false, Ordering::SeqCst);+ let tid = HOOK_THREAD_ID.load(Ordering::SeqCst);+ if tid != 0 {+ unsafe {+ let _ = PostThreadMessageW(tid, WM_QUIT, 0, 0);+ }+ }+ if let Ok(mut guard) = HOOK_THREAD.lock() {+ if let Some(handle) = guard.take() {+ let _ = handle.join();+ }+ }+ if let Ok(mut guard) = EVENT_TX.lock() {+ *guard = None;+ }+ if let Ok(mut guard) = DISPATCH_THREAD.lock() {+ if let Some(handle) = guard.take() {+ let _ = handle.join();+ }+ }+ HOOK_RUNNING.store(false, Ordering::SeqCst);+ }++ pub fn stop() {+ stop_hook_only();+ if let Ok(mut guard) = BINDINGS.write() {+ guard.clear();+ }+ if let Ok(mut sink) = CHANNEL_SINK.lock() {+ *sink = None;+ }+ MAIN_HWND.store(0, Ordering::SeqCst);+ }+}++#[cfg(not(target_os = "windows"))]+mod fallback_impl {+ use super::*;++ pub fn sync(+ _window: &tauri::WebviewWindow,+ _bindings: Vec<NativeOsHotkeyBinding>,+ _recording: bool,+ _channel: Channel<NativeOsHotkeyEvent>,+ ) -> Result<OsHotkeyStatus, String> {+ Ok(OsHotkeyStatus {+ supported: false,+ active: false,+ registered_count: 0,+ recording: false,+ })+ }++ pub fn stop() {}+}++pub fn sync_os_hotkeys(+ window: &tauri::WebviewWindow,+ bindings: Vec<NativeOsHotkeyBinding>,+ recording: bool,+ channel: Channel<NativeOsHotkeyEvent>,+) -> Result<OsHotkeyStatus, String> {+ #[cfg(target_os = "windows")]+ {+ win_impl::sync(window, bindings, recording, channel)+ }+ #[cfg(not(target_os = "windows"))]+ {+ fallback_impl::sync(window, bindings, recording, channel)+ }+}++pub fn stop_os_hotkeys() {+ #[cfg(target_os = "windows")]+ win_impl::stop();+ #[cfg(not(target_os = "windows"))]+ fallback_impl::stop();+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_dom_code_vk_roundtrip() {+ let cases = [+ ("KeyA", 0x41u32, "a"),+ ("KeyQ", 0x51, "q"),+ ("KeyZ", 0x5A, "z"),+ ("Digit0", 0x30, "0"),+ ("Digit9", 0x39, "9"),+ ("Numpad1", 0x61, "1"),+ ("F1", 0x70, "F1"),+ ("F12", 0x7B, "F12"),+ ("BracketLeft", 0xDB, "["),+ ("BracketRight", 0xDD, "]"),+ ("Comma", 0xBC, ","),+ ("Period", 0xBE, "."),+ ("Space", 0x20, " "),+ ("Delete", 0x2E, "Delete"),+ ("ArrowLeft", 0x25, "ArrowLeft"),+ ];++ for (code, expected_vk, expected_key) in cases {+ let vks = dom_code_to_vks(code);+ assert_eq!(vks, vec![expected_vk], "dom_code_to_vks failed for {}", code);+ let mapped = vk_to_dom_code_and_key(expected_vk, false);+ assert_eq!(+ mapped,+ Some((code, expected_key)),+ "vk_to_dom_code_and_key failed for 0x{:X}",+ expected_vk+ );+ }+ }++ #[test]+ fn test_numpad_enter_extended_flag() {+ assert_eq!(vk_to_dom_code_and_key(0x0D, false), Some(("Enter", "Enter")));+ assert_eq!(+ vk_to_dom_code_and_key(0x0D, true),+ Some(("NumpadEnter", "Enter"))+ );+ }++ #[test]+ fn test_unknown_dom_codes_return_empty() {+ assert!(dom_code_to_vks("UnknownKey").is_empty());+ assert!(dom_code_to_vks("MetaLeft").is_empty());+ assert_eq!(vk_to_dom_code_and_key(0x5B, false), None);+ }+}diff --git a/src-tauri/src/timelapse.rs b/src-tauri/src/timelapse.rsindex 5072c3c..2a9fb67 100644--- a/src-tauri/src/timelapse.rs+++ b/src-tauri/src/timelapse.rs@@ -6,6 +6,116 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;const MAX_TIMELAPSE_FRAME_BYTES: usize = 8 * 1024 * 1024; // 8 MB ceiling per keyframeconst MAX_TIMELAPSE_EXPORT_FRAMES: usize = 100_000;+const MAX_TIMELAPSE_BATCH_FRAMES: usize = 2048;+const MAX_TIMELAPSE_BATCH_BYTES: usize = 64 * 1024 * 1024; // 64 MB ceiling per batch IPC+const MIN_BATCH_RECORD_BYTES: usize = 4 + 1 + 4; // frame_index(u32) + ext_code(u8) + data_len(u32)++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FrameBatchEntry {+ pub frame_index: u32,+ pub ext: &'static str,+ pub data: Vec<u8>,+}++fn ext_to_code(ext: &str) -> Result<u8, String> {+ match sanitize_ext(ext)? {+ "webp" => Ok(0),+ "jpg" => Ok(1),+ "png" => Ok(2),+ _ => Err("Unsupported timelapse frame extension".to_string()),+ }+}++fn code_to_ext(code: u8) -> Result<&'static str, String> {+ match code {+ 0 => Ok("webp"),+ 1 => Ok("jpg"),+ 2 => Ok("png"),+ _ => Err(format!("Unknown timelapse extension code: {}", code)),+ }+}++/// Packs a batch of timelapse frames into a compact binary wire frame:+/// `[count: u32 LE] ([frame_index: u32 LE][ext_code: u8][data_len: u32 LE][data])*`+#[allow(dead_code)]+pub fn pack_frame_batch(entries: &[FrameBatchEntry]) -> Result<Vec<u8>, String> {+ if entries.len() > MAX_TIMELAPSE_BATCH_FRAMES {+ return Err("Timelapse frame batch count exceeds safety ceiling".to_string());+ }+ let mut total: usize = 4;+ for entry in entries {+ if entry.data.len() > MAX_TIMELAPSE_FRAME_BYTES {+ return Err("Timelapse frame exceeds 8 MB safety limit".to_string());+ }+ let _ = ext_to_code(entry.ext)?;+ total = total+ .checked_add(MIN_BATCH_RECORD_BYTES)+ .and_then(|n| n.checked_add(entry.data.len()))+ .ok_or_else(|| "Timelapse batch size overflow".to_string())?;+ }+ if total > MAX_TIMELAPSE_BATCH_BYTES {+ return Err("Timelapse frame batch exceeds 64 MB safety limit".to_string());+ }++ let mut out = Vec::with_capacity(total);+ out.extend_from_slice(&(entries.len() as u32).to_le_bytes());+ for entry in entries {+ out.extend_from_slice(&entry.frame_index.to_le_bytes());+ out.push(ext_to_code(entry.ext)?);+ out.extend_from_slice(&(entry.data.len() as u32).to_le_bytes());+ out.extend_from_slice(&entry.data);+ }+ Ok(out)+}++/// Unpacks a binary timelapse frame batch written by the frontend during `.ink` restore.+pub fn unpack_frame_batch(bytes: &[u8]) -> Result<Vec<FrameBatchEntry>, String> {+ if bytes.len() < 4 {+ return Err("Truncated timelapse frame batch header".to_string());+ }+ if bytes.len() > MAX_TIMELAPSE_BATCH_BYTES {+ return Err("Timelapse frame batch exceeds 64 MB safety limit".to_string());+ }+ let count = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;+ if count > MAX_TIMELAPSE_BATCH_FRAMES {+ return Err("Timelapse frame batch count exceeds safety ceiling".to_string());+ }+ if count > (bytes.len() - 4) / MIN_BATCH_RECORD_BYTES {+ return Err("Truncated timelapse frame batch payload".to_string());+ }++ let mut offset = 4usize;+ let mut out = Vec::with_capacity(count);+ for _ in 0..count {+ let header_end = offset+ .checked_add(MIN_BATCH_RECORD_BYTES)+ .filter(|&e| e <= bytes.len())+ .ok_or_else(|| "Truncated timelapse batch entry header".to_string())?;+ let frame_index = u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());+ let ext = code_to_ext(bytes[offset + 4])?;+ let data_len = u32::from_le_bytes(bytes[offset + 5..offset + 9].try_into().unwrap()) as usize;+ offset = header_end;++ if data_len == 0 || data_len > MAX_TIMELAPSE_FRAME_BYTES {+ return Err("Invalid timelapse frame size in batch".to_string());+ }+ let data_end = offset+ .checked_add(data_len)+ .filter(|&e| e <= bytes.len())+ .ok_or_else(|| "Truncated timelapse batch entry data".to_string())?;+ out.push(FrameBatchEntry {+ frame_index,+ ext,+ data: bytes[offset..data_end].to_vec(),+ });+ offset = data_end;+ }++ if offset != bytes.len() {+ return Err("Unexpected trailing bytes in timelapse frame batch".to_string());+ }+ Ok(out)+}/// Unpacks a raw little-endian u32 array of frame indices.pub fn unpack_frame_indices(bytes: &[u8]) -> Result<Vec<u32>, String> {@@ -85,6 +195,81 @@ pub async fn write_frame(Ok(())}+pub async fn write_frames_batch(+ session_id: &str,+ entries: Vec<FrameBatchEntry>,+) -> Result<usize, String> {+ if entries.is_empty() {+ return Ok(0);+ }+ let dir = session_dir(session_id);+ let count = entries.len();+ tokio::task::spawn_blocking(move || -> Result<usize, String> {+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ for entry in entries {+ let safe_ext = sanitize_ext(entry.ext)?;+ let path = dir.join(format!("frame_{:06}.{}", entry.frame_index, safe_ext));+ std::fs::write(path, &entry.data).map_err(|e| e.to_string())?;+ }+ Ok(count)+ })+ .await+ .map_err(|e| format!("Timelapse batch write worker failed: {}", e))?+}++pub async fn list_frames(session_id: &str) -> Result<Vec<(u32, String)>, String> {+ let dir = session_dir(session_id);+ tokio::task::spawn_blocking(move || -> Result<Vec<(u32, String)>, String> {+ if !dir.exists() {+ return Ok(Vec::new());+ }+ let mut found: Vec<(u32, String)> = Vec::new();+ let entries = std::fs::read_dir(&dir).map_err(|e| e.to_string())?;+ for entry in entries.flatten() {+ let path = entry.path();+ if !path.is_file() {+ continue;+ }+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {+ continue;+ };+ let Some(num_str) = stem.strip_prefix("frame_") else {+ continue;+ };+ let Ok(idx) = num_str.parse::<u32>() else {+ continue;+ };+ let Some(ext_raw) = path.extension().and_then(|e| e.to_str()) else {+ continue;+ };+ if let Ok(safe_ext) = sanitize_ext(ext_raw) {+ found.push((idx, safe_ext.to_string()));+ }+ }+ found.sort_by_key(|(idx, _)| *idx);+ Ok(found)+ })+ .await+ .map_err(|e| format!("Timelapse list worker failed: {}", e))?+}++fn resolve_frame_path(dir: &Path, idx: u32, preferred_ext: &str) -> Option<PathBuf> {+ let primary = dir.join(format!("frame_{:06}.{}", idx, preferred_ext));+ if primary.exists() {+ return Some(primary);+ }+ for alt in ["webp", "jpg", "png"] {+ if alt == preferred_ext {+ continue;+ }+ let candidate = dir.join(format!("frame_{:06}.{}", idx, alt));+ if candidate.exists() {+ return Some(candidate);+ }+ }+ None+}+pub async fn read_frame(session_id: &str, frame_index: u32, ext: &str) -> Result<Vec<u8>, String> {let safe_ext = sanitize_ext(ext)?;let path = session_dir(session_id).join(format!("frame_{:06}.{}", frame_index, safe_ext));@@ -132,8 +317,7 @@ pub async fn export_ffmpeg(let mut manifest = String::new();let frame_dur = 1.0 / (safe_fps as f64);for idx in &frame_indices {- let fpath = dir.join(format!("frame_{:06}.{}", idx, safe_ext));- if fpath.exists() {+ if let Some(fpath) = resolve_frame_path(&dir, *idx, safe_ext) {let escaped = escape_ffmpeg_concat_path(&fpath);manifest.push_str(&format!("file '{}'\nduration {:.6}\n", escaped, frame_dur));}@@ -215,4 +399,72 @@ mod tests {assert_eq!(unpack_frame_indices(&raw).unwrap(), vec![0, 1, 42, 99999]);assert!(unpack_frame_indices(&[1, 2, 3]).is_err());}++ #[test]+ fn test_frame_batch_pack_unpack_and_malformed_rejection() {+ let entries = vec![+ FrameBatchEntry {+ frame_index: 0,+ ext: "webp",+ data: vec![0x52, 0x49, 0x46, 0x46, 1, 2, 3],+ },+ FrameBatchEntry {+ frame_index: 5,+ ext: "jpg",+ data: vec![0xff, 0xd8, 0xff, 0xe0, 9, 8],+ },+ ];+ let packed = pack_frame_batch(&entries).expect("pack failed");+ let unpacked = unpack_frame_batch(&packed).expect("unpack failed");+ assert_eq!(unpacked, entries);++ // Truncated header & trailing bytes rejected+ assert!(unpack_frame_batch(&[1, 2]).is_err());+ assert!(unpack_frame_batch(&packed[..packed.len() - 1]).is_err());+ let mut with_trailing = packed.clone();+ with_trailing.push(0x99);+ assert!(unpack_frame_batch(&with_trailing).is_err());+ }++ #[tokio::test]+ async fn test_write_frames_batch_list_and_mixed_ext_resolution() {+ let sid = format!(+ "test_tl_batch_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ );+ let entries = vec![+ FrameBatchEntry {+ frame_index: 0,+ ext: "webp",+ data: b"webp-frame-0".to_vec(),+ },+ FrameBatchEntry {+ frame_index: 1,+ ext: "jpg",+ data: b"jpg-frame-1".to_vec(),+ },+ ];+ let written = write_frames_batch(&sid, entries).await.expect("batch write");+ assert_eq!(written, 2);++ let listed = list_frames(&sid).await.expect("list frames");+ assert_eq!(+ listed,+ vec![(0u32, "webp".to_string()), (1u32, "jpg".to_string())]+ );++ assert_eq!(read_frame(&sid, 0, "webp").await.unwrap(), b"webp-frame-0");+ assert_eq!(read_frame(&sid, 1, "jpg").await.unwrap(), b"jpg-frame-1");++ // Mixed-extension fallback resolves jpg frame even when preferred ext is webp+ let dir = session_dir(&sid);+ let resolved = resolve_frame_path(&dir, 1, "webp").expect("resolve mixed ext");+ assert!(resolved.to_string_lossy().ends_with("frame_000001.jpg"));++ clear_session(&sid).await.expect("clear");+ assert!(list_frames(&sid).await.unwrap().is_empty());+ }}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex d91bad4..5e27cd5 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "Ink Studio",- "version": "1.0.4",+ "version": "1.1.0","identifier": "com.inkstudio.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/App.tsx b/src/App.tsxindex 2ad143b..942f15e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -34,6 +34,7 @@ import {documentStoreActions,scene3DBridge,selectHasOpenDocument,+ toolStoreActions,uiStoreActions,use3DStore,useDocumentStore,@@ -1042,6 +1043,7 @@ export function App() {const handleToggleTimelapseRecording = useCallback(() => {if (!activeDocumentId) return;const next = globalTimelapseManager.toggleRecording(activeDocumentId);+ documentStoreActions.markDocumentDirty(activeDocumentId, true);if (next) {globalTimelapseManager.captureKeyframe(activeDocumentId, layerMgr.layers, dimensions, activeTileGrid, true)@@ -1099,7 +1101,7 @@ export function App() {}}- if (tool === 'brush' || tool === 'eraser') {+ if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {const curLayer = layerMgr.activeLayer;if (curLayer?.type === 'text' || curLayer?.type === 'balloon') {showToast('Use Text/Object tool to edit, or Rasterize Layer to paint directly');@@ -1166,7 +1168,7 @@ export function App() {predictedEvents?: PointerEvent[]) => {const tool = useToolStore.getState().tool;- if (tool === 'brush' || tool === 'eraser') {+ if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {drawing.handlePointerMove(e, coalescedEvents, predictedEvents);return;}@@ -1195,7 +1197,7 @@ export function App() {const handlePointerUp = useCallback((e: React.PointerEvent<HTMLElement>) => {const tool = useToolStore.getState().tool;- if (tool === 'brush' || tool === 'eraser') {+ if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {drawing.handlePointerUp(e);return;}@@ -1286,6 +1288,7 @@ export function App() {zoomIn: nav.zoomIn,zoomOut: nav.zoomOut,resetZoomAndCenter: nav.resetZoomAndCenter,+ resetZoomTo100: nav.resetZoomTo100,resetRotation: nav.resetRotation,toggleFlipHorizontal: nav.toggleFlipHorizontal,toggleFlipVertical: nav.toggleFlipVertical,@@ -1375,10 +1378,15 @@ export function App() {onDeleteBalloon: shapeFillTools.handleDeleteBalloon,frameDragPreview: shapeFillTools.frameDragPreview,shapeDragPreview: shapeFillTools.shapeDragPreview,+ quickShapePreview: drawing.quickShapePreview,+ lassoFillPreview: shapeFillTools.lassoFillPreview,gradientDragPreview: gradientTools.gradientDragPreview,gradientMesh: gradientTools.gradientMesh,+ gradientMeshMarqueeRect: gradientTools.gradientMeshMarqueeRect,+ isRotatingGradientMesh: gradientTools.isRotatingGradientMesh,onApplyGradientMesh: gradientTools.handleApplyGradientMesh,onCancelGradientMesh: gradientTools.handleCancelGradientMesh,+ onStartRotateGradientMesh: gradientTools.handleStartRotateGradientMesh,cloneSourceIndicator: retouchTools.cloneSourceIndicator,penSession: penTools.penSession,onCommitPenPath: penTools.handleCommitPenPath,@@ -1399,6 +1407,7 @@ export function App() {drawing.handlePointerEnter,drawing.handlePointerLeave,drawing.interactionRef,+ drawing.quickShapePreview,handlePointerDown,handlePointerMove,handlePointerUp,@@ -1424,11 +1433,15 @@ export function App() {shapeFillTools.handleDeleteBalloon,shapeFillTools.frameDragPreview,shapeFillTools.shapeDragPreview,+ shapeFillTools.lassoFillPreview,shapeFillTools.handleSampleColor,gradientTools.gradientDragPreview,gradientTools.gradientMesh,+ gradientTools.gradientMeshMarqueeRect,+ gradientTools.isRotatingGradientMesh,gradientTools.handleApplyGradientMesh,gradientTools.handleCancelGradientMesh,+ gradientTools.handleStartRotateGradientMesh,retouchTools.cloneSourceIndicator,penTools.penSession,penTools.handleCommitPenPath,@@ -1447,9 +1460,24 @@ export function App() {documentStoreActions.markDocumentDirty(activeDocumentId, true);}, [activeDocumentId]);+ const handleImportDropped3DModelFile = useCallback(+ (file: File) => {+ toolStoreActions.selectTool('3d');+ if (useUiStore.getState().is3DLayerOpen && scene3DBridge.loadFile) {+ scene3DBridge.loadFile(file);+ } else {+ uiStoreActions.set3DLayerOpen(true, file);+ }+ showToast(`Imported 3D model "${file.name}"`);+ },+ [showToast]+ );+const externalFileDrop = useExternalFileDrop({enabled: hasOpenDocument && appView === 'workspace',+ is3DModeActive: is3DLayerOpen,importImageFileAsLayer: layerMgr.importImageFileAsLayer,+ import3DModelFile: handleImportDropped3DModelFile,onMarkDirty: handleMarkActiveDocumentDirty,showToast,});@@ -1470,6 +1498,7 @@ export function App() {zoomIn={nav.zoomIn}zoomOut={nav.zoomOut}resetZoomAndCenter={nav.resetZoomAndCenter}+ resetZoomTo100={nav.resetZoomTo100}rotation={nav.rotation}resetRotation={nav.resetRotation}flipX={nav.flipX}@@ -1586,6 +1615,7 @@ export function App() {handleCopySelectionToNewLayer={selectionTools.handleCopySelectionToNewLayer}handleGroupSelectedLayers={collab.handleGroupSelectedLayers}handleStartTransform={selectionTools.handleStartTransform}+ setTransformSession={selectionTools.setTransformSession}handleSelectAll={selectionTools.handleSelectAll}handleDeselect={selectionTools.handleDeselect}handleInvertSelection={selectionTools.handleInvertSelection}@@ -1596,6 +1626,7 @@ export function App() {zoomIn={nav.zoomIn}zoomOut={nav.zoomOut}resetZoomAndCenter={nav.resetZoomAndCenter}+ resetZoomTo100={nav.resetZoomTo100}resetRotation={nav.resetRotation}toggleFlipHorizontal={nav.toggleFlipHorizontal}toggleFlipVertical={nav.toggleFlipVertical}diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsxindex 4add6ca..e32d46d 100644--- a/src/components/AppShell.tsx+++ b/src/components/AppShell.tsx@@ -15,6 +15,7 @@ import {PenPathSession,} from '../types/editor';import type { CloneSourceIndicator } from '../hooks/drawing/useRetouchTool';+import type { QuickShapePreviewState } from '../utils/quickShapeEngine';import { CollabPeer } from '../types/multiplayer';import { SparseTileGrid } from '../utils/tileEngine';import { RecentDocument } from '../utils/recentDocumentsManager';@@ -25,10 +26,19 @@ import {resolveModernAccentColor,} from '../types/settings';import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';-import { TextPlacementSession, FrameDragPreview } from '../hooks/drawing/useShapeAndFillTools';+import {+ TextPlacementSession,+ FrameDragPreview,+ LassoFillPreview,+} from '../hooks/drawing/useShapeAndFillTools';+import type { GradientMeshMarqueeRect } from '../hooks/drawing/useGradientTool';import { AutoAction } from '../utils/autoActionEngine';-import { ExternalFileDropTarget } from '../utils/fileDropImport';+import {+ ExternalFileDropPayloadKind,+ ExternalFileDropTarget,+} from '../utils/fileDropImport';import { HalftoneDotShape } from '../utils/screentoneEngine';+import { applyInterfaceScale, DEFAULT_INTERFACE_SCALE } from '../utils/interfaceScale';import {documentStoreActions,selectHasOpenDocument,@@ -124,10 +134,15 @@ interface CanvasAreaContainerProps {onDeleteBalloon: () => void;frameDragPreview?: FrameDragPreview | null;shapeDragPreview?: ShapeDragPreview | null;+ quickShapePreview?: QuickShapePreviewState | null;+ lassoFillPreview?: LassoFillPreview | null;gradientDragPreview?: GradientDragPreview | null;gradientMesh?: GradientMeshState | null;+ gradientMeshMarqueeRect?: GradientMeshMarqueeRect | null;+ isRotatingGradientMesh?: boolean;onApplyGradientMesh?: () => void;onCancelGradientMesh?: () => void;+ onStartRotateGradientMesh?: (e: React.PointerEvent<HTMLElement>) => void;cloneSourceIndicator?: CloneSourceIndicator | null;penSession?: PenPathSession | null;onCommitPenPath?: () => void;@@ -139,6 +154,7 @@ interface CanvasAreaContainerProps {onDeleteAnimationCel: (frameIndex: number) => void;onSelectCelLayer: (layerId: string) => void;isExternalFileDropActive?: boolean;+ externalFileDropKind?: ExternalFileDropPayloadKind;}/**@@ -148,6 +164,7 @@ interface CanvasAreaContainerProps {const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((props) => {const tool = useToolStore((s) => s.tool);const brushSettings = useToolStore((s) => s.brushSettings);+ const fillSettings = useToolStore((s) => s.fillSettings);const liquifySettings = useToolStore((s) => s.liquifySettings);const gradientSettings = useToolStore((s) => s.gradientSettings);const retouchSettings = useToolStore((s) => s.retouchSettings);@@ -162,6 +179,7 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propconst straightRuler = useDocumentStore((s) => s.straightRuler);const activeLockedAxis = useDocumentStore((s) => s.activeLockedAxis);const softProofSettings = useDocumentStore((s) => s.softProofSettings);+ const valueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);const showCheckerboard = useUiStore((s) => s.appSettings.showCheckerboard);const showCursorCoordinates = useUiStore((s) => s.appSettings.showCursorCoordinates);@@ -266,6 +284,8 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propactivePings={props.activePings}remoteDraftCanvasesRef={props.remoteDraftCanvasesRef}tool={tool}+ fillSettings={fillSettings}+ onUpdateFillSettings={toolStoreActions.updateFillSettings}liquifySettings={liquifySettings}onUpdateLiquifySettings={toolStoreActions.updateLiquifySettings}gradientSettings={gradientSettings}@@ -316,10 +336,15 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proponDeleteBalloon={props.onDeleteBalloon}frameDragPreview={props.frameDragPreview}shapeDragPreview={props.shapeDragPreview}+ quickShapePreview={props.quickShapePreview}+ lassoFillPreview={props.lassoFillPreview}gradientDragPreview={props.gradientDragPreview}gradientMesh={props.gradientMesh}+ gradientMeshMarqueeRect={props.gradientMeshMarqueeRect}+ isRotatingGradientMesh={props.isRotatingGradientMesh}onApplyGradientMesh={props.onApplyGradientMesh}onCancelGradientMesh={props.onCancelGradientMesh}+ onStartRotateGradientMesh={props.onStartRotateGradientMesh}cloneSourceIndicator={props.cloneSourceIndicator}penSession={props.penSession}onCommitPenPath={props.onCommitPenPath}@@ -332,7 +357,9 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proponDeleteAnimationCel={props.onDeleteAnimationCel}onSelectCelLayer={props.onSelectCelLayer}softProofSettings={softProofSettings}+ valueCheckEnabled={valueCheckEnabled}isExternalFileDropActive={props.isExternalFileDropActive}+ externalFileDropKind={props.externalFileDropKind}/>);});@@ -342,6 +369,7 @@ interface StatusBarContainerProps {zoom: number;rotation: number;onResetRotation: () => void;+ onResetZoomTo100?: () => void;}/**@@ -349,16 +377,21 @@ interface StatusBarContainerProps {* re-render StatusBar without re-rendering AppShell, Header, or Layers.*/const StatusBarContainer: React.FC<StatusBarContainerProps> = React.memo(- ({ zoom, rotation, onResetRotation }) => {+ ({ zoom, rotation, onResetRotation, onResetZoomTo100 }) => {const tool = useToolStore((s) => s.tool);const brushSettings = useToolStore((s) => s.brushSettings);const colorMode = useDocumentStore((s) => s.colorMode);const hasOpenDocument = useDocumentStore(selectHasOpenDocument);const softProofSettings = useDocumentStore((s) => s.softProofSettings);+ const valueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);const showCursorCoordinates = useUiStore((s) => s.appSettings.showCursorCoordinates);const showPressureInStatusBar = useUiStore((s) => s.appSettings.showPressureInStatusBar);const themePreset = useUiStore((s) => s.appSettings.themePreset);+ const handleToggleValueCheck = useCallback(() => {+ documentStoreActions.toggleValueCheck();+ }, []);+return (<StatusBartool={tool}@@ -366,12 +399,15 @@ const StatusBarContainer: React.FC<StatusBarContainerProps> = React.memo(zoom={zoom}rotation={rotation}onResetRotation={onResetRotation}+ onResetZoomTo100={onResetZoomTo100}colorMode={colorMode}showCursorCoordinates={showCursorCoordinates}showPressureInStatusBar={showPressureInStatusBar}hasOpenDocument={hasOpenDocument}themePreset={themePreset}softProofSettings={softProofSettings}+ valueCheckEnabled={valueCheckEnabled}+ onToggleValueCheck={handleToggleValueCheck}/>);}@@ -394,6 +430,7 @@ export interface AppShellProps {zoomIn: () => void;zoomOut: () => void;resetZoomAndCenter: () => void;+ resetZoomTo100?: () => void;rotation: number;resetRotation: () => void;flipX: boolean;@@ -493,6 +530,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(zoomIn,zoomOut,resetZoomAndCenter,+ resetZoomTo100,rotation,resetRotation,flipX,@@ -575,12 +613,16 @@ export const AppShell: React.FC<AppShellProps> = React.memo(const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);const hasOpenDocument = useDocumentStore(selectHasOpenDocument);const softProofSettings = useDocumentStore((s) => s.softProofSettings);+ const valueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);const appView = useUiStore((s) => s.appView);const modernAccent = useUiStore((s) => s.appSettings.modernAccent || 'neutral');const modernCustomColor = useUiStore((s) => s.appSettings.modernCustomColor);const themePreset = useUiStore((s) => s.appSettings.themePreset);+ const interfaceScale = useUiStore(+ (s) => s.appSettings.interfaceScale ?? DEFAULT_INTERFACE_SCALE+ );const showCheckerboard = useUiStore((s) => s.appSettings.showCheckerboard);const userName = useUiStore((s) => s.appSettings.userName);const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);@@ -606,6 +648,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(root.style.setProperty('--modern-accent-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`);}, [modernAccent, modernCustomColor, themePreset]);+ useEffect(() => {+ void applyInterfaceScale(interfaceScale);+ }, [interfaceScale]);+const modernAccentHex = resolveModernAccentColor(modernAccent, modernCustomColor);const modernAccentRgb = hexToRgb(modernAccentHex) || { r: 229, g: 229, b: 229 };const modernAccentContrast = getAccentContrastColor(modernAccentHex);@@ -674,6 +720,18 @@ export const AppShell: React.FC<AppShellProps> = React.memo(if (activeLayerId) duplicateLayer(activeLayerId);}, [activeLayerId, duplicateLayer]);+ const handleZoomActualSize = useCallback(() => {+ if (resetZoomTo100) {+ resetZoomTo100();+ } else {+ canvasProps.navigation.setZoomLive?.(1.0, true);+ }+ }, [resetZoomTo100, canvasProps.navigation]);++ const handleToggleValueCheck = useCallback(() => {+ documentStoreActions.toggleValueCheck();+ }, []);+const commandHandlers = useMemo<WorkspaceCommandHandlers>(() => ({canUndo: hasOpenDocument && canUndo,@@ -690,7 +748,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(onFlipVertical: toggleFlipVertical,flipX,flipY,+ onToggleValueCheck: handleToggleValueCheck,+ valueCheckEnabled,onResetZoom: resetZoomAndCenter,+ onResetZoomTo100: handleZoomActualSize,onResetRotation: resetRotation,onTransform: canvasProps.onTransformSelection,onDeselect: canvasProps.onDeselect,@@ -714,7 +775,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(toggleFlipVertical,flipX,flipY,+ handleToggleValueCheck,+ valueCheckEnabled,resetZoomAndCenter,+ handleZoomActualSize,resetRotation,canvasProps.onTransformSelection,canvasProps.onDeselect,@@ -723,10 +787,6 @@ export const AppShell: React.FC<AppShellProps> = React.memo(]);- const handleZoomActualSize = useCallback(() => {- canvasProps.navigation.setZoomLive?.(1.0, true);- }, [canvasProps.navigation]);-const handleRotateLeft = useCallback(() => {canvasProps.navigation.rotateBy?.(-15);}, [canvasProps.navigation]);@@ -747,6 +807,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(rotation,flipX,flipY,+ draftCanvasRef: canvasProps.draftCanvasRef,+ activeLayerId: canvasProps.activeLayerId,onZoomIn: zoomIn,onZoomOut: zoomOut,onFitToScreen: resetZoomAndCenter,@@ -762,6 +824,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(canvasProps.navigation,canvasProps.layers,canvasProps.tileGrid,+ canvasProps.draftCanvasRef,+ canvasProps.activeLayerId,dimensions,showCheckerboard,zoom,@@ -936,7 +1000,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(return (<div- className="flex flex-col w-screen h-screen overflow-hidden bg-[#161616] text-[#e5e5e5] font-sans gap-px app-root-container"+ className="flex flex-col w-full h-full overflow-hidden bg-[#161616] text-[#e5e5e5] font-sans gap-px app-root-container"data-theme={themePreset}data-accent={modernAccent}style={modernStyleVars}@@ -981,6 +1045,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(onToggleFlipHorizontal={toggleFlipHorizontal}onToggleFlipVertical={toggleFlipVertical}onResetViewFlip={resetViewFlip}+ valueCheckEnabled={valueCheckEnabled}+ onToggleValueCheck={handleToggleValueCheck}dimensions={dimensions}colorMode={colorMode}menuSections={menuSections}@@ -1051,7 +1117,16 @@ export const AppShell: React.FC<AppShellProps> = React.memo(<div className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative"><CanvasAreaContainer{...canvasProps}- isExternalFileDropActive={externalFileDropTarget?.zone === 'canvas'}+ isExternalFileDropActive={+ externalFileDropTarget?.zone === 'canvas' ||+ externalFileDropTarget?.zone === '3d-stage'+ }+ externalFileDropKind={+ externalFileDropTarget?.zone === 'canvas' ||+ externalFileDropTarget?.zone === '3d-stage'+ ? externalFileDropTarget.payloadKind+ : undefined+ }/></div>@@ -1060,6 +1135,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(zoom={zoom}rotation={rotation}onResetRotation={resetRotation}+ onResetZoomTo100={handleZoomActualSize}/>)}</DockWorkspace>diff --git a/src/components/BrushSizePalette.tsx b/src/components/BrushSizePalette.tsxindex 6c65d04..5305834 100644--- a/src/components/BrushSizePalette.tsx+++ b/src/components/BrushSizePalette.tsx@@ -5,6 +5,7 @@ import {Paintbrush,Square,Eraser,+ Sparkles,RotateCcw,} from 'lucide-react';import { ToolType } from '../types/editor';@@ -54,6 +55,9 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = React.memo(({if (tool === 'eraser') {return <Eraser className="w-3.5 h-3.5 text-rose-400 shrink-0" />;}+ if (tool === 'decoration') {+ return <Sparkles className="w-3.5 h-3.5 text-violet-300 shrink-0" />;+ }if (presetId?.startsWith('pencil') ||presetId === 'mechanical-pencil' ||diff --git a/src/components/BrushStudioModal.tsx b/src/components/BrushStudioModal.tsxindex d99c436..fec899e 100644--- a/src/components/BrushStudioModal.tsx+++ b/src/components/BrushStudioModal.tsx@@ -12,7 +12,7 @@ import {} from 'lucide-react';import type { BrushCategory, BrushSettings, CspBrush } from '../types/editor';import { useToolStore, toolStoreActions } from '../stores';-import { BUILTIN_BRUSHES } from '../utils/presetBrushes';+import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';import {DEFAULT_BRUSH_PRESET_ID,NEUTRAL_BRUSH_DEFAULTS,@@ -86,7 +86,7 @@ export const BrushStudioModal: React.FC<BrushStudioModalProps> = ({useEffect(() => {if (!isOpen) return;- const builtin = BUILTIN_BRUSHES.find((b) => b.id === activePreset);+ const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === activePreset);const custom = getCachedCustomBrushes().find((b) => b.id === activePreset);setBrushName(custom?.name || builtin?.name || brushSettings.brushName || 'Custom Brush');setCategory(custom?.category || builtin?.category || 'custom');diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsxindex 1a2def0..dd8a7bc 100644--- a/src/components/CanvasArea.tsx+++ b/src/components/CanvasArea.tsx@@ -48,6 +48,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {strokeCanvasRef,predictedCanvasRef,tool = 'brush',+ fillSettings,+ onUpdateFillSettings,liquifySettings,onUpdateLiquifySettings,retouchSettings,@@ -58,6 +60,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {showPressureInStatusBar = false,animationTimeline = null,softProofSettings,+ valueCheckEnabled = false,activeLayerId,colorMode = 'color',tileGrid = globalTileGrid,@@ -95,6 +98,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {tipOutline,isCustomTip,isSquare,+ isCursorRotating,+ cursorOrientationOffsetDeg,+ thicknessRatio,cursorWidth,cursorHeight,totalAngleDeg,@@ -106,6 +112,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {viewportRef,brushSettings,onUpdateBrushSettings,+ fillSettings,+ onUpdateFillSettings,liquifySettings,onUpdateLiquifySettings,retouchSettings,@@ -158,6 +166,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {showCheckerboard,hasOpenDocument,softProofSettings,+ valueCheckEnabled,activeLayerId,brushOpacity: brushSettings.opacity,colorMode,@@ -175,6 +184,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {viewportRef,dimensions,brushSettings,+ fillSettings,liquifySettings,retouchSettings,tool,@@ -210,6 +220,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {isPanning,isSpaceDown,tool,+ fillMethod: fillSettings?.method,};// Viewport bounds for positioning floating preview@@ -233,11 +244,13 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {const showFloatingPill =tool === 'brush' ||+ tool === 'decoration' ||tool === 'eraser' ||tool === 'liquify' ||tool === 'retouch' ||tool === 'select-pen' ||- tool === 'select-eraser';+ tool === 'select-eraser' ||+ (tool === 'fill' && fillSettings?.method === 'paint-unfilled');return (<main@@ -257,6 +270,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {tool={tool}brushSettings={brushSettings}onUpdateBrushSettings={onUpdateBrushSettings}+ fillSettings={fillSettings}+ onUpdateFillSettings={onUpdateFillSettings}liquifySettings={liquifySettings}onUpdateLiquifySettings={onUpdateLiquifySettings}retouchSettings={retouchSettings}@@ -317,7 +332,13 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {height: '100%',opacity: brushSettings.opacity ?? 1.0,display: 'block',- filter: isMonochromeActive && liveZoom >= 0.99 ? 'url(#ink-monochrome-threshold)' : undefined,+ filter:+ [+ isMonochromeActive && liveZoom >= 0.99 ? 'url(#ink-monochrome-threshold)' : '',+ valueCheckEnabled ? 'grayscale(100%)' : '',+ ]+ .filter(Boolean)+ .join(' ') || undefined,}}/>@@ -347,6 +368,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {totalAngleDeg={totalAngleDeg}isCustomTip={isCustomTip}isSquare={isSquare}+ isCursorRotating={isCursorRotating}+ cursorOrientationOffsetDeg={cursorOrientationOffsetDeg}+ thicknessRatio={thicknessRatio}tipOutline={tipOutline}isResizingBrush={isResizingBrush}resizePreviewX={resizePreviewX}diff --git a/src/components/CommandBar.tsx b/src/components/CommandBar.tsxindex e7bb848..089c0bd 100644--- a/src/components/CommandBar.tsx+++ b/src/components/CommandBar.tsx@@ -22,6 +22,8 @@ import {ChevronUp,Check,Sparkles,+ Star,+ Contrast,} from 'lucide-react';import {COMMAND_CATALOG,@@ -47,7 +49,10 @@ export interface WorkspaceCommandHandlers {onFlipVertical?: () => void;flipX?: boolean;flipY?: boolean;+ onToggleValueCheck?: () => void;+ valueCheckEnabled?: boolean;onResetZoom?: () => void;+ onResetZoomTo100?: () => void;onResetRotation?: () => void;onTransform?: () => void;onDeselect?: () => void;@@ -70,6 +75,8 @@ export function renderCommandIcon(id: CommandActionId, palettesHidden = false):return <FlipHorizontal className={cls} />;case 'flip-v':return <FlipVertical className={cls} />;+ case 'value-check':+ return <Contrast className={cls} />;case 'clear-layer':return <Eraser className={cls} />;case 'merge-down':@@ -84,6 +91,8 @@ export function renderCommandIcon(id: CommandActionId, palettesHidden = false):return <X className={cls} />;case 'reset-zoom':return <Maximize2 className={cls} />;+ case 'zoom-100':+ return <span className="text-[9px] font-mono font-bold leading-none tracking-tighter">1:1</span>;case 'reset-rotation':return <RotateCcw className={cls} />;case 'swap-colors':@@ -92,6 +101,8 @@ export function renderCommandIcon(id: CommandActionId, palettesHidden = false):return <Sparkles className={cls} />;case 'toggle-palettes':return palettesHidden ? <Eye className={cls} /> : <EyeOff className={cls} />;+ case 'toggle-quick-brushes':+ return <Star className={cls} />;default:return <Sparkles className={cls} />;}@@ -132,9 +143,15 @@ export function executeWorkspaceCommand(case 'flip-v':handlers.onFlipVertical?.();break;+ case 'value-check':+ handlers.onToggleValueCheck?.();+ break;case 'reset-zoom':handlers.onResetZoom?.();break;+ case 'zoom-100':+ handlers.onResetZoomTo100?.();+ break;case 'reset-rotation':handlers.onResetRotation?.();break;@@ -153,6 +170,9 @@ export function executeWorkspaceCommand(case 'toggle-palettes':workspaceStoreActions.togglePalettesHidden();break;+ case 'toggle-quick-brushes':+ workspaceStoreActions.toggleQuickBrushPanelVisible();+ break;}}@@ -160,7 +180,14 @@ export function isCommandDisabled(id: CommandActionId,handlers: WorkspaceCommandHandlers): boolean {- if (id === 'toggle-palettes' || id === 'swap-colors' || id === 'transparent-ink') return false;+ if (+ id === 'toggle-palettes' ||+ id === 'toggle-quick-brushes' ||+ id === 'swap-colors' ||+ id === 'transparent-ink'+ ) {+ return false;+ }if (!handlers.hasOpenDocument) return true;if (id === 'undo') return !handlers.canUndo;if (id === 'redo') return !handlers.canRedo;@@ -170,11 +197,16 @@ export function isCommandDisabled(export function isCommandActive(id: CommandActionId,handlers: WorkspaceCommandHandlers,- palettesHidden: boolean+ palettesHidden: boolean,+ quickBrushPanelVisible?: boolean): boolean {if (id === 'flip-h') return Boolean(handlers.flipX);if (id === 'flip-v') return Boolean(handlers.flipY);+ if (id === 'value-check') return Boolean(handlers.valueCheckEnabled);if (id === 'toggle-palettes') return palettesHidden;+ if (id === 'toggle-quick-brushes') {+ return quickBrushPanelVisible ?? useWorkspaceStore.getState().quickBrushPanel.visible;+ }return false;}@@ -191,6 +223,7 @@ export const CommandBar: React.FC<CommandBarProps> = React.memo(({const showCommandBar = useWorkspaceStore((s) => s.showCommandBar);const activePreset = useWorkspaceStore((s) => s.activePreset);const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const quickBrushPanelVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);const [isCustomizeOpen, setIsCustomizeOpen] = useState(false);const [isPresetMenuOpen, setIsPresetMenuOpen] = useState(false);@@ -247,7 +280,7 @@ export const CommandBar: React.FC<CommandBarProps> = React.memo(({const entry = catalogById.get(cmdId);if (!entry) return null;const disabled = isCommandDisabled(cmdId, handlers);- const active = isCommandActive(cmdId, handlers, palettesHidden);+ const active = isCommandActive(cmdId, handlers, palettesHidden, quickBrushPanelVisible);return (<button@@ -451,6 +484,18 @@ export const CommandBar: React.FC<CommandBarProps> = React.memo(({<span className="text-[10px] font-mono text-[#8a8a8a]">Tab</span></button>+ <button+ type="button"+ onClick={() => {+ workspaceStoreActions.toggleQuickBrushPanelVisible();+ setIsPresetMenuOpen(false);+ }}+ className="w-full flex items-center justify-between px-2 py-1.5 rounded text-left text-[#cccccc] hover:bg-[#2c2c2c]/60 hover:text-white cursor-pointer"+ >+ <span>{quickBrushPanelVisible ? 'Hide Quick Brushes' : 'Show Quick Brushes'}</span>+ <span className="text-[10px] font-mono text-[#8a8a8a]">Shift+B</span>+ </button>+<buttontype="button"onClick={() => {diff --git a/src/components/Csp3DToolbar.tsx b/src/components/Csp3DToolbar.tsxindex e7861f5..a14c950 100644--- a/src/components/Csp3DToolbar.tsx+++ b/src/components/Csp3DToolbar.tsx@@ -15,13 +15,16 @@ import {Layers,Undo2,Redo2,+ Shapes,} from 'lucide-react';import {Gizmo3DMode,TOOL_3D_BEHAVIOR_RULES,Tool3DMode,} from '../utils/tool3DRules';+import { PRIMITIVE_3D_ITEMS, Primitive3DType } from '../utils/primitives3D';import { LightSourceWidget } from './LightSourceWidget';+import { Primitive3DIcon } from './Primitive3DIcon';import { store3DActions, use3DStore } from '../stores';export type Csp3DToolMode = Tool3DMode;@@ -32,6 +35,7 @@ interface Csp3DToolbarProps {onDirectDrag: (mode: Tool3DMode, deltaX: number, deltaY: number, snap: boolean) => void;onDirectDragEnd: () => void;onTriggerImport: () => void;+ onCreatePrimitive: (type: Primitive3DType) => void;onSnapToGround: () => void;onUndo: () => void;onRedo: () => void;@@ -92,6 +96,7 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({onDirectDrag,onDirectDragEnd,onTriggerImport,+ onCreatePrimitive,onSnapToGround,onUndo,onRedo,@@ -103,13 +108,15 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({const activeMode = use3DStore((s) => s.activeMode);const gizmoMode = use3DStore((s) => s.gizmoMode);const loadedModelName = use3DStore((s) => s.loadedModelName);+ const modelKind = use3DStore((s) => s.modelKind);+ const activePrimitiveType = use3DStore((s) => s.activePrimitiveType);const isBaking = use3DStore((s) => s.isBaking);const canUndo3D = use3DStore((s) => s.canUndo3D);const canRedo3D = use3DStore((s) => s.canRedo3D);const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);const lighting = use3DStore((s) => s.lighting);- const [openPopover, setOpenPopover] = useState<'light' | 'help' | null>(null);+ const [openPopover, setOpenPopover] = useState<'primitives' | 'light' | 'help' | null>(null);const hasModel = Boolean(loadedModelName);const dragRef = useRef<{@@ -241,14 +248,15 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({return (<div+ data-drop-zone="3d-stage"className="fixed top-12 left-1/2 -translate-x-1/2 z-50 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-lg px-2 py-1 shadow-2xl flex items-center gap-1.5 text-xs text-[#e5e5e5] select-none max-w-[calc(100vw-24px)]"onPointerDown={(e) => e.stopPropagation()}>- {/* 1. Import 3D Model */}+ {/* 1. Import 3D Model & Primitives */}<buttontype="button"onClick={onTriggerImport}- title="Import 3D Model (.glb, .gltf, .obj)"+ title="Import 3D Model (.glb, .gltf, .obj) — or drag & drop onto canvas"className={`flex items-center gap-1 px-2 py-1 rounded text-[11px] border border-white/[0.06] transition-colors cursor-pointer max-w-[110px] truncate ${loadedModelName? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'@@ -259,6 +267,57 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({<span className="truncate">{loadedModelName || 'Import 3D'}</span></button>+ <div className="relative">+ <button+ type="button"+ onClick={() => setOpenPopover((p) => (p === 'primitives' ? null : 'primitives'))}+ title="Create 3D Primitive (Cube, Sphere, Capsule, Cylinder, Pyramid)"+ data-testid="toolbar-3d-primitives-btn"+ className={`flex items-center gap-1 px-2 py-1 rounded text-[11px] border border-white/[0.06] transition-colors cursor-pointer ${+ openPopover === 'primitives' || modelKind === 'primitive'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-border)] font-medium'+ : 'bg-[#161616] text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Shapes className="w-3 h-3 shrink-0" />+ <span>Primitives</span>+ </button>++ {openPopover === 'primitives' && (+ <div+ data-testid="toolbar-3d-primitives-popover"+ className="absolute top-full mt-2 left-0 w-44 bg-[#202020] border border-white/[0.1] rounded-lg p-1.5 shadow-2xl z-50 space-y-0.5"+ >+ <div className="px-2 py-1 text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ Create Primitive+ </div>+ {PRIMITIVE_3D_ITEMS.map((item) => {+ const isSelected = modelKind === 'primitive' && activePrimitiveType === item.type;+ return (+ <button+ key={item.type}+ type="button"+ onClick={() => {+ onCreatePrimitive(item.type);+ setOpenPopover(null);+ }}+ title={item.description}+ data-testid={`toolbar-3d-primitive-${item.type}`}+ className={`w-full flex items-center gap-2 px-2 py-1.5 rounded text-[11px] transition-colors cursor-pointer ${+ isSelected+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Primitive3DIcon type={item.type} className="w-3.5 h-3.5 shrink-0" />+ <span>{item.label}</span>+ </button>+ );+ })}+ </div>+ )}+ </div>+<div className="w-px h-4 bg-white/[0.08]" />{/* 2. Object Transform Modes (Click or Scrub-Drag) */}diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsxindex 1bedab9..713eaba 100644--- a/src/components/DockWorkspace.tsx+++ b/src/components/DockWorkspace.tsx@@ -24,6 +24,7 @@ import {Play,PinOff,Minus,+ Star,} from 'lucide-react';import { CanvasColorMode, CspBrush } from '../types/editor';import { ThemePreset } from '../types/settings';@@ -59,6 +60,7 @@ import { ToolPropertyInspector } from './ToolPropertyInspector';import { BrushSizePalette } from './BrushSizePalette';import { RightSidebar, RightSidebarColorSection, RightSidebarProps } from './RightSidebar';import { QuickAccessPanel } from './QuickAccessPanel';+import { QuickBrushPanel } from './QuickBrushPanel';import { NavigatorPanel, NavigatorPanelProps } from './NavigatorPanel';import { SubViewPanel } from './SubViewPanel';import { InfoPanel } from './InfoPanel';@@ -1304,6 +1306,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({}) => {const layout = useWorkspaceStore((s) => s.layout);const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const quickBrushVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);const openPopover = useWorkspaceStore((s) => s.openPopover);const [customBrushes, setCustomBrushes] = useSharedCustomBrushes();@@ -1812,18 +1815,35 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({>{children}+ {/* Floating Quick-Access Brush Panel (stays accessible even when other palettes are hidden via Tab) */}+ <QuickBrushPanel customBrushes={customBrushes} />+{/* Unobtrusive Restore Palettes Pill when hidden via Tab */}{palettesHidden && (- <button- type="button"- onClick={() => workspaceStoreActions.setPalettesHidden(false)}- data-testid="restore-palettes-pill"- title="Show Palettes (Tab)"- className="absolute top-2 right-2 z-30 h-6 px-2 rounded-full bg-[#202020]/90 hover:bg-[#2c2c2c] border border-white/[0.12] text-[10px] text-[#cccccc] hover:text-white flex items-center gap-1 shadow-lg cursor-pointer"- >- <Eye className="w-3 h-3 text-[var(--accent)]" />- <span>Show Palettes (Tab)</span>- </button>+ <div className="absolute top-2 right-2 z-30 flex items-center gap-1.5">+ {!quickBrushVisible && (+ <button+ type="button"+ onClick={() => workspaceStoreActions.setQuickBrushPanelVisible(true)}+ data-testid="restore-quick-brushes-pill"+ title="Show Quick-Access Brush Panel (Shift+B)"+ className="h-6 px-2 rounded-full bg-[#202020]/90 hover:bg-[#2c2c2c] border border-white/[0.12] text-[10px] text-[#cccccc] hover:text-white flex items-center gap-1 shadow-lg cursor-pointer"+ >+ <Star className="w-3 h-3 text-amber-300" />+ <span>Quick Brushes (Shift+B)</span>+ </button>+ )}+ <button+ type="button"+ onClick={() => workspaceStoreActions.setPalettesHidden(false)}+ data-testid="restore-palettes-pill"+ title="Show Palettes (Tab)"+ className="h-6 px-2 rounded-full bg-[#202020]/90 hover:bg-[#2c2c2c] border border-white/[0.12] text-[10px] text-[#cccccc] hover:text-white flex items-center gap-1 shadow-lg cursor-pointer"+ >+ <Eye className="w-3 h-3 text-[var(--accent)]" />+ <span>Show Palettes (Tab)</span>+ </button>+ </div>)}</div>diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex 397343b..ab62137 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -576,6 +576,32 @@ export function useDocumentLifecycle({const topEditableLayer = doc.layers.find((l) => l.type === 'raster');const restoredWorkTimeMs = sanitizeWorkTimeMs(doc.workTimeMs);artworkTimeTracker.initDocument(newDocId, restoredWorkTimeMs);++ // Restore embedded time-lapse state & keyframes before activating the document tab+ // so recording automatically resumes and all previously recorded keyframes are ready.+ let restoredTimelapse = { enabled: false, frameCount: 0 };+ if (doc.timelapse || (doc.timelapseFrames && doc.timelapseFrames.length > 0)) {+ const frameTotal = doc.timelapseFrames?.length ?? 0;+ if (frameTotal > 0) {+ uiStoreActions.setLoading(+ true,+ `Restoring time-lapse (${frameTotal} frame${frameTotal === 1 ? '' : 's'})...`+ );+ }+ restoredTimelapse = await globalTimelapseManager.restoreSession(+ newDocId,+ doc.timelapse ?? null,+ doc.timelapseFrames,+ (done, total) => {+ if (total > 0) {+ uiStoreActions.setLoading(true, `Restoring time-lapse (${done}/${total})...`);+ }+ }+ );+ } else {+ await globalTimelapseManager.removeSession(newDocId).catch(() => {});+ }+const newDoc: DocumentTab = {id: newDocId,name: doc.name,@@ -616,7 +642,11 @@ export function useDocumentLifecycle({showToast(openedExt === '.sora'? `Migrated legacy ${file.name} (read-only) — save as .ink`- : `Opened ${file.name}`+ : restoredTimelapse.enabled+ ? restoredTimelapse.frameCount > 0+ ? `Opened ${file.name} — time-lapse resumed (${restoredTimelapse.frameCount} frames)`+ : `Opened ${file.name} — time-lapse resumed`+ : `Opened ${file.name}`);} catch (err: unknown) {console.error('Failed to open file:', err);@@ -723,6 +753,7 @@ export function useDocumentLifecycle({});if (id) {artworkTimeTracker.removeDocument(id);+ globalTimelapseManager.removeSession(id).catch(console.warn);documentStore.closeSession(id).catch(console.warn);recoveryService.closeSession(id).catch(console.warn);}@@ -764,6 +795,11 @@ export function useDocumentLifecycle({const restoredWorkTimeMs = sanitizeWorkTimeMs(manifest.workTimeMs);artworkTimeTracker.initDocument(session.session_id, restoredWorkTimeMs);+ if (manifest.timelapse) {+ await globalTimelapseManager+ .restoreFromScratchDisk(session.session_id, manifest.timelapse, restoredDims)+ .catch(console.warn);+ }const restoredDoc: DocumentTab = {id: session.session_id,name: manifest.documentName,@@ -821,6 +857,7 @@ export function useDocumentLifecycle({async (session: CrashedSessionInfo) => {try {await recoveryService.discardCrashedSession(session.session_id);+ await globalTimelapseManager.removeSession(session.session_id).catch(() => {});uiStoreActions.setCrashedSessions((prev) => {const next = prev.filter((s) => s.session_id !== session.session_id);if (next.length === 0) {@@ -905,6 +942,7 @@ export function useDocumentLifecycle({tlStats.enabled || tlStats.frameCount > 0? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }: null,+ timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(activeDocumentId),workTimeMs,onProgress,};@@ -964,6 +1002,7 @@ export function useDocumentLifecycle({tlStats.enabled || tlStats.frameCount > 0? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }: null,+ timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(docId),workTimeMs: docWorkTimeMs,onProgress,};@@ -1465,6 +1504,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =activeLayerId: doc?.activeLayerId || cur.activeLayerId,timestamp: Date.now(),workTimeMs: artworkTimeTracker.getWorkTimeMs(activeDocumentId),+ timelapse: globalTimelapseManager.getRecoveryMetadata(activeDocumentId),};},async () => {diff --git a/src/components/FloatingBrushPill.tsx b/src/components/FloatingBrushPill.tsxindex 34d01a7..0c21182 100644--- a/src/components/FloatingBrushPill.tsx+++ b/src/components/FloatingBrushPill.tsx@@ -1,10 +1,12 @@import React, { useState, useRef, useCallback } from 'react';-import { ToolType, BrushSettings, LiquifySettings, RetouchSettings } from '../types/editor';+import { ToolType, BrushSettings, FillSettings, LiquifySettings, RetouchSettings } from '../types/editor';interface FloatingBrushPillProps {tool: ToolType;brushSettings: BrushSettings;onUpdateBrushSettings: (patch: Partial<BrushSettings>) => void;+ fillSettings?: FillSettings;+ onUpdateFillSettings?: (patch: Partial<FillSettings>) => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (patch: Partial<LiquifySettings>) => void;retouchSettings?: RetouchSettings;@@ -33,6 +35,8 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({tool,brushSettings,onUpdateBrushSettings,+ fillSettings,+ onUpdateFillSettings,liquifySettings,onUpdateLiquifySettings,retouchSettings,@@ -48,20 +52,25 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({const isLiquify = tool === 'liquify';const isRetouch = tool === 'retouch';+ const isPaintUnfilled = tool === 'fill' && fillSettings?.method === 'paint-unfilled';const usesStrength = isLiquify || isRetouch;- const minSize = isLiquify ? 5 : isRetouch ? 2 : MIN_BRUSH_SIZE;- const maxSize = isLiquify ? 500 : isRetouch ? 300 : MAX_BRUSH_SIZE;+ const minSize = isLiquify ? 5 : isRetouch || isPaintUnfilled ? 2 : MIN_BRUSH_SIZE;+ const maxSize = isLiquify ? 500 : isRetouch || isPaintUnfilled ? 300 : MAX_BRUSH_SIZE;const currentSize = isLiquify? (liquifySettings?.size ?? 80): isRetouch? (retouchSettings?.size ?? 40)- : brushSettings.size;+ : isPaintUnfilled+ ? (fillSettings?.brushSize ?? 24)+ : brushSettings.size;const currentOpacity = isLiquify? (liquifySettings?.strength ?? 50) / 100: isRetouch? (retouchSettings?.strength ?? 50) / 100- : (brushSettings.opacity ?? 1);+ : isPaintUnfilled+ ? (fillSettings?.opacity ?? 1)+ : (brushSettings.opacity ?? 1);const sizeRatio = sizeToRatio(currentSize, minSize, maxSize);const opacityRatio = Math.max(0.01, Math.min(1, currentOpacity));@@ -77,11 +86,13 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({onUpdateLiquifySettings?.({ size: nextSize });} else if (isRetouch) {onUpdateRetouchSettings?.({ size: Math.round(nextSize) });+ } else if (isPaintUnfilled) {+ onUpdateFillSettings?.({ brushSize: Math.round(nextSize) });} else {onUpdateBrushSettings({ size: nextSize });}},- [isLiquify, isRetouch, maxSize, minSize, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]+ [isLiquify, isRetouch, isPaintUnfilled, maxSize, minSize, onUpdateBrushSettings, onUpdateFillSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]);const updateOpacityFromPointer = useCallback(@@ -94,11 +105,13 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({onUpdateLiquifySettings?.({ strength: Math.round(ratio * 100) });} else if (isRetouch) {onUpdateRetouchSettings?.({ strength: Math.round(ratio * 100) });+ } else if (isPaintUnfilled) {+ onUpdateFillSettings?.({ opacity: Math.round(ratio * 100) / 100 });} else {onUpdateBrushSettings({ opacity: Math.round(ratio * 100) / 100 });}},- [isLiquify, isRetouch, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]+ [isLiquify, isRetouch, isPaintUnfilled, onUpdateBrushSettings, onUpdateFillSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]);const showSizeHud = activeDrag === 'size' || hoveredTrack === 'size';diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsxindex e92c3db..c3efd9d 100644--- a/src/components/GlobalShortcutListener.tsx+++ b/src/components/GlobalShortcutListener.tsx@@ -5,6 +5,7 @@ import {CanvasSelection,LayerItem,ToolType,+ TransformMode,TransformSession,} from '../types/editor';import { ModifierAction } from '../types/settings';@@ -18,14 +19,34 @@ import { importBrushFile, isSupportedBrushFileName } from '../utils/inkbBrushForimport { TonalCorrectionType } from '../utils/tonalEngine';import {SPRING_LOADED_HOLD_MS,+ SpringLoadedSubToolController,SpringLoadedToolController,+ KeyboardEventLike,+ buildSubToolShortcutCommands,shortcutManager,} from '../utils/shortcutManager';+import {+ CUSTOM_BRUSHES_CHANGED_EVENT,+ getCachedCustomBrushes,+ loadCustomBrushes,+} from '../utils/brushStorage';+import {+ activateSubToolGroup,+ activateSubToolPreset,+ stepMainTool,+ stepSubTool,+ stepSubToolGroup,+} from '../utils/subToolNavigation';+import {+ subscribeNativeOsHotkeys,+ syncNativeOsHotkeys,+} from '../utils/nativeOsHotkeys';import {documentStoreActions,selectIsAnyModalOpen,toolStoreActions,uiStoreActions,+ useSubToolGroupStore,useToolStore,useUiStore,workspaceStoreActions,@@ -61,7 +82,8 @@ export interface GlobalShortcutListenerProps {handleMoveSelectionToNewLayer: () => void;handleCopySelectionToNewLayer: () => void;handleGroupSelectedLayers: () => void;- handleStartTransform: () => void;+ handleStartTransform: (initialMode?: TransformMode) => void;+ setTransformSession?: React.Dispatch<React.SetStateAction<TransformSession | null>>;handleSelectAll: () => void;handleDeselect: () => void;handleInvertSelection: () => void;@@ -72,6 +94,7 @@ export interface GlobalShortcutListenerProps {zoomIn?: () => void;zoomOut?: () => void;resetZoomAndCenter?: () => void;+ resetZoomTo100?: () => void;resetRotation?: () => void;toggleFlipHorizontal: () => void;toggleFlipVertical: () => void;@@ -90,13 +113,17 @@ const NON_REPEATABLE_COMMANDS = new Set<string>(['color.transparent','view.flipHorizontal','view.flipVertical',+ 'view.valueCheck',+ 'view.navigatorValueMode','view.togglePalettes',+ 'view.toggleQuickBrushPanel','view.toggleLeftPanel','view.softProof','view.gamutWarning','view.straightRuler','view.perspectiveRuler','view.perspectiveSnap',+ 'view.zoomActualSize','anim.toggleTimeline','app.preferences','file.new',@@ -151,12 +178,43 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReapropsRef.current = props;const springControllerRef = useRef(new SpringLoadedToolController(SPRING_LOADED_HOLD_MS));+ const subToolSpringControllerRef = useRef(+ new SpringLoadedSubToolController(SPRING_LOADED_HOLD_MS)+ );const activeModHoldRef = useRef<{modKey: 'Alt' | 'Control' | 'Shift';prevTool: ToolType;tempTool: ToolType;} | null>(null);+ const shortcuts = useUiStore((s) => s.appSettings.shortcuts);+ const customSubToolGroups = useSubToolGroupStore((s) => s.groups);++ // Sync dynamic subtool / custom group shortcut commands & native Windows OS-key bindings+ useEffect(() => {+ let active = true;+ const syncDynamicAndNative = () => {+ if (!active) return;+ const dynamicCommands = buildSubToolShortcutCommands(+ getCachedCustomBrushes(),+ useSubToolGroupStore.getState().groups+ );+ shortcutManager.setDynamicCommands(dynamicCommands);+ const currentShortcuts = useUiStore.getState().appSettings.shortcuts;+ shortcutManager.setOverrides(currentShortcuts);+ syncNativeOsHotkeys(shortcutManager.getCommands(), currentShortcuts);+ };++ syncDynamicAndNative();+ void loadCustomBrushes().then(syncDynamicAndNative);++ window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, syncDynamicAndNative);+ return () => {+ active = false;+ window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, syncDynamicAndNative);+ };+ }, [shortcuts, customSubToolGroups]);+// Flush debounced brush settings on window close/unmountuseEffect(() => {const handleBeforeUnload = () => flushPendingBrushSettingsSave();@@ -192,6 +250,18 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReaMath.min(300, Math.round(stepBrushSizePreset(toolState.retouchSettings.size, dir))));toolStoreActions.updateRetouchSettings({ size: nextSize });+ } else if (+ toolState.tool === 'fill' &&+ toolState.fillSettings.method === 'paint-unfilled'+ ) {+ const nextSize = Math.max(+ 2,+ Math.min(+ 300,+ Math.round(stepBrushSizePreset(toolState.fillSettings.brushSize ?? 24, dir))+ )+ );+ toolStoreActions.updateFillSettings({ brushSize: nextSize });} else if (toolState.tool === 'shape') {const nextWidth = Math.max(1,@@ -224,6 +294,14 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea'view.togglePalettes': () => {if (!propsRef.current.textSession) workspaceStoreActions.togglePalettesHidden();},+ 'view.toggleQuickBrushPanel': () => {+ if (!propsRef.current.textSession) {+ const visible = workspaceStoreActions.toggleQuickBrushPanelVisible();+ propsRef.current.showToast(+ visible ? 'Quick Brush Panel: Shown' : 'Quick Brush Panel: Hidden'+ );+ }+ },'view.toggleLeftPanel': () => {if (!propsRef.current.textSession) uiStoreActions.toggleLeftPanelHidden();},@@ -233,6 +311,24 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea'view.gamutWarning': () => {if (propsRef.current.hasOpenDocument) documentStoreActions.toggleGamutWarning();},+ 'view.valueCheck': () => {+ if (!propsRef.current.hasOpenDocument) return;+ const enabled = documentStoreActions.toggleValueCheck();+ propsRef.current.showToast(+ enabled ? 'Value Check (Live B/W): ON' : 'Value Check (Live B/W): OFF'+ );+ },+ 'view.navigatorValueMode': () => {+ if (!propsRef.current.hasOpenDocument) return;+ const nextMode = workspaceStoreActions.cycleNavigatorPreviewMode();+ const label =+ nextMode === 'bw'+ ? 'Live B/W Tone'+ : nextMode === 'split'+ ? 'Split View (Color | B/W)'+ : 'Color';+ propsRef.current.showToast(`Navigator Preview: ${label}`);+ },'anim.toggleTimeline': () => {const p = propsRef.current;if (!p.hasOpenDocument) return;@@ -286,14 +382,70 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea'edit.delete': () => {const p = propsRef.current;if (!p.hasOpenDocument) return;+ if (p.transformSession?.active) {+ if (+ p.transformSession.mode === 'puppet' &&+ p.transformSession.puppet?.selectedPinId &&+ p.setTransformSession+ ) {+ const delId = p.transformSession.puppet.selectedPinId;+ p.setTransformSession((prev) => {+ if (!prev?.puppet) return prev;+ const nextPins = prev.puppet.pins.filter((pin) => pin.id !== delId);+ return {+ ...prev,+ puppet: {+ ...prev.puppet,+ pins: nextPins,+ selectedPinId: nextPins.length > 0 ? nextPins[nextPins.length - 1].id : null,+ },+ };+ });+ } else if (+ p.transformSession.mode === 'cage' &&+ p.transformSession.cage?.selectedPointId &&+ p.setTransformSession+ ) {+ const delId = p.transformSession.cage.selectedPointId;+ p.setTransformSession((prev) => {+ if (!prev?.cage) return prev;+ if (prev.cage.closed && prev.cage.points.length <= 3) return prev;+ return {+ ...prev,+ cage: {+ ...prev.cage,+ points: prev.cage.points.filter((pt) => pt.id !== delId),+ selectedPointId: null,+ },+ };+ });+ }+ return;+ }if (p.selection) p.handleClearSelection();else p.handleDeleteSelectedLayer();},'edit.transform': () => {- if (propsRef.current.hasOpenDocument) propsRef.current.handleStartTransform();+ if (propsRef.current.hasOpenDocument) propsRef.current.handleStartTransform('affine');+ },+ 'edit.puppetWarp': () => {+ if (propsRef.current.hasOpenDocument) propsRef.current.handleStartTransform('puppet');+ },+ 'edit.cageTransform': () => {+ if (propsRef.current.hasOpenDocument) propsRef.current.handleStartTransform('cage');},'edit.selectAll': () => {- if (propsRef.current.hasOpenDocument) propsRef.current.handleSelectAll();+ if (!propsRef.current.hasOpenDocument) return;+ const toolState = useToolStore.getState();+ if (+ toolState.tool === 'gradient' &&+ toolState.gradientSettings.type === 'mesh' &&+ toolState.activeGradientMesh+ ) {+ toolStoreActions.selectAllActiveGradientMeshNodes();+ return;+ }+ propsRef.current.handleSelectAll();},'edit.deselect': () => {if (propsRef.current.hasOpenDocument) propsRef.current.handleDeselect();@@ -347,6 +499,9 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea'view.zoomIn': () => propsRef.current.zoomIn?.(),'view.zoomOut': () => propsRef.current.zoomOut?.(),'view.resetZoom': () => propsRef.current.resetZoomAndCenter?.(),+ 'view.zoomActualSize': () => {+ if (propsRef.current.hasOpenDocument) propsRef.current.resetZoomTo100?.();+ },'view.resetRotation': () => propsRef.current.resetRotation?.(),'view.flipHorizontal': () => {const p = propsRef.current;@@ -393,6 +548,42 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReatoolStoreActions.selectTool('3d');}},+ 'tool.prevSubTool': () => {+ const res = stepSubTool(-1, getCachedCustomBrushes());+ if (res) propsRef.current.showToast(`Sub Tool: ${res.name}`);+ },+ 'tool.nextSubTool': () => {+ const res = stepSubTool(1, getCachedCustomBrushes());+ if (res) propsRef.current.showToast(`Sub Tool: ${res.name}`);+ },+ 'tool.prevTool': () => {+ const res = stepMainTool(-1, propsRef.current.hasOpenDocument);+ propsRef.current.showToast(`Tool: ${res.label}`);+ },+ 'tool.nextTool': () => {+ const res = stepMainTool(1, propsRef.current.hasOpenDocument);+ propsRef.current.showToast(`Tool: ${res.label}`);+ },+ 'tool.prevSubToolGroup': () => {+ const res = stepSubToolGroup(-1, getCachedCustomBrushes());+ if (res) {+ propsRef.current.showToast(+ res.activatedBrushName+ ? `Group: ${res.groupName} · ${res.activatedBrushName}`+ : `Group: ${res.groupName}`+ );+ }+ },+ 'tool.nextSubToolGroup': () => {+ const res = stepSubToolGroup(1, getCachedCustomBrushes());+ if (res) {+ propsRef.current.showToast(+ res.activatedBrushName+ ? `Group: ${res.groupName} · ${res.activatedBrushName}`+ : `Group: ${res.groupName}`+ );+ }+ },'tool.brushSizeDown': () => stepBrush(-1),'tool.brushSizeUp': () => stepBrush(1),'color.swap': () => toolStoreActions.swapColors(),@@ -423,6 +614,108 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea}};+ const restoreSubToolSnapshot = (+ restored: { tool: ToolType; presetId: string } | null+ ) => {+ if (!restored) return;+ if (restored.tool === 'brush' || restored.tool === 'decoration') {+ activateSubToolPreset(restored.presetId, getCachedCustomBrushes());+ } else {+ toolStoreActions.selectTool(restored.tool);+ }+ };++ const dispatchShortcutCommandDown = (+ e: KeyboardEventLike,+ preventDefault?: () => void+ ): boolean => {+ const p = propsRef.current;+ const uiState = useUiStore.getState();+ const overrides = uiState.appSettings.shortcuts;+ shortcutManager.setOverrides(overrides);+ const matched = shortcutManager.matchEvent(e, overrides);+ if (!matched) return false;++ // Guard special contextual exceptions before preventDefault+ if (matched.id === 'edit.copy' || matched.id === 'edit.cut') {+ const textSel = window.getSelection()?.toString();+ if (textSel && textSel.length > 0) return false;+ }+ if (+ (matched.id === 'view.togglePalettes' ||+ matched.id === 'view.toggleQuickBrushPanel' ||+ matched.id === 'view.toggleLeftPanel') &&+ p.textSession+ ) {+ return false;+ }+ if (+ (matched.id === 'view.flipHorizontal' || matched.id === 'view.flipVertical') &&+ p.isSpaceDown+ ) {+ return false;+ }++ // Direct SubTool shortcut (with spring-loaded hold-to-revert support)+ if (matched.subToolPresetId) {+ if (e.repeat) return true;+ clearModHold();+ preventDefault?.();+ const toolState = useToolStore.getState();+ const activated = subToolSpringControllerRef.current.handleSubToolKeyDown(+ e.code || matched.id,+ matched.subToolPresetId,+ toolState.tool,+ toolState.activePresetId+ );+ if (activated) {+ const res = activateSubToolPreset(matched.subToolPresetId, getCachedCustomBrushes());+ if (res) p.showToast(`Sub Tool: ${res.name}`);+ }+ return true;+ }++ // Direct Custom / Built-in SubTool Group shortcut+ if (matched.subToolGroupId) {+ if (e.repeat) return true;+ clearModHold();+ preventDefault?.();+ const res = activateSubToolGroup(matched.subToolGroupId, getCachedCustomBrushes());+ if (res) {+ p.showToast(+ res.activatedBrushName+ ? `Group: ${res.groupName} · ${res.activatedBrushName}`+ : `Group: ${res.groupName}`+ );+ }+ return true;+ }++ if (matched.springLoaded && matched.toolId) {+ if (e.repeat) return true;+ preventDefault?.();+ const currentTool = useToolStore.getState().tool;+ const nextTool = springControllerRef.current.handleToolKeyDown(+ e.code || matched.id,+ matched.toolId,+ currentTool+ );+ if (nextTool) {+ toolStoreActions.selectTool(nextTool);+ }+ return true;+ }++ if (e.repeat && NON_REPEATABLE_COMMANDS.has(matched.id)) {+ return true;+ }++ clearModHold();+ preventDefault?.();+ shortcutManager.executeCommand(matched.id);+ return true;+ };+const handleKeyDown = (e: KeyboardEvent) => {const p = propsRef.current;const uiState = useUiStore.getState();@@ -440,7 +733,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea!p.isSelectionPenDrawingRef.current) {const onlyAlt = e.key === 'Alt' && !e.ctrlKey && !e.metaKey && !e.shiftKey;- const onlyCtrl = e.key === 'Control' && !e.altKey && !e.shiftKey;+ const onlyCtrl = e.key === 'Control' && !e.metaKey && !e.altKey && !e.shiftKey;const onlyShift = e.key === 'Shift' && !e.ctrlKey && !e.metaKey && !e.altKey;let action: ModifierAction = 'none';@@ -462,7 +755,8 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaconst reserveAltForActiveTool =modKey === 'Alt' &&tempTool === 'pipette' &&- ((curState.tool === 'retouch' && curState.retouchSettings.mode === 'clone-stamp') ||+ (Boolean(p.transformSession?.active) ||+ (curState.tool === 'retouch' && curState.retouchSettings.mode === 'clone-stamp') ||curState.tool === 'pen' ||curState.tool === '3d');if (reserveAltForActiveTool) {@@ -489,58 +783,14 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea(e.code === 'Space' ||e.key === ' ' ||(activeModHoldRef.current.modKey === 'Alt' && (e.ctrlKey || e.metaKey || e.shiftKey)) ||- (activeModHoldRef.current.modKey === 'Control' && (e.altKey || e.shiftKey)) ||+ (activeModHoldRef.current.modKey === 'Control' && (e.altKey || e.shiftKey || e.metaKey)) ||(activeModHoldRef.current.modKey === 'Shift' && (e.ctrlKey || e.metaKey || e.altKey)))) {clearModHold();}- // 2. Match against centralized ShortcutManager (live overrides read imperatively!)- const overrides = uiState.appSettings.shortcuts;- shortcutManager.setOverrides(overrides);- const matched = shortcutManager.matchEvent(e, overrides);-- if (matched) {- // Guard special contextual exceptions before preventDefault- if (matched.id === 'edit.copy' || matched.id === 'edit.cut') {- const textSel = window.getSelection()?.toString();- if (textSel && textSel.length > 0) return;- }- if (- (matched.id === 'view.togglePalettes' || matched.id === 'view.toggleLeftPanel') &&- p.textSession- ) {- return;- }- if (- (matched.id === 'view.flipHorizontal' || matched.id === 'view.flipVertical') &&- p.isSpaceDown- ) {- return;- }-- if (matched.springLoaded && matched.toolId) {- if (e.repeat) return;- e.preventDefault();- const currentTool = useToolStore.getState().tool;- const nextTool = springControllerRef.current.handleToolKeyDown(- e.code || matched.id,- matched.toolId,- currentTool- );- if (nextTool) {- toolStoreActions.selectTool(nextTool);- }- return;- }-- if (e.repeat && NON_REPEATABLE_COMMANDS.has(matched.id)) {- return;- }-- clearModHold();- e.preventDefault();- shortcutManager.executeCommand(matched.id);+ // 2. Match against centralized ShortcutManager (static + dynamic subtools + OS/Win keys)+ if (dispatchShortcutCommandDown(e, () => e.preventDefault())) {return;}@@ -560,27 +810,45 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea} else if (key === 'enter') {if (p.transformSession?.active) {e.preventDefault();+ if (+ p.transformSession.mode === 'cage' &&+ p.transformSession.cage &&+ !p.transformSession.cage.closed &&+ p.transformSession.cage.points.length >= 3 &&+ p.setTransformSession+ ) {+ p.setTransformSession((prev) =>+ prev?.cage+ ? { ...prev, cage: { ...prev.cage, closed: true, phase: 'deform' } }+ : prev+ );+ return;+ }p.handleApplyTransform();}}};const handleKeyUp = (e: KeyboardEvent) => {- // 1. Release spring-loaded tool hold (> 250ms or used while held)- const restored = springControllerRef.current.handleKeyUp(- e.code,- useToolStore.getState().tool- );+ // 1. Release spring-loaded tool & subtool holds (> 250ms or used while held)+ const curToolState = useToolStore.getState();+ const restored = springControllerRef.current.handleKeyUp(e.code, curToolState.tool);if (restored) {toolStoreActions.selectTool(restored);}+ const restoredSub = subToolSpringControllerRef.current.handleKeyUp(+ e.code,+ curToolState.tool,+ curToolState.activePresetId+ );+ restoreSubToolSnapshot(restoredSub);// 2. Release temporary modifier-key tool holdconst mod = activeModHoldRef.current;if (mod) {const released =(mod.modKey === 'Alt' && (e.key === 'Alt' || !e.altKey)) ||- (mod.modKey === 'Control' && (e.key === 'Control' || (!e.ctrlKey && !e.metaKey))) ||+ (mod.modKey === 'Control' && (e.key === 'Control' || !e.ctrlKey)) ||(mod.modKey === 'Shift' && (e.key === 'Shift' || !e.shiftKey));if (released) {if (mod.modKey === 'Alt') e.preventDefault();@@ -591,21 +859,54 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaconst handlePointerDownMarkUsed = () => {springControllerRef.current.markUsedWhileHeld();+ subToolSpringControllerRef.current.markUsedWhileHeld();};const handleWindowBlur = () => {- const restored = springControllerRef.current.cancel(useToolStore.getState().tool);+ const curToolState = useToolStore.getState();+ const restored = springControllerRef.current.cancel(curToolState.tool);if (restored) {toolStoreActions.selectTool(restored);}+ const restoredSub = subToolSpringControllerRef.current.cancel(+ curToolState.tool,+ curToolState.activePresetId+ );+ restoreSubToolSnapshot(restoredSub);clearModHold();};+ // Subscribe to native Windows OS-key (Win-key) hotkeys delivered by Tauri backend+ const unsubNativeOsHotkeys = subscribeNativeOsHotkeys((ev) => {+ if (ev.isRecording) return;+ const p = propsRef.current;+ const uiState = useUiStore.getState();+ const isModalOpen =+ selectIsAnyModalOpen(uiState, p.isHostModalOpen) || uiState.isLoadingFile;+ if (ev.phase === 'keyup') {+ const curToolState = useToolStore.getState();+ const restored = springControllerRef.current.handleKeyUp(ev.code, curToolState.tool);+ if (restored) toolStoreActions.selectTool(restored);+ const restoredSub = subToolSpringControllerRef.current.handleKeyUp(+ ev.code,+ curToolState.tool,+ curToolState.activePresetId+ );+ restoreSubToolSnapshot(restoredSub);+ return;+ }+ if (isModalOpen || isEditableTarget(document.activeElement)) {+ return;+ }+ dispatchShortcutCommandDown(ev);+ });+window.addEventListener('keydown', handleKeyDown);window.addEventListener('keyup', handleKeyUp);window.addEventListener('pointerdown', handlePointerDownMarkUsed, true);window.addEventListener('blur', handleWindowBlur);return () => {+ unsubNativeOsHotkeys();window.removeEventListener('keydown', handleKeyDown);window.removeEventListener('keyup', handleKeyUp);window.removeEventListener('pointerdown', handlePointerDownMarkUsed, true);diff --git a/src/components/GradientOverlay.tsx b/src/components/GradientOverlay.tsxindex 6e0d447..a857dec 100644--- a/src/components/GradientOverlay.tsx+++ b/src/components/GradientOverlay.tsx@@ -1,10 +1,16 @@import React, { useEffect, useRef } from 'react';+import { RotateCw } from 'lucide-react';import type {CanvasDimensions,GradientDragPreview,GradientMeshState,} from '../types/editor';-import { rasterizeMeshGradientToRgba } from '../utils/gradientEngine';+import {+ getGradientMeshBounds,+ getGradientMeshCentroid,+ getSelectedMeshNodeIndices,+ rasterizeMeshGradientToRgba,+} from '../utils/gradientEngine';export interface GradientOverlayProps {dimensions: CanvasDimensions;@@ -13,9 +19,12 @@ export interface GradientOverlayProps {flipY: boolean;dragPreview: GradientDragPreview | null;mesh: GradientMeshState | null;+ marqueeRect?: { x: number; y: number; width: number; height: number } | null;+ isRotatingMesh?: boolean;opacity: number;onApplyMesh?: () => void;onCancelMesh?: () => void;+ onStartRotateMesh?: (e: React.PointerEvent<HTMLElement>) => void;}const MAX_PREVIEW_DIM = 384;@@ -28,9 +37,12 @@ export const GradientOverlay: React.FC<GradientOverlayProps> = React.memo(flipY,dragPreview,mesh,+ marqueeRect = null,+ isRotatingMesh = false,opacity,onApplyMesh,onCancelMesh,+ onStartRotateMesh,}) => {const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);const invZoom = 1 / Math.max(0.05, zoom);@@ -135,110 +147,244 @@ export const GradientOverlay: React.FC<GradientOverlayProps> = React.memo();})()}- {mesh && (- <>- <canvas- ref={previewCanvasRef}- className="absolute inset-0 w-full h-full pointer-events-none z-30"- style={{ opacity: Math.max(0.05, Math.min(1, opacity)) }}- />- <svg- className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"- viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}- >- {/* Horizontal mesh wires */}- {Array.from({ length: mesh.rows }).map((_, r) =>- Array.from({ length: mesh.cols - 1 }).map((__, c) => {- const a = mesh.nodes[r * mesh.cols + c];- const b = mesh.nodes[r * mesh.cols + c + 1];- if (!a || !b) return null;- return (+ {mesh && (() => {+ const selectedIndices = getSelectedMeshNodeIndices(mesh);+ const selectedSet = new Set(selectedIndices);+ const bounds = getGradientMeshBounds(mesh);+ const centroid = getGradientMeshCentroid(mesh);+ const rotationDeg = Math.round(mesh.rotationDeg ?? 0);+ const handleX = centroid.x;+ const handleY = bounds.minY - 28 * invZoom;+ const barTop = Math.max(8, bounds.minY - 66 * invZoom);++ return (+ <>+ <canvas+ ref={previewCanvasRef}+ className="absolute inset-0 w-full h-full pointer-events-none z-30"+ style={{ opacity: Math.max(0.05, Math.min(1, opacity)) }}+ />+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ {/* Horizontal mesh wires */}+ {Array.from({ length: mesh.rows }).map((_, r) =>+ Array.from({ length: mesh.cols - 1 }).map((__, c) => {+ const a = mesh.nodes[r * mesh.cols + c];+ const b = mesh.nodes[r * mesh.cols + c + 1];+ if (!a || !b) return null;+ return (+ <line+ key={`mh-${r}-${c}`}+ x1={a.x}+ y1={a.y}+ x2={b.x}+ y2={b.y}+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ );+ })+ )}+ {/* Vertical mesh wires */}+ {Array.from({ length: mesh.rows - 1 }).map((_, r) =>+ Array.from({ length: mesh.cols }).map((__, c) => {+ const a = mesh.nodes[r * mesh.cols + c];+ const b = mesh.nodes[(r + 1) * mesh.cols + c];+ if (!a || !b) return null;+ return (+ <line+ key={`mv-${r}-${c}`}+ x1={a.x}+ y1={a.y}+ x2={b.x}+ y2={b.y}+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ );+ })+ )}++ {/* Rotation stem & center pivot crosshair */}+ {mesh.nodes.length > 0 && (+ <g><line- key={`mh-${r}-${c}`}- x1={a.x}- y1={a.y}- x2={b.x}- y2={b.y}- stroke="#ffffff"- strokeOpacity={0.75}- strokeWidth={1.25 * invZoom}- strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ x1={centroid.x}+ y1={bounds.minY}+ x2={handleX}+ y2={handleY}+ stroke="#000000"+ strokeOpacity={0.6}+ strokeWidth={2.5 * invZoom}/>- );- })- )}- {/* Vertical mesh wires */}- {Array.from({ length: mesh.rows - 1 }).map((_, r) =>- Array.from({ length: mesh.cols }).map((__, c) => {- const a = mesh.nodes[r * mesh.cols + c];- const b = mesh.nodes[(r + 1) * mesh.cols + c];- if (!a || !b) return null;- return (<line- key={`mv-${r}-${c}`}- x1={a.x}- y1={a.y}- x2={b.x}- y2={b.y}- stroke="#ffffff"- strokeOpacity={0.75}+ x1={centroid.x}+ y1={bounds.minY}+ x2={handleX}+ y2={handleY}+ stroke="#38bdf8"strokeWidth={1.25 * invZoom}- strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}/>- );- })- )}- {/* Draggable control nodes */}- {mesh.nodes.map((node, idx) => {- const isSelected = mesh.selectedNodeIndex === idx;- return (- <g key={`mn-${idx}`}><circle- cx={node.x}- cy={node.y}- r={(isSelected ? 8 : 6) * invZoom}- fill={node.color}- stroke={isSelected ? '#38bdf8' : '#ffffff'}- strokeWidth={(isSelected ? 2.5 : 1.75) * invZoom}+ cx={centroid.x}+ cy={centroid.y}+ r={(isRotatingMesh ? 5 : 3.5) * invZoom}+ fill="none"+ stroke="#38bdf8"+ strokeOpacity={isRotatingMesh ? 0.95 : 0.6}+ strokeWidth={1.25 * invZoom}+ />+ <line+ x1={centroid.x - 6 * invZoom}+ y1={centroid.y}+ x2={centroid.x + 6 * invZoom}+ y2={centroid.y}+ stroke="#38bdf8"+ strokeOpacity={isRotatingMesh ? 0.95 : 0.6}+ strokeWidth={1.1 * invZoom}+ />+ <line+ x1={centroid.x}+ y1={centroid.y - 6 * invZoom}+ x2={centroid.x}+ y2={centroid.y + 6 * invZoom}+ stroke="#38bdf8"+ strokeOpacity={isRotatingMesh ? 0.95 : 0.6}+ strokeWidth={1.1 * invZoom}/></g>- );- })}- </svg>+ )}- {/* Floating Mesh Commit / Cancel Action Bar */}- {mesh.nodes.length > 0 && (- <div- onPointerDown={(e) => e.stopPropagation()}- className="absolute z-40 flex items-center gap-1 px-1.5 py-1 rounded bg-[#181818]/95 border border-white/15 shadow-lg"- style={{- left: `${mesh.nodes[0].x}px`,- top: `${Math.max(8, mesh.nodes[0].y - 36 * invZoom)}px`,- transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,- transformOrigin: 'top left',- }}- >- <span className="text-[10px] text-[#8a8a8a] px-1">- Mesh ({mesh.cols}×{mesh.rows})- </span>+ {/* Marquee multi-selection rectangle */}+ {marqueeRect && (marqueeRect.width > 1 || marqueeRect.height > 1) && (+ <rect+ x={marqueeRect.x}+ y={marqueeRect.y}+ width={marqueeRect.width}+ height={marqueeRect.height}+ fill="rgba(56, 189, 248, 0.14)"+ stroke="#38bdf8"+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}++ {/* Draggable control nodes */}+ {mesh.nodes.map((node, idx) => {+ const isSelected = selectedSet.has(idx);+ const isPrimary = mesh.selectedNodeIndex === idx;+ return (+ <g key={`mn-${idx}`}>+ {isSelected && (+ <circle+ cx={node.x}+ cy={node.y}+ r={11.5 * invZoom}+ fill="none"+ stroke={isPrimary ? '#38bdf8' : '#7dd3fc'}+ strokeOpacity={0.75}+ strokeWidth={1.5 * invZoom}+ />+ )}+ <circle+ cx={node.x}+ cy={node.y}+ r={(isSelected ? (isPrimary ? 8.5 : 7.5) : 6) * invZoom}+ fill={node.color}+ stroke={isSelected ? (isPrimary ? '#38bdf8' : '#e0f2fe') : '#ffffff'}+ strokeWidth={(isSelected ? 2.5 : 1.75) * invZoom}+ />+ </g>+ );+ })}+ </svg>++ {/* Interactive On-Canvas Rotation Handle (rotates all vertices simultaneously) */}+ {mesh.nodes.length > 0 && onStartRotateMesh && (<buttontype="button"- onClick={onApplyMesh}- className="px-2 py-0.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer"+ title="Drag to rotate all mesh vertices (Shift: 15° snap)"+ onPointerDown={(e) => {+ e.stopPropagation();+ onStartRotateMesh(e);+ }}+ className={`absolute z-36 w-6 h-6 rounded-full flex items-center justify-center bg-[#181818]/95 border text-[#38bdf8] shadow-md transition-colors ${+ isRotatingMesh+ ? 'border-[#38bdf8] bg-[#0c4a6e]/90 cursor-grabbing'+ : 'border-white/30 hover:border-[#38bdf8] hover:bg-[#222222] cursor-grab'+ }`}+ style={{+ left: `${handleX}px`,+ top: `${handleY}px`,+ transform: `translate(-50%, -50%) scale(${(flipX ? -1 : 1) * invZoom}, ${+ (flipY ? -1 : 1) * invZoom+ })`,+ transformOrigin: 'center center',+ }}>- Apply+ <RotateCw className="w-3.5 h-3.5" /></button>- <button- type="button"- onClick={onCancelMesh}- className="px-2 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ )}++ {/* Live Rotation Angle Badge while dragging rotation handle */}+ {isRotatingMesh && (+ <div+ className="absolute pointer-events-none z-40 px-1.5 py-0.5 rounded bg-[#161616]/95 border border-[#38bdf8]/50 text-[#e5e5e5] font-mono text-[10px] whitespace-nowrap shadow"+ style={{+ left: `${handleX}px`,+ top: `${handleY - 20 * invZoom}px`,+ transform: `translate(-50%, -50%) scale(${(flipX ? -1 : 1) * invZoom}, ${+ (flipY ? -1 : 1) * invZoom+ })`,+ transformOrigin: 'center center',+ }}>- Cancel- </button>- </div>- )}- </>- )}+ {rotationDeg}°+ </div>+ )}++ {/* Floating Mesh Commit / Cancel Action Bar */}+ {mesh.nodes.length > 0 && (+ <div+ onPointerDown={(e) => e.stopPropagation()}+ className="absolute z-40 flex items-center gap-1 px-1.5 py-1 rounded bg-[#181818]/95 border border-white/15 shadow-lg"+ style={{+ left: `${bounds.minX}px`,+ top: `${barTop}px`,+ transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,+ transformOrigin: 'top left',+ }}+ >+ <span className="text-[10px] text-[#8a8a8a] px-1 whitespace-nowrap">+ Mesh ({mesh.cols}×{mesh.rows})+ {selectedIndices.length > 0 ? ` · ${selectedIndices.length} sel` : ''}+ {rotationDeg !== 0 ? ` · ${rotationDeg}°` : ''}+ </span>+ <button+ type="button"+ onClick={onApplyMesh}+ className="px-2 py-0.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer"+ >+ Apply+ </button>+ <button+ type="button"+ onClick={onCancelMesh}+ className="px-2 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ >+ Cancel+ </button>+ </div>+ )}+ </>+ );+ })()}</>);}diff --git a/src/components/Header.tsx b/src/components/Header.tsxindex 7c75700..739b730 100644--- a/src/components/Header.tsx+++ b/src/components/Header.tsx@@ -7,6 +7,7 @@ import {RotateCcw,FlipHorizontal,FlipVertical,+ Contrast,} from 'lucide-react';import {CanvasDimensions,@@ -38,6 +39,8 @@ export interface HeaderProps {onToggleFlipHorizontal?: () => void;onToggleFlipVertical?: () => void;onResetViewFlip?: () => void;+ valueCheckEnabled?: boolean;+ onToggleValueCheck?: () => void;dimensions?: CanvasDimensions;colorMode?: CanvasColorMode;menuSections?: MenuSection[];@@ -76,6 +79,8 @@ export const Header: React.FC<HeaderProps> = React.memo(({onToggleFlipHorizontal,onToggleFlipVertical,onResetViewFlip,+ valueCheckEnabled = false,+ onToggleValueCheck,colorMode = 'color',menuSections,hasOpenDocument = true,@@ -103,6 +108,8 @@ export const Header: React.FC<HeaderProps> = React.memo(({onFlipVertical: onToggleFlipVertical,flipX,flipY,+ onToggleValueCheck,+ valueCheckEnabled,onResetZoom,onResetRotation,hasOpenDocument,@@ -117,6 +124,8 @@ export const Header: React.FC<HeaderProps> = React.memo(({onToggleFlipVertical,flipX,flipY,+ onToggleValueCheck,+ valueCheckEnabled,onResetZoom,onResetRotation,hasOpenDocument,@@ -178,6 +187,19 @@ export const Header: React.FC<HeaderProps> = React.memo(({</span>)}+ {hasOpenDocument && valueCheckEnabled && (+ <button+ type="button"+ onClick={onToggleValueCheck}+ data-testid="header-value-check-badge"+ title="Live 1-Click Value Check (B/W Tone Check) is active — display only, layer colors unchanged. Click or press Shift+Y to return to Color."+ className="h-6 px-1.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] font-mono uppercase text-[var(--accent)] border border-[var(--accent)]/40 flex items-center gap-1 transition-colors cursor-pointer"+ >+ <Contrast className="w-3 h-3" />+ <span>Value B/W</span>+ </button>+ )}+{hasOpenDocument && (flipX || flipY) && (<buttontype="button"@@ -236,13 +258,30 @@ export const Header: React.FC<HeaderProps> = React.memo(({</button></div>- {/* Non-Destructive View Flip Controls (CSP-style Mirror View) */}- {(onToggleFlipHorizontal || onToggleFlipVertical) && (+ {/* Non-Destructive View Flip & 1-Click Value Check Controls */}+ {(onToggleFlipHorizontal || onToggleFlipVertical || onToggleValueCheck) && (<divclassName={`h-6 flex items-center rounded px-0.5 gap-0.5 bg-[#161616] ${!hasOpenDocument ? 'opacity-40 pointer-events-none' : ''}`}>+ {onToggleValueCheck && (+ <button+ type="button"+ data-testid="header-value-check-btn"+ onClick={onToggleValueCheck}+ aria-label="1-Click Value Check (Live B/W)"+ aria-pressed={valueCheckEnabled}+ title="1-Click Value Check (Shift+Y) — Live B/W Tone Check (non-destructive)"+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${+ valueCheckEnabled+ ? 'bg-[#2c2c2c] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Contrast className="w-3.5 h-3.5" />+ </button>+ )}{onToggleFlipHorizontal && (<buttontype="button"diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsxindex 1c57b76..d990bd9 100644--- a/src/components/LeftPanel.tsx+++ b/src/components/LeftPanel.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useEffect, useCallback } from 'react';-import { CspBrush } from '../types/editor';+import { CspBrush, isBrushLikeTool } from '../types/editor';import {loadCustomBrushes,getCachedCustomBrushes,@@ -98,7 +98,7 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(};}, [isDraggingWidth]);- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';+ const isBrushOrEraser = isBrushLikeTool(currentTool);return (<div className="flex h-full select-none z-10 shrink-0 gap-px bg-[#161616]">diff --git a/src/components/LeftSidebar.tsx b/src/components/LeftSidebar.tsxindex 4b2d58f..254c9cf 100644--- a/src/components/LeftSidebar.tsx+++ b/src/components/LeftSidebar.tsx@@ -1,5 +1,5 @@import React, { useEffect } from 'react';-import { Paintbrush, Eraser, ArrowLeftRight, Pipette } from 'lucide-react';+import { Paintbrush, Eraser, ArrowLeftRight, Pipette, Sparkles } from 'lucide-react';import { ToolType } from '../types/editor';import { LiquifyIcon } from './LiquifyIcon';@@ -72,6 +72,23 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({</div></button>+ {/* Decoration Button */}+ <button+ type="button"+ onClick={() => onSelectTool('decoration')}+ title="Decoration Tool"+ className={`w-10 h-10 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${+ currentTool === 'decoration'+ ? 'bg-[#2c2c2c] border border-[#3a3a3a] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'+ }`}+ >+ <Sparkles className="w-5 h-5" />+ <div className="absolute left-12 bg-[#161616] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-[#2c2c2c] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">+ Decoration+ </div>+ </button>+{/* Eraser Button */}<buttontype="button"diff --git a/src/components/Local3DContainer.tsx b/src/components/Local3DContainer.tsxindex fea92cc..3a7b503 100644--- a/src/components/Local3DContainer.tsx+++ b/src/components/Local3DContainer.tsx@@ -26,6 +26,11 @@ import {HumanoidBones,PosePresetName,} from '../utils/mannequin3D';+import {+ createPrimitive3DObject,+ PRIMITIVE_3D_ITEMS,+ Primitive3DType,+} from '../utils/primitives3D';import {BonePoseSnapshot,Camera3DPreset,@@ -47,10 +52,12 @@ import {scene3DBridge,store3DActions,toolStoreActions,+ uiStoreActions,use3DStore,} from '../stores';import { Csp3DToolbar } from './Csp3DToolbar';import { LTExtractionModal, LTPreviewBuffers } from './LTExtractionModal';+import { Primitive3DIcon } from './Primitive3DIcon';import { Upload, Box } from 'lucide-react';export type ShadingMode = Shading3DMode;@@ -126,6 +133,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({const canvasRef = useRef<HTMLCanvasElement | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);const loadedFileKeyRef = useRef<string | null>(null);+ const loadRequestIdRef = useRef<number>(0);const [webglError, setWebglError] = useState<string | null>(null);const [sceneReadyVersion, setSceneReadyVersion] = useState<number>(0);const [isLTModalOpen, setIsLTModalOpen] = useState<boolean>(false);@@ -1475,8 +1483,9 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({(innerContent: THREE.Object3D,displayName: string,- kind: 'imported',- detectedBones: HumanoidBones | null+ kind: 'imported' | 'primitive',+ detectedBones: HumanoidBones | null,+ primitiveType: Primitive3DType | null = null) => {const scene = sceneRef.current;if (!scene) return;@@ -1509,7 +1518,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({mannequinBonesRef.current = null;}- store3DActions.setLoadedModel(displayName, kind, hasBones);+ store3DActions.setLoadedModel(displayName, kind, hasBones, primitiveType);store3DActions.setModelTransform({position: [0, 0, 0],rotation: [0, 0, 0],@@ -1540,13 +1549,30 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({[applyShadingAndStyle, captureSceneSnapshot, syncGizmoAttachment, syncHistoryFlagsToStore]);- // Load 3D model from file (.glb, .gltf, .obj)+ // Create a built-in 3D primitive (cube, sphere, capsule, cylinder, pyramid)+ const createPrimitive = useCallback(+ (type: Primitive3DType) => {+ if (!sceneRef.current) return;+ loadRequestIdRef.current += 1;+ clearCurrentModel();+ const { group, displayName } = createPrimitive3DObject(type);+ attachNormalizedObject(group, displayName, 'primitive', null, type);+ },+ [attachNormalizedObject, clearCurrentModel]+ );++ // Load 3D model from file (.glb, .gltf, .obj) via direct buffer/text parsing (CSP-safe in Tauri & Web)const loadFromFile = useCallback((file: File) => {if (!sceneRef.current) return;const fileName = file.name.toLowerCase();+ const requestId = ++loadRequestIdRef.current;const fitAndAttach = (model: THREE.Group | THREE.Object3D) => {+ if (!sceneRef.current || loadRequestIdRef.current !== requestId) {+ disposeThreeResources(model, null);+ return;+ }clearCurrentModel();const toRemove: THREE.Object3D[] = [];@@ -1600,38 +1626,50 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({normalizedWrapper.add(model);const detectedBones = findHumanoidBones(model);- attachNormalizedObject(normalizedWrapper, file.name, 'imported', detectedBones);+ attachNormalizedObject(normalizedWrapper, file.name, 'imported', detectedBones, null);+ };++ const reportLoadError = (kindLabel: string, err: unknown) => {+ console.error(`[3D] ${kindLabel} load error:`, err);+ if (loadRequestIdRef.current === requestId) {+ uiStoreActions.showToast(`Failed to load 3D model "${file.name}".`);+ }};- const blobUrl = URL.createObjectURL(file);if (fileName.endsWith('.glb') || fileName.endsWith('.gltf')) {const loader = new GLTFLoader();- loader.load(- blobUrl,- (gltf) => {- URL.revokeObjectURL(blobUrl);- fitAndAttach(gltf.scene);- },- undefined,- (err) => {- URL.revokeObjectURL(blobUrl);- console.error('[3D] GLTF load error:', err);- }- );+ const readPromise: Promise<ArrayBuffer | string> = fileName.endsWith('.gltf')+ ? file.text()+ : file.arrayBuffer();+ void readPromise+ .then((data) => {+ if (!sceneRef.current || loadRequestIdRef.current !== requestId) return;+ loader.parse(+ data,+ '',+ (gltf) => {+ fitAndAttach(gltf.scene);+ },+ (err) => {+ reportLoadError('GLTF', err);+ }+ );+ })+ .catch((err) => {+ reportLoadError('GLTF', err);+ });} else if (fileName.endsWith('.obj')) {const loader = new OBJLoader();- loader.load(- blobUrl,- (obj) => {- URL.revokeObjectURL(blobUrl);+ void file+ .text()+ .then((text) => {+ if (!sceneRef.current || loadRequestIdRef.current !== requestId) return;+ const obj = loader.parse(text);fitAndAttach(obj);- },- undefined,- (err) => {- URL.revokeObjectURL(blobUrl);- console.error('[3D] OBJ load error:', err);- }- );+ })+ .catch((err) => {+ reportLoadError('OBJ', err);+ });}},[attachNormalizedObject, clearCurrentModel]@@ -1853,6 +1891,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({if (!isOpen) return;scene3DBridge.triggerFilePicker = () => fileInputRef.current?.click();scene3DBridge.loadFile = loadFromFile;+ scene3DBridge.createPrimitive = createPrimitive;scene3DBridge.applyNumericTransform = applyNumericTransform;scene3DBridge.applyTransformDelta = applyTransformDelta;scene3DBridge.rotateModelYaw = rotateModelYaw;@@ -1876,6 +1915,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({return () => {scene3DBridge.triggerFilePicker = undefined;scene3DBridge.loadFile = undefined;+ scene3DBridge.createPrimitive = undefined;scene3DBridge.applyNumericTransform = undefined;scene3DBridge.applyTransformDelta = undefined;scene3DBridge.rotateModelYaw = undefined;@@ -1898,6 +1938,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({}, [isOpen,loadFromFile,+ createPrimitive,applyNumericTransform,applyTransformDelta,rotateModelYaw,@@ -2232,25 +2273,6 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({e.stopPropagation();}}}- onDragOver={(e) => {- if (!isInteractive) return;- e.preventDefault();- e.stopPropagation();- }}- onDrop={(e) => {- if (!isInteractive) return;- e.preventDefault();- e.stopPropagation();- const file = e.dataTransfer.files?.[0];- if (file) {- const name = file.name.toLowerCase();- if (name.endsWith('.glb') || name.endsWith('.gltf') || name.endsWith('.obj')) {- const fileKey = `${file.name}-${file.size}-${file.lastModified}`;- loadedFileKeyRef.current = fileKey;- loadFromFile(file);- }- }- }}><divref={canvasHostRef}@@ -2283,7 +2305,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({{!webglError && !loadedModelName && is3DToolActive && isReferenceVisible && (<div className="absolute inset-0 flex items-center justify-center pointer-events-none"><div- className="bg-[#202020]/95 border border-white/[0.1] backdrop-blur-md rounded-lg px-5 py-4 flex flex-col items-center space-y-3 pointer-events-auto shadow-2xl text-center w-64"+ className="bg-[#202020]/95 border border-white/[0.1] backdrop-blur-md rounded-lg px-5 py-4 flex flex-col items-center space-y-3 pointer-events-auto shadow-2xl text-center w-72"onPointerDown={(e) => e.stopPropagation()}><div className="w-9 h-9 rounded-md bg-[#161616] border border-white/[0.08] flex items-center justify-center text-[var(--accent)]">@@ -2292,7 +2314,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({<div><p className="text-xs font-medium text-[#e5e5e5]">3D Reference Stage</p><p className="text-[11px] text-[#8a8a8a] mt-1">- Drop a .glb, .gltf, or .obj 3D model here to begin.+ Drag & drop a .glb, .gltf, or .obj model onto the canvas, or create a primitive.</p></div><button@@ -2303,6 +2325,26 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({<Upload className="w-3.5 h-3.5" /><span>Import 3D Model</span></button>+ <div className="w-full pt-2 border-t border-white/[0.08] space-y-1.5">+ <p className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ Create Primitive+ </p>+ <div className="grid grid-cols-5 gap-1">+ {PRIMITIVE_3D_ITEMS.map((item) => (+ <button+ key={item.type}+ type="button"+ onClick={() => createPrimitive(item.type)}+ title={item.description}+ data-testid={`empty-3d-primitive-${item.type}`}+ className="flex flex-col items-center justify-center gap-1 py-1.5 px-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[#cccccc] hover:text-[#e5e5e5] transition-colors cursor-pointer"+ >+ <Primitive3DIcon type={item.type} className="w-4 h-4 text-[var(--accent)]" />+ <span className="text-[9px] leading-none">{item.label}</span>+ </button>+ ))}+ </div>+ </div></div></div>)}@@ -2324,6 +2366,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({onDirectDrag={(mode, dx, dy, snap) => applyTransformDelta(mode, dx, dy, snap)}onDirectDragEnd={commitHistoryNow}onTriggerImport={() => fileInputRef.current?.click()}+ onCreatePrimitive={createPrimitive}onSnapToGround={handleSnapToGround}onUndo={() => {handleUndo3D();diff --git a/src/components/NavigatorPanel.tsx b/src/components/NavigatorPanel.tsxindex 540d1c2..baf085f 100644--- a/src/components/NavigatorPanel.tsx+++ b/src/components/NavigatorPanel.tsx@@ -8,12 +8,27 @@ import {FlipHorizontal,FlipVertical,Compass,+ Contrast,+ Columns2,} from 'lucide-react';import { CanvasDimensions, LayerItem } from '../types/editor';import { ThemePreset } from '../types/settings';+import { NavigatorPreviewMode } from '../types/workspace';import { SparseTileGrid } from '../utils/tileEngine';import { ViewportCompositor } from '../utils/compositor';import { formatRotationDegrees } from '../utils/canvasUtils';+import {+ applyPerceptualGrayscaleToImageData,+ clampNavigatorSplitRatio,+ DEFAULT_NAVIGATOR_SPLIT_RATIO,+} from '../utils/valueCheck';+import {+ documentStoreActions,+ useDocumentStore,+ useToolStore,+ useWorkspaceStore,+ workspaceStoreActions,+} from '../stores';import {CameraTransformState,CanvasNavigationHandle,@@ -22,11 +37,16 @@ import {formatZoomPercent,} from '../hooks/useCanvasNavigation';-export const NAVIGATOR_PREVIEW_THROTTLE_MS = 200;+export const NAVIGATOR_PREVIEW_THROTTLE_MS = 120;const PREVIEW_PADDING = 8;const MAX_PREVIEW_LONG_EDGE = 256;const SLIDER_MAX = 1000;+interface NavigatorDraftCanvasLike extends HTMLCanvasElement {+ __draftHasContent?: boolean;+ __draftVersion?: number;+}+export interface DocPoint {x: number;y: number;@@ -169,6 +189,20 @@ export function computePreviewBoxMetrics(};}+/**+ * Maps a pointer's clientX inside the Navigator preview stage to a clamped [0.05..0.95]+ * Color | B/W split ratio relative to the document thumbnail rectangle.+ */+export function computeNavigatorSplitRatioFromClientX(+ clientX: number,+ stageLeft: number,+ metrics: PreviewBoxMetrics+): number {+ const localX = clientX - stageLeft;+ const rel = (localX - metrics.offsetX) / Math.max(1, metrics.drawW);+ return clampNavigatorSplitRatio(rel);+}+export interface NavigatorPanelProps {viewportRef: React.RefObject<HTMLDivElement | null>;navigation: CanvasNavigationHandle;@@ -189,6 +223,14 @@ export interface NavigatorPanelProps {onResetRotation: () => void;onToggleFlipHorizontal: () => void;onToggleFlipVertical: () => void;+ draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;+ activeLayerId?: string;+ previewMode?: NavigatorPreviewMode;+ onChangePreviewMode?: (mode: NavigatorPreviewMode) => void;+ splitRatio?: number;+ onChangeSplitRatio?: (ratio: number, persist?: boolean) => void;+ valueCheckEnabled?: boolean;+ onToggleValueCheck?: () => void;themePreset?: ThemePreset;throttleMs?: number;}@@ -214,12 +256,62 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(onResetRotation,onToggleFlipHorizontal,onToggleFlipVertical,+ draftCanvasRef,+ activeLayerId,+ previewMode: previewModeProp,+ onChangePreviewMode,+ splitRatio: splitRatioProp,+ onChangeSplitRatio,+ valueCheckEnabled: valueCheckProp,+ onToggleValueCheck,themePreset = 'modern',throttleMs = NAVIGATOR_PREVIEW_THROTTLE_MS,}) => {+ const storePreviewMode = useWorkspaceStore((s) => s.navigatorPreviewMode);+ const storeSplitRatio = useWorkspaceStore((s) => s.navigatorSplitRatio);+ const storeValueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);++ const activePreviewMode: NavigatorPreviewMode = previewModeProp ?? storePreviewMode;+ const activeSplitRatio = clampNavigatorSplitRatio(splitRatioProp ?? storeSplitRatio);+ const isValueCheckEnabled = valueCheckProp ?? storeValueCheckEnabled;++ const handleSelectPreviewMode = useCallback(+ (mode: NavigatorPreviewMode) => {+ if (onChangePreviewMode) {+ onChangePreviewMode(mode);+ } else {+ workspaceStoreActions.setNavigatorPreviewMode(mode);+ }+ },+ [onChangePreviewMode]+ );++ const handleUpdateSplitRatio = useCallback(+ (ratio: number, persist = true) => {+ const clamped = clampNavigatorSplitRatio(ratio);+ if (onChangeSplitRatio) {+ onChangeSplitRatio(clamped, persist);+ } else {+ workspaceStoreActions.setNavigatorSplitRatio(clamped, persist);+ }+ },+ [onChangeSplitRatio]+ );++ const handleToggleValueCheck = useCallback(() => {+ if (onToggleValueCheck) {+ onToggleValueCheck();+ } else {+ documentStoreActions.toggleValueCheck();+ }+ }, [onToggleValueCheck]);const stageRef = useRef<HTMLDivElement | null>(null);const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const colorBufferCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const bwBufferCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const colorGenRef = useRef<number>(0);+ const bwGenRef = useRef<number>(-1);const overlayCanvasRef = useRef<HTMLCanvasElement | null>(null);const zoomSliderRef = useRef<HTMLInputElement | null>(null);const zoomLabelRef = useRef<HTMLSpanElement | null>(null);@@ -230,6 +322,7 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(height: 120,});const [isDraggingFrame, setIsDraggingFrame] = useState(false);+ const [isDraggingSplit, setIsDraggingSplit] = useState(false);const metricsRef = useRef<PreviewBoxMetrics>(computePreviewBoxMetrics(200, 120, dimensions)@@ -241,8 +334,31 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(dimensions,tileGrid,showCheckerboard,+ activeLayerId,+ draftCanvasRef,+ previewMode: activePreviewMode,+ splitRatio: activeSplitRatio,+ });+ latestSceneRef.current = {+ layers,+ dimensions,+ tileGrid,+ showCheckerboard,+ activeLayerId,+ draftCanvasRef,+ previewMode: activePreviewMode,+ splitRatio: activeSplitRatio,+ };++ const splitDragRef = useRef<{+ active: boolean;+ pointerId: number | null;+ latestRatio: number;+ }>({+ active: false,+ pointerId: null,+ latestRatio: activeSplitRatio,});- latestSceneRef.current = { layers, dimensions, tileGrid, showCheckerboard };const dragStateRef = useRef<{active: boolean;@@ -350,32 +466,145 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo([getMainViewportSize, navigation]);- // Throttled low-LOD preview composite (<= 1 render per ~200ms during rapid brush strokes)+ // Throttled low-LOD preview composite (<= 1 render per throttleMs during rapid brush strokes)const lastPreviewTsRef = useRef<number>(0);const lastContentVersionRef = useRef<number>(-1);+ const lastDraftVersionRef = useRef<number>(-1);+ const lastDraftHadContentRef = useRef<boolean>(false);const previewTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const ensureBwBufferSynced = useCallback(+ (colorCanvas: HTMLCanvasElement, targetW: number, targetH: number): HTMLCanvasElement | null => {+ if (typeof document === 'undefined') return null;+ if (!bwBufferCanvasRef.current) {+ bwBufferCanvasRef.current = document.createElement('canvas');+ }+ const bwCanvas = bwBufferCanvasRef.current;+ if (bwCanvas.width !== targetW) bwCanvas.width = targetW;+ if (bwCanvas.height !== targetH) bwCanvas.height = targetH;++ if (bwGenRef.current === colorGenRef.current) {+ return bwCanvas;+ }++ const bwCtx = bwCanvas.getContext('2d', { willReadFrequently: true });+ if (!bwCtx) return null;++ bwCtx.clearRect(0, 0, targetW, targetH);+ bwCtx.drawImage(colorCanvas, 0, 0);+ try {+ const imgData = bwCtx.getImageData(0, 0, targetW, targetH);+ applyPerceptualGrayscaleToImageData(imgData);+ bwCtx.putImageData(imgData, 0, 0);+ } catch {+ // Ignore in headless/mock contexts without getImageData+ }+ bwGenRef.current = colorGenRef.current;+ return bwCanvas;+ },+ []+ );++ const presentPreviewToDisplay = useCallback(+ (overrideMode?: NavigatorPreviewMode, overrideSplitRatio?: number) => {+ const displayCanvas = previewCanvasRef.current;+ const colorCanvas = colorBufferCanvasRef.current;+ if (!displayCanvas || !colorCanvas) return;+ const w = Math.max(1, colorCanvas.width);+ const h = Math.max(1, colorCanvas.height);+ if (displayCanvas.width !== w) displayCanvas.width = w;+ if (displayCanvas.height !== h) displayCanvas.height = h;++ const displayCtx = displayCanvas.getContext('2d');+ if (!displayCtx) return;++ const mode = overrideMode ?? latestSceneRef.current.previewMode;+ const ratio = clampNavigatorSplitRatio(+ overrideSplitRatio ?? latestSceneRef.current.splitRatio+ );++ displayCtx.save();+ displayCtx.setTransform(1, 0, 0, 1, 0, 0);+ displayCtx.clearRect(0, 0, w, h);++ if (mode === 'color') {+ displayCtx.drawImage(colorCanvas, 0, 0);+ } else {+ const bwCanvas = ensureBwBufferSynced(colorCanvas, w, h);+ if (mode === 'bw') {+ displayCtx.drawImage(bwCanvas ?? colorCanvas, 0, 0);+ } else {+ // Split View: Left = Color, Right = Live perceptual B/W tones+ const splitPx = Math.max(0, Math.min(w, Math.round(w * ratio)));+ if (splitPx > 0) {+ displayCtx.drawImage(colorCanvas, 0, 0, splitPx, h, 0, 0, splitPx, h);+ }+ if (splitPx < w) {+ displayCtx.drawImage(+ bwCanvas ?? colorCanvas,+ splitPx,+ 0,+ w - splitPx,+ h,+ splitPx,+ 0,+ w - splitPx,+ h+ );+ }+ }+ }++ displayCtx.restore();+ },+ [ensureBwBufferSynced]+ );+const renderPreviewNow = useCallback(() => {- const canvas = previewCanvasRef.current;- if (!canvas) return;- const { layers: curLayers, dimensions: curDims, tileGrid: curGrid, showCheckerboard: curCheck } =- latestSceneRef.current;+ const displayCanvas = previewCanvasRef.current;+ if (!displayCanvas || typeof document === 'undefined') return;+ const {+ layers: curLayers,+ dimensions: curDims,+ tileGrid: curGrid,+ showCheckerboard: curCheck,+ activeLayerId: curActiveLayerId,+ draftCanvasRef: curDraftRef,+ } = latestSceneRef.current;const docW = Math.max(1, curDims.width);const docH = Math.max(1, curDims.height);const scale = Math.min(1, MAX_PREVIEW_LONG_EDGE / Math.max(docW, docH));const targetW = Math.max(1, Math.round(docW * scale));const targetH = Math.max(1, Math.round(docH * scale));- if (canvas.width !== targetW) canvas.width = targetW;- if (canvas.height !== targetH) canvas.height = targetH;- ViewportCompositor.renderLowResPreview(canvas, curLayers, curDims, curGrid, {+ if (!colorBufferCanvasRef.current) {+ colorBufferCanvasRef.current = document.createElement('canvas');+ }+ const colorCanvas = colorBufferCanvasRef.current;+ if (colorCanvas.width !== targetW) colorCanvas.width = targetW;+ if (colorCanvas.height !== targetH) colorCanvas.height = targetH;++ const draftEl = (curDraftRef?.current as NavigatorDraftCanvasLike | null) ?? null;+ const draftHasContent = Boolean(draftEl && draftEl.__draftHasContent);+ const draftOpacity = useToolStore.getState().brushSettings.opacity ?? 1.0;++ ViewportCompositor.renderLowResPreview(colorCanvas, curLayers, curDims, curGrid, {showCheckerboard: curCheck,+ activeDraftCanvas: draftHasContent ? draftEl : null,+ activeDraftLayerId: draftHasContent ? (curActiveLayerId ?? null) : null,+ activeDraftOpacity: draftOpacity,});++ colorGenRef.current += 1;if (typeof curGrid.getContentVersion === 'function') {lastContentVersionRef.current = curGrid.getContentVersion();}+ lastDraftVersionRef.current = draftEl?.__draftVersion ?? -1;+ lastDraftHadContentRef.current = draftHasContent;lastPreviewTsRef.current = Date.now();- }, []);++ presentPreviewToDisplay();+ }, [presentPreviewToDisplay]);const scheduleThrottledPreview = useCallback(() => {const now = Date.now();@@ -421,14 +650,30 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(scheduleThrottledPreview();}, [layers, dimensions, showCheckerboard, tileGrid, scheduleThrottledPreview]);- // Subscribe to SparseTileGrid changes with 200ms throttle, ignoring draft-only redraw notifications+ // Re-present instantly (0 tile recomposite!) when switching Color / Split / B&W or scrubbing split+ useEffect(() => {+ presentPreviewToDisplay(activePreviewMode, activeSplitRatio);+ }, [activePreviewMode, activeSplitRatio, presentPreviewToDisplay]);++ // Subscribe to SparseTileGrid changes with throttling, including live active-stroke draft updatesuseEffect(() => {lastContentVersionRef.current = -1;const unsub = tileGrid.subscribe(() => {- if (- typeof tileGrid.getContentVersion === 'function' &&- tileGrid.getContentVersion() === lastContentVersionRef.current- ) {+ const contentChanged =+ typeof tileGrid.getContentVersion !== 'function' ||+ tileGrid.getContentVersion() !== lastContentVersionRef.current;++ const draftEl =+ (latestSceneRef.current.draftCanvasRef?.current as NavigatorDraftCanvasLike | null) ??+ null;+ const draftHasContent = Boolean(draftEl && draftEl.__draftHasContent);+ const draftVersion = draftEl?.__draftVersion ?? -1;+ const draftChanged =+ Boolean(draftEl) &&+ ((draftHasContent && draftVersion !== lastDraftVersionRef.current) ||+ (!draftHasContent && lastDraftHadContentRef.current));++ if (!contentChanged && !draftChanged) {return;}scheduleThrottledPreview();@@ -579,7 +824,110 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(navigation.commitCameraState?.();}, [navigation]);+ const handleSplitPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) return;+ e.stopPropagation();+ e.preventDefault();+ const stage = stageRef.current;+ if (!stage) return;+ const rect = stage.getBoundingClientRect();+ const nextRatio = computeNavigatorSplitRatioFromClientX(+ e.clientX,+ rect.left,+ metricsRef.current+ );+ splitDragRef.current = {+ active: true,+ pointerId: e.pointerId,+ latestRatio: nextRatio,+ };+ setIsDraggingSplit(true);+ presentPreviewToDisplay('split', nextRatio);+ handleUpdateSplitRatio(nextRatio, false);+ try {+ e.currentTarget.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore in synthetic pointer events+ }+ },+ [handleUpdateSplitRatio, presentPreviewToDisplay]+ );++ const handleSplitPointerMove = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (!splitDragRef.current.active) return;+ e.stopPropagation();+ const stage = stageRef.current;+ if (!stage) return;+ const rect = stage.getBoundingClientRect();+ const nextRatio = computeNavigatorSplitRatioFromClientX(+ e.clientX,+ rect.left,+ metricsRef.current+ );+ splitDragRef.current.latestRatio = nextRatio;+ presentPreviewToDisplay('split', nextRatio);+ handleUpdateSplitRatio(nextRatio, false);+ },+ [handleUpdateSplitRatio, presentPreviewToDisplay]+ );++ const finishSplitDrag = useCallback(+ (e?: React.PointerEvent<HTMLDivElement>) => {+ if (!splitDragRef.current.active) return;+ e?.stopPropagation();+ const pid = splitDragRef.current.pointerId;+ const finalRatio = splitDragRef.current.latestRatio;+ splitDragRef.current.active = false;+ splitDragRef.current.pointerId = null;+ setIsDraggingSplit(false);+ if (e && pid !== null) {+ try {+ e.currentTarget.releasePointerCapture?.(pid);+ } catch {+ // Ignore in synthetic pointer events+ }+ }+ handleUpdateSplitRatio(finalRatio, true);+ },+ [handleUpdateSplitRatio]+ );++ const handleSplitDoubleClick = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ e.stopPropagation();+ handleUpdateSplitRatio(DEFAULT_NAVIGATOR_SPLIT_RATIO, true);+ },+ [handleUpdateSplitRatio]+ );++ const handleSplitKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'ArrowLeft') {+ e.preventDefault();+ handleUpdateSplitRatio(activeSplitRatio - 0.05, true);+ } else if (e.key === 'ArrowRight') {+ e.preventDefault();+ handleUpdateSplitRatio(activeSplitRatio + 0.05, true);+ } else if (e.key === 'Home') {+ e.preventDefault();+ handleUpdateSplitRatio(0.05, true);+ } else if (e.key === 'End') {+ e.preventDefault();+ handleUpdateSplitRatio(0.95, true);+ } else if (e.key === '0' || e.key === 'Enter') {+ e.preventDefault();+ handleUpdateSplitRatio(DEFAULT_NAVIGATOR_SPLIT_RATIO, true);+ }+ },+ [activeSplitRatio, handleUpdateSplitRatio]+ );+const m = metricsRef.current;+ const splitLineLeft = m.offsetX + m.drawW * activeSplitRatio;+ const splitLeftWidth = m.drawW * activeSplitRatio;+ const splitRightWidth = m.drawW * (1 - activeSplitRatio);const btnBase ='h-5 px-1 rounded text-[10px] flex items-center justify-center text-[#a3a3a3] hover:text-[#f5f5f5] hover:bg-[#2c2c2c] transition-colors cursor-pointer';@@ -591,6 +939,7 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(<divdata-testid="navigator-panel"data-theme-preset={themePreset}+ data-preview-mode={activePreviewMode}className="flex flex-col h-full min-h-0 select-none bg-[#202020] text-[#e5e5e5]">{/* Interactive Canvas Preview Stage */}@@ -602,7 +951,11 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(onPointerUp={finishStageDrag}onPointerCancel={finishStageDrag}className={`relative flex-1 min-h-[76px] overflow-hidden bg-[#141414] ${- isDraggingFrame ? 'cursor-grabbing' : 'cursor-grab'+ isDraggingSplit+ ? 'cursor-ew-resize'+ : isDraggingFrame+ ? 'cursor-grabbing'+ : 'cursor-grab'}`}title="Click or drag red viewport frame to pan canvas">@@ -624,6 +977,94 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(data-testid="navigator-overlay-canvas"className="absolute inset-0 w-full h-full pointer-events-none"/>++ {/* Live B/W Mode Corner Badge */}+ {activePreviewMode === 'bw' && (+ <span+ data-testid="nav-bw-badge"+ className="pointer-events-none absolute top-1.5 left-1.5 z-10 px-1.5 py-0.5 rounded bg-black/70 border border-white/15 text-[9px] font-mono uppercase tracking-wider text-[#e5e5e5]"+ >+ B/W Tone+ </span>+ )}++ {/* Split View (Color | B/W) Interactive Divider & Micro-Labels */}+ {activePreviewMode === 'split' && (+ <>+ {splitLeftWidth >= 28 && (+ <span+ data-testid="nav-split-color-label"+ style={{+ left: `${m.offsetX + 4}px`,+ top: `${m.offsetY + 4}px`,+ }}+ className="pointer-events-none absolute z-10 px-1 py-[1px] rounded bg-black/65 border border-white/10 text-[8px] font-mono uppercase tracking-wider text-[#e5e5e5]"+ >+ CLR+ </span>+ )}+ {splitRightWidth >= 28 && (+ <span+ data-testid="nav-split-bw-label"+ style={{+ right: `${Math.max(4, m.stageW - (m.offsetX + m.drawW) + 4)}px`,+ top: `${m.offsetY + 4}px`,+ }}+ className="pointer-events-none absolute z-10 px-1 py-[1px] rounded bg-black/65 border border-white/10 text-[8px] font-mono uppercase tracking-wider text-[#e5e5e5]"+ >+ B/W+ </span>+ )}+ <div+ role="slider"+ tabIndex={0}+ data-testid="nav-split-handle"+ aria-label="Color and B/W Split Position"+ aria-valuemin={5}+ aria-valuemax={95}+ aria-valuenow={Math.round(activeSplitRatio * 100)}+ onPointerDown={handleSplitPointerDown}+ onPointerMove={handleSplitPointerMove}+ onPointerUp={finishSplitDrag}+ onPointerCancel={finishSplitDrag}+ onDoubleClick={handleSplitDoubleClick}+ onKeyDown={handleSplitKeyDown}+ title="Drag to compare Color | B/W tones (Double-click to center 50%)"+ style={{+ left: `${splitLineLeft}px`,+ top: `${m.offsetY}px`,+ height: `${m.drawH}px`,+ }}+ className="absolute z-20 w-3 -ml-1.5 flex items-center justify-center cursor-ew-resize group focus:outline-none"+ >+ <div className="w-[1.5px] h-full bg-white/85 shadow-[0_0_3px_rgba(0,0,0,0.9)] group-hover:bg-[var(--accent)] transition-colors" />+ <div+ className={`absolute w-3.5 h-3.5 rounded-full flex items-center justify-center border shadow-md transition-transform ${+ isDraggingSplit+ ? 'bg-[var(--accent)] border-white scale-110'+ : 'bg-[#1b1b1b]/95 border-white/80 group-hover:border-[var(--accent)] group-hover:scale-105'+ }`}+ >+ <span className="w-[1px] h-1.5 bg-white/80 mr-[1.5px]" />+ <span className="w-[1px] h-1.5 bg-white/80" />+ </div>+ </div>+ </>+ )}++ {/* Main Canvas Value Check Active Pill */}+ {isValueCheckEnabled && (+ <button+ type="button"+ data-testid="nav-canvas-value-badge"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={handleToggleValueCheck}+ title="Main Canvas Value Check (Live B/W) is ON — Click to return main canvas to Color"+ className="absolute top-1.5 right-1.5 z-20 px-1.5 py-0.5 rounded bg-black/75 hover:bg-black/90 border border-[var(--accent)]/60 text-[9px] font-mono uppercase tracking-wider text-[var(--accent)] cursor-pointer transition-colors"+ >+ Canvas B/W+ </button>+ )}</div>{/* Compact Control Bar */}@@ -686,7 +1127,7 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(type="button"data-testid="nav-zoom-100"onClick={onZoomActualSize}- title="Actual Pixels (100%)"+ title="Reset Zoom to 100% (Ctrl+1)"className={`${btnBase} px-1 font-mono`}>100%@@ -749,6 +1190,73 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(</button></div></div>++ {/* Row 3: Navigator Tone Preview Mode (Color / Split / B/W) + 1-Click Main Canvas Value Check */}+ <div className="flex items-center justify-between gap-1 pt-0.5 border-t border-white/[0.05]">+ <div+ role="group"+ aria-label="Navigator Preview Mode"+ className="flex items-center rounded bg-[#141414] p-[1px] border border-white/[0.06] gap-[1px]"+ >+ <button+ type="button"+ data-testid="nav-mode-color"+ aria-pressed={activePreviewMode === 'color'}+ onClick={() => handleSelectPreviewMode('color')}+ title="Color Navigator Preview"+ className={`h-[18px] px-1.5 rounded-[3px] text-[9px] font-medium transition-colors cursor-pointer ${+ activePreviewMode === 'color'+ ? 'bg-[#2c2c2c] text-white'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Color+ </button>+ <button+ type="button"+ data-testid="nav-mode-split"+ aria-pressed={activePreviewMode === 'split'}+ onClick={() => handleSelectPreviewMode('split')}+ title="Split View — Compare Color & Live B/W Tones in Navigator (Alt+Shift+Y)"+ className={`h-[18px] px-1.5 rounded-[3px] text-[9px] font-medium flex items-center gap-0.5 transition-colors cursor-pointer ${+ activePreviewMode === 'split'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-inset ring-[var(--accent-border)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ <Columns2 className="w-2.5 h-2.5" />+ <span>Split</span>+ </button>+ <button+ type="button"+ data-testid="nav-mode-bw"+ aria-pressed={activePreviewMode === 'bw'}+ onClick={() => handleSelectPreviewMode('bw')}+ title="Live B/W Preview in Navigator — Paint in color on main canvas while monitoring B/W values in real time"+ className={`h-[18px] px-1.5 rounded-[3px] text-[9px] font-mono font-medium transition-colors cursor-pointer ${+ activePreviewMode === 'bw'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-inset ring-[var(--accent-border)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ B/W+ </button>+ </div>++ <button+ type="button"+ data-testid="nav-value-check"+ aria-pressed={isValueCheckEnabled}+ onClick={handleToggleValueCheck}+ title="1-Click Value Check — Toggle Live B/W Tone Check on Main Canvas (Shift+Y)"+ className={`${btnBase} gap-1 px-1.5 font-medium shrink-0 ${+ isValueCheckEnabled ? btnActive : 'bg-[#141414] border border-white/[0.06]'+ }`}+ >+ <Contrast className="w-3 h-3" />+ <span>Value</span>+ </button>+ </div></div></div>);diff --git a/src/components/Primitive3DIcon.tsx b/src/components/Primitive3DIcon.tsxnew file mode 100644index 0000000..aa314d7--- /dev/null+++ b/src/components/Primitive3DIcon.tsx@@ -0,0 +1,54 @@+import React from 'react';+import { Primitive3DType } from '../utils/primitives3D';++interface Primitive3DIconProps {+ type: Primitive3DType;+ className?: string;+}++export const Primitive3DIcon: React.FC<Primitive3DIconProps> = ({+ type,+ className = 'w-3.5 h-3.5',+}) => {+ switch (type) {+ case 'cube':+ return (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">+ <path d="M8 2L13.5 5V11L8 14L2.5 11V5L8 2Z" />+ <path d="M8 8V14" />+ <path d="M8 8L13.5 5" />+ <path d="M8 8L2.5 5" />+ </svg>+ );+ case 'sphere':+ return (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">+ <circle cx="8" cy="8" r="5.5" />+ <ellipse cx="8" cy="8" rx="5.5" ry="2.2" />+ <ellipse cx="8" cy="8" rx="2.4" ry="5.5" />+ </svg>+ );+ case 'capsule':+ return (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">+ <rect x="4.5" y="2" width="7" height="12" rx="3.5" />+ <path d="M4.5 6.2C5.6 6.9 10.4 6.9 11.5 6.2" />+ <path d="M4.5 9.8C5.6 10.5 10.4 10.5 11.5 9.8" />+ </svg>+ );+ case 'cylinder':+ return (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">+ <ellipse cx="8" cy="4" rx="4.5" ry="1.8" />+ <path d="M3.5 4V12C3.5 13 5.5 13.8 8 13.8C10.5 13.8 12.5 13 12.5 12V4" />+ </svg>+ );+ case 'pyramid':+ return (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">+ <path d="M8 2.2L13.6 11.6L8 13.8L2.4 11.6L8 2.2Z" />+ <path d="M8 2.2V13.8" />+ </svg>+ );+ }+};diff --git a/src/components/QuickAccessPanel.tsx b/src/components/QuickAccessPanel.tsxindex c945525..720a7d6 100644--- a/src/components/QuickAccessPanel.tsx+++ b/src/components/QuickAccessPanel.tsx@@ -23,17 +23,14 @@ import {Palette,PenTool,Shapes,+ Sparkles,} from 'lucide-react';-import { ToolType } from '../types/editor';+import { ToolType, isPaintTool } from '../types/editor';import { ThemePreset } from '../types/settings';import { COMMAND_CATALOG, CommandActionId, QuickAccessItem } from '../types/workspace';-import { BUILTIN_BRUSHES } from '../utils/presetBrushes';-import {- NEUTRAL_BRUSH_DEFAULTS,- getEffectiveBrushSettings,- migrateLegacyPresetId,- saveActivePresetId,-} from '../utils/brushPresetManager';+import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';+import { migrateLegacyPresetId } from '../utils/brushPresetManager';+import { activateSubToolPreset } from '../utils/subToolNavigation';import {toolStoreActions,useToolStore,@@ -51,6 +48,7 @@ import { LiquifyIcon } from './LiquifyIcon';const QUICK_TOOL_CATALOG: Array<{ id: ToolType; label: string }> = [{ id: 'brush', label: 'Brush' },+ { id: 'decoration', label: 'Decoration' },{ id: 'eraser', label: 'Eraser' },{ id: 'pipette', label: 'Eyedropper' },{ id: 'liquify', label: 'Liquify' },@@ -72,6 +70,8 @@ function renderToolIcon(tool: ToolType): React.ReactNode {switch (tool) {case 'brush':return <Paintbrush className={cls} />;+ case 'decoration':+ return <Sparkles className={cls} />;case 'eraser':return <Eraser className={cls} />;case 'pipette':@@ -118,6 +118,7 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({const items = useWorkspaceStore((s) => s.quickAccessItems);const viewMode = useWorkspaceStore((s) => s.quickAccessViewMode);const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const quickBrushPanelVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);const activeTool = useToolStore((s) => s.tool);const primaryColor = useToolStore((s) => s.primaryColor);@@ -142,15 +143,7 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({return;}if (item.kind === 'brush' && item.brushPresetId) {- const resolvedPresetId = migrateLegacyPresetId(item.brushPresetId);- toolStoreActions.selectTool('brush');- saveActivePresetId(resolvedPresetId);- const effective = getEffectiveBrushSettings(resolvedPresetId);- toolStoreActions.updateBrushSettings({- ...NEUTRAL_BRUSH_DEFAULTS,- ...effective,- preset: resolvedPresetId,- });+ activateSubToolPreset(item.brushPresetId);}};@@ -272,12 +265,12 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({const active =(item.kind === 'command' &&item.commandId &&- isCommandActive(item.commandId, handlers, palettesHidden)) ||+ isCommandActive(item.commandId, handlers, palettesHidden, quickBrushPanelVisible)) ||(item.kind === 'tool' && item.toolId === activeTool) ||(item.kind === 'brush' &&item.brushPresetId &&migrateLegacyPresetId(item.brushPresetId) === activePresetId &&- activeTool === 'brush') ||+ isPaintTool(activeTool)) ||(item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase());return (@@ -322,12 +315,12 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({!isEditing &&((item.kind === 'command' &&item.commandId &&- isCommandActive(item.commandId, handlers, palettesHidden)) ||+ isCommandActive(item.commandId, handlers, palettesHidden, quickBrushPanelVisible)) ||(item.kind === 'tool' && item.toolId === activeTool) ||(item.kind === 'brush' &&item.brushPresetId &&migrateLegacyPresetId(item.brushPresetId) === activePresetId &&- activeTool === 'brush') ||+ isPaintTool(activeTool)) ||(item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase()));return (@@ -479,7 +472,7 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({))}{addTab === 'brush' &&- BUILTIN_BRUSHES.map((b) => (+ ALL_BUILTIN_BRUSHES.map((b) => (<buttonkey={b.id}type="button"diff --git a/src/components/QuickBrushPanel.tsx b/src/components/QuickBrushPanel.tsxnew file mode 100644index 0000000..84925d7--- /dev/null+++ b/src/components/QuickBrushPanel.tsx@@ -0,0 +1,878 @@+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import {+ ArrowDown,+ ArrowLeft,+ ArrowRight,+ ArrowUp,+ Eye,+ EyeOff,+ Lock,+ Plus,+ Sliders,+ SlidersHorizontal,+ Trash2,+ Unlock,+ X,+} from 'lucide-react';+import { BrushPresetId, CspBrush, isPaintTool } from '../types/editor';+import { QuickBrushTileSize } from '../types/workspace';+import { migrateLegacyPresetId } from '../utils/brushPresetManager';+import {+ uiStoreActions,+ useToolStore,+ useWorkspaceStore,+ workspaceStoreActions,+} from '../stores';+import {+ DND_BRUSH_MIME,+ DND_QUICK_BRUSH_REORDER_MIME,+ ResolvedQuickBrush,+ activateQuickBrush,+ clampQuickBrushPosition,+ getCategoryAccentStyle,+ resolveQuickBrush,+} from '../utils/quickBrushUtils';+import { BrushPreview } from './BrushPreview';+import { QuickBrushPanelSettings } from './QuickBrushPanelSettings';++export interface QuickBrushPanelProps {+ customBrushes: CspBrush[];+}++interface TileDimensions {+ width: number;+ height: number;+ iconSize: number;+ strokeWidth: number;+ strokeHeight: number;+}++function getTileDimensions(tileSize: QuickBrushTileSize, showNames: boolean): TileDimensions {+ if (tileSize === 'compact') {+ return showNames+ ? { width: 56, height: 50, iconSize: 24, strokeWidth: 46, strokeHeight: 24 }+ : { width: 40, height: 40, iconSize: 24, strokeWidth: 32, strokeHeight: 26 };+ }+ if (tileSize === 'large') {+ return showNames+ ? { width: 84, height: 74, iconSize: 42, strokeWidth: 70, strokeHeight: 38 }+ : { width: 58, height: 58, iconSize: 38, strokeWidth: 48, strokeHeight: 38 };+ }+ // medium (default — closely matches the sleek reference proportions)+ return showNames+ ? { width: 68, height: 60, iconSize: 32, strokeWidth: 56, strokeHeight: 30 }+ : { width: 48, height: 48, iconSize: 30, strokeWidth: 38, strokeHeight: 30 };+}++/** 6-dot drag grip icon matching the subtle tactile grip in vertical & horizontal floating bars */+const GripDotsIcon: React.FC<{ orientation: 'vertical' | 'horizontal'; locked: boolean }> = ({+ orientation,+ locked,+}) => {+ const dots =+ orientation === 'vertical'+ ? [+ [2, 2],+ [6, 2],+ [10, 2],+ [2, 6],+ [6, 6],+ [10, 6],+ ]+ : [+ [2, 2],+ [6, 2],+ [2, 6],+ [6, 6],+ [2, 10],+ [6, 10],+ ];+ const vb = orientation === 'vertical' ? '0 0 12 8' : '0 0 8 12';+ const w = orientation === 'vertical' ? 12 : 8;+ const h = orientation === 'vertical' ? 8 : 12;++ return (+ <svg+ width={w}+ height={h}+ viewBox={vb}+ aria-hidden="true"+ className={locked ? 'opacity-30' : 'opacity-65 group-hover:opacity-100 transition-opacity'}+ >+ {dots.map(([cx, cy], i) => (+ <circle key={i} cx={cx} cy={cy} r="1.05" fill="currentColor" />+ ))}+ </svg>+ );+};++/** Crisp white brush tip dab thumbnail matching the reference quick-brush aesthetic */+const BrushTipThumbnail: React.FC<{+ brush: ResolvedQuickBrush;+ size: number;+}> = React.memo(({ brush, size }) => {+ const gradId = useId();++ if (brush.tipDataUrl) {+ const scaleX = brush.thicknessVertical ? Math.max(0.28, Math.min(1, brush.thickness)) : 1;+ const scaleY = !brush.thicknessVertical ? Math.max(0.28, Math.min(1, brush.thickness)) : 1;+ const transformParts: string[] = [];+ if (brush.angle) transformParts.push(`rotate(${brush.angle}deg)`);+ if (scaleX !== 1 || scaleY !== 1) transformParts.push(`scale(${scaleX}, ${scaleY})`);++ return (+ <img+ src={brush.tipDataUrl}+ alt=""+ draggable={false}+ style={{+ width: size,+ height: size,+ transform: transformParts.length > 0 ? transformParts.join(' ') : undefined,+ }}+ className={`object-contain pointer-events-none select-none ${+ brush.isColorTip ? '' : 'drop-shadow-[0_1px_2px_rgba(0,0,0,0.45)]'+ }`}+ />+ );+ }++ // Analytical SVG dab for brushes without a bitmap tip (e.g. G-Pen, Dot Pen, Soft Glaze Airbrush, Velvet Blend, Eraser)+ const clampedHardness = Math.max(0, Math.min(1, brush.hardness));+ const rx = brush.thicknessVertical ? Math.max(12, Math.round(42 * Math.min(1, brush.thickness))) : 42;+ const ry = !brush.thicknessVertical ? Math.max(12, Math.round(42 * Math.min(1, brush.thickness))) : 42;+ const isSoft = clampedHardness < 0.9;+ const coreStop = Math.round(clampedHardness * 78);++ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 100 100"+ aria-hidden="true"+ className="pointer-events-none select-none overflow-visible"+ >+ {isSoft && (+ <defs>+ <radialGradient id={gradId} cx="50%" cy="50%" r="50%">+ <stop offset="0%" stopColor="#ffffff" stopOpacity="1" />+ <stop offset={`${coreStop}%`} stopColor="#ffffff" stopOpacity="0.92" />+ <stop+ offset={`${Math.min(98, coreStop + Math.round((100 - coreStop) * 0.52))}%`}+ stopColor="#ffffff"+ stopOpacity="0.34"+ />+ <stop offset="100%" stopColor="#ffffff" stopOpacity="0" />+ </radialGradient>+ </defs>+ )}+ <g transform={brush.angle ? `rotate(${brush.angle} 50 50)` : undefined}>+ <ellipse+ cx="50"+ cy="50"+ rx={rx}+ ry={ry}+ fill={isSoft ? `url(#${gradId})` : '#ffffff'}+ stroke={brush.isEraser ? 'rgba(229, 138, 163, 0.9)' : undefined}+ strokeWidth={brush.isEraser ? 5 : undefined}+ strokeDasharray={brush.isEraser ? '9 6' : undefined}+ />+ </g>+ </svg>+ );+});+BrushTipThumbnail.displayName = 'BrushTipThumbnail';++export const QuickBrushPanel: React.FC<QuickBrushPanelProps> = React.memo(({ customBrushes }) => {+ const config = useWorkspaceStore((s) => s.quickBrushPanel);+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);+ const activeTool = useToolStore((s) => s.tool);+ const activePresetId = useToolStore((s) => s.activePresetId);++ const panelRef = useRef<HTMLDivElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const settingsBtnRef = useRef<HTMLButtonElement>(null);+ const contextMenuRef = useRef<HTMLDivElement>(null);++ const [isDraggingPanel, setIsDraggingPanel] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [settingsInitialTab, setSettingsInitialTab] = useState<'settings' | 'brushes'>('settings');+ const [isDropTargetOver, setIsDropTargetOver] = useState(false);+ const [draggedTileId, setDraggedTileId] = useState<BrushPresetId | null>(null);+ const [dragOverTileId, setDragOverTileId] = useState<BrushPresetId | null>(null);+ const [tileContextMenu, setTileContextMenu] = useState<{+ brush: ResolvedQuickBrush;+ index: number;+ x: number;+ y: number;+ } | null>(null);++ const isShouldRender =+ config.visible && (!palettesHidden || config.keepVisibleWhenPalettesHidden);++ const resolvedBrushes = useMemo(+ () =>+ config.brushIds+ .map((id) => resolveQuickBrush(id, customBrushes))+ .filter((b): b is ResolvedQuickBrush => b !== null),+ [config.brushIds, customBrushes]+ );++ const tileDim = useMemo(+ () => getTileDimensions(config.tileSize, config.showNames),+ [config.tileSize, config.showNames]+ );++ // Close settings or tile context menu if panel hides+ useEffect(() => {+ if (!isShouldRender) {+ setSettingsOpen(false);+ setTileContextMenu(null);+ }+ }, [isShouldRender]);++ // Keep custom-positioned floating bar clamped inside viewport on window resize or orientation change+ useEffect(() => {+ if (!isShouldRender || !config.position) return;+ const clampNow = () => {+ const el = panelRef.current;+ const curPos = useWorkspaceStore.getState().quickBrushPanel.position;+ if (!el || !curPos) return;+ const rect = el.getBoundingClientRect();+ const clamped = clampQuickBrushPosition(curPos.x, curPos.y, rect.width, rect.height);+ if (clamped.x !== curPos.x || clamped.y !== curPos.y) {+ workspaceStoreActions.setQuickBrushPanelPosition(clamped, false);+ }+ };+ const raf = requestAnimationFrame(clampNow);+ window.addEventListener('resize', clampNow);+ return () => {+ cancelAnimationFrame(raf);+ window.removeEventListener('resize', clampNow);+ };+ }, [+ isShouldRender,+ config.position,+ config.orientation,+ config.columns,+ config.tileSize,+ resolvedBrushes.length,+ ]);++ // Close tile context menu on outside click / Escape+ useEffect(() => {+ if (!tileContextMenu) return;+ const handleOutside = (e: MouseEvent) => {+ if (contextMenuRef.current?.contains(e.target as Node)) return;+ setTileContextMenu(null);+ };+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') setTileContextMenu(null);+ };+ window.addEventListener('mousedown', handleOutside);+ window.addEventListener('keydown', handleKey);+ return () => {+ window.removeEventListener('mousedown', handleOutside);+ window.removeEventListener('keydown', handleKey);+ };+ }, [tileContextMenu]);++ const handleStartPanelDrag = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0 || config.locked) return;+ const el = panelRef.current;+ if (!el) return;++ e.preventDefault();+ e.stopPropagation();++ const rect = el.getBoundingClientRect();+ const startX = e.clientX;+ const startY = e.clientY;+ const origX = rect.left;+ const origY = rect.top;+ const panelW = rect.width;+ const panelH = rect.height;+ let moved = false;++ const onMove = (ev: PointerEvent) => {+ const dx = ev.clientX - startX;+ const dy = ev.clientY - startY;+ if (!moved) {+ if (Math.hypot(dx, dy) < 4) return;+ moved = true;+ setIsDraggingPanel(true);+ setSettingsOpen(false);+ setTileContextMenu(null);+ }+ const nextPos = clampQuickBrushPosition(origX + dx, origY + dy, panelW, panelH);+ workspaceStoreActions.setQuickBrushPanelPosition(nextPos, false);+ };++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ setIsDraggingPanel(false);+ };++ const onUp = (ev: PointerEvent) => {+ const wasMoved = moved;+ cleanup();+ if (wasMoved) {+ const finalPos = clampQuickBrushPosition(+ origX + (ev.clientX - startX),+ origY + (ev.clientY - startY),+ panelW,+ panelH+ );+ workspaceStoreActions.setQuickBrushPanelPosition(finalPos, true);+ }+ };++ const onCancel = () => {+ cleanup();+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ },+ [config.locked]+ );++ const handleDropOnPanel = useCallback(+ (e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setIsDropTargetOver(false);+ setDragOverTileId(null);+ if (config.locked) return;++ const incomingBrushId = e.dataTransfer.getData(DND_BRUSH_MIME);+ if (incomingBrushId) {+ const resolved = resolveQuickBrush(incomingBrushId, customBrushes);+ const added = workspaceStoreActions.addQuickBrush(incomingBrushId);+ if (added) {+ uiStoreActions.showToast(`Added "${resolved?.name || 'Brush'}" to Quick Brushes`);+ } else {+ uiStoreActions.showToast(`"${resolved?.name || 'Brush'}" is already in Quick Brushes`);+ }+ }+ setDraggedTileId(null);+ },+ [config.locked, customBrushes]+ );++ const handleOpenSettings = (tab: 'settings' | 'brushes' = 'settings') => {+ setTileContextMenu(null);+ if (settingsOpen && settingsInitialTab === tab) {+ setSettingsOpen(false);+ } else {+ setSettingsInitialTab(tab);+ setSettingsOpen(true);+ }+ };++ if (!isShouldRender) return null;++ const isHorizontal = config.orientation === 'horizontal';+ const isFixed = config.position !== null;+ const activeNormalizedPreset = migrateLegacyPresetId(activePresetId);++ const containerPositionStyle: React.CSSProperties = isFixed+ ? {+ position: 'fixed',+ left: config.position!.x,+ top: config.position!.y,+ zIndex: isDraggingPanel ? 49 : 44,+ }+ : {+ zIndex: 36,+ };++ const autoAnchorClass = isFixed+ ? ''+ : isHorizontal+ ? `${showStatusBar ? 'bottom-9' : 'bottom-3'} absolute left-1/2 -translate-x-1/2`+ : 'absolute right-3 top-1/2 -translate-y-1/2';++ const gridStyle: React.CSSProperties = isHorizontal+ ? {+ display: 'grid',+ gridAutoFlow: 'column',+ gridTemplateRows: `repeat(${config.columns}, ${tileDim.height}px)`,+ gridAutoColumns: `${tileDim.width}px`,+ gap: '5px',+ }+ : {+ display: 'grid',+ gridTemplateColumns: `repeat(${config.columns}, ${tileDim.width}px)`,+ gap: '5px',+ };++ const controlButtons = (+ <>+ <button+ type="button"+ data-testid="quick-brush-lock-btn"+ onClick={() => {+ const locked = workspaceStoreActions.toggleQuickBrushPanelLocked();+ uiStoreActions.showToast(+ locked ? 'Quick Brush Panel locked' : 'Quick Brush Panel unlocked'+ );+ }}+ title={config.locked ? 'Unlock Quick Brush Panel' : 'Lock Panel Position & Brushes'}+ aria-label={config.locked ? 'Unlock Quick Brush Panel' : 'Lock Quick Brush Panel'}+ aria-pressed={config.locked}+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${+ config.locked+ ? 'text-[var(--accent)] bg-white/[0.1]'+ : 'text-[#a8a8a8] hover:text-white hover:bg-white/[0.08]'+ }`}+ >+ {config.locked ? <Lock className="w-3.5 h-3.5" /> : <Unlock className="w-3.5 h-3.5" />}+ </button>++ <button+ ref={settingsBtnRef}+ type="button"+ data-testid="quick-brush-settings-btn"+ onClick={() => handleOpenSettings('settings')}+ title="Quick Brush Panel Settings"+ aria-label="Quick Brush Panel Settings"+ aria-expanded={settingsOpen}+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${+ settingsOpen+ ? 'text-[var(--accent)] bg-white/[0.1]'+ : 'text-[#a8a8a8] hover:text-white hover:bg-white/[0.08]'+ }`}+ >+ <SlidersHorizontal className="w-3.5 h-3.5" />+ </button>++ <button+ type="button"+ data-testid="quick-brush-close-btn"+ onClick={() => {+ setSettingsOpen(false);+ workspaceStoreActions.setQuickBrushPanelVisible(false);+ uiStoreActions.showToast('Quick Brush Panel hidden (Shift+B to reopen)');+ }}+ title="Hide Quick Brush Panel (Shift+B)"+ aria-label="Hide Quick Brush Panel"+ className="w-6 h-6 rounded flex items-center justify-center text-[#a8a8a8] hover:text-white hover:bg-white/[0.08] transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>++ {config.showHideUiButton && (+ <button+ type="button"+ data-testid="quick-brush-hide-ui-btn"+ onClick={() => workspaceStoreActions.togglePalettesHidden()}+ title={palettesHidden ? 'Show All Palettes (Tab)' : 'Hide All Other Palettes (Tab)'}+ aria-label={palettesHidden ? 'Show All Palettes' : 'Hide All Other Palettes'}+ aria-pressed={palettesHidden}+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${+ palettesHidden+ ? 'text-[var(--accent)] bg-white/[0.1]'+ : 'text-[#a8a8a8] hover:text-white hover:bg-white/[0.08]'+ }`}+ >+ {palettesHidden ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}+ </button>+ )}+ </>+ );++ const panelElement = (+ <div+ ref={panelRef}+ data-testid="quick-brush-panel"+ data-orientation={config.orientation}+ data-locked={String(config.locked)}+ role="toolbar"+ aria-label="Quick-Access Brush Panel"+ onPointerDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ onDragOver={(e) => {+ if (config.locked) return;+ if (+ e.dataTransfer.types.includes(DND_BRUSH_MIME) ||+ e.dataTransfer.types.includes(DND_QUICK_BRUSH_REORDER_MIME)+ ) {+ e.preventDefault();+ e.dataTransfer.dropEffect = e.dataTransfer.types.includes(DND_BRUSH_MIME) ? 'copy' : 'move';+ if (e.dataTransfer.types.includes(DND_BRUSH_MIME)) {+ setIsDropTargetOver(true);+ }+ }+ }}+ onDragLeave={(e) => {+ if (!panelRef.current?.contains(e.relatedTarget as Node)) {+ setIsDropTargetOver(false);+ setDragOverTileId(null);+ }+ }}+ onDrop={handleDropOnPanel}+ style={{+ ...containerPositionStyle,+ backgroundColor: `rgba(28, 28, 28, ${config.opacity})`,+ backdropFilter: 'blur(10px)',+ }}+ className={`${autoAnchorClass} pointer-events-auto flex ${+ isHorizontal ? 'flex-row items-center px-1.5 py-1.5' : 'flex-col items-center px-1.5 py-1.5'+ } rounded-[10px] border transition-[border-color,box-shadow] select-none shadow-[0_12px_34px_rgba(0,0,0,0.72)] ${+ isDropTargetOver+ ? 'border-[var(--accent)] ring-2 ring-[var(--accent)]/40'+ : isDraggingPanel+ ? 'border-white/[0.25]'+ : 'border-white/[0.12]'+ }`}+ >+ {/* Drag Handle (+ rotated title in Horizontal mode matching reference layout) */}+ <div+ data-testid="quick-brush-drag-handle"+ onPointerDown={handleStartPanelDrag}+ onDoubleClick={() => {+ if (!config.locked) {+ workspaceStoreActions.toggleQuickBrushPanelOrientation();+ }+ }}+ title={+ config.locked+ ? 'Panel locked — unlock to drag or flip orientation'+ : 'Drag to move panel • Double-click to flip Vertical / Horizontal'+ }+ className={`group flex items-center justify-center shrink-0 text-[#9c9c9c] ${+ config.locked ? 'cursor-default' : 'cursor-grab active:cursor-grabbing hover:text-[#e5e5e5]'+ } ${+ isHorizontal+ ? 'flex-col gap-1 pr-1.5 py-0.5 self-stretch min-w-[20px]'+ : 'flex-row w-full pb-1.5 pt-0.5'+ }`}+ >+ <GripDotsIcon orientation={config.orientation} locked={config.locked} />+ {isHorizontal && config.showTitle && config.title.trim().length > 0 && (+ <span+ data-testid="quick-brush-title-label"+ style={{ writingMode: 'vertical-rl' }}+ className="text-[10px] font-medium tracking-wide text-[#9e9e9e] max-h-[40px] overflow-hidden text-ellipsis whitespace-nowrap leading-none"+ >+ {config.title}+ </span>+ )}+ </div>++ {/* Brush Tiles List / Grid */}+ <div+ ref={scrollRef}+ onWheel={(e) => {+ if (isHorizontal && scrollRef.current && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {+ scrollRef.current.scrollLeft += e.deltaY;+ }+ }}+ className={+ isHorizontal+ ? 'overflow-x-auto overflow-y-hidden no-scrollbar max-w-[calc(100vw-160px)]'+ : 'overflow-y-auto overflow-x-hidden no-scrollbar max-h-[calc(100vh-160px)]'+ }+ >+ {resolvedBrushes.length === 0 ? (+ <button+ type="button"+ data-testid="quick-brush-empty-add-btn"+ onClick={() => handleOpenSettings('brushes')}+ style={{ width: Math.max(tileDim.width, 64), height: tileDim.height }}+ className="rounded-lg border border-dashed border-white/[0.18] bg-[#222222]/80 hover:bg-[#2c2c2c] text-[#9a9a9a] hover:text-white flex flex-col items-center justify-center gap-1 text-[10px] cursor-pointer transition-colors"+ title="Add brushes to Quick-Access Brush Panel"+ >+ <Plus className="w-4 h-4 text-[var(--accent)]" />+ <span>Add</span>+ </button>+ ) : (+ <div style={gridStyle}>+ {resolvedBrushes.map((brush, index) => {+ const isSelected = brush.isEraser+ ? activeTool === 'eraser'+ : isPaintTool(activeTool) &&+ migrateLegacyPresetId(brush.id) === activeNormalizedPreset;+ const accent = config.showCategoryColors+ ? getCategoryAccentStyle(brush.category)+ : { barColor: null, cardTint: null, label: '' };+ const isBeingDragged = draggedTileId === brush.id;+ const isDragTarget = dragOverTileId === brush.id && draggedTileId !== brush.id;++ const cardBg = isSelected+ ? 'rgba(66, 72, 75, 0.96)'+ : accent.cardTint+ ? `linear-gradient(0deg, ${accent.cardTint}, ${accent.cardTint}), rgba(32, 32, 32, 0.92)`+ : 'rgba(32, 32, 32, 0.92)';++ return (+ <div+ key={brush.id}+ data-testid={`quick-brush-tile-${brush.id}`}+ data-selected={String(isSelected)}+ draggable={!config.locked}+ onDragStart={(e) => {+ if (config.locked) return;+ e.stopPropagation();+ e.dataTransfer.setData(DND_QUICK_BRUSH_REORDER_MIME, brush.id);+ e.dataTransfer.effectAllowed = 'move';+ setDraggedTileId(brush.id);+ }}+ onDragOver={(e) => {+ if (config.locked) return;+ if (e.dataTransfer.types.includes(DND_QUICK_BRUSH_REORDER_MIME)) {+ e.preventDefault();+ e.stopPropagation();+ e.dataTransfer.dropEffect = 'move';+ setDragOverTileId(brush.id);+ }+ }}+ onDrop={(e) => {+ if (config.locked) return;+ const reorderedId = e.dataTransfer.getData(DND_QUICK_BRUSH_REORDER_MIME);+ if (reorderedId) {+ e.preventDefault();+ e.stopPropagation();+ workspaceStoreActions.reorderQuickBrush(reorderedId, brush.id);+ setDraggedTileId(null);+ setDragOverTileId(null);+ }+ }}+ onDragEnd={() => {+ setDraggedTileId(null);+ setDragOverTileId(null);+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setSettingsOpen(false);+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ setTileContextMenu({+ brush,+ index,+ x: Math.max(8, Math.min(vw - 176, e.clientX)),+ y: Math.max(40, Math.min(vh - 150, e.clientY)),+ });+ }}+ onClick={() => {+ void activateQuickBrush(brush, customBrushes);+ }}+ role="button"+ tabIndex={0}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ void activateQuickBrush(brush, customBrushes);+ }+ }}+ title={brush.desc ? `${brush.name} — ${brush.desc}` : brush.name}+ style={{+ width: tileDim.width,+ height: tileDim.height,+ background: cardBg,+ }}+ className={`group relative rounded-[7px] flex flex-col items-center justify-center overflow-hidden transition-all cursor-pointer border ${+ isDragTarget+ ? 'border-[var(--accent)] ring-1 ring-[var(--accent)]'+ : isSelected+ ? 'border-[var(--accent)] ring-1 ring-[var(--accent)]/60 shadow-[0_0_0_1px_rgba(255,255,255,0.12)_inset]'+ : 'border-white/[0.08] hover:border-white/[0.22]'+ } ${isBeingDragged ? 'opacity-45' : 'opacity-100'}`}+ >+ {/* Subtle Category Left Accent Bar (like Blend purple / Natural Paint teal) */}+ {accent.barColor && (+ <span+ aria-hidden="true"+ style={{ backgroundColor: accent.barColor }}+ className="absolute left-[3px] top-[5px] bottom-[5px] w-[2.5px] rounded-full opacity-90 pointer-events-none"+ />+ )}++ {/* Brush Preview (Tip Dab or S-Curve Stroke) */}+ <div+ className={`flex items-center justify-center w-full ${+ config.showNames ? 'flex-1 min-h-0 pt-1 px-1.5' : 'h-full p-1.5'+ }`}+ >+ {config.previewStyle === 'stroke' ? (+ <BrushPreview+ preset={brush.id}+ settings={brush.previewSettings}+ tool={brush.isEraser ? 'eraser' : 'brush'}+ strokeColor="#ffffff"+ width={tileDim.strokeWidth}+ height={tileDim.strokeHeight}+ />+ ) : (+ <BrushTipThumbnail brush={brush} size={tileDim.iconSize} />+ )}+ </div>++ {/* Truncated Brush Name */}+ {config.showNames && (+ <span+ className={`w-full px-1 pb-1 text-center text-[10px] leading-[1.15] truncate pointer-events-none ${+ isSelected ? 'text-white font-medium' : 'text-[#dedede]'+ }`}+ >+ {brush.name}+ </span>+ )}++ {/* Subtle hover remove badge when unlocked */}+ {!config.locked && (+ <button+ type="button"+ data-testid={`quick-brush-remove-${brush.id}`}+ onClick={(e) => {+ e.stopPropagation();+ workspaceStoreActions.removeQuickBrush(brush.id);+ uiStoreActions.showToast(`Removed "${brush.name}" from Quick Brushes`);+ }}+ title={`Remove ${brush.name}`}+ aria-label={`Remove ${brush.name} from Quick Brushes`}+ className="opacity-0 group-hover:opacity-100 focus:opacity-100 absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full bg-black/70 hover:bg-rose-500/90 text-[#cccccc] hover:text-white flex items-center justify-center transition-opacity cursor-pointer"+ >+ <X className="w-2.5 h-2.5" />+ </button>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Control Buttons Cluster: Lock, Settings, Close (+ optional Hide UI) */}+ <div+ className={+ isHorizontal+ ? 'grid grid-cols-2 gap-0.5 pl-1.5 items-center justify-items-center shrink-0'+ : 'flex items-center justify-center gap-0.5 pt-1.5 shrink-0 flex-wrap'+ }+ >+ {controlButtons}+ </div>++ {/* Settings Popover (Portaled to document.body) */}+ {settingsOpen && (+ <QuickBrushPanelSettings+ anchorRef={settingsBtnRef}+ initialTab={settingsInitialTab}+ customBrushes={customBrushes}+ onClose={() => setSettingsOpen(false)}+ />+ )}++ {/* Right-Click Context Menu for Individual Brush Tiles */}+ {tileContextMenu &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ ref={contextMenuRef}+ data-testid="quick-brush-tile-context-menu"+ style={{+ position: 'fixed',+ left: tileContextMenu.x,+ top: tileContextMenu.y,+ zIndex: 1000,+ }}+ onPointerDown={(e) => e.stopPropagation()}+ className="w-44 rounded-md bg-[#202020] border border-white/[0.12] shadow-2xl p-1 text-[11px] text-[#e5e5e5] select-none"+ >+ <div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate">+ {tileContextMenu.brush.name}+ </div>+ <div className="my-0.5 h-px bg-white/[0.08]" />++ {!tileContextMenu.brush.isEraser && (+ <button+ type="button"+ onClick={async () => {+ const target = tileContextMenu.brush;+ setTileContextMenu(null);+ await activateQuickBrush(target, customBrushes);+ uiStoreActions.setBrushStudioModalOpen(true);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-left cursor-pointer"+ >+ <Sliders className="w-3 h-3 text-[var(--accent)]" />+ <span>Edit in Brush Studio</span>+ </button>+ )}++ {!config.locked && (+ <>+ <button+ type="button"+ disabled={tileContextMenu.index === 0}+ onClick={() => {+ workspaceStoreActions.moveQuickBrush(tileContextMenu.brush.id, -1);+ setTileContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] disabled:opacity-35 text-left cursor-pointer"+ >+ {isHorizontal ? (+ <ArrowLeft className="w-3 h-3 text-[#8a8a8a]" />+ ) : (+ <ArrowUp className="w-3 h-3 text-[#8a8a8a]" />+ )}+ <span>{isHorizontal ? 'Move Left' : 'Move Up'}</span>+ </button>++ <button+ type="button"+ disabled={tileContextMenu.index === resolvedBrushes.length - 1}+ onClick={() => {+ workspaceStoreActions.moveQuickBrush(tileContextMenu.brush.id, 1);+ setTileContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] disabled:opacity-35 text-left cursor-pointer"+ >+ {isHorizontal ? (+ <ArrowRight className="w-3 h-3 text-[#8a8a8a]" />+ ) : (+ <ArrowDown className="w-3 h-3 text-[#8a8a8a]" />+ )}+ <span>{isHorizontal ? 'Move Right' : 'Move Down'}</span>+ </button>++ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ onClick={() => {+ const target = tileContextMenu.brush;+ workspaceStoreActions.removeQuickBrush(target.id);+ uiStoreActions.showToast(`Removed "${target.name}" from Quick Brushes`);+ setTileContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-rose-400 text-left cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ <span>Remove from Panel</span>+ </button>+ </>+ )}+ </div>,+ document.body+ )}+ </div>+ );++ // When dragged to custom fixed screen coordinates, portal to document.body so it floats freely+ // across the entire viewport without clipping; when auto-anchored, sit cleanly inside the center canvas area!+ return isFixed && typeof document !== 'undefined'+ ? createPortal(panelElement, document.body)+ : panelElement;+});++QuickBrushPanel.displayName = 'QuickBrushPanel';diff --git a/src/components/QuickBrushPanelSettings.tsx b/src/components/QuickBrushPanelSettings.tsxnew file mode 100644index 0000000..7de9878--- /dev/null+++ b/src/components/QuickBrushPanelSettings.tsx@@ -0,0 +1,721 @@+import React, { useEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import {+ Check,+ ChevronDown,+ ChevronUp,+ Eraser,+ Eye,+ EyeOff,+ Lock,+ Paintbrush,+ Plus,+ RotateCcw,+ Rows3,+ Columns3,+ Search,+ SlidersHorizontal,+ Star,+ Trash2,+ Unlock,+ X,+} from 'lucide-react';+import { BrushPresetId, CspBrush } from '../types/editor';+import {+ QuickBrushPanelOrientation,+ QuickBrushPanelState,+ QuickBrushPreviewStyle,+ QuickBrushTileSize,+} from '../types/workspace';+import { ALL_BUILTIN_BRUSHES, ALL_BUILTIN_BRUSH_SECTIONS } from '../utils/presetBrushes';+import { ERASER_PRESET_ID, migrateLegacyPresetId } from '../utils/brushPresetManager';+import {+ uiStoreActions,+ useToolStore,+ useWorkspaceStore,+ workspaceStoreActions,+} from '../stores';+import { getCategoryAccentStyle, resolveQuickBrush } from '../utils/quickBrushUtils';++export interface QuickBrushPanelSettingsProps {+ anchorRef: React.RefObject<HTMLElement | null>;+ initialTab?: 'settings' | 'brushes';+ customBrushes: CspBrush[];+ onClose: () => void;+}++const POPOVER_WIDTH = 286;+const POPOVER_EST_HEIGHT = 430;++export const QuickBrushPanelSettings: React.FC<QuickBrushPanelSettingsProps> = React.memo(+ ({ anchorRef, initialTab = 'settings', customBrushes, onClose }) => {+ const config = useWorkspaceStore((s) => s.quickBrushPanel);+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const activePresetId = useToolStore((s) => s.activePresetId);+ const activeTool = useToolStore((s) => s.tool);++ const [activeTab, setActiveTab] = useState<'settings' | 'brushes'>(initialTab);+ const [searchQuery, setSearchQuery] = useState('');+ const popoverRef = useRef<HTMLDivElement>(null);++ const computePos = (): { top: number; left: number } => {+ if (typeof window === 'undefined') return { top: 64, left: 64 };+ const rect = anchorRef.current?.getBoundingClientRect();+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const pad = 10;++ if (!rect) {+ return {+ left: Math.max(pad, Math.round((vw - POPOVER_WIDTH) / 2)),+ top: Math.max(44, Math.round((vh - POPOVER_EST_HEIGHT) / 2)),+ };+ }++ // Prefer opening to the left if anchor is on the right half of viewport, else to the right+ let left =+ rect.left > vw / 2 ? rect.left - POPOVER_WIDTH - 10 : rect.right + 10;+ if (left < pad) left = rect.right + 10;+ if (left + POPOVER_WIDTH > vw - pad) left = vw - POPOVER_WIDTH - pad;+ left = Math.max(pad, left);++ let top = rect.top - 40;+ if (top + POPOVER_EST_HEIGHT > vh - pad) {+ top = vh - POPOVER_EST_HEIGHT - pad;+ }+ top = Math.max(42, top);++ return { top: Math.round(top), left: Math.round(left) };+ };++ const [pos, setPos] = useState<{ top: number; left: number }>(() => computePos());++ useEffect(() => {+ setPos(computePos());+ const handleOutside = (e: MouseEvent) => {+ const target = e.target as Node;+ if (+ popoverRef.current?.contains(target) ||+ anchorRef.current?.contains(target)+ ) {+ return;+ }+ onClose();+ };+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onClose();+ }+ };+ const handleResize = () => setPos(computePos());++ window.addEventListener('mousedown', handleOutside);+ window.addEventListener('keydown', handleKey);+ window.addEventListener('resize', handleResize);+ return () => {+ window.removeEventListener('mousedown', handleOutside);+ window.removeEventListener('keydown', handleKey);+ window.removeEventListener('resize', handleResize);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [onClose]);++ const pinnedSet = useMemo(+ () => new Set(config.brushIds.map((id) => migrateLegacyPresetId(id))),+ [config.brushIds]+ );++ const currentActiveId: BrushPresetId =+ activeTool === 'eraser' ? ERASER_PRESET_ID : migrateLegacyPresetId(activePresetId);+ const isCurrentPinned = pinnedSet.has(currentActiveId);++ const pinnedEntries = useMemo(+ () =>+ config.brushIds+ .map((id) => resolveQuickBrush(id, customBrushes))+ .filter((b): b is NonNullable<typeof b> => b !== null),+ [config.brushIds, customBrushes]+ );++ const normalizedQuery = searchQuery.trim().toLowerCase();++ const filteredBuiltinSections = useMemo(() => {+ return ALL_BUILTIN_BRUSH_SECTIONS.map((sec) => ({+ ...sec,+ brushes: ALL_BUILTIN_BRUSHES.filter(+ (b) =>+ b.category === sec.id &&+ (!normalizedQuery ||+ b.name.toLowerCase().includes(normalizedQuery) ||+ sec.label.toLowerCase().includes(normalizedQuery))+ ),+ })).filter((s) => s.brushes.length > 0);+ }, [normalizedQuery]);++ const filteredCustomBrushes = useMemo(() => {+ if (!normalizedQuery) return customBrushes;+ return customBrushes.filter((b) =>+ b.name.toLowerCase().includes(normalizedQuery)+ );+ }, [customBrushes, normalizedQuery]);++ const update = (patch: Partial<Omit<QuickBrushPanelState, 'brushIds'>>) => {+ workspaceStoreActions.updateQuickBrushPanelSettings(patch);+ };++ const handleToggleBrush = (id: BrushPresetId, name: string) => {+ const added = workspaceStoreActions.toggleQuickBrush(id);+ uiStoreActions.showToast(+ added ? `Added "${name}" to Quick Brushes` : `Removed "${name}" from Quick Brushes`+ );+ };++ const content = (+ <div+ ref={popoverRef}+ data-testid="quick-brush-settings-popover"+ role="dialog"+ aria-label="Quick-Access Brush Panel Settings"+ onPointerDown={(e) => e.stopPropagation()}+ onWheel={(e) => e.stopPropagation()}+ style={{+ position: 'fixed',+ top: pos.top,+ left: pos.left,+ width: POPOVER_WIDTH,+ zIndex: 1000,+ }}+ className="rounded-lg bg-[#202020] border border-white/[0.14] shadow-[0_18px_48px_rgba(0,0,0,0.82)] text-[#e5e5e5] text-[11px] flex flex-col max-h-[calc(100vh-56px)] select-none overflow-hidden"+ >+ {/* Header */}+ <div className="h-8 px-2.5 flex items-center justify-between bg-[#181818] border-b border-white/[0.08] shrink-0">+ <div className="flex items-center gap-1.5 font-medium text-[#e5e5e5]">+ <SlidersHorizontal className="w-3.5 h-3.5 text-[var(--accent)]" />+ <span>Quick Brush Panel</span>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close Quick Brush Settings"+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ {/* Tabs */}+ <div className="grid grid-cols-2 gap-1 p-1.5 bg-[#1a1a1a] border-b border-white/[0.06] shrink-0">+ <button+ type="button"+ data-testid="quick-brush-tab-settings"+ onClick={() => setActiveTab('settings')}+ className={`h-6 rounded text-[11px] font-medium flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${+ activeTab === 'settings'+ ? 'bg-[#2c2c2c] text-[#f0f0f0]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ <SlidersHorizontal className="w-3 h-3" />+ <span>Panel Settings</span>+ </button>+ <button+ type="button"+ data-testid="quick-brush-tab-brushes"+ onClick={() => setActiveTab('brushes')}+ className={`h-6 rounded text-[11px] font-medium flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${+ activeTab === 'brushes'+ ? 'bg-[#2c2c2c] text-[#f0f0f0]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ <Star className="w-3 h-3" />+ <span>Brushes ({pinnedEntries.length})</span>+ </button>+ </div>++ {/* Body */}+ {activeTab === 'settings' ? (+ <div className="p-2.5 space-y-3 overflow-y-auto min-h-0">+ {/* Orientation */}+ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">Orientation</div>+ <div className="grid grid-cols-2 gap-1">+ {(+ [+ { id: 'vertical', label: 'Vertical', icon: <Columns3 className="w-3.5 h-3.5" /> },+ { id: 'horizontal', label: 'Horizontal', icon: <Rows3 className="w-3.5 h-3.5" /> },+ ] as Array<{ id: QuickBrushPanelOrientation; label: string; icon: React.ReactNode }>+ ).map((opt) => {+ const active = config.orientation === opt.id;+ return (+ <button+ key={opt.id}+ type="button"+ data-testid={`quick-brush-orient-${opt.id}`}+ onClick={() => update({ orientation: opt.id })}+ className={`h-7 px-2 rounded flex items-center justify-center gap-1.5 transition-colors cursor-pointer border ${+ active+ ? 'bg-[#2c2c2c] text-[#f5f5f5] border-[var(--accent-border)] font-medium'+ : 'bg-[#161616] text-[#9a9a9a] border-transparent hover:bg-[#252525] hover:text-[#e5e5e5]'+ }`}+ >+ {opt.icon}+ <span>{opt.label}</span>+ </button>+ );+ })}+ </div>+ </div>++ {/* Tile Size & Columns/Rows */}+ <div className="grid grid-cols-2 gap-2">+ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">Tile Size</div>+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ { id: 'compact', label: 'S' },+ { id: 'medium', label: 'M' },+ { id: 'large', label: 'L' },+ ] as Array<{ id: QuickBrushTileSize; label: string }>+ ).map((sz) => (+ <button+ key={sz.id}+ type="button"+ data-testid={`quick-brush-size-${sz.id}`}+ onClick={() => update({ tileSize: sz.id })}+ className={`h-6 rounded-sm text-[10px] font-medium transition-colors cursor-pointer ${+ config.tileSize === sz.id+ ? 'bg-[#2c2c2c] text-[#f5f5f5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {sz.label}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">+ {config.orientation === 'vertical' ? 'Columns' : 'Rows'}+ </div>+ <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">+ {([1, 2] as const).map((n) => (+ <button+ key={n}+ type="button"+ data-testid={`quick-brush-cols-${n}`}+ onClick={() => update({ columns: n })}+ className={`h-6 rounded-sm text-[10px] font-medium transition-colors cursor-pointer ${+ config.columns === n+ ? 'bg-[#2c2c2c] text-[#f5f5f5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {n}+ </button>+ ))}+ </div>+ </div>+ </div>++ {/* Preview Style */}+ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">Preview Style</div>+ <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">+ {(+ [+ { id: 'tip', label: 'Brush Tip' },+ { id: 'stroke', label: 'Stroke Curve' },+ ] as Array<{ id: QuickBrushPreviewStyle; label: string }>+ ).map((st) => (+ <button+ key={st.id}+ type="button"+ data-testid={`quick-brush-preview-${st.id}`}+ onClick={() => update({ previewStyle: st.id })}+ className={`h-6 rounded-sm text-[10px] font-medium transition-colors cursor-pointer ${+ config.previewStyle === st.id+ ? 'bg-[#2c2c2c] text-[#f5f5f5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {st.label}+ </button>+ ))}+ </div>+ </div>++ {/* Opacity Slider */}+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px]">+ <span className="uppercase tracking-wider text-[#8a8a8a]">Panel Opacity</span>+ <span className="font-mono text-[#d4d4d4]">+ {Math.round(config.opacity * 100)}%+ </span>+ </div>+ <input+ type="range"+ data-testid="quick-brush-opacity-slider"+ min={40}+ max={100}+ step={5}+ value={Math.round(config.opacity * 100)}+ onChange={(e) => update({ opacity: Number(e.target.value) / 100 })}+ className="w-full"+ />+ </div>++ {/* Panel Title Input */}+ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">Panel Label</div>+ <input+ type="text"+ data-testid="quick-brush-title-input"+ value={config.title}+ maxLength={28}+ placeholder="Favorites"+ onChange={(e) => update({ title: e.target.value })}+ className="w-full h-7 px-2 rounded bg-[#161616] text-[11px] text-[#e5e5e5]"+ />+ </div>++ {/* Toggles */}+ <div className="space-y-1.5 pt-0.5 border-t border-white/[0.06]">+ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <span className="text-[#d4d4d4]">Show brush names</span>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-names"+ checked={config.showNames}+ onChange={(e) => update({ showNames: e.target.checked })}+ />+ </label>++ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <span className="text-[#d4d4d4]">Category color accents</span>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-colors"+ checked={config.showCategoryColors}+ onChange={(e) => update({ showCategoryColors: e.target.checked })}+ />+ </label>++ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <span className="text-[#d4d4d4]">Show panel label (horizontal)</span>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-title"+ checked={config.showTitle}+ onChange={(e) => update({ showTitle: e.target.checked })}+ />+ </label>++ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <div>+ <div className="text-[#d4d4d4]">Keep visible when UI hidden (Tab)</div>+ <div className="text-[9px] text-[#7c7c7c]">+ Stay on canvas when all palettes are hidden+ </div>+ </div>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-keep-visible"+ checked={config.keepVisibleWhenPalettesHidden}+ onChange={(e) => update({ keepVisibleWhenPalettesHidden: e.target.checked })}+ />+ </label>++ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <span className="text-[#d4d4d4]">Show Hide/Show UI button on bar</span>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-hide-ui-btn"+ checked={config.showHideUiButton}+ onChange={(e) => update({ showHideUiButton: e.target.checked })}+ />+ </label>++ <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">+ <span className="text-[#d4d4d4] flex items-center gap-1.5">+ {config.locked ? (+ <Lock className="w-3 h-3 text-[var(--accent)]" />+ ) : (+ <Unlock className="w-3 h-3 text-[#8a8a8a]" />+ )}+ <span>Lock position & brush list</span>+ </span>+ <input+ type="checkbox"+ data-testid="quick-brush-toggle-lock"+ checked={config.locked}+ onChange={(e) => update({ locked: e.target.checked })}+ />+ </label>+ </div>++ {/* Footer quick actions */}+ <div className="pt-2 border-t border-white/[0.08] space-y-1.5">+ <button+ type="button"+ data-testid="quick-brush-toggle-all-ui-btn"+ onClick={() => workspaceStoreActions.togglePalettesHidden()}+ className="w-full h-7 px-2 rounded bg-[#2a2a2a] hover:bg-[#343434] text-[#f0f0f0] flex items-center justify-between cursor-pointer transition-colors"+ >+ <span className="flex items-center gap-1.5">+ {palettesHidden ? (+ <Eye className="w-3.5 h-3.5 text-[var(--accent)]" />+ ) : (+ <EyeOff className="w-3.5 h-3.5 text-[var(--accent)]" />+ )}+ <span>{palettesHidden ? 'Show All Palettes' : 'Hide All Other Palettes'}</span>+ </span>+ <span className="text-[10px] font-mono text-[#8a8a8a]">Tab</span>+ </button>++ <div className="grid grid-cols-2 gap-1">+ <button+ type="button"+ data-testid="quick-brush-reset-pos-btn"+ onClick={() => workspaceStoreActions.setQuickBrushPanelPosition(null, true)}+ className="h-6 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc] hover:text-white text-[10px] cursor-pointer transition-colors"+ >+ Snap to Edge+ </button>+ <button+ type="button"+ data-testid="quick-brush-reset-all-btn"+ onClick={() => {+ workspaceStoreActions.resetQuickBrushPanel();+ uiStoreActions.showToast('Quick Brush Panel reset to defaults');+ }}+ className="h-6 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-amber-300/90 hover:text-amber-200 text-[10px] flex items-center justify-center gap-1 cursor-pointer transition-colors"+ >+ <RotateCcw className="w-3 h-3" />+ <span>Reset Panel</span>+ </button>+ </div>+ </div>+ </div>+ ) : (+ <div className="p-2.5 flex flex-col gap-2 min-h-0 overflow-hidden">+ {/* Quick Add Active Brush / Eraser */}+ <div className="grid grid-cols-2 gap-1 shrink-0">+ <button+ type="button"+ disabled={isCurrentPinned}+ onClick={() => {+ const resolved = resolveQuickBrush(currentActiveId, customBrushes);+ const added = workspaceStoreActions.addQuickBrush(currentActiveId);+ if (added) {+ uiStoreActions.showToast(+ `Added "${resolved?.name || 'Brush'}" to Quick Brushes`+ );+ }+ }}+ className="h-6 px-1.5 rounded bg-[#2a2a2a] hover:bg-[#343434] disabled:opacity-40 disabled:cursor-not-allowed text-[10px] text-[#e5e5e5] flex items-center justify-center gap-1 cursor-pointer"+ >+ <Plus className="w-3 h-3 text-[var(--accent)]" />+ <span className="truncate">+ {isCurrentPinned ? 'Active Pinned' : 'Add Active'}+ </span>+ </button>++ <button+ type="button"+ onClick={() => handleToggleBrush(ERASER_PRESET_ID, 'Eraser')}+ className={`h-6 px-1.5 rounded text-[10px] flex items-center justify-center gap-1 cursor-pointer ${+ pinnedSet.has(ERASER_PRESET_ID)+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-border)]'+ : 'bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc]'+ }`}+ >+ <Eraser className="w-3 h-3" />+ <span>{pinnedSet.has(ERASER_PRESET_ID) ? 'Eraser Pinned' : '+ Pin Eraser'}</span>+ </button>+ </div>++ {/* Pinned Order Management */}+ <div className="space-y-1 shrink-0">+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">+ <span className="uppercase tracking-wider">Pinned ({pinnedEntries.length})</span>+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={() => workspaceStoreActions.resetQuickBrushPanelItems()}+ className="hover:text-amber-300 cursor-pointer"+ title="Restore default brushes"+ >+ Defaults+ </button>+ {pinnedEntries.length > 0 && (+ <button+ type="button"+ onClick={() => workspaceStoreActions.clearQuickBrushes()}+ className="hover:text-rose-400 cursor-pointer"+ title="Clear all pinned brushes"+ >+ Clear+ </button>+ )}+ </div>+ </div>++ {pinnedEntries.length === 0 ? (+ <div className="px-2 py-2 rounded bg-[#161616] text-center text-[10px] text-[#7c7c7c]">+ No brushes pinned yet. Pick any brush below or click the star in Sub Tool.+ </div>+ ) : (+ <div className="max-h-28 overflow-y-auto space-y-0.5 pr-0.5">+ {pinnedEntries.map((brush, idx) => {+ const accent = getCategoryAccentStyle(brush.category);+ return (+ <div+ key={brush.id}+ className="flex items-center justify-between gap-1 px-1.5 py-1 rounded bg-[#161616]"+ >+ <div className="flex items-center gap-1.5 min-w-0">+ <span+ className="w-1 h-3 rounded-full shrink-0"+ style={{ backgroundColor: accent.barColor || '#555555' }}+ />+ <span className="truncate text-[11px] text-[#e5e5e5]">{brush.name}</span>+ </div>+ <div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ disabled={idx === 0}+ onClick={() => workspaceStoreActions.moveQuickBrush(brush.id, -1)}+ title="Move earlier"+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"+ >+ <ChevronUp className="w-3 h-3" />+ </button>+ <button+ type="button"+ disabled={idx === pinnedEntries.length - 1}+ onClick={() => workspaceStoreActions.moveQuickBrush(brush.id, 1)}+ title="Move later"+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"+ >+ <ChevronDown className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => workspaceStoreActions.removeQuickBrush(brush.id)}+ title="Remove from Quick Brushes"+ className="p-0.5 text-[#8a8a8a] hover:text-rose-400 cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Search & Add Brushes Catalog */}+ <div className="relative shrink-0 pt-1 border-t border-white/[0.08]">+ <Search className="w-3 h-3 text-[#7a7a7a] absolute left-2 top-1/2 -translate-y-1/2 mt-0.5 pointer-events-none" />+ <input+ type="text"+ data-testid="quick-brush-search-input"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ placeholder="Search brushes to add..."+ className="w-full h-6 pl-6 pr-2 rounded bg-[#161616] text-[10px] text-[#e5e5e5]"+ />+ </div>++ <div className="flex-1 min-h-0 max-h-44 overflow-y-auto space-y-2 pr-0.5">+ {filteredBuiltinSections.map((sec) => (+ <div key={sec.id} className="space-y-0.5">+ <div className="text-[9px] uppercase tracking-wider text-[#6f6f6f] px-1">+ {sec.label}+ </div>+ {sec.brushes.map((b) => {+ const isPinned = pinnedSet.has(b.id);+ return (+ <button+ key={b.id}+ type="button"+ data-testid={`quick-brush-catalog-toggle-${b.id}`}+ onClick={() => handleToggleBrush(b.id, b.name)}+ className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded text-left transition-colors cursor-pointer ${+ isPinned+ ? 'bg-[#2c2c2c] text-[#f2f2f2]'+ : 'bg-[#161616] text-[#a0a0a0] hover:bg-[#242424] hover:text-[#e5e5e5]'+ }`}+ >+ <span className="flex items-center gap-1.5 min-w-0">+ <Paintbrush className="w-3 h-3 shrink-0 opacity-75" />+ <span className="truncate text-[10px]">{b.name}</span>+ </span>+ {isPinned ? (+ <Check className="w-3 h-3 text-[var(--accent)] shrink-0" />+ ) : (+ <Plus className="w-3 h-3 text-[#8a8a8a] shrink-0" />+ )}+ </button>+ );+ })}+ </div>+ ))}++ {filteredCustomBrushes.length > 0 && (+ <div className="space-y-0.5">+ <div className="text-[9px] uppercase tracking-wider text-[#6f6f6f] px-1">+ Imported / Custom+ </div>+ {filteredCustomBrushes.map((b) => {+ const isPinned = pinnedSet.has(b.id);+ return (+ <button+ key={b.id}+ type="button"+ data-testid={`quick-brush-catalog-toggle-${b.id}`}+ onClick={() => handleToggleBrush(b.id, b.name)}+ className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded text-left transition-colors cursor-pointer ${+ isPinned+ ? 'bg-[#2c2c2c] text-[#f2f2f2]'+ : 'bg-[#161616] text-[#a0a0a0] hover:bg-[#242424] hover:text-[#e5e5e5]'+ }`}+ >+ <span className="flex items-center gap-1.5 min-w-0">+ {b.tipDataUrl ? (+ <img+ src={b.tipDataUrl}+ alt=""+ className="w-3 h-3 object-contain shrink-0 brightness-125"+ />+ ) : (+ <Paintbrush className="w-3 h-3 shrink-0 opacity-75" />+ )}+ <span className="truncate text-[10px]">{b.name}</span>+ </span>+ {isPinned ? (+ <Check className="w-3 h-3 text-[var(--accent)] shrink-0" />+ ) : (+ <Plus className="w-3 h-3 text-[#8a8a8a] shrink-0" />+ )}+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );++ return typeof document !== 'undefined' ? createPortal(content, document.body) : content;+ }+);++QuickBrushPanelSettings.displayName = 'QuickBrushPanelSettings';diff --git a/src/components/QuickShapeOverlay.tsx b/src/components/QuickShapeOverlay.tsxnew file mode 100644index 0000000..61b6ec2--- /dev/null+++ b/src/components/QuickShapeOverlay.tsx@@ -0,0 +1,189 @@+import React from 'react';+import type { CanvasDimensions } from '../types/editor';+import type { QuickShapePreviewState } from '../utils/quickShapeEngine';++export interface QuickShapeOverlayProps {+ dimensions: CanvasDimensions;+ zoom: number;+ rotation: number;+ flipX: boolean;+ flipY: boolean;+ preview: QuickShapePreviewState;+}++export const QuickShapeOverlay: React.FC<QuickShapeOverlayProps> = React.memo(+ ({ dimensions, zoom, rotation, flipX, flipY, preview }) => {+ const invZoom = 1 / Math.max(0.05, zoom);+ const crossArm = 5 * invZoom;+ const handleR = 4.5 * invZoom;+ const activeR = 6 * invZoom;+ const cornerSize = 8 * invZoom;+ const activeCornerSize = 10 * invZoom;++ const fx = flipX ? -1 : 1;+ const fy = flipY ? -1 : 1;++ return (+ <>+ <svg+ data-testid="quick-shape-overlay-svg"+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ {/* Optional auxiliary guide line (chord for arc, radius for circle) */}+ {preview.guideLine && (+ <line+ x1={preview.guideLine.x1}+ y1={preview.guideLine.y1}+ x2={preview.guideLine.x2}+ y2={preview.guideLine.y2}+ stroke="#38bdf8"+ strokeOpacity={0.45}+ strokeWidth={1.1 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}++ {/* Dual-contrast crisp geometric guide outline */}+ {preview.svgPath && (+ <>+ <path+ d={preview.svgPath}+ fill="none"+ stroke="rgba(0, 0, 0, 0.55)"+ strokeWidth={2.6 * invZoom}+ strokeLinejoin="round"+ strokeLinecap="round"+ />+ <path+ d={preview.svgPath}+ fill="none"+ stroke="#38bdf8"+ strokeOpacity={0.9}+ strokeWidth={1.35 * invZoom}+ strokeDasharray={`${5 * invZoom} ${3.5 * invZoom}`}+ strokeLinejoin="round"+ strokeLinecap="round"+ />+ </>+ )}++ {/* Subtle center crosshair */}+ {preview.centerMarker && (+ <g opacity={0.75}>+ <line+ x1={preview.centerMarker.x - crossArm}+ y1={preview.centerMarker.y}+ x2={preview.centerMarker.x + crossArm}+ y2={preview.centerMarker.y}+ stroke="#000000"+ strokeWidth={2.4 * invZoom}+ />+ <line+ x1={preview.centerMarker.x}+ y1={preview.centerMarker.y - crossArm}+ x2={preview.centerMarker.x}+ y2={preview.centerMarker.y + crossArm}+ stroke="#000000"+ strokeWidth={2.4 * invZoom}+ />+ <line+ x1={preview.centerMarker.x - crossArm}+ y1={preview.centerMarker.y}+ x2={preview.centerMarker.x + crossArm}+ y2={preview.centerMarker.y}+ stroke="#38bdf8"+ strokeWidth={1.2 * invZoom}+ />+ <line+ x1={preview.centerMarker.x}+ y1={preview.centerMarker.y - crossArm}+ x2={preview.centerMarker.x}+ y2={preview.centerMarker.y + crossArm}+ stroke="#38bdf8"+ strokeWidth={1.2 * invZoom}+ />+ </g>+ )}++ {/* Interactive handles & corners */}+ {preview.handles.map((h) => {+ const isActive = Boolean(h.active);+ const isCorner = h.kind === 'corner';+ const fill = isActive ? '#38bdf8' : '#161616';+ const stroke = '#ffffff';+ const sw = (isActive ? 2 : 1.5) * invZoom;++ return (+ <g key={h.id} data-quickshape-handle={h.id} data-active={isActive ? 'true' : 'false'}>+ {isActive && (+ <circle+ cx={h.x}+ cy={h.y}+ r={11 * invZoom}+ fill="rgba(56, 189, 248, 0.18)"+ stroke="#38bdf8"+ strokeOpacity={0.65}+ strokeWidth={1.1 * invZoom}+ />+ )}+ {isCorner ? (+ <rect+ x={h.x - (isActive ? activeCornerSize : cornerSize) * 0.5}+ y={h.y - (isActive ? activeCornerSize : cornerSize) * 0.5}+ width={isActive ? activeCornerSize : cornerSize}+ height={isActive ? activeCornerSize : cornerSize}+ rx={1.5 * invZoom}+ fill={fill}+ stroke={stroke}+ strokeWidth={sw}+ />+ ) : (+ <circle+ cx={h.x}+ cy={h.y}+ r={isActive ? activeR : handleR}+ fill={fill}+ stroke={stroke}+ strokeWidth={sw}+ />+ )}+ </g>+ );+ })}+ </svg>++ {/* Compact floating HUD badge showing recognized QuickShape & live dimensions */}+ <div+ data-testid="quick-shape-hud-badge"+ className="absolute pointer-events-none z-35 px-2 py-1 rounded bg-[#161616]/92 border border-[#38bdf8]/45 shadow-[0_6px_20px_rgba(0,0,0,0.65)] text-[#e5e5e5] whitespace-nowrap flex items-center gap-1.5"+ style={{+ left: `${preview.anchorPos.x}px`,+ top: `${preview.anchorPos.y}px`,+ transform: `translate(${14 * invZoom}px, ${-28 * invZoom}px) scale(${invZoom}) scale(${fx}, ${fy}) rotate(${-rotation}deg)`,+ transformOrigin: 'top left',+ }}+ >+ <span className="w-1.5 h-1.5 rounded-full bg-[#38bdf8] shrink-0" />+ <span className="text-[10px] font-semibold tracking-tight text-[#f5f5f5]">+ {preview.label}+ </span>+ {preview.readout && (+ <>+ <span className="text-[10px] text-[#8a8a8a]">·</span>+ <span className="font-mono text-[10px] text-[#d4d4d4]">{preview.readout}</span>+ </>+ )}+ {preview.hint && (+ <>+ <span className="text-[10px] text-[#8a8a8a]">·</span>+ <span className="text-[9px] text-[#8a8a8a]">{preview.hint}</span>+ </>+ )}+ </div>+ </>+ );+ }+);++QuickShapeOverlay.displayName = 'QuickShapeOverlay';diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsxindex 6f37f14..f9a8dcc 100644--- a/src/components/SelectionOverlay.tsx+++ b/src/components/SelectionOverlay.tsx@@ -126,7 +126,7 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({.marching-ants-black {stroke: #000000;stroke-width: 1.5;- fill: rgba(92, 225, 230, 0.12);+ fill: none;}.marching-ants-white {stroke: #ffffff;@@ -140,7 +140,7 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({{pathD && (<>- <path d={pathD} className="marching-ants-black" />+ <path d={pathD} className="marching-ants-black" fill="none" /><path d={pathD} className="marching-ants-white" fill="none" /></>)}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 88166a5..5c9e98d 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -1,6 +1,14 @@-import React, { useState, useEffect, useMemo } from 'react';+import React, { useState, useEffect, useMemo, useRef } from 'react';import { version as APP_VERSION } from '../../package.json';import { safeLocalStorageSetItem } from '../utils/safeStorage';+import {+ DEFAULT_INTERFACE_SCALE,+ INTERFACE_SCALE_PRESETS,+ INTERFACE_SCALE_STEP,+ MAX_INTERFACE_SCALE,+ MIN_INTERFACE_SCALE,+ clampInterfaceScale,+} from '../utils/interfaceScale';import {X,Palette,@@ -19,6 +27,8 @@ import {ArrowDownToLine,Loader2,RefreshCw,+ Minus,+ Plus,} from 'lucide-react';import { isTauriEnvironment } from '../hooks/useMultiplayer';import { updaterService } from '../services/updaterService';@@ -39,7 +49,7 @@ import {ShortcutCategory,resolveModernAccentColor,} from '../types/settings';-import { CanvasColorMode } from '../types/editor';+import { CanvasColorMode, CspBrush } from '../types/editor';import { DPI_PRESETS } from './NewCanvasModal';import { PressureCurveEditor } from './PressureCurveEditor';import { PerformanceSettingsTab } from './PerformanceSettingsTab';@@ -47,11 +57,23 @@ import {CommandDefinition,DEFAULT_COMMANDS,SHORTCUT_CATEGORIES,+ buildSubToolShortcutCommands,findShortcutConflicts,formatShortcutFromEvent,formatShortcutLabel,+ getOsModifierDisplayName,resolveCommandShortcut,} from '../utils/shortcutManager';+import {+ CUSTOM_BRUSHES_CHANGED_EVENT,+ getCachedCustomBrushes,+ loadCustomBrushes,+} from '../utils/brushStorage';+import { useSubToolGroupStore } from '../stores/useSubToolGroupStore';+import {+ acquireNativeOsHotkeyRecording,+ subscribeNativeOsHotkeys,+} from '../utils/nativeOsHotkeys';interface SettingsModalProps {isOpen: boolean;@@ -138,15 +160,51 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({...DEFAULT_APP_SETTINGS,...settings,}));+ const [draftInterfaceScale, setDraftInterfaceScale] = useState<number>(() =>+ clampInterfaceScale(settings.interfaceScale)+ );+ const [interfaceScaleInput, setInterfaceScaleInput] = useState<string>(() =>+ String(clampInterfaceScale(settings.interfaceScale))+ );+ const isDraggingScaleSliderRef = useRef(false);+ const draftInterfaceScaleRef = useRef(draftInterfaceScale);+ draftInterfaceScaleRef.current = draftInterfaceScale;const [searchQuery, setSearchQuery] = useState<string>('');const [selectedCategory, setSelectedCategory] = useState<'All' | ShortcutCategory>('All');const [recordingCommandId, setRecordingCommandId] = useState<string | null>(null);+ const [recordWithOsModifier, setRecordWithOsModifier] = useState<boolean>(false);+ const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());+ const customSubToolGroups = useSubToolGroupStore((s) => s.groups);const [pendingConflict, setPendingConflict] = useState<{commandId: string;shortcut: string;conflicts: CommandDefinition[];} | null>(null);+ const osKeyLabel = getOsModifierDisplayName();++ const allCommands = useMemo(+ () => [...DEFAULT_COMMANDS, ...buildSubToolShortcutCommands(customBrushes, customSubToolGroups)],+ [customBrushes, customSubToolGroups]+ );++ useEffect(() => {+ if (!isOpen) return;+ let active = true;+ setCustomBrushes([...getCachedCustomBrushes()]);+ void loadCustomBrushes().then((loaded) => {+ if (active) setCustomBrushes(loaded);+ });+ const handleChanged = () => {+ if (active) setCustomBrushes([...getCachedCustomBrushes()]);+ };+ window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);+ return () => {+ active = false;+ window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);+ };+ }, [isOpen]);+const isDesktopTauri = isTauriEnvironment();const updaterStatus = useUpdaterStore((s) => s.status);const runtimeAppVersion = useUpdaterStore((s) => s.currentVersion);@@ -155,10 +213,16 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({const updateErrorMessage = useUpdaterStore((s) => s.errorMessage);useEffect(() => {- setLocalSettings({+ const merged = {...DEFAULT_APP_SETTINGS,...settings,- });+ };+ setLocalSettings(merged);+ if (!isDraggingScaleSliderRef.current) {+ const clampedScale = clampInterfaceScale(merged.interfaceScale);+ setDraftInterfaceScale(clampedScale);+ setInterfaceScaleInput(String(clampedScale));+ }}, [settings]);useEffect(() => {@@ -170,31 +234,43 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({useEffect(() => {if (!isOpen) {setRecordingCommandId(null);+ setRecordWithOsModifier(false);setPendingConflict(null);}}, [isOpen]);- // Global capture listener while recording a shortcut keybinding+ // Global capture listener (DOM + native Windows OS-key hook) while recording a shortcut keybindinguseEffect(() => {if (!isOpen || !recordingCommandId) return;- const handleRecordKeyDown = (e: KeyboardEvent) => {- e.preventDefault();- e.stopPropagation();-- if (e.key === 'Escape' && !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) {+ const releaseNativeRecording = acquireNativeOsHotkeyRecording();++ const applyCapturedEvent = (ev: {+ key: string;+ code?: string;+ ctrlKey?: boolean;+ metaKey?: boolean;+ shiftKey?: boolean;+ altKey?: boolean;+ }) => {+ if (ev.key === 'Escape' && !ev.ctrlKey && !ev.metaKey && !ev.altKey && !ev.shiftKey) {setRecordingCommandId(null);+ setRecordWithOsModifier(false);setPendingConflict(null);return;}- const captured = formatShortcutFromEvent(e);+ const captured = formatShortcutFromEvent({+ ...ev,+ metaKey: Boolean(ev.metaKey || recordWithOsModifier),+ });if (!captured) return;const conflicts = findShortcutConflicts(recordingCommandId,captured,- localSettings.shortcuts+ localSettings.shortcuts,+ allCommands);if (conflicts.length > 0) {setPendingConflict({@@ -203,6 +279,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({conflicts,});setRecordingCommandId(null);+ setRecordWithOsModifier(false);return;}@@ -214,18 +291,32 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({setLocalSettings(updated);onUpdateSettings(updated);setRecordingCommandId(null);+ setRecordWithOsModifier(false);setPendingConflict(null);};+ const handleRecordKeyDown = (e: KeyboardEvent) => {+ e.preventDefault();+ e.stopPropagation();+ applyCapturedEvent(e);+ };++ const unsubNative = subscribeNativeOsHotkeys((ev) => {+ if (ev.phase !== 'keydown' || ev.repeat) return;+ applyCapturedEvent(ev);+ });+window.addEventListener('keydown', handleRecordKeyDown, true);return () => {window.removeEventListener('keydown', handleRecordKeyDown, true);+ unsubNative();+ releaseNativeRecording();};- }, [isOpen, recordingCommandId, localSettings, onUpdateSettings]);+ }, [isOpen, recordingCommandId, recordWithOsModifier, localSettings, onUpdateSettings, allCommands]);const filteredCommands = useMemo(() => {const q = searchQuery.trim().toLowerCase();- return DEFAULT_COMMANDS.filter((cmd) => {+ return allCommands.filter((cmd) => {if (selectedCategory !== 'All' && cmd.category !== selectedCategory) return false;if (!q) return true;const bound = formatShortcutLabel(resolveCommandShortcut(cmd, localSettings.shortcuts));@@ -233,10 +324,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({cmd.label.toLowerCase().includes(q) ||cmd.description.toLowerCase().includes(q) ||cmd.category.toLowerCase().includes(q) ||+ (cmd.groupBadge && cmd.groupBadge.toLowerCase().includes(q)) ||bound.toLowerCase().includes(q));});- }, [searchQuery, selectedCategory, localSettings.shortcuts]);+ }, [allCommands, searchQuery, selectedCategory, localSettings.shortcuts]);if (!isOpen) return null;@@ -246,9 +338,17 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({onUpdateSettings(updated);};+ const commitInterfaceScale = (rawScale: number) => {+ const clamped = clampInterfaceScale(rawScale);+ setDraftInterfaceScale(clamped);+ setInterfaceScaleInput(String(clamped));+ handleChange('interfaceScale', clamped);+ };+const handleResetDefaults = () => {setRecordingCommandId(null);setPendingConflict(null);+ isDraggingScaleSliderRef.current = false;const fresh: AppSettings = {...DEFAULT_APP_SETTINGS,shortcuts: {},@@ -259,6 +359,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({},};setLocalSettings(fresh);+ setDraftInterfaceScale(DEFAULT_INTERFACE_SCALE);+ setInterfaceScaleInput(String(DEFAULT_INTERFACE_SCALE));onUpdateSettings(fresh);onShowToast('Preferences reset to defaults');};@@ -267,7 +369,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({if (!pendingConflict) return;const nextShortcuts = { ...localSettings.shortcuts };for (const c of pendingConflict.conflicts) {- nextShortcuts[c.id] = '';+ if (c.defaultShortcut) {+ nextShortcuts[c.id] = '';+ } else {+ delete nextShortcuts[c.id];+ }}nextShortcuts[pendingConflict.commandId] = pendingConflict.shortcut;const updated: AppSettings = { ...localSettings, shortcuts: nextShortcuts };@@ -284,7 +390,14 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({};const handleClearSingleShortcut = (commandId: string) => {- handleChange('shortcuts', { ...localSettings.shortcuts, [commandId]: '' });+ const cmd = allCommands.find((c) => c.id === commandId);+ const nextShortcuts = { ...localSettings.shortcuts };+ if (cmd && !cmd.defaultShortcut) {+ delete nextShortcuts[commandId];+ } else {+ nextShortcuts[commandId] = '';+ }+ handleChange('shortcuts', nextShortcuts);};const handleResetAllShortcuts = () => {@@ -358,7 +471,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({><divonClick={(e) => e.stopPropagation()}- className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-3xl flex flex-col overflow-hidden text-xs text-[#e5e5e5] h-[600px]"+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-3xl flex flex-col overflow-hidden text-xs text-[#e5e5e5] h-[600px] max-h-full">{/* Header */}<div className="h-10 px-4 flex items-center justify-between bg-[#161616] shrink-0">@@ -374,10 +487,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({</div>{/* Body */}- <div className="flex flex-1 overflow-hidden gap-px bg-[#161616]">+ <div className="flex flex-1 min-h-0 overflow-hidden gap-px bg-[#161616]">{/* Left Navigation */}- <div className="w-44 bg-[#202020] p-2 flex flex-col justify-between shrink-0">- <div className="space-y-0.5">+ <div className="w-44 bg-[#202020] p-2 flex flex-col justify-between gap-2 shrink-0 min-h-0">+ <div className="space-y-0.5 overflow-y-auto min-h-0">{tabs.map((t) => {const active = activeTab === t.id;return (@@ -525,6 +638,158 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({</div></section>+ <section className="space-y-2.5" data-testid="settings-interface-size-section">+ <div className="flex items-center justify-between gap-2">+ <div>+ <h3 className="text-xs font-medium text-[#e5e5e5]">Interface Size</h3>+ <p className="text-[11px] text-[#8a8a8a]">+ Adjust UI scale for menus, panels, and controls ({MIN_INTERFACE_SCALE}%–{MAX_INTERFACE_SCALE}%)+ </p>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ type="button"+ data-testid="settings-interface-scale-dec"+ aria-label="Decrease Interface Size"+ disabled={draftInterfaceScale <= MIN_INTERFACE_SCALE}+ onClick={() =>+ commitInterfaceScale(draftInterfaceScale - INTERFACE_SCALE_STEP)+ }+ className="w-6 h-6 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"+ title={`Decrease (-${INTERFACE_SCALE_STEP}%)`}+ >+ <Minus className="w-3 h-3" />+ </button>+ <div className="flex items-center bg-[#161616] rounded px-1.5 h-6">+ <input+ type="number"+ data-testid="settings-interface-scale-input"+ aria-label="Interface Size Percentage"+ min={MIN_INTERFACE_SCALE}+ max={MAX_INTERFACE_SCALE}+ step={INTERFACE_SCALE_STEP}+ value={interfaceScaleInput}+ onChange={(e) => setInterfaceScaleInput(e.target.value)}+ onBlur={() => {+ const parsed = Number(interfaceScaleInput);+ if (Number.isFinite(parsed)) {+ commitInterfaceScale(parsed);+ } else {+ setInterfaceScaleInput(String(draftInterfaceScale));+ }+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ const parsed = Number(interfaceScaleInput);+ if (Number.isFinite(parsed)) {+ commitInterfaceScale(parsed);+ } else {+ setInterfaceScaleInput(String(draftInterfaceScale));+ }+ (e.currentTarget as HTMLInputElement).blur();+ }+ }}+ className="w-10 bg-transparent text-right font-mono text-xs text-[#e5e5e5] focus:shadow-none"+ />+ <span className="font-mono text-[11px] text-[#8a8a8a] ml-0.5">%</span>+ </div>+ <button+ type="button"+ data-testid="settings-interface-scale-inc"+ aria-label="Increase Interface Size"+ disabled={draftInterfaceScale >= MAX_INTERFACE_SCALE}+ onClick={() =>+ commitInterfaceScale(draftInterfaceScale + INTERFACE_SCALE_STEP)+ }+ className="w-6 h-6 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"+ title={`Increase (+${INTERFACE_SCALE_STEP}%)`}+ >+ <Plus className="w-3 h-3" />+ </button>+ <button+ type="button"+ data-testid="settings-interface-scale-reset"+ disabled={draftInterfaceScale === DEFAULT_INTERFACE_SCALE}+ onClick={() => commitInterfaceScale(DEFAULT_INTERFACE_SCALE)}+ className="h-6 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"+ title="Reset Interface Size to 100%"+ >+ Reset+ </button>+ </div>+ </div>++ <div className="bg-[#161616] rounded p-3 space-y-2.5">+ <div className="space-y-1">+ <input+ type="range"+ data-testid="settings-interface-scale-slider"+ aria-label="Interface Size"+ min={MIN_INTERFACE_SCALE}+ max={MAX_INTERFACE_SCALE}+ step={INTERFACE_SCALE_STEP}+ value={draftInterfaceScale}+ onPointerDown={() => {+ isDraggingScaleSliderRef.current = true;+ const handleWindowPointerEnd = () => {+ window.removeEventListener('pointerup', handleWindowPointerEnd);+ window.removeEventListener('pointercancel', handleWindowPointerEnd);+ if (!isDraggingScaleSliderRef.current) return;+ isDraggingScaleSliderRef.current = false;+ commitInterfaceScale(draftInterfaceScaleRef.current);+ };+ window.addEventListener('pointerup', handleWindowPointerEnd);+ window.addEventListener('pointercancel', handleWindowPointerEnd);+ }}+ onChange={(e) => {+ const next = clampInterfaceScale(Number(e.target.value));+ setDraftInterfaceScale(next);+ setInterfaceScaleInput(String(next));+ if (!isDraggingScaleSliderRef.current) {+ handleChange('interfaceScale', next);+ }+ }}+ onPointerUp={(e) => {+ if (!isDraggingScaleSliderRef.current) return;+ isDraggingScaleSliderRef.current = false;+ commitInterfaceScale(Number((e.currentTarget as HTMLInputElement).value));+ }}+ onPointerCancel={() => {+ isDraggingScaleSliderRef.current = false;+ commitInterfaceScale(draftInterfaceScale);+ }}+ className="w-full"+ />+ <div className="flex items-center justify-between text-[10px] font-mono text-[#8a8a8a]">+ <span>{MIN_INTERFACE_SCALE}%</span>+ <span>{DEFAULT_INTERFACE_SCALE}%</span>+ <span>{MAX_INTERFACE_SCALE}%</span>+ </div>+ </div>++ <div className="grid grid-cols-6 gap-1.5">+ {INTERFACE_SCALE_PRESETS.map((preset) => {+ const isSelected = draftInterfaceScale === preset;+ return (+ <button+ key={preset}+ type="button"+ data-testid={`settings-interface-scale-preset-${preset}`}+ onClick={() => commitInterfaceScale(preset)}+ className={`py-1 rounded font-mono text-[11px] transition-colors cursor-pointer ${+ isSelected+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'+ }`}+ >+ {preset}%+ </button>+ );+ })}+ </div>+ </div>+ </section>+<section className="space-y-2"><h3 className="text-xs font-medium text-[#e5e5e5]">Artist Name</h3><input@@ -861,6 +1126,25 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({onChange={(e) => handleChange('smoothingEnabled', e.target.checked)}/></label>+ <label className="flex items-start justify-between gap-3 py-1.5 pt-2 mt-1 border-t border-[#262626] cursor-pointer">+ <div className="min-w-0">+ <div className="text-xs text-[#e5e5e5]">+ QuickShape (Hold Pen to Snap Shape)+ </div>+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed mt-0.5">+ Hold the stylus still (~350 ms) at the end of a freehand stroke to snap it+ into a smooth line, arc, circle, ellipse, triangle, or rectangle, then drag+ handles or corners before lifting.+ </p>+ </div>+ <input+ type="checkbox"+ data-testid="settings-quick-shape-toggle"+ className="mt-0.5 shrink-0"+ checked={Boolean(localSettings.quickShapeEnabled)}+ onChange={(e) => handleChange('quickShapeEnabled', e.target.checked)}+ />+ </label></section><section className="space-y-2">@@ -920,6 +1204,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({<buttonkey={cat}type="button"+ data-testid={`settings-shortcut-cat-${cat}`}onClick={() => setSelectedCategory(cat)}className={`px-2.5 py-1 rounded text-[11px] transition-colors cursor-pointer ${active@@ -933,6 +1218,40 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({})}</div>+ {/* OS/Win Key Support & Active Recording Helper Bar */}+ {recordingCommandId ? (+ <div+ data-testid="settings-shortcut-recording-bar"+ className="px-2.5 py-2 rounded bg-[var(--accent-subtle)] border border-[var(--accent-border)] flex items-center justify-between gap-2 text-[11px]"+ >+ <div className="text-[#e5e5e5] min-w-0 truncate">+ Recording shortcut — press any key combo with Ctrl, {osKeyLabel}, Shift, or Alt+ (Esc to cancel)+ </div>+ <button+ type="button"+ data-testid="shortcut-record-os-toggle"+ aria-pressed={recordWithOsModifier}+ onClick={() => setRecordWithOsModifier((v) => !v)}+ className={`px-2 py-0.5 rounded font-mono text-[10px] shrink-0 cursor-pointer border transition-colors ${+ recordWithOsModifier+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] border-transparent font-semibold'+ : 'bg-[#161616] text-[#d4d4d4] border-white/[0.14] hover:bg-[#2c2c2c]'+ }`}+ title={`Combine the next key press with the ${osKeyLabel} (OS) modifier key`}+ >+ + {osKeyLabel} {recordWithOsModifier ? 'ON' : ''}+ </button>+ </div>+ ) : (+ <div className="text-[10px] text-[#8a8a8a] px-0.5">+ Click any key badge to rebind. Supports <span className="font-mono text-[#b5b5b5]">Ctrl</span>,{' '}+ <span className="font-mono text-[#b5b5b5]">{osKeyLabel} (OS)</span>,{' '}+ <span className="font-mono text-[#b5b5b5]">Shift</span>, and{' '}+ <span className="font-mono text-[#b5b5b5]">Alt</span> — including direct shortcuts for custom sub tools & groups.+ </div>+ )}+{/* Conflict Resolution Banner */}{pendingConflict && (<div className="p-2.5 rounded bg-amber-500/10 border border-amber-500/40 flex items-center justify-between gap-2 text-[11px]">@@ -987,6 +1306,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({<span className="text-[9px] px-1.5 py-0.5 rounded bg-[#161616] text-[#8a8a8a]">{cmd.category}</span>+ {cmd.groupBadge && (+ <span className="text-[9px] px-1.5 py-0.5 rounded bg-[#262626] text-[#b5b5b5] shrink-0">+ {cmd.groupBadge}+ </span>+ )}{cmd.springLoaded && (<spanclassName="text-[9px] px-1.5 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)]"@@ -1004,8 +1328,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({<div className="flex items-center gap-1 shrink-0"><buttontype="button"+ data-testid={`settings-shortcut-record-${cmd.id}`}onClick={() => {setPendingConflict(null);+ setRecordWithOsModifier(false);setRecordingCommandId(isRecording ? null : cmd.id);}}className={`px-2 py-1 rounded font-mono text-[10px] min-w-[84px] text-center transition-colors cursor-pointer ${diff --git a/src/components/StatusBar.tsx b/src/components/StatusBar.tsxindex f82cfbc..4a269f6 100644--- a/src/components/StatusBar.tsx+++ b/src/components/StatusBar.tsx@@ -18,12 +18,15 @@ interface StatusBarProps {zoom: number;rotation: number;onResetRotation: () => void;+ onResetZoomTo100?: () => void;colorMode?: CanvasColorMode;showCursorCoordinates?: boolean;showPressureInStatusBar?: boolean;hasOpenDocument?: boolean;themePreset?: ThemePreset;softProofSettings?: SoftProofSettings;+ valueCheckEnabled?: boolean;+ onToggleValueCheck?: () => void;}export const StatusBar: React.FC<StatusBarProps> = React.memo(({@@ -32,12 +35,15 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({zoom,rotation,onResetRotation,+ onResetZoomTo100,colorMode = 'color',showCursorCoordinates = true,showPressureInStatusBar = true,hasOpenDocument = true,themePreset: _themePreset = 'modern',softProofSettings,+ valueCheckEnabled = false,+ onToggleValueCheck,}) => {const posTextRef = useRef<HTMLSpanElement>(null);const pressureBarRef = useRef<HTMLDivElement>(null);@@ -110,6 +116,20 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({</span></>)}+ {valueCheckEnabled && (+ <>+ <span className="text-white/20">|</span>+ <button+ type="button"+ data-testid="status-value-check-badge"+ onClick={onToggleValueCheck}+ className="text-[var(--modern-accent)] hover:text-white font-mono text-[10px] font-medium cursor-pointer transition-colors"+ title="1-Click Value Check (Live B/W Tone Check) is ON — Click or press Shift+Y to disable"+ >+ [Value Check: B/W]+ </button>+ </>+ )}</>) : (<span className="text-white/30 italic text-[10px]">No active document</span>@@ -167,8 +187,19 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({{/* Zoom */}<div- className={`bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-1.5 ${hasOpenDocument ? '' : 'opacity-40'}`}- title="Canvas Zoom Level"+ onClick={hasOpenDocument ? onResetZoomTo100 : undefined}+ className={`bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-1.5 ${+ hasOpenDocument+ ? onResetZoomTo100+ ? 'cursor-pointer hover:bg-white/[0.08] text-white/90 hover:text-white'+ : ''+ : 'opacity-40 pointer-events-none'+ }`}+ title={+ onResetZoomTo100+ ? 'Canvas Zoom Level (Click to Reset to 100% — Ctrl+1)'+ : 'Canvas Zoom Level'+ }><span className="text-white/40 text-[10px]">Zoom:</span><span className="text-white/90 font-medium text-[11px]">{hasOpenDocument ? formatZoomPercent(zoom) : '—'}</span>diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsxindex bcc9ace..05d5676 100644--- a/src/components/SubToolList.tsx+++ b/src/components/SubToolList.tsx@@ -1,4 +1,5 @@-import React, { useState, useRef } from 'react';+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';import {Droplets,Paintbrush,@@ -11,12 +12,32 @@ import {Trash2,Loader2,FolderDown,+ FolderPlus,+ Folder,ChevronDown,ChevronRight,Sliders,AlertTriangle,+ Star,+ Sparkles,+ Layers,+ MoreHorizontal,+ Keyboard,+ PencilLine,+ ArrowLeft,+ ArrowRight,+ Check,+ X,+ Undo2,+ GripVertical,} from 'lucide-react';-import { BrushCategory, BrushPresetId, CspBrush } from '../types/editor';+import {+ BrushCategory,+ BrushPresetId,+ CspBrush,+ DecorationCategory,+ isPaintTool,+} from '../types/editor';import {buildExportableBrush,exportBrushToInkbFile,@@ -25,72 +46,475 @@ import {} from '../utils/inkbBrushFormat';import {deleteCustomBrush,- prepareBrushSettingsForCsp,saveCustomBrush,} from '../utils/brushStorage';import {+ ALL_BUILTIN_BRUSHES,+ ALL_BUILTIN_BRUSH_SECTIONS,BUILTIN_BRUSHES,BUILTIN_BRUSH_SECTIONS,+ DECORATION_BRUSHES,+ DECORATION_BRUSH_SECTIONS,+ DEFAULT_DECORATION_PRESET_ID,BuiltinBrushDefinition,+ isDecorationCategory,+ resolveStaticBrushAssetUrl,} from '../utils/presetBrushes';import {DEFAULT_BRUSH_PRESET_ID,- NEUTRAL_BRUSH_DEFAULTS,- getEffectiveBrushSettings,- getSavedBrushSettings,+ migrateLegacyPresetId,+ saveActiveDecorationPresetId,saveActivePresetId,} from '../utils/brushPresetManager';-import { useToolStore, toolStoreActions, uiStoreActions } from '../stores';+import {+ useToolStore,+ useUiStore,+ uiStoreActions,+ useWorkspaceStore,+ workspaceStoreActions,+ useSubToolGroupStore,+ subToolGroupStoreActions,+} from '../stores';+import {+ BuiltinTargetGroupId,+ CustomSubToolGroup,+ SUBTOOL_GROUP_COLOR_SWATCHES,+ SubToolGroupIconId,+ getEffectiveBrushGroupId,+ getFactoryGroupIdForBrush,+ getGroupDisplayLabel,+ getOrderedBrushIdsInBuiltinGroup,+ isBuiltinGroupTab,+ isBuiltinTargetGroupId,+ isDecorationCustomGroup,+} from '../utils/subToolGroups';+import { activateSubToolPreset } from '../utils/subToolNavigation';+import {+ DEFAULT_COMMANDS,+ buildSubToolShortcutCommands,+ formatShortcutLabel,+ getSubToolCommandId,+ getSubToolGroupCommandId,+} from '../utils/shortcutManager';+import { SubToolShortcutModal } from './SubToolShortcutModal';export interface SubToolListProps {customBrushes: CspBrush[];setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;}+type BrushPointerDropTarget =+ | { kind: 'create-group' }+ | { kind: 'group-tab'; groupId: string }+ | { kind: 'group-section'; groupId: string }+ | {+ kind: 'brush-row';+ groupId: string;+ targetPresetId: BrushPresetId;+ position: 'before' | 'after';+ }+ | { kind: 'quick-brush-panel' };++interface ActiveBrushPointerDrag {+ presetId: BrushPresetId;+ name: string;+ sourceGroupId: string;+ pointerX: number;+ pointerY: number;+ target: BrushPointerDropTarget | null;+}++interface ActiveGroupTabPointerDrag {+ groupId: string;+ name: string;+ pointerX: number;+ pointerY: number;+ targetGroupId: string | null;+}+function renderBuiltinIcon(icon: BuiltinBrushDefinition['icon']) {if (icon === 'pen') return <PenTool className="w-3 h-3 shrink-0 opacity-80" />;if (icon === 'pencil') return <Pencil className="w-3 h-3 shrink-0 opacity-80" />;if (icon === 'droplets') return <Droplets className="w-3 h-3 shrink-0 text-sky-300/85" />;if (icon === 'palette') return <Palette className="w-3 h-3 shrink-0 text-rose-300/85" />;+ if (icon === 'sparkles') return <Sparkles className="w-3 h-3 shrink-0 text-violet-300/85" />;return <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />;}+function renderGroupIcon(icon: SubToolGroupIconId | undefined, color?: string | null) {+ const style = color ? { color } : undefined;+ const cls = 'w-2.5 h-2.5 shrink-0';+ switch (icon) {+ case 'pen':+ return <PenTool className={cls} style={style} />;+ case 'pencil':+ return <Pencil className={cls} style={style} />;+ case 'paintbrush':+ return <Paintbrush className={cls} style={style} />;+ case 'droplets':+ return <Droplets className={cls} style={style} />;+ case 'palette':+ return <Palette className={cls} style={style} />;+ case 'sparkles':+ return <Sparkles className={cls} style={style} />;+ case 'star':+ return <Star className={cls} style={style} />;+ case 'layers':+ return <Layers className={cls} style={style} />;+ case 'folder':+ default:+ return <Folder className={cls} style={style} />;+ }+}++function shortBuiltinTabLabel(id: BrushCategory, fallback: string): string {+ if (id === 'natural-paint') return 'Natural';+ return fallback;+}++function pointInRect(x: number, y: number, rect: DOMRect): boolean {+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;+}++/**+ * Pure hit-test for pointer-driven brush drag-and-drop (works reliably in Tauri 2 WebView2,+ * browsers, mouse, and stylus without HTML5 drag-drop interference).+ */+function detectBrushDropTarget(+ clientX: number,+ clientY: number,+ draggedPresetId: BrushPresetId,+ rootEl: HTMLElement | null+): BrushPointerDropTarget | null {+ if (typeof document === 'undefined') return null;++ // 1. Check floating Quick Brush Panel first (outside SubToolList root)+ const quickPanel = document.querySelector?.('[data-testid="quick-brush-panel"]') as HTMLElement | null;+ if (quickPanel && pointInRect(clientX, clientY, quickPanel.getBoundingClientRect())) {+ return { kind: 'quick-brush-panel' };+ }++ if (!rootEl) return null;++ // 2. Check "+ Group" button directly+ const createBtns = rootEl.querySelectorAll?.('[data-subtool-drop="create-group"]');+ if (createBtns) {+ for (let i = 0; i < createBtns.length; i++) {+ const el = createBtns[i] as HTMLElement;+ if (pointInRect(clientX, clientY, el.getBoundingClientRect())) {+ return { kind: 'create-group' };+ }+ }+ }++ // 3. Check specific group tabs (custom & built-in)+ const tabEls = rootEl.querySelectorAll?.('[data-subtool-drop-tab]');+ if (tabEls) {+ for (let i = 0; i < tabEls.length; i++) {+ const el = tabEls[i] as HTMLElement;+ const gid = el.getAttribute('data-subtool-drop-tab');+ if (gid && pointInRect(clientX, clientY, el.getBoundingClientRect())) {+ return { kind: 'group-tab', groupId: gid };+ }+ }+ }++ // 4. Empty space on the tab bar -> CSP drag-to-create new group!+ const tabBar = rootEl.querySelector?.(+ '[data-testid="subtool-group-tab-bar"], [data-testid="subtool-decoration-tab-bar"]'+ ) as HTMLElement | null;+ if (tabBar && pointInRect(clientX, clientY, tabBar.getBoundingClientRect())) {+ return { kind: 'create-group' };+ }++ // 5. Check individual brush rows for precise before/after insertion+ const rowEls = rootEl.querySelectorAll?.('[data-subtool-drop-row]');+ if (rowEls) {+ for (let i = 0; i < rowEls.length; i++) {+ const el = rowEls[i] as HTMLElement;+ const rect = el.getBoundingClientRect();+ if (!pointInRect(clientX, clientY, rect)) continue;+ const raw = el.getAttribute('data-subtool-drop-row');+ if (!raw) continue;+ const sep = raw.indexOf('|');+ if (sep < 0) continue;+ const groupId = raw.slice(0, sep);+ const targetPresetId = raw.slice(sep + 1);+ if (targetPresetId === draggedPresetId) {+ return { kind: 'group-section', groupId };+ }+ const midY = rect.top + rect.height / 2;+ return {+ kind: 'brush-row',+ groupId,+ targetPresetId,+ position: clientY < midY ? 'before' : 'after',+ };+ }+ }++ // 6. Check group section containers (headers, empty zones, bottom padding)+ const secEls = rootEl.querySelectorAll?.('[data-subtool-drop-section]');+ if (secEls) {+ for (let i = 0; i < secEls.length; i++) {+ const el = secEls[i] as HTMLElement;+ const gid = el.getAttribute('data-subtool-drop-section');+ if (gid && pointInRect(clientX, clientY, el.getBoundingClientRect())) {+ return { kind: 'group-section', groupId: gid };+ }+ }+ }++ return null;+}++function detectCustomGroupTabDropTarget(+ clientX: number,+ clientY: number,+ draggedGroupId: string,+ rootEl: HTMLElement | null+): string | null {+ if (!rootEl) return null;+ const tabEls = rootEl.querySelectorAll?.('[data-subtool-custom-tab]');+ if (!tabEls) return null;+ for (let i = 0; i < tabEls.length; i++) {+ const el = tabEls[i] as HTMLElement;+ const gid = el.getAttribute('data-subtool-custom-tab');+ if (gid && gid !== draggedGroupId && pointInRect(clientX, clientY, el.getBoundingClientRect())) {+ return gid;+ }+ }+ return null;+}+export const SubToolList: React.FC<SubToolListProps> = React.memo(({ customBrushes, setCustomBrushes }) => {const currentTool = useToolStore((s) => s.tool);const activePreset = useToolStore((s) => s.activePresetId);+ const quickBrushIds = useWorkspaceStore((s) => s.quickBrushPanel.brushIds);+ const quickBrushVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);+ const customGroups = useSubToolGroupStore((s) => s.groups);+ const activeTab = useSubToolGroupStore((s) => s.activeTab);+ const activeDecorationTab = useSubToolGroupStore((s) => s.activeDecorationTab);+ const brushGroupOverrides = useSubToolGroupStore((s) => s.brushGroupOverrides);+ const builtinGroupOrders = useSubToolGroupStore((s) => s.builtinGroupOrders);+ const appSettings = useUiStore((s) => s.appSettings);+ const shortcuts = appSettings.shortcuts;+ const isDecorationMode = currentTool === 'decoration';++ const quickBrushSet = useMemo(+ () => new Set(quickBrushIds.map((id) => migrateLegacyPresetId(id))),+ [quickBrushIds]+ );++ const builtinById = useMemo(+ () => new Map<string, BuiltinBrushDefinition>(ALL_BUILTIN_BRUSHES.map((b) => [b.id, b])),+ []+ );++ const customById = useMemo(+ () => new Map<string, CspBrush>(customBrushes.map((b) => [b.id, b])),+ [customBrushes]+ );++ const allShortcutCommands = useMemo(+ () => [...DEFAULT_COMMANDS, ...buildSubToolShortcutCommands(customBrushes, customGroups)],+ [customBrushes, customGroups]+ );const [isImportingSut, setIsImportingSut] = useState(false);const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});+ const [isCreatingGroup, setIsCreatingGroup] = useState(false);+ const [newGroupName, setNewGroupName] = useState('');+ const [newGroupColor, setNewGroupColor] = useState<string | null>('#818cf8');+ const [renamingGroupId, setRenamingGroupId] = useState<string | null>(null);+ const [renameDraft, setRenameDraft] = useState('');+ const [addBrushesGroupId, setAddBrushesGroupId] = useState<string | null>(null);++ // Pointer-event drag-and-drop state (works natively in Tauri 2 WebView2 & browsers)+ const [activeBrushDrag, setActiveBrushDrag] = useState<ActiveBrushPointerDrag | null>(null);+ const [activeGroupDrag, setActiveGroupDrag] = useState<ActiveGroupTabPointerDrag | null>(null);+ const suppressNextClickRef = useRef(false);++ const [brushContextMenu, setBrushContextMenu] = useState<{+ presetId: BrushPresetId;+ name: string;+ isCustom: boolean;+ customBrush?: CspBrush;+ x: number;+ y: number;+ } | null>(null);++ const [groupContextMenu, setGroupContextMenu] = useState<{+ group: CustomSubToolGroup;+ index: number;+ x: number;+ y: number;+ } | null>(null);++ const [shortcutModalTarget, setShortcutModalTarget] = useState<{+ commandId: string;+ label: string;+ kind: 'subtool' | 'group';+ } | null>(null);++ const rootRef = useRef<HTMLDivElement>(null);+ const scrollListRef = useRef<HTMLDivElement>(null);const sutInputRef = useRef<HTMLInputElement>(null);+ const contextMenuRef = useRef<HTMLDivElement>(null);++ // Keep latest data accessible inside window pointer drag listeners+ const customGroupsRef = useRef(customGroups);+ customGroupsRef.current = customGroups;+ const customBrushesRef = useRef(customBrushes);+ customBrushesRef.current = customBrushes;++ // Close context menus on outside click or Escape+ useEffect(() => {+ if (!brushContextMenu && !groupContextMenu) return;+ const handleOutside = (e: MouseEvent) => {+ if (contextMenuRef.current?.contains(e.target as Node)) return;+ setBrushContextMenu(null);+ setGroupContextMenu(null);+ };+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ setBrushContextMenu(null);+ setGroupContextMenu(null);+ }+ };+ window.addEventListener('mousedown', handleOutside);+ window.addEventListener('keydown', handleKey);+ return () => {+ window.removeEventListener('mousedown', handleOutside);+ window.removeEventListener('keydown', handleKey);+ };+ }, [brushContextMenu, groupContextMenu]);++ const brushCustomGroups = useMemo(+ () => customGroups.filter((g) => !isDecorationCustomGroup(g)),+ [customGroups]+ );+ const decorationCustomGroups = useMemo(+ () => customGroups.filter((g) => isDecorationCustomGroup(g)),+ [customGroups]+ );+ const scopedCustomGroups = isDecorationMode ? decorationCustomGroups : brushCustomGroups;++ // Ensure activeTab remains valid if a custom group was deleted externally+ const effectiveActiveTab = useMemo(() => {+ if (activeTab === 'all' || activeTab === 'custom' || isBuiltinGroupTab(activeTab)) {+ return activeTab;+ }+ return brushCustomGroups.some((g) => g.id === activeTab) ? activeTab : 'all';+ }, [activeTab, brushCustomGroups]);++ const effectiveActiveDecorationTab = useMemo(() => {+ if (activeDecorationTab === 'all' || isDecorationCategory(activeDecorationTab)) {+ return activeDecorationTab;+ }+ return decorationCustomGroups.some((g) => g.id === activeDecorationTab)+ ? activeDecorationTab+ : 'all';+ }, [activeDecorationTab, decorationCustomGroups]);++ const activeCustomGroup = useMemo(() => {+ const targetTab = isDecorationMode ? effectiveActiveDecorationTab : effectiveActiveTab;+ return scopedCustomGroups.find((g) => g.id === targetTab) ?? null;+ }, [isDecorationMode, effectiveActiveDecorationTab, effectiveActiveTab, scopedCustomGroups]);++ const builtinGroupMemberIds = useMemo(() => {+ const map: Record<BuiltinTargetGroupId, BrushPresetId[]> = {+ pen: [],+ sketch: [],+ brush: [],+ blend: [],+ 'natural-paint': [],+ 'deco-background': [],+ 'deco-clothing': [],+ 'deco-effect': [],+ custom: [],+ };+ for (const sec of ALL_BUILTIN_BRUSH_SECTIONS) {+ map[sec.id] = getOrderedBrushIdsInBuiltinGroup(+ sec.id,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ }+ map.custom = getOrderedBrushIdsInBuiltinGroup(+ 'custom',+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ return map;+ }, [customGroups, customBrushes, brushGroupOverrides, builtinGroupOrders]);++ const builtinGroupMemberIdsRef = useRef(builtinGroupMemberIds);+ builtinGroupMemberIdsRef.current = builtinGroupMemberIds;++ const handleTogglePinToQuickPanel = (+ presetId: BrushPresetId,+ brushName: string,+ e?: React.MouseEvent+ ) => {+ e?.stopPropagation();+ const added = workspaceStoreActions.toggleQuickBrush(presetId);+ if (added && !useWorkspaceStore.getState().quickBrushPanel.visible) {+ workspaceStoreActions.setQuickBrushPanelVisible(true);+ }+ uiStoreActions.showToast(+ added+ ? `Added "${brushName}" to Quick Brush Panel`+ : `Removed "${brushName}" from Quick Brush Panel`+ );+ };const toggleSection = (key: string) => {setCollapsedSections((prev) => ({ ...prev, [key]: !prev[key] }));};const handleSelectBrushPreset = (presetId: BrushPresetId) => {- toolStoreActions.selectTool('brush');- saveActivePresetId(presetId);- const effective = getEffectiveBrushSettings(presetId, customBrushes);- toolStoreActions.updateBrushSettings({- ...NEUTRAL_BRUSH_DEFAULTS,- ...effective,- preset: presetId,- });+ activateSubToolPreset(presetId, customBrushes);};- const handleSelectCustomBrush = async (brush: CspBrush) => {- toolStoreActions.selectTool('brush');- saveActivePresetId(brush.id);- const prepared = await prepareBrushSettingsForCsp(brush);- const saved = getSavedBrushSettings(brush.id);- toolStoreActions.updateBrushSettings({- ...NEUTRAL_BRUSH_DEFAULTS,- ...prepared,- ...saved,- preset: brush.id,- });+ const updateShortcutOverride = (+ commandId: string,+ shortcut: string | null,+ clearConflictIds?: string[]+ ) => {+ const latest = useUiStore.getState().appSettings;+ const nextShortcuts = { ...latest.shortcuts };+ if (clearConflictIds) {+ for (const cid of clearConflictIds) {+ nextShortcuts[cid] = '';+ }+ }+ if (shortcut === null) {+ delete nextShortcuts[commandId];+ } else {+ nextShortcuts[commandId] = shortcut;+ }+ uiStoreActions.updateAppSettings({ ...latest, shortcuts: nextShortcuts });+ if (shortcut) {+ uiStoreActions.showToast(`Shortcut assigned: ${formatShortcutLabel(shortcut)}`);+ } else {+ uiStoreActions.showToast('Shortcut cleared');+ }+ };++ const removeOrphanShortcut = (commandId: string) => {+ const latest = useUiStore.getState().appSettings;+ if (Object.prototype.hasOwnProperty.call(latest.shortcuts, commandId)) {+ const nextShortcuts = { ...latest.shortcuts };+ delete nextShortcuts[commandId];+ uiStoreActions.updateAppSettings({ ...latest, shortcuts: nextShortcuts });+ }};const handleImportBrush = async (file: File) => {@@ -104,7 +528,25 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(b.name.toLowerCase() !== parsedBrush.name.toLowerCase() && b.id !== parsedBrush.id),]);- saveActivePresetId(parsedBrush.id);+ if (isDecorationMode) {+ if (activeCustomGroup) {+ subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, activeCustomGroup.id);+ } else {+ const targetDecoGroup = isDecorationCategory(effectiveActiveDecorationTab)+ ? effectiveActiveDecorationTab+ : 'deco-effect';+ subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, targetDecoGroup);+ }+ saveActiveDecorationPresetId(parsedBrush.id);+ } else if (activeCustomGroup) {+ subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, activeCustomGroup.id);+ saveActivePresetId(parsedBrush.id);+ } else if (isBuiltinGroupTab(effectiveActiveTab)) {+ subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, effectiveActiveTab);+ saveActivePresetId(parsedBrush.id);+ } else {+ saveActivePresetId(parsedBrush.id);+ }if (parsedBrush.importWarnings && parsedBrush.importWarnings.length > 0) {const count = parsedBrush.importWarnings.length;const first = parsedBrush.importWarnings[0];@@ -114,7 +556,11 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(: `Imported "${parsedBrush.name}" with ${count} CSP import notices — check inspector`);} else {- uiStoreActions.showToast(`Imported brush "${parsedBrush.name}"`);+ uiStoreActions.showToast(+ activeCustomGroup+ ? `Imported "${parsedBrush.name}" into "${activeCustomGroup.name}"`+ : `Imported brush "${parsedBrush.name}"`+ );}} catch (err: unknown) {const msg =@@ -143,8 +589,8 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(}};- const handleDeleteCustomBrush = async (e: React.MouseEvent, brush: CspBrush) => {- e.stopPropagation();+ const handleDeleteCustomBrush = async (e: React.MouseEvent | undefined, brush: CspBrush) => {+ e?.stopPropagation();const subtitle = brush.badge? `${brush.badge} brush`: 'Imported custom brush';@@ -163,9 +609,14 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(});if (confirmed) {await deleteCustomBrush(brush.id);+ workspaceStoreActions.removeQuickBrush(brush.id);+ subToolGroupStoreActions.removeBrushFromAllGroups(brush.id);+ removeOrphanShortcut(getSubToolCommandId(brush.id));setCustomBrushes((prev) => prev.filter((b) => b.id !== brush.id));if (activePreset === brush.id) {- handleSelectBrushPreset(DEFAULT_BRUSH_PRESET_ID);+ handleSelectBrushPreset(+ isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID+ );}}};@@ -173,22 +624,37 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(const handleCreateNewBrush = async () => {const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;const base = buildExportableBrush('impasto-bristle-oil', customBrushes);+ const targetCategory: BrushCategory = isDecorationMode+ ? isDecorationCategory(effectiveActiveDecorationTab)+ ? effectiveActiveDecorationTab+ : 'deco-effect'+ : 'natural-paint';const newBrush: CspBrush = {...base,id,- name: 'New Natural Brush',- category: 'natural-paint',- badge: 'Studio',+ name: isDecorationMode ? 'New Decoration Brush' : 'New Natural Brush',+ category: targetCategory,+ badge: isDecorationMode ? 'Decoration' : 'Studio',importedAt: Date.now(),};await saveCustomBrush(newBrush);setCustomBrushes((prev) => [newBrush, ...prev]);- await handleSelectCustomBrush(newBrush);+ if (isDecorationMode) {+ subToolGroupStoreActions.moveBrushToGroup(+ newBrush.id,+ activeCustomGroup ? activeCustomGroup.id : targetCategory+ );+ } else if (activeCustomGroup) {+ subToolGroupStoreActions.moveBrushToGroup(newBrush.id, activeCustomGroup.id);+ } else if (isBuiltinGroupTab(effectiveActiveTab)) {+ subToolGroupStoreActions.moveBrushToGroup(newBrush.id, effectiveActiveTab);+ }+ activateSubToolPreset(newBrush.id, [newBrush, ...customBrushes]);uiStoreActions.setBrushStudioModalOpen(true);};- const handleDuplicateActiveBrush = async () => {- const sourceId = activePreset || DEFAULT_BRUSH_PRESET_ID;+ const handleDuplicateActiveBrush = async (sourcePresetId?: BrushPresetId) => {+ const sourceId = sourcePresetId || activePreset || DEFAULT_BRUSH_PRESET_ID;const liveSettings = useToolStore.getState().brushSettings;const exported = buildExportableBrush(sourceId, customBrushes, liveSettings);const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;@@ -200,16 +666,771 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(importedAt: Date.now(),};await saveCustomBrush(dupBrush);- setCustomBrushes((prev) => [dupBrush, ...prev]);- await handleSelectCustomBrush(dupBrush);+ const nextList = [dupBrush, ...customBrushes];+ setCustomBrushes(nextList);+ const ownerGroupId = getEffectiveBrushGroupId(+ sourceId,+ customGroups,+ brushGroupOverrides,+ customBrushes+ );+ if (ownerGroupId && ownerGroupId !== 'custom') {+ subToolGroupStoreActions.moveBrushToGroup(dupBrush.id, ownerGroupId);+ }+ activateSubToolPreset(dupBrush.id, nextList);uiStoreActions.setBrushStudioModalOpen(true);};- const brushesByCategory = (cat: BrushCategory) =>- BUILTIN_BRUSHES.filter((b) => b.category === cat);+ const handleCommitCreateGroup = () => {+ const created = subToolGroupStoreActions.createGroup({+ name: newGroupName.trim() || `Custom Group ${scopedCustomGroups.length + 1}`,+ color: newGroupColor,+ toolScope: isDecorationMode ? 'decoration' : 'brush',+ selectTab: true,+ });+ setIsCreatingGroup(false);+ setNewGroupName('');+ uiStoreActions.showToast(`Created Sub Tool group "${created.name}"`);+ };++ const handleCreateGroupFromBrush = useCallback((presetId: BrushPresetId, brushName: string) => {+ const decoScope = useToolStore.getState().tool === 'decoration';+ const existingCount = useSubToolGroupStore+ .getState()+ .groups.filter((g) => (decoScope ? isDecorationCustomGroup(g) : !isDecorationCustomGroup(g)))+ .length;+ const created = subToolGroupStoreActions.createGroup({+ name: `Custom Group ${existingCount + 1}`,+ color: '#818cf8',+ toolScope: decoScope ? 'decoration' : 'brush',+ initialBrushIds: [presetId],+ selectTab: true,+ });+ setRenamingGroupId(created.id);+ setRenameDraft(created.name);+ uiStoreActions.showToast(`Created "${created.name}" with "${brushName}"`);+ }, []);++ const handleDeleteCustomGroup = async (group: CustomSubToolGroup) => {+ const confirmed = await uiStoreActions.confirmDialog({+ variant: 'danger',+ title: 'Delete Sub Tool Group',+ message: `Delete custom group "${group.name}"?`,+ detail:+ group.brushIds.length > 0+ ? `Its ${group.brushIds.length} sub tool${group.brushIds.length === 1 ? '' : 's'} will safely return to their default sections.`+ : 'This removes the empty custom Sub Tool group.',+ confirmLabel: 'Delete Group',+ cancelLabel: 'Cancel',+ });+ if (confirmed) {+ subToolGroupStoreActions.deleteGroup(group.id);+ removeOrphanShortcut(getSubToolGroupCommandId(group.id));+ if (addBrushesGroupId === group.id) setAddBrushesGroupId(null);+ uiStoreActions.showToast(`Deleted group "${group.name}"`);+ }+ };++ const handleCommitRenameGroup = (groupId: string) => {+ const trimmed = renameDraft.trim();+ if (trimmed) {+ subToolGroupStoreActions.renameGroup(groupId, trimmed);+ }+ setRenamingGroupId(null);+ setRenameDraft('');+ };++ const openBrushMenu = (+ e: React.MouseEvent,+ presetId: BrushPresetId,+ name: string,+ customBrush?: CspBrush+ ) => {+ e.preventDefault();+ e.stopPropagation();+ setGroupContextMenu(null);+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ setBrushContextMenu({+ presetId,+ name,+ isCustom: Boolean(customBrush),+ customBrush,+ x: Math.max(8, Math.min(vw - 216, e.clientX)),+ y: Math.max(40, Math.min(vh - 340, e.clientY)),+ });+ };++ const openGroupMenu = (e: React.MouseEvent, group: CustomSubToolGroup, index: number) => {+ e.preventDefault();+ e.stopPropagation();+ setBrushContextMenu(null);+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ setGroupContextMenu({+ group,+ index,+ x: Math.max(8, Math.min(vw - 196, e.clientX)),+ y: Math.max(40, Math.min(vh - 240, e.clientY)),+ });+ };++ // Unified Pointer-Event Drag for Brush Rows (works in Tauri 2 Windows WebView2 + Browser + Stylus!)+ const startBrushPointerDrag = useCallback(+ (+ e: React.PointerEvent<HTMLDivElement>,+ presetId: BrushPresetId,+ name: string,+ sourceGroupId: string+ ) => {+ if (e.button !== 0) return;+ // Never hijack clicks on inner action buttons (Pin star, menu, export, delete)+ if ((e.target as HTMLElement | null)?.closest?.('button, input')) return;++ const startX = e.clientX;+ const startY = e.clientY;+ let isDragging = false;+ let latestTarget: BrushPointerDropTarget | null = null;++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ window.removeEventListener('keydown', onKeyDown);+ if (typeof document !== 'undefined' && document.body?.style) {+ document.body.style.cursor = '';+ }+ setActiveBrushDrag(null);+ };++ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape' && isDragging) {+ ev.preventDefault();+ ev.stopPropagation();+ cleanup();+ }+ };++ const onMove = (ev: PointerEvent) => {+ const dist = Math.hypot(ev.clientX - startX, ev.clientY - startY);+ if (!isDragging) {+ if (dist < 6) return;+ isDragging = true;+ setBrushContextMenu(null);+ setGroupContextMenu(null);+ if (typeof document !== 'undefined' && document.body?.style) {+ document.body.style.cursor = 'grabbing';+ }+ }++ // Gentle auto-scroll near top/bottom of SubToolList scroll area+ const scrollEl = scrollListRef.current;+ if (scrollEl) {+ const sr = scrollEl.getBoundingClientRect();+ if (ev.clientX >= sr.left && ev.clientX <= sr.right) {+ if (ev.clientY >= sr.top && ev.clientY < sr.top + 22) {+ scrollEl.scrollTop -= 8;+ } else if (ev.clientY <= sr.bottom && ev.clientY > sr.bottom - 22) {+ scrollEl.scrollTop += 8;+ }+ }+ }++ latestTarget = detectBrushDropTarget(ev.clientX, ev.clientY, presetId, rootRef.current);+ setActiveBrushDrag({+ presetId,+ name,+ sourceGroupId,+ pointerX: ev.clientX,+ pointerY: ev.clientY,+ target: latestTarget,+ });+ };++ const onCancel = () => {+ cleanup();+ };++ const onUp = () => {+ const wasDragging = isDragging;+ const finalTarget = latestTarget;+ cleanup();+ if (!wasDragging) return;++ // Suppress the synthetic trailing click right after drag release+ suppressNextClickRef.current = true;+ setTimeout(() => {+ suppressNextClickRef.current = false;+ }, 0);++ if (!finalTarget) return;++ if (finalTarget.kind === 'create-group') {+ handleCreateGroupFromBrush(presetId, name);+ return;+ }++ if (finalTarget.kind === 'quick-brush-panel') {+ const added = workspaceStoreActions.addQuickBrush(presetId);+ uiStoreActions.showToast(+ added ? `Added "${name}" to Quick Brushes` : `"${name}" is already in Quick Brushes`+ );+ return;+ }++ if (finalTarget.kind === 'brush-row') {+ const visibleIds = isBuiltinTargetGroupId(finalTarget.groupId)+ ? builtinGroupMemberIdsRef.current[finalTarget.groupId]+ : undefined;+ subToolGroupStoreActions.reorderBrushInGroup(+ finalTarget.groupId,+ presetId,+ finalTarget.targetPresetId,+ finalTarget.position,+ visibleIds+ );+ if (finalTarget.groupId !== sourceGroupId) {+ const targetLabel = getGroupDisplayLabel(+ finalTarget.groupId,+ customGroupsRef.current+ );+ uiStoreActions.showToast(`Moved "${name}" to "${targetLabel}"`);+ }+ return;+ }++ if (finalTarget.kind === 'group-tab' || finalTarget.kind === 'group-section') {+ if (finalTarget.groupId === sourceGroupId) return;+ const visibleIds = isBuiltinTargetGroupId(finalTarget.groupId)+ ? builtinGroupMemberIdsRef.current[finalTarget.groupId]+ : undefined;+ const moved = subToolGroupStoreActions.moveBrushToGroup(+ presetId,+ finalTarget.groupId,+ undefined,+ visibleIds+ );+ if (moved) {+ const targetLabel = getGroupDisplayLabel(+ finalTarget.groupId,+ customGroupsRef.current+ );+ uiStoreActions.showToast(`Moved "${name}" to "${targetLabel}"`);+ }+ }+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ window.addEventListener('keydown', onKeyDown);+ },+ [handleCreateGroupFromBrush]+ );++ // Unified Pointer-Event Drag for Reordering Custom Group Tabs+ const startCustomGroupTabDrag = useCallback(+ (e: React.PointerEvent<HTMLButtonElement>, group: CustomSubToolGroup) => {+ if (e.button !== 0) return;+ const startX = e.clientX;+ const startY = e.clientY;+ let isDragging = false;+ let latestTargetGroupId: string | null = null;++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ window.removeEventListener('keydown', onKeyDown);+ setActiveGroupDrag(null);+ };++ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape' && isDragging) {+ ev.preventDefault();+ cleanup();+ }+ };++ const onMove = (ev: PointerEvent) => {+ if (!isDragging) {+ if (Math.hypot(ev.clientX - startX, ev.clientY - startY) < 6) return;+ isDragging = true;+ }+ latestTargetGroupId = detectCustomGroupTabDropTarget(+ ev.clientX,+ ev.clientY,+ group.id,+ rootRef.current+ );+ setActiveGroupDrag({+ groupId: group.id,+ name: group.name,+ pointerX: ev.clientX,+ pointerY: ev.clientY,+ targetGroupId: latestTargetGroupId,+ });+ };++ const onCancel = () => cleanup();++ const onUp = () => {+ const wasDragging = isDragging;+ const targetId = latestTargetGroupId;+ cleanup();+ if (!wasDragging) return;+ suppressNextClickRef.current = true;+ setTimeout(() => {+ suppressNextClickRef.current = false;+ }, 0);+ if (targetId && targetId !== group.id) {+ subToolGroupStoreActions.reorderGroup(group.id, targetId);+ }+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ window.addEventListener('keydown', onKeyDown);+ },+ []+ );++ const resolveMemberEntry = (+ presetId: BrushPresetId+ ): { id: BrushPresetId; builtin?: BuiltinBrushDefinition; custom?: CspBrush } | null => {+ const custom = customById.get(presetId);+ if (custom) return { id: custom.id, custom };+ const norm = migrateLegacyPresetId(presetId);+ const builtin = builtinById.get(norm);+ if (builtin) return { id: builtin.id, builtin };+ return null;+ };++ const renderBrushRow = (+ presetId: BrushPresetId,+ options: {+ builtin?: BuiltinBrushDefinition;+ custom?: CspBrush;+ ownerGroupId: string;+ }+ ) => {+ const { builtin, custom, ownerGroupId } = options;+ const name = custom ? custom.name : builtin ? builtin.name : presetId;+ const isSelected =+ isPaintTool(currentTool) &&+ (activePreset === presetId ||+ (!activePreset &&+ presetId ===+ (isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID)));+ const isPinned = quickBrushSet.has(migrateLegacyPresetId(presetId));+ const boundShortcut = shortcuts[getSubToolCommandId(presetId)] || '';++ const isBeingDragged = activeBrushDrag?.presetId === presetId;+ const dropRowMatch =+ activeBrushDrag?.target?.kind === 'brush-row' &&+ activeBrushDrag.target.groupId === ownerGroupId &&+ activeBrushDrag.target.targetPresetId === presetId+ ? activeBrushDrag.target.position+ : null;++ return (+ <div+ key={presetId}+ data-testid={`subtool-row-${presetId}`}+ data-subtool-drop-row={`${ownerGroupId}|${presetId}`}+ onPointerDown={(e) => startBrushPointerDrag(e, presetId, name, ownerGroupId)}+ onClick={() => {+ if (suppressNextClickRef.current) return;+ handleSelectBrushPreset(presetId);+ }}+ onContextMenu={(e) => openBrushMenu(e, presetId, name, custom)}+ title={+ builtin+ ? `${builtin.name} - ${builtin.desc}${boundShortcut ? ` (${formatShortcutLabel(boundShortcut)})` : ''} — Drag to move or reorder`+ : `${name}${boundShortcut ? ` (${formatShortcutLabel(boundShortcut)})` : ''} — Drag to move or reorder`+ }+ className={`relative group w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer select-none ${+ isBeingDragged+ ? 'opacity-40 bg-[#2c2c2c]/60'+ : isSelected+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'+ }`}+ >+ {/* Crisp CSP-style insertion indicator bar */}+ {dropRowMatch === 'before' && (+ <div+ data-testid={`subtool-drop-indicator-before-${presetId}`}+ className="pointer-events-none absolute left-1 right-1 -top-[1px] h-[2px] rounded-full bg-[var(--accent)] z-20"+ />+ )}+ {dropRowMatch === 'after' && (+ <div+ data-testid={`subtool-drop-indicator-after-${presetId}`}+ className="pointer-events-none absolute left-1 right-1 -bottom-[1px] h-[2px] rounded-full bg-[var(--accent)] z-20"+ />+ )}++ {custom ? (+ custom.tipDataUrl ? (+ <img+ src={custom.tipDataUrl}+ alt=""+ draggable={false}+ className="w-3 h-3 object-contain shrink-0 brightness-125 pointer-events-none"+ />+ ) : (+ <Paintbrush className="w-3 h-3 shrink-0 opacity-70" />+ )+ ) : builtin ? (+ builtin.staticTips && builtin.staticTips.length > 0 ? (+ <img+ src={resolveStaticBrushAssetUrl(builtin.staticTips[0].assetPath)}+ alt=""+ draggable={false}+ className="w-3.5 h-3.5 object-contain shrink-0 brightness-110 pointer-events-none"+ />+ ) : (+ renderBuiltinIcon(builtin.icon)+ )+ ) : (+ <Paintbrush className="w-3 h-3 shrink-0 opacity-70" />+ )}++ <span className="text-[11px] truncate leading-tight flex-1">{name}</span>++ {custom?.importWarnings && custom.importWarnings.length > 0 && (+ <span+ title={custom.importWarnings.join('\n')}+ className="text-amber-400 shrink-0"+ aria-label="Import warning"+ >+ <AlertTriangle className="w-2.5 h-2.5" />+ </span>+ )}++ {boundShortcut && (+ <span+ data-testid={`subtool-shortcut-badge-${presetId}`}+ className="text-[8.5px] font-mono px-1 py-px rounded bg-[#161616] text-[var(--accent)] border border-white/[0.08] shrink-0"+ title={`Shortcut: ${formatShortcutLabel(boundShortcut)}`}+ >+ {formatShortcutLabel(boundShortcut)}+ </span>+ )}++ <div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ data-testid={`subtool-quick-pin-${presetId}`}+ onClick={(e) => handleTogglePinToQuickPanel(presetId, name, e)}+ title={+ isPinned+ ? `Remove ${name} from Quick Brush Panel`+ : `Add ${name} to Quick Brush Panel`+ }+ aria-label={+ isPinned+ ? `Remove ${name} from Quick Brush Panel`+ : `Add ${name} to Quick Brush Panel`+ }+ aria-pressed={isPinned}+ className={`shrink-0 cursor-pointer transition-opacity ${+ isPinned+ ? 'opacity-95 text-amber-300 hover:text-amber-200'+ : 'opacity-0 group-hover:opacity-100 focus:opacity-100 text-[#8a8a8a] hover:text-amber-300'+ }`}+ >+ <Star className="w-2.5 h-2.5" fill={isPinned ? 'currentColor' : 'none'} />+ </button>+ <button+ type="button"+ data-testid={`subtool-menu-btn-${presetId}`}+ onClick={(e) => openBrushMenu(e, presetId, name, custom)}+ title={`Sub Tool options for ${name} (move group, shortcut, export)`}+ aria-label={`Options for ${name}`}+ className="opacity-0 group-hover:opacity-100 focus:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5] shrink-0 cursor-pointer"+ >+ <MoreHorizontal className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ onClick={(e) => handleExportBrush(presetId, e)}+ title={`Export ${name} (.inkb)`}+ className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5] shrink-0 cursor-pointer"+ >+ <Download className="w-2.5 h-2.5" />+ </button>+ {custom && (+ <button+ type="button"+ onClick={(e) => void handleDeleteCustomBrush(e, custom)}+ title="Delete brush"+ className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"+ >+ <Trash2 className="w-2.5 h-2.5" />+ </button>+ )}+ </div>+ </div>+ );+ };++ const renderCustomGroupSection = (+ group: CustomSubToolGroup,+ groupIndex: number,+ isFocusedSingleView: boolean+ ) => {+ const sectionKey = `custom-group:${group.id}`;+ const isCollapsed = !isFocusedSingleView && Boolean(collapsedSections[sectionKey]);+ const groupShortcut = shortcuts[getSubToolGroupCommandId(group.id)] || '';+ const isRenaming = renamingGroupId === group.id;+ const isAddingBrushes = addBrushesGroupId === group.id;+ const isSectionHighlighted =+ activeBrushDrag?.target?.kind === 'group-section' &&+ activeBrushDrag.target.groupId === group.id;++ const resolvedMembers = group.brushIds+ .map((bid) => resolveMemberEntry(bid))+ .filter((x): x is NonNullable<typeof x> => x !== null);++ return (+ <div+ key={group.id}+ data-testid={`subtool-custom-group-section-${group.id}`}+ data-subtool-drop-section={group.id}+ className={`space-y-0.5 rounded transition-colors ${+ isSectionHighlighted+ ? 'bg-[var(--accent-subtle)] ring-1 ring-[var(--accent)] p-0.5'+ : ''+ }`}+ >+ {/* Custom Group Header */}+ <div className="group/grp flex items-center justify-between gap-1 px-1 py-0.5">+ {isRenaming ? (+ <div className="flex items-center gap-1 flex-1 min-w-0">+ <input+ type="text"+ data-testid={`subtool-group-rename-input-${group.id}`}+ autoFocus+ value={renameDraft}+ maxLength={32}+ onChange={(e) => setRenameDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleCommitRenameGroup(group.id);+ if (e.key === 'Escape') {+ setRenamingGroupId(null);+ setRenameDraft('');+ }+ }}+ onBlur={() => handleCommitRenameGroup(group.id)}+ className="flex-1 min-w-0 bg-[#161616] px-1.5 py-0.5 rounded text-[10px] text-[#e5e5e5] border border-[var(--accent-border)]"+ />+ </div>+ ) : (+ <button+ type="button"+ onClick={() =>+ isFocusedSingleView ? undefined : toggleSection(sectionKey)+ }+ onDoubleClick={() => {+ setRenamingGroupId(group.id);+ setRenameDraft(group.name);+ }}+ onContextMenu={(e) => openGroupMenu(e, group, groupIndex)}+ className="flex items-center gap-1 min-w-0 flex-1 text-left text-[9.5px] uppercase tracking-wider text-[#b5b5b5] hover:text-[#f0f0f0] select-none cursor-pointer"+ title={`${group.name} (double-click to rename, right-click for options)`}+ >+ {!isFocusedSingleView &&+ (isCollapsed ? (+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />+ ) : (+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ ))}+ {group.color ? (+ <span+ className="w-1.5 h-1.5 rounded-full shrink-0"+ style={{ backgroundColor: group.color }}+ />+ ) : (+ renderGroupIcon(group.icon, group.color)+ )}+ <span className="truncate font-medium">{group.name}</span>+ <span className="text-[9px] text-[#6e6e6e] font-mono shrink-0">+ ({resolvedMembers.length})+ </span>+ </button>+ )}++ <div className="flex items-center gap-0.5 shrink-0">+ {groupShortcut && (+ <span+ data-testid={`subtool-group-shortcut-badge-${group.id}`}+ className="text-[8.5px] font-mono px-1 py-px rounded bg-[#161616] text-[var(--accent)] border border-white/[0.08]"+ title={`Group shortcut: ${formatShortcutLabel(groupShortcut)}`}+ >+ {formatShortcutLabel(groupShortcut)}+ </span>+ )}+ <button+ type="button"+ data-testid={`subtool-group-add-brushes-btn-${group.id}`}+ onClick={() =>+ setAddBrushesGroupId((cur) => (cur === group.id ? null : group.id))+ }+ title={`Add or manage brushes in "${group.name}"`}+ className={`p-0.5 rounded cursor-pointer transition-colors ${+ isAddingBrushes+ ? 'text-[var(--accent)] bg-[#2c2c2c]'+ : 'text-[#7c7c7c] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Plus className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid={`subtool-group-menu-btn-${group.id}`}+ onClick={(e) => openGroupMenu(e, group, groupIndex)}+ title={`Options for "${group.name}"`}+ className="p-0.5 rounded text-[#7c7c7c] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"+ >+ <MoreHorizontal className="w-2.5 h-2.5" />+ </button>+ </div>+ </div>++ {/* Inline Add Brushes Picker for this custom group */}+ {isAddingBrushes && (+ <div+ data-testid={`subtool-group-brush-picker-${group.id}`}+ className="mx-0.5 p-1.5 rounded bg-[#161616] border border-white/[0.08] space-y-1"+ >+ <div className="flex items-center justify-between text-[9.5px] text-[#9a9a9a]">+ <span>Assign brushes to “{group.name}”</span>+ <button+ type="button"+ onClick={() => setAddBrushesGroupId(null)}+ className="text-[#8a8a8a] hover:text-white cursor-pointer"+ aria-label="Close brush picker"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ <div className="max-h-32 overflow-y-auto space-y-0.5 pr-0.5">+ {customBrushes.map((cb) => {+ const inThisGroup = group.brushIds.includes(cb.id);+ return (+ <button+ key={cb.id}+ type="button"+ data-testid={`subtool-group-pick-${group.id}-${cb.id}`}+ onClick={() => {+ if (inThisGroup) {+ subToolGroupStoreActions.removeBrushFromAllGroups(cb.id);+ } else {+ subToolGroupStoreActions.moveBrushToGroup(cb.id, group.id);+ }+ }}+ className={`w-full flex items-center justify-between gap-1 px-1.5 py-0.5 rounded text-[10px] cursor-pointer ${+ inThisGroup+ ? 'bg-[#2c2c2c] text-[#f0f0f0]'+ : 'text-[#8a8a8a] hover:bg-[#242424] hover:text-[#e5e5e5]'+ }`}+ >+ <span className="truncate">{cb.name}</span>+ {inThisGroup ? (+ <Check className="w-2.5 h-2.5 text-[var(--accent)] shrink-0" />+ ) : (+ <Plus className="w-2.5 h-2.5 opacity-60 shrink-0" />+ )}+ </button>+ );+ })}+ {(isDecorationMode ? DECORATION_BRUSHES : BUILTIN_BRUSHES).map((bb) => {+ const inThisGroup = group.brushIds.includes(bb.id);+ return (+ <button+ key={bb.id}+ type="button"+ data-testid={`subtool-group-pick-${group.id}-${bb.id}`}+ onClick={() => {+ if (inThisGroup) {+ subToolGroupStoreActions.removeBrushFromAllGroups(bb.id);+ } else {+ subToolGroupStoreActions.moveBrushToGroup(bb.id, group.id);+ }+ }}+ className={`w-full flex items-center justify-between gap-1 px-1.5 py-0.5 rounded text-[10px] cursor-pointer ${+ inThisGroup+ ? 'bg-[#2c2c2c] text-[#f0f0f0]'+ : 'text-[#8a8a8a] hover:bg-[#242424] hover:text-[#e5e5e5]'+ }`}+ >+ <span className="truncate">{bb.name}</span>+ {inThisGroup ? (+ <Check className="w-2.5 h-2.5 text-[var(--accent)] shrink-0" />+ ) : (+ <Plus className="w-2.5 h-2.5 opacity-60 shrink-0" />+ )}+ </button>+ );+ })}+ </div>+ </div>+ )}++ {!isCollapsed &&+ (resolvedMembers.length === 0 ? (+ <div className="mx-0.5 px-2 py-2 rounded border border-dashed border-white/[0.1] bg-[#181818]/70 text-center space-y-1">+ <div className="text-[10px] text-[#7c7c7c]">+ Drag any brush here or add sub tools+ </div>+ <button+ type="button"+ onClick={() => setAddBrushesGroupId(group.id)}+ className="px-2 py-0.5 rounded bg-[#2a2a2a] hover:bg-[#343434] text-[10px] text-[#e5e5e5] cursor-pointer"+ >+ + Add Sub Tools+ </button>+ </div>+ ) : (+ resolvedMembers.map((m) =>+ renderBrushRow(m.id, {+ builtin: m.builtin,+ custom: m.custom,+ ownerGroupId: group.id,+ })+ )+ ))}+ </div>+ );+ };++ const getDragGhostHint = (drag: ActiveBrushPointerDrag): string | null => {+ const t = drag.target;+ if (!t) return null;+ if (t.kind === 'create-group') return '+ Create New Group';+ if (t.kind === 'quick-brush-panel') return '+ Pin to Quick Brushes';+ if (t.kind === 'group-tab' || t.kind === 'group-section') {+ if (t.groupId === drag.sourceGroupId) return null;+ return `Move to ${getGroupDisplayLabel(t.groupId, customGroups)}`;+ }+ if (t.kind === 'brush-row') {+ const grpLabel = getGroupDisplayLabel(t.groupId, customGroups);+ return t.groupId === drag.sourceGroupId+ ? `Reorder (${t.position})`+ : `Move to ${grpLabel}`;+ }+ return null;+ };++ const importedMemberIds = builtinGroupMemberIds.custom;+ const isCreateGroupDropActive = activeBrushDrag?.target?.kind === 'create-group';return (- <>+ <div ref={rootRef} className="flex flex-col flex-1 min-h-0 overflow-hidden">+ {/* Top Action Bar */}<div className="px-1.5 py-1 flex items-center justify-between gap-0.5 shrink-0"><div className="flex items-center gap-0.5"><button@@ -223,7 +1444,23 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</button><buttontype="button"- onClick={handleDuplicateActiveBrush}+ data-testid="subtool-toolbar-new-group-btn"+ onClick={() => {+ setIsCreatingGroup((v) => !v);+ setNewGroupName('');+ }}+ title="Create Custom Sub Tool Group"+ className={`h-5 px-1 rounded flex items-center gap-0.5 text-[10px] shrink-0 cursor-pointer transition-colors ${+ isCreatingGroup+ ? 'text-[var(--accent)] bg-[#2c2c2c]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <FolderPlus className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => void handleDuplicateActiveBrush()}title="Duplicate Active Brush"className="h-5 px-1 rounded flex items-center text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer">@@ -239,6 +1476,24 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</button></div><div className="flex items-center gap-0.5">+ <button+ type="button"+ data-testid="subtool-toggle-quick-brush-panel"+ onClick={() => workspaceStoreActions.toggleQuickBrushPanelVisible()}+ title={+ quickBrushVisible+ ? 'Hide Quick-Access Brush Panel (Shift+B)'+ : 'Show Quick-Access Brush Panel (Shift+B)'+ }+ aria-pressed={quickBrushVisible}+ className={`h-5 px-1 rounded flex items-center gap-0.5 text-[10px] shrink-0 cursor-pointer transition-colors ${+ quickBrushVisible+ ? 'text-amber-300 bg-[#2c2c2c]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Star className="w-2.5 h-2.5" fill={quickBrushVisible ? 'currentColor' : 'none'} />+ </button><buttontype="button"onClick={() => sutInputRef.current?.click()}@@ -249,7 +1504,12 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</button><buttontype="button"- onClick={() => handleExportBrush(activePreset || DEFAULT_BRUSH_PRESET_ID)}+ onClick={() =>+ handleExportBrush(+ activePreset ||+ (isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID)+ )+ }title="Export Active Brush (.inkb)"className="h-5 px-1 rounded flex items-center gap-0.5 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer">@@ -258,6 +1518,344 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</div></div>+ {/* Wrapping CSP-Style Sub Tool Group Tab Bar (scoped to Decoration when Decoration tool is active) */}+ {isDecorationMode ? (+ <div+ data-testid="subtool-decoration-tab-bar"+ className={`px-1.5 py-1 flex flex-wrap items-center gap-1 shrink-0 bg-[#1a1a1a] border-y transition-colors ${+ isCreateGroupDropActive+ ? 'border-[var(--accent)] bg-[var(--accent-subtle)]'+ : 'border-white/[0.06]'+ }`}+ >+ <button+ type="button"+ data-testid="subtool-deco-tab-all"+ onClick={() => subToolGroupStoreActions.setActiveDecorationTab('all')}+ className={`h-5 px-1.5 rounded text-[10px] shrink-0 transition-colors cursor-pointer ${+ effectiveActiveDecorationTab === 'all'+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ title="Show all Decoration sub tools"+ >+ All+ </button>++ {/* User Custom Decoration SubTool Group Tabs */}+ {decorationCustomGroups.map((group, idx) => {+ const isTabActive = effectiveActiveDecorationTab === group.id;+ const grpShortcut = shortcuts[getSubToolGroupCommandId(group.id)];+ const isBrushDropOver =+ activeBrushDrag?.target?.kind === 'group-tab' &&+ activeBrushDrag.target.groupId === group.id;+ const isGroupReorderOver = activeGroupDrag?.targetGroupId === group.id;++ return (+ <button+ key={group.id}+ type="button"+ data-testid={`subtool-group-tab-${group.id}`}+ data-subtool-drop-tab={group.id}+ data-subtool-custom-tab={group.id}+ onPointerDown={(e) => startCustomGroupTabDrag(e, group)}+ onClick={() => {+ if (suppressNextClickRef.current) return;+ subToolGroupStoreActions.setActiveDecorationTab(group.id);+ }}+ onDoubleClick={() => {+ subToolGroupStoreActions.setActiveDecorationTab(group.id);+ setRenamingGroupId(group.id);+ setRenameDraft(group.name);+ }}+ onContextMenu={(e) => openGroupMenu(e, group, idx)}+ title={`${group.name}${grpShortcut ? ` (${formatShortcutLabel(grpShortcut)})` : ''} — Drag brushes here or right-click for options`}+ className={`h-5 px-1.5 rounded flex items-center gap-1 text-[10px] shrink-0 max-w-[100px] transition-colors cursor-pointer ${+ isBrushDropOver || isGroupReorderOver+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent)]'+ : isTabActive+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#9a9a9a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ {group.color ? (+ <span+ className="w-1.5 h-1.5 rounded-full shrink-0"+ style={{ backgroundColor: group.color }}+ />+ ) : (+ renderGroupIcon(group.icon, group.color)+ )}+ <span className="truncate">{group.name}</span>+ </button>+ );+ })}++ {DECORATION_BRUSH_SECTIONS.map((sec) => {+ const isTabActive = effectiveActiveDecorationTab === sec.id;+ const isBrushDropOver =+ activeBrushDrag?.target?.kind === 'group-tab' &&+ activeBrushDrag.target.groupId === sec.id;+ return (+ <button+ key={sec.id}+ type="button"+ data-testid={`subtool-group-tab-${sec.id}`}+ data-subtool-drop-tab={sec.id}+ onClick={() =>+ subToolGroupStoreActions.setActiveDecorationTab(sec.id as DecorationCategory)+ }+ title={`${sec.label} decoration brushes — Drag any brush here to move it into ${sec.label}`}+ className={`h-5 px-1.5 rounded text-[10px] shrink-0 transition-colors cursor-pointer ${+ isBrushDropOver+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent)]'+ : isTabActive+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ {sec.label}+ </button>+ );+ })}++ {/* Always-visible "+ Group" Button & CSP Drag-to-Create Drop Target */}+ <button+ type="button"+ data-testid="subtool-create-group-btn"+ data-subtool-drop="create-group"+ onClick={() => {+ setIsCreatingGroup((v) => !v);+ setNewGroupName('');+ }}+ title="Create Custom Sub Tool Group (click or drag any brush here)"+ aria-label="Create Custom Sub Tool Group"+ className={`h-5 px-1.5 rounded flex items-center gap-0.5 text-[10px] shrink-0 transition-colors cursor-pointer border ${+ isCreateGroupDropActive+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] border-transparent font-semibold'+ : isCreatingGroup+ ? 'bg-[#2c2c2c] text-[var(--accent)] border-[var(--accent-border)]'+ : activeBrushDrag+ ? 'bg-[#242424] text-[var(--accent)] border-dashed border-[var(--accent-border)]'+ : 'bg-[#222222] text-[#a0a0a0] hover:text-[var(--accent)] hover:bg-[#2a2a2a] border-white/[0.08]'+ }`}+ >+ <FolderPlus className="w-2.5 h-2.5 shrink-0" />+ <span>{activeBrushDrag ? 'New Group' : '+ Group'}</span>+ </button>+ </div>+ ) : (+ <div+ data-testid="subtool-group-tab-bar"+ className={`px-1.5 py-1 flex flex-wrap items-center gap-1 shrink-0 bg-[#1a1a1a] border-y transition-colors ${+ isCreateGroupDropActive+ ? 'border-[var(--accent)] bg-[var(--accent-subtle)]'+ : 'border-white/[0.06]'+ }`}+ >+ <button+ type="button"+ data-testid="subtool-group-tab-all"+ onClick={() => subToolGroupStoreActions.setActiveTab('all')}+ className={`h-5 px-1.5 rounded text-[10px] shrink-0 transition-colors cursor-pointer ${+ effectiveActiveTab === 'all'+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ title="Show all Sub Tool groups"+ >+ All+ </button>++ {/* User Custom SubTool Group Tabs */}+ {brushCustomGroups.map((group, idx) => {+ const isTabActive = effectiveActiveTab === group.id;+ const grpShortcut = shortcuts[getSubToolGroupCommandId(group.id)];+ const isBrushDropOver =+ activeBrushDrag?.target?.kind === 'group-tab' &&+ activeBrushDrag.target.groupId === group.id;+ const isGroupReorderOver = activeGroupDrag?.targetGroupId === group.id;++ return (+ <button+ key={group.id}+ type="button"+ data-testid={`subtool-group-tab-${group.id}`}+ data-subtool-drop-tab={group.id}+ data-subtool-custom-tab={group.id}+ onPointerDown={(e) => startCustomGroupTabDrag(e, group)}+ onClick={() => {+ if (suppressNextClickRef.current) return;+ subToolGroupStoreActions.setActiveTab(group.id);+ }}+ onDoubleClick={() => {+ subToolGroupStoreActions.setActiveTab(group.id);+ setRenamingGroupId(group.id);+ setRenameDraft(group.name);+ }}+ onContextMenu={(e) => openGroupMenu(e, group, idx)}+ title={`${group.name}${grpShortcut ? ` (${formatShortcutLabel(grpShortcut)})` : ''} — Drag brushes here or right-click for options`}+ className={`h-5 px-1.5 rounded flex items-center gap-1 text-[10px] shrink-0 max-w-[100px] transition-colors cursor-pointer ${+ isBrushDropOver || isGroupReorderOver+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent)]'+ : isTabActive+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#9a9a9a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ {group.color ? (+ <span+ className="w-1.5 h-1.5 rounded-full shrink-0"+ style={{ backgroundColor: group.color }}+ />+ ) : (+ renderGroupIcon(group.icon, group.color)+ )}+ <span className="truncate">{group.name}</span>+ </button>+ );+ })}++ {/* Built-in Category Tabs (now full drop targets so you can move ANY brush into ANY group!) */}+ {BUILTIN_BRUSH_SECTIONS.map((sec) => {+ const isTabActive = effectiveActiveTab === sec.id;+ const isBrushDropOver =+ activeBrushDrag?.target?.kind === 'group-tab' &&+ activeBrushDrag.target.groupId === sec.id;+ return (+ <button+ key={sec.id}+ type="button"+ data-testid={`subtool-group-tab-${sec.id}`}+ data-subtool-drop-tab={sec.id}+ onClick={() => subToolGroupStoreActions.setActiveTab(sec.id)}+ title={`${sec.label} sub tools — Drag any brush here to move it into ${sec.label}`}+ className={`h-5 px-1.5 rounded text-[10px] shrink-0 transition-colors cursor-pointer ${+ isBrushDropOver+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent)]'+ : isTabActive+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ {shortBuiltinTabLabel(sec.id, sec.label)}+ </button>+ );+ })}++ {importedMemberIds.length > 0 && (+ <button+ type="button"+ data-testid="subtool-group-tab-custom"+ data-subtool-drop-tab="custom"+ onClick={() => subToolGroupStoreActions.setActiveTab('custom')}+ title="Imported & custom brushes — Drag any brush here to move it into Imported"+ className={`h-5 px-1.5 rounded text-[10px] shrink-0 transition-colors cursor-pointer ${+ activeBrushDrag?.target?.kind === 'group-tab' &&+ activeBrushDrag.target.groupId === 'custom'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent)]'+ : effectiveActiveTab === 'custom'+ ? 'bg-[#2c2c2c] text-[#f0f0f0] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#242424]'+ }`}+ >+ Imported+ </button>+ )}++ {/* Always-visible "+ Group" Button & CSP Drag-to-Create Drop Target */}+ <button+ type="button"+ data-testid="subtool-create-group-btn"+ data-subtool-drop="create-group"+ onClick={() => {+ setIsCreatingGroup((v) => !v);+ setNewGroupName('');+ }}+ title="Create Custom Sub Tool Group (click or drag any brush here)"+ aria-label="Create Custom Sub Tool Group"+ className={`h-5 px-1.5 rounded flex items-center gap-0.5 text-[10px] shrink-0 transition-colors cursor-pointer border ${+ isCreateGroupDropActive+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] border-transparent font-semibold'+ : isCreatingGroup+ ? 'bg-[#2c2c2c] text-[var(--accent)] border-[var(--accent-border)]'+ : activeBrushDrag+ ? 'bg-[#242424] text-[var(--accent)] border-dashed border-[var(--accent-border)]'+ : 'bg-[#222222] text-[#a0a0a0] hover:text-[var(--accent)] hover:bg-[#2a2a2a] border-white/[0.08]'+ }`}+ >+ <FolderPlus className="w-2.5 h-2.5 shrink-0" />+ <span>{activeBrushDrag ? 'New Group' : '+ Group'}</span>+ </button>+ </div>+ )}++ {/* Inline New Custom Group Creator */}+ {isCreatingGroup && (+ <div+ data-testid="subtool-create-group-form"+ className="px-2 py-1.5 bg-[#181818] border-b border-white/[0.08] space-y-1.5 shrink-0"+ >+ <div className="flex items-center gap-1">+ <input+ type="text"+ data-testid="subtool-create-group-input"+ autoFocus+ value={newGroupName}+ maxLength={32}+ placeholder={`Custom Group ${scopedCustomGroups.length + 1}`}+ onChange={(e) => setNewGroupName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ handleCommitCreateGroup();+ } else if (e.key === 'Escape') {+ setIsCreatingGroup(false);+ }+ }}+ className="flex-1 min-w-0 h-6 px-2 rounded bg-[#121212] text-[11px] text-[#e5e5e5] placeholder-[#6e6e6e] border border-white/[0.1]"+ />+ <button+ type="button"+ data-testid="subtool-create-group-confirm"+ onClick={handleCommitCreateGroup}+ className="h-6 px-2 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer shrink-0"+ >+ Create+ </button>+ <button+ type="button"+ onClick={() => setIsCreatingGroup(false)}+ aria-label="Cancel creating group"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer shrink-0"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ <div className="flex items-center gap-1.5">+ <span className="text-[9.5px] text-[#7c7c7c]">Tag:</span>+ {SUBTOOL_GROUP_COLOR_SWATCHES.map((sw) => {+ const selected = newGroupColor === sw.hex;+ return (+ <button+ key={sw.id}+ type="button"+ onClick={() => setNewGroupColor(sw.hex)}+ title={sw.label}+ aria-label={`Color ${sw.label}`}+ className={`w-3.5 h-3.5 rounded-full flex items-center justify-center cursor-pointer transition-transform ${+ selected ? 'ring-1 ring-white scale-110' : 'opacity-70 hover:opacity-100'+ }`}+ style={{+ backgroundColor: sw.hex || '#3a3a3a',+ }}+ />+ );+ })}+ </div>+ </div>+ )}+<inputtype="file"ref={sutInputRef}@@ -272,6 +1870,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo({/* Compact High-Density Sectioned Sub-Tool List */}<div+ ref={scrollListRef}onDragOver={(e) => {if (e.dataTransfer.types.includes('Files')) {e.preventDefault();@@ -280,12 +1879,16 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(}}onDragLeave={() => setIsDraggingFileOver(false)}onDrop={(e) => {- e.preventDefault();- setIsDraggingFileOver(false);- const files = Array.from(e.dataTransfer.files).filter((f) =>- isSupportedBrushFileName(f.name)- );- for (const f of files) handleImportBrush(f);+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {+ e.preventDefault();+ setIsDraggingFileOver(false);+ const files = Array.from(e.dataTransfer.files).filter((f) =>+ isSupportedBrushFileName(f.name)+ );+ for (const f of files) handleImportBrush(f);+ } else {+ setIsDraggingFileOver(false);+ }}}className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-1 relative min-h-[84px]">@@ -303,138 +1906,668 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</div>)}- {BUILTIN_BRUSH_SECTIONS.map((section) => {- const items = brushesByCategory(section.id);- if (items.length === 0) return null;- const isCollapsed = Boolean(collapsedSections[section.id]);+ {/* Focused Single Custom Group View (works in both Brush and Decoration modes) */}+ {activeCustomGroup &&+ renderCustomGroupSection(+ activeCustomGroup,+ scopedCustomGroups.findIndex((g) => g.id === activeCustomGroup.id),+ true+ )}- return (- <div key={section.id} className="space-y-0.5">- <button- type="button"- onClick={() => toggleSection(section.id)}- className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"+ {/* 'All' View: User Custom Groups at top (scoped to active tool mode) */}+ {((isDecorationMode && effectiveActiveDecorationTab === 'all') ||+ (!isDecorationMode && effectiveActiveTab === 'all')) &&+ scopedCustomGroups.map((group, idx) => renderCustomGroupSection(group, idx, false))}++ {/* Decoration Tool Group Sections (Background, Clothing, Effect — CSP-style) */}+ {isDecorationMode &&+ (effectiveActiveDecorationTab === 'all' ||+ isDecorationCategory(effectiveActiveDecorationTab)) &&+ DECORATION_BRUSH_SECTIONS.filter(+ (sec) =>+ effectiveActiveDecorationTab === 'all' || sec.id === effectiveActiveDecorationTab+ ).map((section) => {+ const memberIds = builtinGroupMemberIds[section.id];+ const resolvedItems = memberIds+ .map((id) => resolveMemberEntry(id))+ .filter((x): x is NonNullable<typeof x> => x !== null);+ if (+ resolvedItems.length === 0 &&+ effectiveActiveDecorationTab === 'all' &&+ !activeBrushDrag+ ) {+ return null;+ }+ const isCollapsed =+ effectiveActiveDecorationTab === 'all' && Boolean(collapsedSections[section.id]);+ const isSectionHighlighted =+ activeBrushDrag?.target?.kind === 'group-section' &&+ activeBrushDrag.target.groupId === section.id;++ return (+ <div+ key={section.id}+ data-testid={`subtool-builtin-section-${section.id}`}+ data-subtool-drop-section={section.id}+ className={`space-y-0.5 rounded transition-colors ${+ isSectionHighlighted+ ? 'bg-[var(--accent-subtle)] ring-1 ring-[var(--accent)] p-0.5'+ : ''+ }`}>- {isCollapsed ? (- <ChevronRight className="w-2.5 h-2.5 shrink-0" />- ) : (- <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ {effectiveActiveDecorationTab === 'all' && (+ <button+ type="button"+ onClick={() => toggleSection(section.id)}+ className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"+ >+ {isCollapsed ? (+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />+ ) : (+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ )}+ <span>{section.label}</span>+ <span className="text-[8.5px] text-[#5c5c5c] font-mono">+ ({resolvedItems.length})+ </span>+ </button>)}- <span>{section.label}</span>- </button>- {!isCollapsed &&- items.map((item) => {- const isSelected =- currentTool === 'brush' &&- (activePreset === item.id ||- (!activePreset && item.id === DEFAULT_BRUSH_PRESET_ID));-- return (- <div- key={item.id}- onClick={() => handleSelectBrushPreset(item.id)}- title={`${item.name} - ${item.desc}`}- className={`group w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${- isSelected- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'- }`}- >- {renderBuiltinIcon(item.icon)}- <span className="text-[11px] truncate leading-tight flex-1">- {item.name}- </span>- <button- type="button"- onClick={(e) => handleExportBrush(item.id, e)}- title={`Export ${item.name} (.inkb)`}- className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5] shrink-0 cursor-pointer"- >- <Download className="w-2.5 h-2.5" />- </button>+ {!isCollapsed &&+ (resolvedItems.length === 0 ? (+ <div className="px-2 py-2 text-[10px] text-[#7c7c7c] text-center border border-dashed border-white/[0.08] rounded">+ Drag any brush here to add to {section.label}+ </div>+ ) : (+ resolvedItems.map((m) =>+ renderBrushRow(m.id, {+ builtin: m.builtin,+ custom: m.custom,+ ownerGroupId: section.id,+ })+ )+ ))}+ </div>+ );+ })}++ {/* Built-in Sections (full drop targets for cross-group drag & reorder!) */}+ {!isDecorationMode &&+ (effectiveActiveTab === 'all' || isBuiltinGroupTab(effectiveActiveTab)) &&+ BUILTIN_BRUSH_SECTIONS.filter(+ (sec) => effectiveActiveTab === 'all' || sec.id === effectiveActiveTab+ ).map((section) => {+ const memberIds = builtinGroupMemberIds[section.id];+ const resolvedItems = memberIds+ .map((id) => resolveMemberEntry(id))+ .filter((x): x is NonNullable<typeof x> => x !== null);+ if (resolvedItems.length === 0 && effectiveActiveTab === 'all' && !activeBrushDrag) {+ return null;+ }+ const isCollapsed =+ effectiveActiveTab === 'all' && Boolean(collapsedSections[section.id]);+ const isSectionHighlighted =+ activeBrushDrag?.target?.kind === 'group-section' &&+ activeBrushDrag.target.groupId === section.id;++ return (+ <div+ key={section.id}+ data-testid={`subtool-builtin-section-${section.id}`}+ data-subtool-drop-section={section.id}+ className={`space-y-0.5 rounded transition-colors ${+ isSectionHighlighted+ ? 'bg-[var(--accent-subtle)] ring-1 ring-[var(--accent)] p-0.5'+ : ''+ }`}+ >+ {effectiveActiveTab === 'all' && (+ <button+ type="button"+ onClick={() => toggleSection(section.id)}+ className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"+ >+ {isCollapsed ? (+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />+ ) : (+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ )}+ <span>{section.label}</span>+ </button>+ )}++ {!isCollapsed &&+ (resolvedItems.length === 0 ? (+ <div className="px-2 py-2 text-[10px] text-[#7c7c7c] text-center border border-dashed border-white/[0.08] rounded">+ Drag any brush here to add to {section.label}</div>- );- })}+ ) : (+ resolvedItems.map((m) =>+ renderBrushRow(m.id, {+ builtin: m.builtin,+ custom: m.custom,+ ownerGroupId: section.id,+ })+ )+ ))}+ </div>+ );+ })}++ {/* Imported / Custom Brushes Section */}+ {!isDecorationMode &&+ (effectiveActiveTab === 'all' || effectiveActiveTab === 'custom') &&+ (importedMemberIds.length > 0 || (effectiveActiveTab === 'custom' && activeBrushDrag)) && (+ <div+ data-testid="subtool-builtin-section-custom"+ data-subtool-drop-section="custom"+ className={`space-y-0.5 pt-0.5 rounded transition-colors ${+ activeBrushDrag?.target?.kind === 'group-section' &&+ activeBrushDrag.target.groupId === 'custom'+ ? 'bg-[var(--accent-subtle)] ring-1 ring-[var(--accent)] p-0.5'+ : ''+ }`}+ >+ {effectiveActiveTab === 'all' && (+ <button+ type="button"+ onClick={() => toggleSection('custom')}+ className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"+ >+ {collapsedSections.custom ? (+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />+ ) : (+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ )}+ <span>Imported</span>+ </button>+ )}++ {(effectiveActiveTab === 'custom' || !collapsedSections.custom) &&+ importedMemberIds+ .map((id) => resolveMemberEntry(id))+ .filter((x): x is NonNullable<typeof x> => x !== null)+ .map((m) =>+ renderBrushRow(m.id, {+ builtin: m.builtin,+ custom: m.custom,+ ownerGroupId: 'custom',+ })+ )}</div>- );- })}+ )}+ </div>++ {/* Portaled Floating Drag Ghost (Brush Move / Reorder / Create Group) */}+ {activeBrushDrag &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ data-testid="subtool-drag-ghost"+ style={{+ position: 'fixed',+ left: activeBrushDrag.pointerX + 14,+ top: activeBrushDrag.pointerY + 12,+ zIndex: 1200,+ }}+ className="pointer-events-none select-none flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-[#202020]/95 border border-[var(--accent)] shadow-[0_12px_32px_rgba(0,0,0,0.75)] text-[11px] text-[#f0f0f0]"+ >+ <GripVertical className="w-3 h-3 text-[var(--accent)] shrink-0" />+ <span className="font-medium max-w-[140px] truncate">{activeBrushDrag.name}</span>+ {getDragGhostHint(activeBrushDrag) && (+ <span className="text-[10px] text-[var(--accent)] border-l border-white/[0.12] pl-1.5 whitespace-nowrap">+ {getDragGhostHint(activeBrushDrag)}+ </span>+ )}+ </div>,+ document.body+ )}++ {/* Portaled Floating Drag Ghost (Custom Group Tab Reorder) */}+ {activeGroupDrag &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ style={{+ position: 'fixed',+ left: activeGroupDrag.pointerX + 12,+ top: activeGroupDrag.pointerY + 10,+ zIndex: 1200,+ }}+ className="pointer-events-none select-none flex items-center gap-1.5 px-2 py-1 rounded bg-[#202020]/95 border border-[var(--accent)] shadow-2xl text-[10px] text-[#f0f0f0]"+ >+ <Folder className="w-3 h-3 text-[var(--accent)]" />+ <span>{activeGroupDrag.name}</span>+ </div>,+ document.body+ )}++ {/* Portaled Brush Right-Click / Options Context Menu */}+ {brushContextMenu &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ ref={contextMenuRef}+ data-testid="subtool-brush-context-menu"+ style={{+ position: 'fixed',+ left: brushContextMenu.x,+ top: brushContextMenu.y,+ zIndex: 1000,+ }}+ onPointerDown={(e) => e.stopPropagation()}+ className="w-52 max-h-[80vh] overflow-y-auto rounded-md bg-[#202020] border border-white/[0.12] shadow-2xl p-1 text-[11px] text-[#e5e5e5] select-none"+ >+ <div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate font-medium">+ {brushContextMenu.name}+ </div>+ <div className="my-0.5 h-px bg-white/[0.08]" />- {customBrushes.length > 0 && (- <div className="space-y-0.5 pt-0.5"><buttontype="button"- onClick={() => toggleSection('custom')}- className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"+ data-testid="subtool-ctx-set-shortcut"+ onClick={() => {+ const target = brushContextMenu;+ setBrushContextMenu(null);+ setShortcutModalTarget({+ commandId: getSubToolCommandId(target.presetId),+ label: target.name,+ kind: 'subtool',+ });+ }}+ className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left">- {collapsedSections.custom ? (- <ChevronRight className="w-2.5 h-2.5 shrink-0" />- ) : (- <ChevronDown className="w-2.5 h-2.5 shrink-0" />+ <span className="flex items-center gap-1.5">+ <Keyboard className="w-3 h-3 text-[var(--accent)]" />+ <span>Set Shortcut...</span>+ </span>+ {shortcuts[getSubToolCommandId(brushContextMenu.presetId)] && (+ <span className="text-[9px] font-mono text-[#9a9a9a]">+ {formatShortcutLabel(shortcuts[getSubToolCommandId(brushContextMenu.presetId)])}+ </span>)}- <span>Imported</span></button>- {!collapsedSections.custom &&- customBrushes.map((brush) => {- const isSelected = currentTool === 'brush' && activePreset === brush.id;- return (- <div- key={brush.id}- onClick={() => handleSelectCustomBrush(brush)}- title={brush.name}- className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${- isSelected- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'- }`}- >- <div className="flex items-center gap-1.5 min-w-0">- {brush.tipDataUrl ? (- <img- src={brush.tipDataUrl}- alt=""- className="w-3 h-3 object-contain shrink-0 brightness-125"- />- ) : (- <Paintbrush className="w-3 h-3 shrink-0 opacity-70" />- )}- <span className="text-[11px] truncate leading-tight">{brush.name}</span>- {brush.importWarnings && brush.importWarnings.length > 0 && (- <span- title={brush.importWarnings.join('\n')}- className="text-amber-400 shrink-0"- aria-label="Import warning"- >- <AlertTriangle className="w-2.5 h-2.5" />- </span>- )}- </div>- <div className="flex items-center gap-1 shrink-0">+ {shortcuts[getSubToolCommandId(brushContextMenu.presetId)] && (+ <button+ type="button"+ onClick={() => {+ updateShortcutOverride(getSubToolCommandId(brushContextMenu.presetId), null);+ setBrushContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-[#9a9a9a] hover:text-[#e5e5e5] cursor-pointer text-left"+ >+ <X className="w-3 h-3" />+ <span>Clear Shortcut</span>+ </button>+ )}++ <div className="my-0.5 h-px bg-white/[0.08]" />+ <div className="px-2 py-0.5 text-[9.5px] uppercase tracking-wider text-[#7c7c7c]">+ Move to Sub Tool Group+ </div>++ {(() => {+ const currentGroupId = getEffectiveBrushGroupId(+ brushContextMenu.presetId,+ customGroups,+ brushGroupOverrides,+ customBrushes+ );+ const factoryGroupId = getFactoryGroupIdForBrush(+ brushContextMenu.presetId,+ customBrushes+ );++ return (+ <>+ {scopedCustomGroups.map((g) => {+ const isMember = currentGroupId === g.id;+ return (<button+ key={g.id}type="button"- onClick={(e) => handleExportBrush(brush.id, e)}- title={`Export ${brush.name} (.inkb)`}- className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5] shrink-0 cursor-pointer"+ data-testid={`subtool-ctx-move-group-${g.id}`}+ onClick={() => {+ subToolGroupStoreActions.moveBrushToGroup(+ brushContextMenu.presetId,+ g.id+ );+ uiStoreActions.showToast(+ `Moved "${brushContextMenu.name}" to "${g.name}"`+ );+ setBrushContextMenu(null);+ }}+ className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left">- <Download className="w-2.5 h-2.5" />+ <span className="flex items-center gap-1.5 min-w-0">+ <span+ className="w-1.5 h-1.5 rounded-full shrink-0"+ style={{ backgroundColor: g.color || '#8a8a8a' }}+ />+ <span className="truncate">{g.name}</span>+ </span>+ {isMember && <Check className="w-3 h-3 text-[var(--accent)] shrink-0" />}</button>+ );+ })}++ {(isDecorationMode ? DECORATION_BRUSH_SECTIONS : BUILTIN_BRUSH_SECTIONS).map(+ (sec) => {+ const isMember = currentGroupId === sec.id;+ return (<button+ key={sec.id}type="button"- onClick={(e) => void handleDeleteCustomBrush(e, brush)}- title="Delete brush"- className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"+ data-testid={`subtool-ctx-move-group-${sec.id}`}+ onClick={() => {+ subToolGroupStoreActions.moveBrushToGroup(+ brushContextMenu.presetId,+ sec.id,+ undefined,+ builtinGroupMemberIds[sec.id]+ );+ uiStoreActions.showToast(+ `Moved "${brushContextMenu.name}" to "${sec.label}"`+ );+ setBrushContextMenu(null);+ }}+ className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-[#cccccc] hover:text-white cursor-pointer text-left">- <Trash2 className="w-2.5 h-2.5" />+ <span className="truncate">{sec.label}</span>+ {isMember && <Check className="w-3 h-3 text-[var(--accent)] shrink-0" />}</button>- </div>- </div>- );- })}- </div>+ );+ })}++ <button+ type="button"+ data-testid="subtool-ctx-new-group-with-brush"+ onClick={() => {+ const target = brushContextMenu;+ setBrushContextMenu(null);+ handleCreateGroupFromBrush(target.presetId, target.name);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-[var(--accent)] cursor-pointer text-left"+ >+ <FolderPlus className="w-3 h-3 shrink-0" />+ <span>New Group with Brush...</span>+ </button>++ {currentGroupId !== factoryGroupId && (+ <button+ type="button"+ data-testid="subtool-ctx-return-default"+ onClick={() => {+ subToolGroupStoreActions.removeBrushFromAllGroups(+ brushContextMenu.presetId+ );+ uiStoreActions.showToast(+ `Returned "${brushContextMenu.name}" to default section`+ );+ setBrushContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-[#b5b5b5] hover:text-white cursor-pointer text-left"+ >+ <Undo2 className="w-3 h-3 shrink-0" />+ <span>Return to Default Section</span>+ </button>+ )}+ </>+ );+ })()}++ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ onClick={() => {+ handleTogglePinToQuickPanel(brushContextMenu.presetId, brushContextMenu.name);+ setBrushContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Star className="w-3 h-3 text-amber-300" />+ <span>+ {quickBrushSet.has(migrateLegacyPresetId(brushContextMenu.presetId))+ ? 'Unpin from Quick Brushes'+ : 'Pin to Quick Brushes'}+ </span>+ </button>++ <button+ type="button"+ onClick={() => {+ const target = brushContextMenu;+ setBrushContextMenu(null);+ activateSubToolPreset(target.presetId, customBrushes);+ uiStoreActions.setBrushStudioModalOpen(true);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Sliders className="w-3 h-3 text-[#8a8a8a]" />+ <span>Edit in Brush Studio</span>+ </button>++ <button+ type="button"+ onClick={() => {+ const target = brushContextMenu;+ setBrushContextMenu(null);+ void handleDuplicateActiveBrush(target.presetId);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Copy className="w-3 h-3 text-[#8a8a8a]" />+ <span>Duplicate</span>+ </button>++ <button+ type="button"+ onClick={() => {+ const target = brushContextMenu;+ setBrushContextMenu(null);+ void handleExportBrush(target.presetId);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Download className="w-3 h-3 text-[#8a8a8a]" />+ <span>Export (.inkb)</span>+ </button>++ {brushContextMenu.customBrush && (+ <>+ <div className="my-0.5 h-px bg-white/[0.08]" />+ <button+ type="button"+ onClick={() => {+ const cb = brushContextMenu.customBrush!;+ setBrushContextMenu(null);+ void handleDeleteCustomBrush(undefined, cb);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-rose-400 cursor-pointer text-left"+ >+ <Trash2 className="w-3 h-3" />+ <span>Delete Brush</span>+ </button>+ </>+ )}+ </div>,+ document.body)}- </div>- </>++ {/* Portaled Custom Group Right-Click / Options Menu */}+ {groupContextMenu &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ ref={contextMenuRef}+ data-testid="subtool-group-context-menu"+ style={{+ position: 'fixed',+ left: groupContextMenu.x,+ top: groupContextMenu.y,+ zIndex: 1000,+ }}+ onPointerDown={(e) => e.stopPropagation()}+ className="w-48 rounded-md bg-[#202020] border border-white/[0.12] shadow-2xl p-1 text-[11px] text-[#e5e5e5] select-none"+ >+ <div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate font-medium">+ Group: {groupContextMenu.group.name}+ </div>+ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ data-testid="subtool-grp-ctx-rename"+ onClick={() => {+ const grp = groupContextMenu.group;+ setGroupContextMenu(null);+ setRenamingGroupId(grp.id);+ setRenameDraft(grp.name);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <PencilLine className="w-3 h-3 text-[#8a8a8a]" />+ <span>Rename Group</span>+ </button>++ <button+ type="button"+ data-testid="subtool-grp-ctx-add-brushes"+ onClick={() => {+ const grp = groupContextMenu.group;+ setGroupContextMenu(null);+ if (isDecorationCustomGroup(grp)) {+ subToolGroupStoreActions.setActiveDecorationTab(grp.id);+ } else {+ subToolGroupStoreActions.setActiveTab(grp.id);+ }+ setAddBrushesGroupId(grp.id);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Plus className="w-3 h-3 text-[var(--accent)]" />+ <span>Manage Brushes...</span>+ </button>++ <button+ type="button"+ data-testid="subtool-grp-ctx-shortcut"+ onClick={() => {+ const grp = groupContextMenu.group;+ setGroupContextMenu(null);+ setShortcutModalTarget({+ commandId: getSubToolGroupCommandId(grp.id),+ label: `Group: ${grp.name}`,+ kind: 'group',+ });+ }}+ className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <span className="flex items-center gap-1.5">+ <Keyboard className="w-3 h-3 text-[var(--accent)]" />+ <span>Set Shortcut...</span>+ </span>+ {shortcuts[getSubToolGroupCommandId(groupContextMenu.group.id)] && (+ <span className="text-[9px] font-mono text-[#9a9a9a]">+ {formatShortcutLabel(+ shortcuts[getSubToolGroupCommandId(groupContextMenu.group.id)]+ )}+ </span>+ )}+ </button>++ <div className="px-2 py-1 space-y-1">+ <div className="text-[9.5px] text-[#7c7c7c]">Group Tag Color</div>+ <div className="flex items-center gap-1.5">+ {SUBTOOL_GROUP_COLOR_SWATCHES.map((sw) => (+ <button+ key={sw.id}+ type="button"+ onClick={() => {+ subToolGroupStoreActions.updateGroupAppearance(+ groupContextMenu.group.id,+ { color: sw.hex }+ );+ setGroupContextMenu(null);+ }}+ title={sw.label}+ className={`w-3.5 h-3.5 rounded-full cursor-pointer ${+ groupContextMenu.group.color === sw.hex+ ? 'ring-1 ring-white scale-110'+ : 'opacity-75 hover:opacity-100'+ }`}+ style={{ backgroundColor: sw.hex || '#3a3a3a' }}+ />+ ))}+ </div>+ </div>++ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ disabled={groupContextMenu.index <= 0}+ onClick={() => {+ subToolGroupStoreActions.moveGroup(groupContextMenu.group.id, -1);+ setGroupContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer text-left"+ >+ <ArrowLeft className="w-3 h-3 text-[#8a8a8a]" />+ <span>Move Group Left</span>+ </button>++ <button+ type="button"+ disabled={groupContextMenu.index >= scopedCustomGroups.length - 1}+ onClick={() => {+ subToolGroupStoreActions.moveGroup(groupContextMenu.group.id, 1);+ setGroupContextMenu(null);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer text-left"+ >+ <ArrowRight className="w-3 h-3 text-[#8a8a8a]" />+ <span>Move Group Right</span>+ </button>++ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ data-testid="subtool-grp-ctx-delete"+ onClick={() => {+ const grp = groupContextMenu.group;+ setGroupContextMenu(null);+ void handleDeleteCustomGroup(grp);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-rose-400 cursor-pointer text-left"+ >+ <Trash2 className="w-3 h-3" />+ <span>Delete Group</span>+ </button>+ </div>,+ document.body+ )}++ {/* Inline SubTool / Custom Group Shortcut Recorder Modal */}+ {shortcutModalTarget && (+ <SubToolShortcutModal+ commandId={shortcutModalTarget.commandId}+ targetLabel={shortcutModalTarget.label}+ targetKind={shortcutModalTarget.kind}+ currentShortcut={shortcuts[shortcutModalTarget.commandId] || ''}+ shortcuts={shortcuts}+ allCommands={allShortcutCommands}+ onAssign={(cmdId, shortcut, conflictIds) =>+ updateShortcutOverride(cmdId, shortcut, conflictIds)+ }+ onClear={(cmdId) => updateShortcutOverride(cmdId, null)}+ onClose={() => setShortcutModalTarget(null)}+ />+ )}+ </div>);});diff --git a/src/components/SubToolShortcutModal.tsx b/src/components/SubToolShortcutModal.tsxnew file mode 100644index 0000000..e810ebf--- /dev/null+++ b/src/components/SubToolShortcutModal.tsx@@ -0,0 +1,238 @@+import React, { useEffect, useState } from 'react';+import { createPortal } from 'react-dom';+import { AlertTriangle, Keyboard, Trash2, X } from 'lucide-react';+import {+ CommandDefinition,+ formatShortcutFromEvent,+ formatShortcutLabel,+ getOsModifierDisplayName,+ findShortcutConflicts,+} from '../utils/shortcutManager';+import {+ acquireNativeOsHotkeyRecording,+ subscribeNativeOsHotkeys,+} from '../utils/nativeOsHotkeys';+import { ShortcutOverrides } from '../types/settings';++export interface SubToolShortcutModalProps {+ commandId: string;+ targetLabel: string;+ targetKind: 'subtool' | 'group';+ currentShortcut: string;+ shortcuts: ShortcutOverrides;+ allCommands: readonly CommandDefinition[];+ onAssign: (commandId: string, shortcut: string, clearConflictIds?: string[]) => void;+ onClear: (commandId: string) => void;+ onClose: () => void;+}++export const SubToolShortcutModal: React.FC<SubToolShortcutModalProps> = ({+ commandId,+ targetLabel,+ targetKind,+ currentShortcut,+ shortcuts,+ allCommands,+ onAssign,+ onClear,+ onClose,+}) => {+ const [osModifierPinned, setOsModifierPinned] = useState(false);+ const [pendingConflict, setPendingConflict] = useState<{+ shortcut: string;+ conflicts: CommandDefinition[];+ } | null>(null);++ const osKeyName = getOsModifierDisplayName();++ useEffect(() => {+ const releaseNative = acquireNativeOsHotkeyRecording();++ const processCapture = (ev: {+ key: string;+ code?: string;+ ctrlKey?: boolean;+ metaKey?: boolean;+ shiftKey?: boolean;+ altKey?: boolean;+ }) => {+ if (+ ev.key === 'Escape' &&+ !ev.ctrlKey &&+ !ev.metaKey &&+ !ev.altKey &&+ !ev.shiftKey+ ) {+ onClose();+ return;+ }++ const captured = formatShortcutFromEvent({+ ...ev,+ metaKey: Boolean(ev.metaKey || osModifierPinned),+ });+ if (!captured) return;++ const conflicts = findShortcutConflicts(commandId, captured, shortcuts, allCommands);+ if (conflicts.length > 0) {+ setPendingConflict({ shortcut: captured, conflicts });+ return;+ }++ onAssign(commandId, captured);+ onClose();+ };++ const handleKeyDown = (e: KeyboardEvent) => {+ e.preventDefault();+ e.stopPropagation();+ processCapture(e);+ };++ const unsubNative = subscribeNativeOsHotkeys((ev) => {+ if (ev.phase !== 'keydown' || ev.repeat) return;+ processCapture(ev);+ });++ window.addEventListener('keydown', handleKeyDown, true);+ return () => {+ window.removeEventListener('keydown', handleKeyDown, true);+ unsubNative();+ releaseNative();+ };+ }, [commandId, shortcuts, allCommands, osModifierPinned, onAssign, onClose]);++ const modalContent = (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={`Set Shortcut for ${targetLabel}`}+ data-testid="subtool-shortcut-modal"+ className="fixed inset-0 z-[1100] flex items-center justify-center bg-black/65 p-4 select-none"+ onClick={onClose}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-full max-w-[340px] rounded-lg bg-[#202020] border border-white/[0.12] shadow-[0_24px_64px_rgba(0,0,0,0.85)] overflow-hidden text-xs text-[#e5e5e5]"+ >+ <div className="h-9 px-3 flex items-center justify-between bg-[#161616] border-b border-white/[0.08]">+ <div className="flex items-center gap-1.5 min-w-0">+ <Keyboard className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ <span className="font-medium truncate">+ {targetKind === 'group' ? 'Group Shortcut' : 'Sub Tool Shortcut'}+ </span>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close shortcut recorder"+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="p-3.5 space-y-3">+ <div className="space-y-0.5">+ <div className="text-[11px] text-[#8a8a8a]">+ {targetKind === 'group' ? 'Sub Tool Group' : 'Sub Tool'}+ </div>+ <div className="text-xs font-medium text-[#f0f0f0] truncate">{targetLabel}</div>+ </div>++ <div className="rounded-md bg-[#161616] border border-[var(--accent-border)] px-3 py-3 text-center space-y-1.5">+ <div className="text-[11px] font-medium text-[var(--accent)]">+ Press any key combination...+ </div>+ <div className="text-[10px] text-[#8a8a8a]">+ Supports Ctrl, {osKeyName}, Shift, Alt · Esc to cancel+ </div>+ {currentShortcut && (+ <div className="pt-1 text-[10px] text-[#9a9a9a]">+ Current:{' '}+ <span className="font-mono text-[#e5e5e5] bg-[#262626] px-1.5 py-0.5 rounded">+ {formatShortcutLabel(currentShortcut)}+ </span>+ </div>+ )}+ </div>++ <div className="flex items-center justify-between gap-2">+ <button+ type="button"+ data-testid="subtool-shortcut-os-toggle"+ onClick={() => setOsModifierPinned((v) => !v)}+ aria-pressed={osModifierPinned}+ className={`px-2 py-1 rounded text-[10px] font-mono transition-colors cursor-pointer border ${+ osModifierPinned+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-border)] font-semibold'+ : 'bg-[#161616] text-[#9a9a9a] border-white/[0.08] hover:text-[#e5e5e5] hover:bg-[#282828]'+ }`}+ title={`Toggle ${osKeyName} key modifier for the next key press`}+ >+ + {osKeyName} Key {osModifierPinned ? '(Active)' : ''}+ </button>++ {currentShortcut && (+ <button+ type="button"+ data-testid="subtool-shortcut-clear-btn"+ onClick={() => {+ onClear(commandId);+ onClose();+ }}+ className="flex items-center gap-1 px-2 py-1 rounded bg-[#161616] hover:bg-rose-500/20 text-[#9a9a9a] hover:text-rose-300 text-[10px] cursor-pointer transition-colors"+ >+ <Trash2 className="w-3 h-3" />+ <span>Clear</span>+ </button>+ )}+ </div>++ {pendingConflict && (+ <div className="p-2.5 rounded bg-amber-500/10 border border-amber-500/40 space-y-2 text-[11px]">+ <div className="flex items-start gap-2 text-amber-200">+ <AlertTriangle className="w-3.5 h-3.5 shrink-0 text-amber-400 mt-0.5" />+ <span>+ <strong className="font-mono">+ {formatShortcutLabel(pendingConflict.shortcut)}+ </strong>{' '}+ is already assigned to{' '}+ <strong>{pendingConflict.conflicts.map((c) => c.label).join(', ')}</strong>.+ Replace it?+ </span>+ </div>+ <div className="flex items-center justify-end gap-1.5">+ <button+ type="button"+ onClick={() => setPendingConflict(null)}+ className="px-2 py-1 rounded bg-[#161616] text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer text-[10px]"+ >+ Cancel+ </button>+ <button+ type="button"+ data-testid="subtool-shortcut-replace-btn"+ onClick={() => {+ onAssign(+ commandId,+ pendingConflict.shortcut,+ pendingConflict.conflicts.map((c) => c.id)+ );+ onClose();+ }}+ className="px-2.5 py-1 rounded bg-amber-500 text-black font-medium cursor-pointer text-[10px]"+ >+ Replace+ </button>+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ );++ return typeof document !== 'undefined' ? createPortal(modalContent, document.body) : modalContent;+};diff --git a/src/components/TimelapseExportModal.tsx b/src/components/TimelapseExportModal.tsxindex 0f77e53..c8856ff 100644--- a/src/components/TimelapseExportModal.tsx+++ b/src/components/TimelapseExportModal.tsx@@ -17,6 +17,7 @@ import {TimelapseResolution,} from '../utils/timelapseEngine';import { downloadFile } from '../utils/saveManager';+import { documentStoreActions } from '../stores';interface TimelapseExportModalProps {isOpen: boolean;@@ -52,6 +53,12 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({const previewUrlRef = useRef<string | null>(null);+ // Reset scrubber state when switching active documents+ useEffect(() => {+ setPreviewIdx(0);+ setIsPlayingPreview(false);+ }, [documentId]);+useEffect(() => {if (!isOpen) return;setStats(globalTimelapseManager.getStats(documentId));@@ -134,6 +141,7 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({const handleToggleRecording = () => {if (!documentId) return;const next = globalTimelapseManager.toggleRecording(documentId);+ documentStoreActions.markDocumentDirty(documentId, true);if (next) {onCaptureNow?.();showToast?.('Time-lapse recording enabled');@@ -146,6 +154,7 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({if (!documentId) return;setIsPlayingPreview(false);await globalTimelapseManager.clearSession(documentId);+ documentStoreActions.markDocumentDirty(documentId, true);setPreviewIdx(0);showToast?.('Time-lapse frames cleared');};diff --git a/src/components/Tool3DPropertyInspector.tsx b/src/components/Tool3DPropertyInspector.tsxindex f9d41c9..c03ce0a 100644--- a/src/components/Tool3DPropertyInspector.tsx+++ b/src/components/Tool3DPropertyInspector.tsx@@ -20,7 +20,9 @@ import {Tool3DMode,} from '../utils/tool3DRules';import { PosePresetName } from '../utils/mannequin3D';+import { PRIMITIVE_3D_ITEMS } from '../utils/primitives3D';import { LightSourceWidget } from './LightSourceWidget';+import { Primitive3DIcon } from './Primitive3DIcon';import {scene3DBridge,selectHasOpenDocument,@@ -93,6 +95,8 @@ export const Tool3DPropertyInspector: React.FC = () => {const snapEnabled = use3DStore((s) => s.snapEnabled);const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);const loadedModelName = use3DStore((s) => s.loadedModelName);+ const modelKind = use3DStore((s) => s.modelKind);+ const activePrimitiveType = use3DStore((s) => s.activePrimitiveType);const isMannequinActive = use3DStore((s) => s.isMannequinActive);const activeIKHandle = use3DStore((s) => s.activeIKHandle);const showIKHandles = use3DStore((s) => s.showIKHandles);@@ -136,7 +140,7 @@ export const Tool3DPropertyInspector: React.FC = () => {<div className="p-2.5 space-y-2.5 overflow-y-auto flex-1"><div className="text-[11px] font-medium text-[#e5e5e5]">3D Studio Tool</div><p className="text-[10px] text-[#8a8a8a] leading-relaxed">- Open the 3D reference stage to position, light, and extract lineart from imported .glb / .gltf / .obj models directly on the canvas.+ Open the 3D reference stage to create primitives or drop .glb / .gltf / .obj models directly onto the canvas.</p><buttontype="button"@@ -182,7 +186,10 @@ export const Tool3DPropertyInspector: React.FC = () => {];return (- <div className="flex flex-col flex-1 min-h-0 overflow-hidden text-[#e5e5e5]">+ <div+ data-drop-zone="3d-stage"+ className="flex flex-col flex-1 min-h-0 overflow-hidden text-[#e5e5e5]"+ >{/* Header + Quick Model Source Actions */}<div className="px-2 pt-2 pb-1.5 border-b border-white/[0.06] space-y-1.5 shrink-0"><div className="flex items-center justify-between gap-1">@@ -205,12 +212,42 @@ export const Tool3DPropertyInspector: React.FC = () => {<buttontype="button"onClick={() => scene3DBridge.triggerFilePicker?.()}+ title="Click to browse or drag & drop .glb, .gltf, or .obj onto canvas"className="w-full flex items-center justify-center gap-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] cursor-pointer"><Upload className="w-3 h-3 text-[var(--accent)]" /><span>Import 3D Model (.glb / .obj)</span></button>+ {/* Quick 3D Primitives */}+ <div className="space-y-1">+ <span className="text-[9px] uppercase tracking-wider text-[#6e6e6e]">+ Primitives+ </span>+ <div className="grid grid-cols-5 gap-0.5">+ {PRIMITIVE_3D_ITEMS.map((item) => {+ const isSelected = modelKind === 'primitive' && activePrimitiveType === item.type;+ return (+ <button+ key={item.type}+ type="button"+ onClick={() => scene3DBridge.createPrimitive?.(item.type)}+ title={item.description}+ data-testid={`inspector-3d-primitive-${item.type}`}+ className={`flex flex-col items-center justify-center gap-0.5 py-1 px-0.5 rounded border text-[8.5px] leading-tight transition-colors cursor-pointer ${+ isSelected+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] border-transparent font-medium'+ : 'bg-[#161616] hover:bg-[#2c2c2c] border-white/[0.06] text-[#cccccc] hover:text-[#e5e5e5]'+ }`}+ >+ <Primitive3DIcon type={item.type} className="w-3.5 h-3.5 shrink-0" />+ <span className="truncate max-w-full">{item.label}</span>+ </button>+ );+ })}+ </div>+ </div>+{/* Inspector Section Tabs */}<divclassName={`grid gap-0.5 bg-[#161616] p-0.5 rounded ${diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsxindex 7737836..bbb35e7 100644--- a/src/components/ToolPropertyInspector.tsx+++ b/src/components/ToolPropertyInspector.tsx@@ -40,12 +40,18 @@ import {RetouchTonalRange,CloneSampleMode,PenToolMode,+ isBrushLikeTool,+ isPaintTool,} from '../types/editor';import { isOpenShape } from '../utils/shapeEngine';-import { GRADIENT_PRESETS, resolveGradientStops } from '../utils/gradientEngine';+import {+ GRADIENT_PRESETS,+ getSelectedMeshNodeIndices,+ resolveGradientStops,+} from '../utils/gradientEngine';import { saveCustomBrushDebounced } from '../utils/brushStorage';import { resolveBrushTipImage } from '../utils/brushOutline';-import { BUILTIN_BRUSHES } from '../utils/presetBrushes';+import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';import {resetBrushSettingsToDefault,ERASER_PRESET_ID,@@ -62,6 +68,7 @@ import {} from '../stores';import { Tool3DPropertyInspector } from './Tool3DPropertyInspector';import { PigmentBlendControl } from './PigmentBlendControl';+import { resolveBrushCursorRotationSpec } from './canvasArea/types';interface CompactSliderProps {label: string;@@ -185,6 +192,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactconst activePenSelectedAnchor = useToolStore((s) => s.activePenSelectedAnchor);const primaryColor = useToolStore((s) => s.primaryColor);const secondaryColor = useToolStore((s) => s.secondaryColor);+ const isTransparentColor = useToolStore((s) => s.isTransparentColor);const balloonSettings = useToolStore((s) => s.balloonSettings);const vectorEditSettings = useToolStore((s) => s.vectorEditSettings);const wandSettings = useToolStore((s) => s.wandSettings);@@ -194,7 +202,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactconst [warningsExpanded, setWarningsExpanded] = useState<boolean>(false);const previewCanvasRef = useRef<HTMLCanvasElement>(null);- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';+ const isBrushOrEraser = isBrushLikeTool(currentTool);useEffect(() => {setWarningsExpanded(false);@@ -338,9 +346,9 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React}, [isHidden, isBrushOrEraser, width, currentTool, brushSettings, secondaryColor]);const activePreset: BrushPresetId = brushSettings.preset || DEFAULT_BRUSH_PRESET_ID;- const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);+ const activeBuiltinBrush = ALL_BUILTIN_BRUSHES.find((b) => b.id === activePreset);const isCustomBrushActive =- currentTool === 'brush' &&+ isPaintTool(currentTool) &&(activePreset.startsWith('csp-') ||(Boolean(brushSettings.customTipDataUrl) && !activeBuiltinBrush));const activeCustomBrush = isCustomBrushActive@@ -371,6 +379,10 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = ReactsharpCorners: newSettings.sharpCorners ?? activeCustomBrush.sharpCorners,angle: newSettings.customTipAngle ?? activeCustomBrush.angle,angleDynamics: newSettings.customTipAngleDynamics ?? activeCustomBrush.angleDynamics,+ rotateCursor:+ 'rotateCursor' in newSettings+ ? newSettings.rotateCursor+ : activeCustomBrush.rotateCursor,flipH: newSettings.flipH ?? activeCustomBrush.flipH,flipV: newSettings.flipV ?? activeCustomBrush.flipV,isRibbon: newSettings.isRibbon ?? activeCustomBrush.isRibbon,@@ -429,16 +441,22 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactif (currentTool === 'fill') {const method = fillSettings.method ?? 'refer-all';+ const isSmartFill = method === 'enclose-and-fill' || method === 'paint-unfilled';+ const smartReferMode = fillSettings.smartReferMode ?? 'refer-reference';+ const encloseTarget = fillSettings.encloseTarget ?? 'all-enclosed';+ const paintUnfilledSize = Math.max(2, Math.min(300, Math.round(fillSettings.brushSize ?? 24)));return (<div className="p-2.5 space-y-3 overflow-y-auto flex-1"><div className="text-[11px] font-medium text-[#e5e5e5]">Fill</div><div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-[#6e6e6e] px-1 pb-0.5">+ Bucket Fill+ </div>{([{ id: 'refer-all', label: 'All Visible' },{ id: 'refer-active', label: 'Active Layer' },{ id: 'refer-reference', label: 'Reference Layer' },- { id: 'lasso', label: 'Lasso Fill' },] as const).map((m) => (<button@@ -454,8 +472,187 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React{m.label}</button>))}+ <div className="text-[10px] uppercase tracking-wider text-[#6e6e6e] px-1 pt-1.5 pb-0.5">+ Smart Line Fill+ </div>+ {(+ [+ {+ id: 'enclose-and-fill',+ label: 'Enclose and Fill',+ title: 'Draw a lasso around complex line art to fill all closed areas inside without affecting the background',+ },+ {+ id: 'paint-unfilled',+ label: 'Paint Unfilled Area',+ title: 'Brush over outlines to fill only tiny enclosed unfilled corners and crevices',+ },+ {+ id: 'lasso',+ label: 'Lasso Fill',+ title: 'Draw a freehand shape to fill directly',+ },+ ] as const+ ).map((m) => (+ <button+ key={m.id}+ type="button"+ title={m.title}+ onClick={() => toolStoreActions.updateFillSettings({ method: m.id })}+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${+ method === m.id+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'+ }`}+ >+ {m.label}+ </button>+ ))}</div>- {method !== 'lasso' && (+ {method === 'lasso' ? (+ <div className="space-y-2.5 pt-1 border-t border-[#2c2c2c]">+ <CompactSlider+ label="Opacity"+ valueLabel={`${Math.round((fillSettings.opacity ?? 1) * 100)}%`}+ min={1}+ max={100}+ value={Math.round((fillSettings.opacity ?? 1) * 100)}+ onChange={(v) => toolStoreActions.updateFillSettings({ opacity: v / 100 })}+ />+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Transparent (Erase)</span>+ <input+ type="checkbox"+ checked={isTransparentColor}+ onChange={() => toolStoreActions.toggleTransparentColor()}+ />+ </label>+ <div className="text-[10px] text-[#6e6e6e]">+ Draw a closed shape on canvas to fill. Press Esc to cancel.+ </div>+ </div>+ ) : isSmartFill ? (+ <div className="space-y-2.5 pt-1 border-t border-[#2c2c2c]">+ {method === 'paint-unfilled' && (+ <CompactSlider+ label="Brush Size"+ valueLabel={`${paintUnfilledSize}px`}+ min={2}+ max={300}+ value={paintUnfilledSize}+ onChange={(v) => toolStoreActions.updateFillSettings({ brushSize: v })}+ />+ )}+ <div className="space-y-1">+ <div className="text-[10px] text-[#8a8a8a]">Refer Source</div>+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['refer-reference', 'Reference'],+ ['refer-all', 'All'],+ ['active', 'Active'],+ ] as const+ ).map(([id, lbl]) => (+ <button+ key={id}+ type="button"+ onClick={() => toolStoreActions.updateFillSettings({ smartReferMode: id })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ smartReferMode === id+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ </div>+ {method === 'enclose-and-fill' && (+ <div className="space-y-1">+ <div className="text-[10px] text-[#8a8a8a]">Target Area</div>+ <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['all-enclosed', 'All Enclosed'],+ ['unfilled-only', 'Unfilled Only'],+ ] as const+ ).map(([id, lbl]) => (+ <button+ key={id}+ type="button"+ onClick={() => toolStoreActions.updateFillSettings({ encloseTarget: id })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ encloseTarget === id+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ </div>+ )}+ <CompactSlider+ label="Opacity"+ valueLabel={`${Math.round((fillSettings.opacity ?? 1) * 100)}%`}+ min={1}+ max={100}+ value={Math.round((fillSettings.opacity ?? 1) * 100)}+ onChange={(v) => toolStoreActions.updateFillSettings({ opacity: v / 100 })}+ />+ <CompactSlider+ label="Tolerance"+ valueLabel={`${fillSettings.tolerance ?? 32}`}+ min={0}+ max={100}+ value={fillSettings.tolerance ?? 32}+ onChange={(v) => toolStoreActions.updateFillSettings({ tolerance: v })}+ />+ <CompactSlider+ label="Close Gap"+ valueLabel={`${fillSettings.smartCloseGap ?? 10}px`}+ min={0}+ max={40}+ value={fillSettings.smartCloseGap ?? 10}+ onChange={(v) => toolStoreActions.updateFillSettings({ smartCloseGap: v })}+ />+ <CompactSlider+ label="Area Scaling"+ valueLabel={`${(fillSettings.smartAreaScale ?? 1) > 0 ? '+' : ''}${fillSettings.smartAreaScale ?? 1}px`}+ min={-20}+ max={20}+ value={fillSettings.smartAreaScale ?? 1}+ onChange={(v) => toolStoreActions.updateFillSettings({ smartAreaScale: v })}+ />+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Anti-Alias</span>+ <input+ type="checkbox"+ checked={fillSettings.antiAlias ?? true}+ onChange={(e) =>+ toolStoreActions.updateFillSettings({ antiAlias: e.target.checked })+ }+ />+ </label>+ {method === 'enclose-and-fill' && (+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Transparent (Erase)</span>+ <input+ type="checkbox"+ checked={isTransparentColor}+ onChange={() => toolStoreActions.toggleTransparentColor()}+ />+ </label>+ )}+ <div className="text-[10px] text-[#6e6e6e]">+ {method === 'enclose-and-fill'+ ? 'Lasso around line art (e.g. hair strands) to fill all closed areas inside without affecting the background. Press Esc to cancel.'+ : 'Brush over outlines and tight corners to fill only tiny enclosed unfilled pixels. Press [ / ] to resize, Esc to cancel.'}+ </div>+ </div>+ ) : (<><CompactSliderlabel="Tolerance"@@ -506,10 +703,36 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React}).join(', ');+ const selectedMeshIndices = activeGradientMesh+ ? getSelectedMeshNodeIndices(activeGradientMesh)+ : [];+ const primarySelectedMeshIdx =+ activeGradientMesh &&+ activeGradientMesh.selectedNodeIndex !== null &&+ selectedMeshIndices.includes(activeGradientMesh.selectedNodeIndex)+ ? activeGradientMesh.selectedNodeIndex+ : selectedMeshIndices.length > 0+ ? selectedMeshIndices[0]+ : null;const selectedMeshNode =- activeGradientMesh && activeGradientMesh.selectedNodeIndex !== null- ? activeGradientMesh.nodes[activeGradientMesh.selectedNodeIndex]+ activeGradientMesh && primarySelectedMeshIdx !== null+ ? activeGradientMesh.nodes[primarySelectedMeshIdx]: null;+ const meshRotationDeg = Math.round(activeGradientMesh?.rotationDeg ?? 0);+ const hasMixedMeshNodeColors =+ Boolean(activeGradientMesh && selectedMeshNode && selectedMeshIndices.length > 1) &&+ selectedMeshIndices.some(+ (idx) =>+ activeGradientMesh!.nodes[idx]?.color.toLowerCase() !==+ selectedMeshNode!.color.toLowerCase()+ );+ const selectedMeshAvgOpacity =+ activeGradientMesh && selectedMeshIndices.length > 0+ ? selectedMeshIndices.reduce(+ (acc, idx) => acc + (activeGradientMesh.nodes[idx]?.opacity ?? 1),+ 0+ ) / selectedMeshIndices.length+ : 1;return (<div className="p-2 space-y-3 overflow-y-auto flex-1">@@ -722,35 +945,117 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = ReactonChange={(v) => toolStoreActions.updateGradientSettings({ meshRows: v })}/>- {selectedMeshNode && activeGradientMesh?.selectedNodeIndex !== null && (+ {activeGradientMesh && (+ <div className="space-y-1.5 p-1.5 rounded bg-[#161616]">+ <CompactSlider+ label="Rotate Mesh"+ valueLabel={`${meshRotationDeg}°`}+ min={-180}+ max={180}+ value={meshRotationDeg}+ onChange={(v) => toolStoreActions.setActiveGradientMeshRotation(v)}+ />+ <div className="grid grid-cols-4 gap-1">+ {(+ [+ { label: '-45°', onClick: () => toolStoreActions.rotateActiveGradientMesh(-45) },+ { label: '+45°', onClick: () => toolStoreActions.rotateActiveGradientMesh(45) },+ { label: '+90°', onClick: () => toolStoreActions.rotateActiveGradientMesh(90) },+ { label: '0°', onClick: () => toolStoreActions.setActiveGradientMeshRotation(0) },+ ] as const+ ).map((btn) => (+ <button+ key={btn.label}+ type="button"+ onClick={btn.onClick}+ className="py-0.5 rounded bg-[#242424] text-[#cccccc] hover:text-[#ffffff] hover:bg-[#333333] text-[10px] font-mono cursor-pointer"+ >+ {btn.label}+ </button>+ ))}+ </div>+ </div>+ )}++ {activeGradientMesh && (<div className="space-y-1.5 p-1.5 rounded bg-[#161616]">- <div className="flex items-center justify-between text-[10px]">- <span className="text-[#8a8a8a]">- Node #{activeGradientMesh!.selectedNodeIndex! + 1}+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">+ <span>+ Vertices ({selectedMeshIndices.length}/{activeGradientMesh.nodes.length})</span>- <input- type="color"- value={selectedMeshNode.color}- onChange={(e) =>- toolStoreActions.updateActiveGradientMeshNode(- activeGradientMesh!.selectedNodeIndex!,- { color: e.target.value }- )- }- className="w-6 h-5 bg-transparent border-0 cursor-pointer"- />+ </div>+ <div className="grid grid-cols-3 gap-1">+ <button+ type="button"+ onClick={() => toolStoreActions.selectAllActiveGradientMeshNodes()}+ className="py-0.5 rounded bg-[#242424] text-[#cccccc] hover:text-[#ffffff] hover:bg-[#333333] text-[10px] cursor-pointer"+ >+ Select All+ </button>+ <button+ type="button"+ onClick={() => toolStoreActions.invertActiveGradientMeshSelection()}+ className="py-0.5 rounded bg-[#242424] text-[#cccccc] hover:text-[#ffffff] hover:bg-[#333333] text-[10px] cursor-pointer"+ >+ Invert+ </button>+ <button+ type="button"+ onClick={() => toolStoreActions.clearActiveGradientMeshSelection()}+ className="py-0.5 rounded bg-[#242424] text-[#cccccc] hover:text-[#ffffff] hover:bg-[#333333] text-[10px] cursor-pointer"+ >+ Clear+ </button>+ </div>+ <div className="text-[9px] text-[#6e6e6e]">+ Shift+Click or drag box to multi-select vertices+ </div>+ </div>+ )}++ {selectedMeshNode && selectedMeshIndices.length > 0 && (+ <div className="space-y-1.5 p-1.5 rounded bg-[#161616]">+ <div className="flex items-center justify-between gap-1 text-[10px]">+ <span className="text-[#8a8a8a] truncate">+ {selectedMeshIndices.length === 1+ ? `Node #${selectedMeshIndices[0] + 1}`+ : `${selectedMeshIndices.length} Nodes${hasMixedMeshNodeColors ? ' (Mixed)' : ''}`}+ </span>+ <div className="flex items-center gap-1 shrink-0">+ <button+ type="button"+ onClick={() =>+ toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {+ color: primaryColor,+ })+ }+ title="Apply current foreground color to selected vertices"+ className="px-1.5 py-0.5 rounded bg-[#242424] text-[#cccccc] hover:text-[#ffffff] hover:bg-[#333333] text-[9px] cursor-pointer"+ >+ Use FG+ </button>+ <input+ type="color"+ value={selectedMeshNode.color}+ onChange={(e) =>+ toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {+ color: e.target.value,+ })+ }+ className="w-6 h-5 bg-transparent border-0 cursor-pointer"+ />+ </div></div><CompactSlider- label="Node Opacity"- valueLabel={`${Math.round(selectedMeshNode.opacity * 100)}%`}+ label={selectedMeshIndices.length > 1 ? 'Nodes Opacity' : 'Node Opacity'}+ valueLabel={`${Math.round(selectedMeshAvgOpacity * 100)}%`}min={0}max={100}- value={Math.round(selectedMeshNode.opacity * 100)}+ value={Math.round(selectedMeshAvgOpacity * 100)}onChange={(v) =>- toolStoreActions.updateActiveGradientMeshNode(- activeGradientMesh!.selectedNodeIndex!,- { opacity: v / 100 }- )+ toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {+ opacity: v / 100,+ })}/></div>@@ -1810,6 +2115,42 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React);}+ if (currentTool === 'transform') {+ return (+ <div className="p-2.5 space-y-2.5 overflow-y-auto flex-1">+ <div className="flex items-center gap-1.5 text-[11px] font-medium text-[#e5e5e5]">+ <Scaling className="w-3.5 h-3.5 text-[var(--accent)]" />+ <span>Transform & Warp</span>+ </div>+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed">+ Use the floating transform bar on the canvas to switch between{' '}+ <span className="text-[#cccccc]">Free</span>,{' '}+ <span className="text-[#cccccc]">Perspective</span>,{' '}+ <span className="text-[#cccccc]">Mesh</span>,{' '}+ <span className="text-[#cccccc]">Puppet Warp</span>, and{' '}+ <span className="text-[#cccccc]">Cage Transform</span>.+ </p>+ <div className="space-y-1.5 rounded bg-[#161616] border border-white/[0.06] p-2 text-[10px] text-[#999999]">+ <div className="text-[#cccccc] font-medium">Puppet Warp Tips</div>+ <div>• Click artwork to place 5–6 joint pins</div>+ <div>• Drag pins to bend arms, head, or folds</div>+ <div>• Drag ring handle or Alt+Drag to tilt/rotate</div>+ <div>• Right-click or Delete removes a pin</div>+ </div>+ <div className="space-y-1.5 rounded bg-[#161616] border border-white/[0.06] p-2 text-[10px] text-[#999999]">+ <div className="text-[#cccccc] font-medium">Cage Transform Tips</div>+ <div>• Drag vertices or edges to warp smoothly</div>+ <div>• Switch to Edit Cage to add/shape points</div>+ <div>• Click Redraw to outline a specific region</div>+ </div>+ <div className="text-[10px] text-[#777777] flex items-center justify-between pt-1 border-t border-white/[0.06]">+ <span>Apply: Enter</span>+ <span>Cancel: Esc</span>+ </div>+ </div>+ );+ }+if (currentTool === 'object') {return (<div className="p-2.5 space-y-2.5 overflow-y-auto flex-1">@@ -2079,7 +2420,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactconst currentAntiAlias = brushSettings.antiAlias ?? 2;const activeImportWarnings =- currentTool === 'brush'+ isPaintTool(currentTool)? activeCustomBrush?.importWarnings?.length? activeCustomBrush.importWarnings: brushSettings.importWarnings?.length@@ -2093,7 +2434,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React<div className="shrink-0 bg-[#1b1b1b] border-t border-[#2a2a2a] px-2 py-1.5 space-y-1.5"><div className="flex items-center gap-1"><canvas ref={previewCanvasRef} className="flex-1 h-8 rounded bg-[#161616] block min-w-0" />- {currentTool === 'brush' && (+ {isPaintTool(currentTool) && (<buttontype="button"onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}@@ -2337,18 +2678,33 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = ReactonChange={(e) =>handleUpdateBrushSettings({customTipAngleDynamics: e.target.value as CspAngleDynamicsMode,+ rotateCursor: undefined,})}className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"><option value="none">None</option><option value="direction">Direction of Line</option>+ <option value="initial-direction">Initial Direction</option><option value="tilt">Pen Tilt</option><option value="twist">Barrel Twist</option><option value="random">Random</option><option value="direction-random">Direction + Random</option></select></div>+ <label+ className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer"+ title="Rotate the brush cursor silhouette as you move to track brush direction"+ >+ <span>This brush rotates</span>+ <input+ type="checkbox"+ checked={resolveBrushCursorRotationSpec(brushSettings, currentTool).enabled}+ onChange={(e) =>+ handleUpdateBrushSettings({ rotateCursor: e.target.checked })+ }+ />+ </label><div className="grid grid-cols-2 gap-1.5"><div className="space-y-0.5"><span className="text-[10px] text-[#8a8a8a]">Flip H</span>diff --git a/src/components/ToolStrip.tsx b/src/components/ToolStrip.tsxindex 4e2ae9f..75c5684 100644--- a/src/components/ToolStrip.tsx+++ b/src/components/ToolStrip.tsx@@ -23,6 +23,7 @@ import {Droplets,Feather,Box,+ Sparkles,} from 'lucide-react';import { ToolType } from '../types/editor';import { LiquifyIcon } from './LiquifyIcon';@@ -80,6 +81,15 @@ export const ToolStrip: React.FC<ToolStripProps> = React.memo(if (isHidden) uiStoreActions.toggleLeftPanelHidden();},},+ {+ id: 'decoration',+ label: 'Decoration',+ icon: <Sparkles className="w-3.5 h-3.5" />,+ onClick: () => {+ toolStoreActions.selectTool('decoration');+ if (isHidden) uiStoreActions.toggleLeftPanelHidden();+ },+ },{ id: 'eraser', label: 'Eraser (E)', icon: <Eraser className="w-3.5 h-3.5" /> },{ id: 'pipette', label: 'Eyedropper (I)', icon: <Pipette className="w-3.5 h-3.5" /> },{@@ -152,6 +162,7 @@ export const ToolStrip: React.FC<ToolStripProps> = React.memo(<React.Fragment key={item.id}><buttontype="button"+ data-testid={`toolstrip-${item.id}-btn`}onClick={() =>item.onClick ? item.onClick() : toolStoreActions.selectTool(item.id)}diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsxindex 16095f2..958780e 100644--- a/src/components/TransformOverlay.tsx+++ b/src/components/TransformOverlay.tsx@@ -1,20 +1,56 @@-import React, { useRef, useLayoutEffect, useEffect, useMemo } from 'react';-import { TransformSession, Point2D, TransformMode } from '../types/editor';+import React, { useRef, useLayoutEffect, useEffect, useMemo, useState } from 'react';+import {+ TransformSession,+ Point2D,+ TransformMode,+ PuppetRigidityMode,+ PuppetMeshDensity,+ PuppetPin,+ CagePoint,+} from '../types/editor';import {FlipHorizontal,FlipVertical,RotateCcw,+ Trash2,+ Grid,+ ArrowUp,+ ArrowDown,+ PenTool,+ Move,+ Sparkles,+ Check,} from 'lucide-react';import {renderPerspectiveQuad,renderMeshWarp,+ renderDeformedTriangles,createDefaultPerspectiveQuad,createDefaultMeshPoints,computeMeshSubdivisions,getPointsBounds,getMeshSurfaceBounds,evaluateMeshSurface,+ extractCanvasPixelBuffer,} from '../utils/transformEngine';+import {+ switchTransformSessionMode,+ flipTransformSession,+ resetTransformSession,+} from '../utils/transformModeTransition';+import {+ buildPuppetMesh,+ ensurePuppetMesh,+ getDeformedMeshBounds,+ mapDeformedPointToPuppetRest,+ solvePuppetDeformation,+} from '../utils/puppetWarpEngine';+import {+ buildAutoCagePoints,+ createInitialCageState,+ evaluateCageMesh,+} from '../utils/cageWarpEngine';+import { releaseTemporaryCanvas } from '../utils/tileEngine';interface TransformOverlayProps {session: TransformSession;@@ -22,24 +58,32 @@ interface TransformOverlayProps {rotation: number; // canvas viewport rotationflipX?: boolean;flipY?: boolean;+ isSpaceDown?: boolean;onUpdateSession: (updater: (prev: TransformSession) => TransformSession) => void;onApply: () => void;onCancel: () => void;}+const EXPANSION_STEPS = [0, 2, 4, 6, 10, 16, 24] as const;+export const TransformOverlay: React.FC<TransformOverlayProps> = ({session,zoom,rotation: canvasRotation,flipX = false,flipY = false,+ isSpaceDown = false,onUpdateSession,onApply,onCancel,}) => {const containerRef = useRef<HTMLDivElement>(null);+ const docOriginRef = useRef<HTMLDivElement>(null);const previewCanvasRef = useRef<HTMLCanvasElement>(null);const activeDragCleanupRef = useRef<(() => void) | null>(null);+ const pinIdCounterRef = useRef(1);+ const cageIdCounterRef = useRef(100);+ const [hoverDocPt, setHoverDocPt] = useState<Point2D | null>(null);useEffect(() => {return () => {@@ -49,6 +93,15 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({};}, []);+ // Release superseded intermediate baked canvases after commit (React StrictMode safe)+ useEffect(() => {+ const retired = session.retiredCanvases;+ if (!retired || retired.length === 0) return;+ for (const canvas of retired) {+ releaseTemporaryCanvas(canvas);+ }+ }, [session.retiredCanvases]);+const mode: TransformMode = session.mode || 'affine';// Ensure perspectiveQuad exists@@ -59,9 +112,20 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({session.y,session.width,session.height,- session.rotation+ session.rotation,+ session.flipH,+ session.flipV);- }, [session.perspectiveQuad, session.x, session.y, session.width, session.height, session.rotation]);+ }, [+ session.perspectiveQuad,+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV,+ ]);// Ensure meshPoints existsconst meshPoints: Point2D[][] = useMemo(() => {@@ -71,7 +135,53 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({return createDefaultMeshPoints(quad, cols, rows);}, [session.meshPoints, quad, session.meshCols, session.meshRows]);- // Compute bounding box for perspective or mesh mode+ // Resolve Puppet mesh & live ARAP deformation+ const puppetMesh = useMemo(() => {+ if (mode !== 'puppet' || !session.sourceCanvas) return null;+ const srcPixels = session.sourcePixels ?? extractCanvasPixelBuffer(session.sourceCanvas) ?? undefined;+ return ensurePuppetMesh(+ session.puppet,+ srcPixels,+ session.sourceCanvas.width,+ session.sourceCanvas.height,+ quad+ );+ }, [mode, session.puppet, session.sourcePixels, session.sourceCanvas, quad]);++ const puppetSolved = useMemo(() => {+ if (mode !== 'puppet' || !puppetMesh) return null;+ return solvePuppetDeformation(+ puppetMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ }, [mode, puppetMesh, session.puppet?.pins, session.puppet?.rigidity]);++ // Resolve Cage state & live MVC mesh evaluation+ const cageState = useMemo(() => {+ if (mode !== 'cage' || !session.sourceCanvas) return null;+ if (session.cage) return session.cage;+ const srcPixels = session.sourcePixels ?? extractCanvasPixelBuffer(session.sourceCanvas) ?? undefined;+ return createInitialCageState(+ srcPixels,+ session.sourceCanvas.width,+ session.sourceCanvas.height,+ quad+ );+ }, [mode, session.cage, session.sourcePixels, session.sourceCanvas, quad]);++ const cageEval = useMemo(() => {+ if (mode !== 'cage' || !cageState || !session.sourceCanvas) return null;+ return evaluateCageMesh(+ session.sourceCanvas.width,+ session.sourceCanvas.height,+ quad,+ cageState,+ false+ );+ }, [mode, cageState, session.sourceCanvas, quad]);++ // Compute bounding box for current transform modeconst nonAffineBounds = useMemo(() => {if (mode === 'perspective') {return getPointsBounds(quad);@@ -79,6 +189,12 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({if (mode === 'mesh') {return getMeshSurfaceBounds(meshPoints, 6);}+ if (mode === 'puppet' && puppetSolved) {+ return getDeformedMeshBounds(puppetSolved.x, puppetSolved.y);+ }+ if (mode === 'cage' && cageEval) {+ return getDeformedMeshBounds(cageEval.deformedX, cageEval.deformedY);+ }if (session.rotation) {const cx = session.x + session.width / 2;const cy = session.y + session.height / 2;@@ -106,9 +222,20 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({width: session.width,height: session.height,};- }, [mode, quad, meshPoints, session.x, session.y, session.width, session.height, session.rotation]);-- // Draw affine preview only when entering affine mode or when sourceCanvas changes (zero per-frame reallocation)+ }, [+ mode,+ quad,+ meshPoints,+ puppetSolved,+ cageEval,+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ ]);++ // Draw affine preview only when entering affine mode or when sourceCanvas changesuseLayoutEffect(() => {if (mode !== 'affine') return;const canvas = previewCanvasRef.current;@@ -125,9 +252,9 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({ctx.drawImage(session.sourceCanvas, 0, 0);}, [mode, session.sourceCanvas]);- // Draw perspective / mesh warp preview synchronously when control points change+ // Draw perspective / mesh / puppet / cage warp preview synchronouslyuseLayoutEffect(() => {- if (mode !== 'perspective' && mode !== 'mesh') return;+ if (mode === 'affine') return;const canvas = previewCanvasRef.current;if (!canvas || !session.sourceCanvas) return;@@ -147,16 +274,14 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({{ x: quad[2].x - nonAffineBounds.minX, y: quad[2].y - nonAffineBounds.minY },{ x: quad[3].x - nonAffineBounds.minX, y: quad[3].y - nonAffineBounds.minY },];-renderPerspectiveQuad(ctx, session.sourceCanvas, localQuad, 24);- } else {+ } else if (mode === 'mesh') {const localMesh: Point2D[][] = meshPoints.map((row) =>row.map((pt) => ({x: pt.x - nonAffineBounds.minX,y: pt.y - nonAffineBounds.minY,})));-const subPerCell = computeMeshSubdivisions(session.sourceCanvas.width,session.sourceCanvas.height,@@ -164,28 +289,52 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({false);renderMeshWarp(ctx, session.sourceCanvas, localMesh, subPerCell);+ } else if (mode === 'puppet' && puppetMesh && puppetSolved) {+ const n = puppetSolved.x.length;+ const localX = new Float32Array(n);+ const localY = new Float32Array(n);+ const ox = nonAffineBounds.minX;+ const oy = nonAffineBounds.minY;+ for (let i = 0; i < n; i++) {+ localX[i] = puppetSolved.x[i] - ox;+ localY[i] = puppetSolved.y[i] - oy;+ }+ renderDeformedTriangles(+ ctx,+ session.sourceCanvas,+ localX,+ localY,+ puppetMesh.uvX,+ puppetMesh.uvY,+ puppetMesh.triangles,+ puppetSolved.triOrder+ );+ } else if (mode === 'cage' && cageEval) {+ const n = cageEval.deformedX.length;+ const localX = new Float32Array(n);+ const localY = new Float32Array(n);+ const ox = nonAffineBounds.minX;+ const oy = nonAffineBounds.minY;+ for (let i = 0; i < n; i++) {+ localX[i] = cageEval.deformedX[i] - ox;+ localY[i] = cageEval.deformedY[i] - oy;+ }+ renderDeformedTriangles(+ ctx,+ session.sourceCanvas,+ localX,+ localY,+ cageEval.uvX,+ cageEval.uvY,+ cageEval.triangles+ );}- }, [mode, session.sourceCanvas, nonAffineBounds, quad, meshPoints]);+ }, [mode, session.sourceCanvas, nonAffineBounds, quad, meshPoints, puppetMesh, puppetSolved, cageEval]);- // Mode switching handler+ // Mode switching handler: preserves all prior edits across mode changesconst handleSwitchMode = (newMode: TransformMode) => {if (newMode === mode) return;-- onUpdateSession((prev) => {- const q = prev.perspectiveQuad || createDefaultPerspectiveQuad(prev.x, prev.y, prev.width, prev.height, prev.rotation);- const cols = prev.meshCols || 4;- const rows = prev.meshRows || 4;- const m = prev.meshPoints || createDefaultMeshPoints(q, cols, rows);-- return {- ...prev,- mode: newMode,- perspectiveQuad: q,- meshCols: cols,- meshRows: rows,- meshPoints: m,- };- });+ onUpdateSession((prev) => switchTransformSessionMode(prev, newMode));};// Mesh resolution change handler@@ -199,7 +348,6 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({const row: Point2D[] = [];for (let c = 0; c < size; c++) {const u = size > 1 ? c / (size - 1) : 0;- // Resample position from existing surface without integer rounding distortionconst evaluated = evaluateMeshSurface(existingMesh, u, v);row.push({ x: evaluated.x, y: evaluated.y });}@@ -228,6 +376,589 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({};};+ // Convert absolute screen client coords to exact document canvas coordinates+ const clientToCanvas = (clientX: number, clientY: number): Point2D => {+ const originRect = docOriginRef.current?.getBoundingClientRect();+ if (!originRect) return { x: 0, y: 0 };+ const { dx, dy } = screenDeltaToCanvas(clientX - originRect.left, clientY - originRect.top);+ return { x: dx, y: dy };+ };++ // --- Puppet Warp Controls & Handlers ---+ const handleChangePuppetRigidity = (rigidity: PuppetRigidityMode) => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return { ...prev, puppet: { ...p, rigidity } };+ });+ };++ const handleChangePuppetMeshParams = (density: PuppetMeshDensity, expansion: number) => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ const srcPixels = prev.sourcePixels ?? extractCanvasPixelBuffer(prev.sourceCanvas) ?? undefined;+ const activeQuad =+ prev.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ prev.x,+ prev.y,+ prev.width,+ prev.height,+ prev.rotation,+ prev.flipH,+ prev.flipV+ );+ const nextMesh = buildPuppetMesh(+ srcPixels,+ prev.sourceCanvas.width,+ prev.sourceCanvas.height,+ activeQuad,+ density,+ expansion+ );+ return {+ ...prev,+ puppet: {+ ...p,+ density,+ expansion,+ mesh: nextMesh,+ },+ };+ });+ };++ const handleTogglePuppetShowMesh = () => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return { ...prev, puppet: { ...p, showMesh: !p.showMesh } };+ });+ };++ const handleDeletePuppetPin = (pinId: string) => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ const nextPins = p.pins.filter((pin) => pin.id !== pinId);+ const nextSelected =+ p.selectedPinId === pinId+ ? nextPins.length > 0+ ? nextPins[nextPins.length - 1].id+ : null+ : p.selectedPinId;+ return {+ ...prev,+ puppet: { ...p, pins: nextPins, selectedPinId: nextSelected },+ };+ });+ };++ const handleClearPuppetPins = () => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return { ...prev, puppet: { ...p, pins: [], selectedPinId: null } };+ });+ };++ const handleAdjustPinDepth = (pinId: string, delta: number) => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return {+ ...prev,+ puppet: {+ ...p,+ pins: p.pins.map((pin) =>+ pin.id === pinId ? { ...pin, depth: Math.max(-10, Math.min(10, pin.depth + delta)) } : pin+ ),+ },+ };+ });+ };++ const handleResetPinRotation = (pinId: string) => {+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return {+ ...prev,+ puppet: {+ ...p,+ pins: p.pins.map((pin) => (pin.id === pinId ? { ...pin, rotation: 0 } : pin)),+ },+ };+ });+ };++ const startDragPuppetPin = (pin: PuppetPin, e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown) return;+ e.stopPropagation();+ e.preventDefault();++ if (activeDragCleanupRef.current) activeDragCleanupRef.current();++ // Alt+Drag on a pin rotates it directly+ if (e.altKey) {+ startRotatePuppetPin(pin, e);+ return;+ }++ onUpdateSession((prev) =>+ prev.puppet ? { ...prev, puppet: { ...prev.puppet, selectedPinId: pin.id } } : prev+ );++ const startClientX = e.clientX;+ const startClientY = e.clientY;+ const initX = pin.x;+ const initY = pin.y;+ const pinId = pin.id;++ const handlePointerMove = (ev: PointerEvent) => {+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startClientX, ev.clientY - startClientY);+ let finalDx = dx;+ let finalDy = dy;+ if (ev.shiftKey) {+ if (Math.abs(finalDx) > Math.abs(finalDy)) finalDy = 0;+ else finalDx = 0;+ }+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return {+ ...prev,+ puppet: {+ ...p,+ selectedPinId: pinId,+ pins: p.pins.map((item) =>+ item.id === pinId ? { ...item, x: initX + finalDx, y: initY + finalDy } : item+ ),+ },+ };+ });+ };++ const handlePointerUp = () => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ activeDragCleanupRef.current = null;+ };++ activeDragCleanupRef.current = handlePointerUp;+ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ };++ const startRotatePuppetPin = (pin: PuppetPin, e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown) return;+ e.stopPropagation();+ e.preventDefault();++ if (activeDragCleanupRef.current) activeDragCleanupRef.current();++ const pinId = pin.id;+ const initRot = pin.rotation;+ const startDoc = clientToCanvas(e.clientX, e.clientY);+ const startAngle = Math.atan2(startDoc.y - pin.y, startDoc.x - pin.x);++ const handlePointerMove = (ev: PointerEvent) => {+ const curDoc = clientToCanvas(ev.clientX, ev.clientY);+ const dx = curDoc.x - pin.x;+ const dy = curDoc.y - pin.y;+ if (dx * dx + dy * dy < 1e-4) return;+ const curAngle = Math.atan2(dy, dx);+ let deltaDeg = ((curAngle - startAngle) * 180) / Math.PI;+ // Wrap delta smoothly into (-180, 180]+ while (deltaDeg > 180) deltaDeg -= 360;+ while (deltaDeg <= -180) deltaDeg += 360;+ let nextRot = initRot + deltaDeg;+ if (ev.shiftKey) {+ nextRot = Math.round(nextRot / 15) * 15;+ }+ nextRot = Math.max(-180, Math.min(180, Math.round(nextRot * 10) / 10));+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return {+ ...prev,+ puppet: {+ ...p,+ selectedPinId: pinId,+ pins: p.pins.map((item) => (item.id === pinId ? { ...item, rotation: nextRot } : item)),+ },+ };+ });+ };++ const handlePointerUp = () => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ activeDragCleanupRef.current = null;+ };++ activeDragCleanupRef.current = handlePointerUp;+ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ };++ const handlePuppetSurfacePointerDown = (e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown || !puppetMesh || !puppetSolved) return;+ e.stopPropagation();+ e.preventDefault();++ const docPt = clientToCanvas(e.clientX, e.clientY);+ const hit = mapDeformedPointToPuppetRest(+ puppetMesh,+ puppetSolved.x,+ puppetSolved.y,+ docPt.x,+ docPt.y+ );++ const maxSnapDist = 28 / Math.max(0.1, zoom);+ if (!hit.inside && hit.distSq > maxSnapDist * maxSnapDist) {+ // Clicked well outside the artwork -> just clear selection+ onUpdateSession((prev) =>+ prev.puppet ? { ...prev, puppet: { ...prev.puppet, selectedPinId: null } } : prev+ );+ return;+ }++ const newPinId = `pin-${Date.now()}-${pinIdCounterRef.current++}`;+ const newPin: PuppetPin = {+ id: newPinId,+ restX: hit.restX,+ restY: hit.restY,+ x: docPt.x,+ y: docPt.y,+ rotation: 0,+ depth: 0,+ };++ onUpdateSession((prev) => {+ const existing = prev.puppet;+ return {+ ...prev,+ puppet: {+ rigidity: existing?.rigidity ?? 'normal',+ density: existing?.density ?? 'normal',+ expansion: existing?.expansion ?? 6,+ showMesh: existing?.showMesh ?? true,+ mesh: existing?.mesh ?? puppetMesh,+ pins: [...(existing?.pins ?? []), newPin],+ selectedPinId: newPinId,+ },+ };+ });++ // Immediately enable fluid click-and-drag after placing pin (with small 3px deadzone)+ if (activeDragCleanupRef.current) activeDragCleanupRef.current();+ const startClientX = e.clientX;+ const startClientY = e.clientY;+ let dragged = false;++ const handlePointerMove = (ev: PointerEvent) => {+ const distScreen = Math.hypot(ev.clientX - startClientX, ev.clientY - startClientY);+ if (!dragged && distScreen < 3) return;+ dragged = true;+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startClientX, ev.clientY - startClientY);+ onUpdateSession((prev) => {+ const p = prev.puppet;+ if (!p) return prev;+ return {+ ...prev,+ puppet: {+ ...p,+ pins: p.pins.map((item) =>+ item.id === newPinId ? { ...item, x: newPin.x + dx, y: newPin.y + dy } : item+ ),+ },+ };+ });+ };++ const handlePointerUp = () => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ activeDragCleanupRef.current = null;+ };++ activeDragCleanupRef.current = handlePointerUp;+ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ };++ // --- Cage Transform Controls & Handlers ---+ const handleSetCagePhase = (phase: 'edit' | 'deform') => {+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ if (!c) return prev;+ if (phase === 'deform' && c.points.length < 3) return prev;+ return {+ ...prev,+ cage: {+ ...c,+ phase,+ closed: phase === 'deform' ? true : c.closed,+ },+ };+ });+ };++ const handleStartRedrawCage = () => {+ onUpdateSession((prev) => ({+ ...prev,+ cage: {+ points: [],+ closed: false,+ phase: 'edit',+ selectedPointId: null,+ showMesh: prev.cage?.showMesh ?? false,+ },+ }));+ };++ const handleAutoFitCage = () => {+ onUpdateSession((prev) => {+ const srcPixels = prev.sourcePixels ?? extractCanvasPixelBuffer(prev.sourceCanvas) ?? undefined;+ const activeQuad =+ prev.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ prev.x,+ prev.y,+ prev.width,+ prev.height,+ prev.rotation,+ prev.flipH,+ prev.flipV+ );+ return {+ ...prev,+ cage: {+ points: buildAutoCagePoints(+ srcPixels,+ prev.sourceCanvas.width,+ prev.sourceCanvas.height,+ activeQuad+ ),+ closed: true,+ phase: 'deform',+ selectedPointId: null,+ showMesh: prev.cage?.showMesh ?? false,+ },+ };+ });+ };++ const handleToggleCageMesh = () => {+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ if (!c) return prev;+ return { ...prev, cage: { ...c, showMesh: !c.showMesh } };+ });+ };++ const handleCloseCage = () => {+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ if (!c || c.points.length < 3) return prev;+ return { ...prev, cage: { ...c, closed: true, phase: 'deform' } };+ });+ };++ const handleDeleteCagePoint = (ptId: string) => {+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ if (!c) return prev;+ if (c.closed && c.points.length <= 3) return prev;+ const nextPts = c.points.filter((pt) => pt.id !== ptId);+ return {+ ...prev,+ cage: {+ ...c,+ points: nextPts,+ selectedPointId: c.selectedPointId === ptId ? null : c.selectedPointId,+ },+ };+ });+ };++ const handleCageSurfacePointerDown = (e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown || !cageState) return;+ if (cageState.closed) return; // When closed, vertex/edge handles drive interaction+ e.stopPropagation();+ e.preventDefault();++ const docPt = clientToCanvas(e.clientX, e.clientY);++ // Clicking near first point closes custom cage once >= 3 points exist+ if (cageState.points.length >= 3) {+ const first = cageState.points[0];+ const closeDist = 14 / Math.max(0.1, zoom);+ if (Math.hypot(docPt.x - first.x, docPt.y - first.y) <= closeDist) {+ handleCloseCage();+ return;+ }+ }++ const newPt: CagePoint = {+ id: `cage-${Date.now()}-${cageIdCounterRef.current++}`,+ restX: docPt.x,+ restY: docPt.y,+ x: docPt.x,+ y: docPt.y,+ };+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ return {+ ...prev,+ cage: {+ ...c,+ points: [...c.points, newPt],+ selectedPointId: newPt.id,+ },+ };+ });+ };++ const startDragCageVertex = (pt: CagePoint, index: number, e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown || !cageState) return;+ e.stopPropagation();+ e.preventDefault();++ // Closing an open custom cage by clicking vertex 0+ if (!cageState.closed && index === 0 && cageState.points.length >= 3) {+ handleCloseCage();+ return;+ }++ if (activeDragCleanupRef.current) activeDragCleanupRef.current();++ const isEditPhase = cageState.phase === 'edit';+ const startClientX = e.clientX;+ const startClientY = e.clientY;+ const initX = pt.x;+ const initY = pt.y;+ const initRestX = pt.restX;+ const initRestY = pt.restY;+ const ptId = pt.id;++ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ return { ...prev, cage: { ...c, selectedPointId: ptId } };+ });++ const handlePointerMove = (ev: PointerEvent) => {+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startClientX, ev.clientY - startClientY);+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ return {+ ...prev,+ cage: {+ ...c,+ selectedPointId: ptId,+ points: c.points.map((item) => {+ if (item.id !== ptId) return item;+ if (isEditPhase) {+ return {+ ...item,+ restX: initRestX + dx,+ restY: initRestY + dy,+ x: initX + dx,+ y: initY + dy,+ };+ }+ return { ...item, x: initX + dx, y: initY + dy };+ }),+ },+ };+ });+ };++ const handlePointerUp = () => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ activeDragCleanupRef.current = null;+ };++ activeDragCleanupRef.current = handlePointerUp;+ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ };++ const handleCageEdgePointerDown = (edgeIndex: number, e: React.PointerEvent) => {+ if (e.button !== 0 || isSpaceDown || !cageState || !cageState.closed) return;+ e.stopPropagation();+ e.preventDefault();++ const n = cageState.points.length;+ if (n < 3) return;+ const i0 = edgeIndex;+ const i1 = (edgeIndex + 1) % n;++ // In Edit Cage phase: clicking an edge inserts a new control vertex along that edge+ if (cageState.phase === 'edit') {+ const docPt = clientToCanvas(e.clientX, e.clientY);+ const a = cageState.points[i0];+ const b = cageState.points[i1];+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const lenSq = dx * dx + dy * dy;+ const t = lenSq > 1e-6 ? Math.max(0.05, Math.min(0.95, ((docPt.x - a.x) * dx + (docPt.y - a.y) * dy) / lenSq)) : 0.5;+ const inserted: CagePoint = {+ id: `cage-${Date.now()}-${cageIdCounterRef.current++}`,+ restX: a.restX + t * (b.restX - a.restX),+ restY: a.restY + t * (b.restY - a.restY),+ x: a.x + t * dx,+ y: a.y + t * dy,+ };+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ const nextPts = [...c.points];+ nextPts.splice(i0 + 1, 0, inserted);+ return { ...prev, cage: { ...c, points: nextPts, selectedPointId: inserted.id } };+ });+ return;+ }++ // In Deform phase: dragging a cage edge translates both endpoints smoothly together+ if (activeDragCleanupRef.current) activeDragCleanupRef.current();+ const startClientX = e.clientX;+ const startClientY = e.clientY;+ const p0 = { ...cageState.points[i0] };+ const p1 = { ...cageState.points[i1] };++ const handlePointerMove = (ev: PointerEvent) => {+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startClientX, ev.clientY - startClientY);+ onUpdateSession((prev) => {+ const c = prev.cage ?? cageState;+ return {+ ...prev,+ cage: {+ ...c,+ points: c.points.map((item) => {+ if (item.id === p0.id) return { ...item, x: p0.x + dx, y: p0.y + dy };+ if (item.id === p1.id) return { ...item, x: p1.x + dx, y: p1.y + dy };+ return item;+ }),+ },+ };+ });+ };++ const handlePointerUp = () => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ activeDragCleanupRef.current = null;+ };++ activeDragCleanupRef.current = handlePointerUp;+ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ };+// Start dragging a perspective corner pinconst startDragPerspectiveCorner = (index: number, e: React.PointerEvent) => {e.stopPropagation();@@ -425,37 +1156,76 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({};const handleFlipH = () => {- onUpdateSession((prev) => ({ ...prev, flipH: !prev.flipH }));+ onUpdateSession((prev) => flipTransformSession(prev, 'horizontal'));};const handleFlipV = () => {- onUpdateSession((prev) => ({ ...prev, flipV: !prev.flipV }));+ onUpdateSession((prev) => flipTransformSession(prev, 'vertical'));};const handleReset = () => {- onUpdateSession((prev) => {- const defQuad = createDefaultPerspectiveQuad(prev.bounds.x, prev.bounds.y, prev.bounds.width, prev.bounds.height, 0);- return {- ...prev,- x: prev.bounds.x,- y: prev.bounds.y,- width: prev.bounds.width,- height: prev.bounds.height,- rotation: 0,- flipH: false,- flipV: false,- perspectiveQuad: defQuad,- meshPoints: createDefaultMeshPoints(defQuad, prev.meshCols || 4, prev.meshRows || 4),- };- });+ onUpdateSession((prev) => resetTransformSession(prev));};+ // Build SVG path string for Puppet triangulated mesh wireframe+ const puppetWireframePath = useMemo(() => {+ if (mode !== 'puppet' || !puppetMesh || !puppetSolved || session.puppet?.showMesh === false) {+ return '';+ }+ const edges = puppetMesh.edges;+ const xs = puppetSolved.x;+ const ys = puppetSolved.y;+ const parts: string[] = [];+ for (let i = 0; i < edges.length; i += 2) {+ const a = edges[i];+ const b = edges[i + 1];+ parts.push(`M${xs[a].toFixed(1)} ${ys[a].toFixed(1)}L${xs[b].toFixed(1)} ${ys[b].toFixed(1)}`);+ }+ return parts.join('');+ }, [mode, puppetMesh, puppetSolved, session.puppet?.showMesh]);++ // Build SVG path string for optional Cage internal mesh wireframe+ const cageWireframePath = useMemo(() => {+ if (mode !== 'cage' || !cageEval || !cageState?.showMesh) return '';+ const edges = cageEval.edges;+ const xs = cageEval.deformedX;+ const ys = cageEval.deformedY;+ const parts: string[] = [];+ for (let i = 0; i < edges.length; i += 2) {+ const a = edges[i];+ const b = edges[i + 1];+ parts.push(`M${xs[a].toFixed(1)} ${ys[a].toFixed(1)}L${xs[b].toFixed(1)} ${ys[b].toFixed(1)}`);+ }+ return parts.join('');+ }, [mode, cageEval, cageState?.showMesh]);+const invZoom = zoom > 0 ? 1 / zoom : 1;const handleSize = 8;const pinSize = 10;+ const puppetPins = session.puppet?.pins ?? [];+ const selectedPin =+ mode === 'puppet' && session.puppet?.selectedPinId+ ? puppetPins.find((p) => p.id === session.puppet?.selectedPinId) ?? null+ : null;++ const currentExpansion = session.puppet?.expansion ?? 6;+ const stepExpansion = (dir: -1 | 1) => {+ let idx = EXPANSION_STEPS.findIndex((v) => v >= currentExpansion);+ if (idx < 0) idx = EXPANSION_STEPS.length - 1;+ const nextIdx = Math.max(0, Math.min(EXPANSION_STEPS.length - 1, idx + dir));+ handleChangePuppetMeshParams(session.puppet?.density ?? 'normal', EXPANSION_STEPS[nextIdx]);+ };+return (<>+ {/* Exact (0, 0) document-space anchor for pan/zoom/rotation/flip-invariant clientToCanvas */}+ <div+ ref={docOriginRef}+ className="absolute left-0 top-0 w-0 h-0 pointer-events-none"+ aria-hidden="true"+ />+{/* 1. Affine Mode Container */}{mode === 'affine' && (<div@@ -542,8 +1312,8 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({</div>)}- {/* 2. Perspective or Mesh Warp Preview Canvas & Handles Container */}- {(mode === 'perspective' || mode === 'mesh') && (+ {/* 2. Non-Affine Warp Preview Canvas & Handles (Perspective / Mesh / Puppet / Cage) */}+ {mode !== 'affine' && (<>{/* Deformed Preview Canvas */}<div@@ -562,27 +1332,47 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({/></div>- {/* SVG Overlay for Quad or Mesh Lattice Lines */}+ {/* Interactive Click Surface for Puppet Pin Placement or Custom Cage Drawing */}+ {(mode === 'puppet' || (mode === 'cage' && cageState && !cageState.closed)) &&+ !isSpaceDown && (+ <div+ data-testid={+ mode === 'puppet' ? 'puppet-warp-surface' : 'cage-draw-surface'+ }+ onPointerDown={+ mode === 'puppet'+ ? handlePuppetSurfacePointerDown+ : handleCageSurfacePointerDown+ }+ onPointerMove={+ mode === 'cage' && cageState && !cageState.closed+ ? (e) => setHoverDocPt(clientToCanvas(e.clientX, e.clientY))+ : undefined+ }+ onPointerLeave={+ mode === 'cage' ? () => setHoverDocPt(null) : undefined+ }+ className="absolute inset-0 z-31 cursor-crosshair pointer-events-auto"+ />+ )}++ {/* SVG Overlay for Quad, Mesh Lattice, Puppet Wireframe, or Cage Polygon */}<svg- className="absolute inset-0 pointer-events-none z-31 overflow-visible"+ className="absolute inset-0 pointer-events-none z-32 overflow-visible"style={{ width: '100%', height: '100%' }}>{mode === 'perspective' && (- <>- {/* Perspective Quad Polygon Outline */}- <polygon- points={`${quad[0].x},${quad[0].y} ${quad[1].x},${quad[1].y} ${quad[2].x},${quad[2].y} ${quad[3].x},${quad[3].y}`}- fill="none"- stroke="#22d3ee"- strokeWidth={1.5 * invZoom}- strokeDasharray={`${4 * invZoom} ${4 * invZoom}`}- />- </>+ <polygon+ points={`${quad[0].x},${quad[0].y} ${quad[1].x},${quad[1].y} ${quad[2].x},${quad[2].y} ${quad[3].x},${quad[3].y}`}+ fill="none"+ stroke="#22d3ee"+ strokeWidth={1.5 * invZoom}+ strokeDasharray={`${4 * invZoom} ${4 * invZoom}`}+ />)}{mode === 'mesh' && (<>- {/* Horizontal Mesh Lattice Lines */}{meshPoints.map((row, r) => (<polylinekey={`h-${r}`}@@ -593,8 +1383,6 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({strokeDasharray={`${3 * invZoom} ${3 * invZoom}`}/>))}-- {/* Vertical Mesh Lattice Lines */}{meshPoints[0]?.map((_, c) => (<polylinekey={`v-${c}`}@@ -607,6 +1395,93 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({))}</>)}++ {mode === 'puppet' && puppetWireframePath && (+ <path+ d={puppetWireframePath}+ fill="none"+ stroke="#38bdf8"+ strokeOpacity={0.34}+ strokeWidth={0.9 * invZoom}+ strokeLinejoin="round"+ />+ )}++ {mode === 'cage' && cageWireframePath && (+ <path+ d={cageWireframePath}+ fill="none"+ stroke="#38bdf8"+ strokeOpacity={0.28}+ strokeWidth={0.9 * invZoom}+ />+ )}++ {mode === 'cage' && cageState && cageState.points.length > 0 && (+ <>+ {cageState.closed ? (+ <>+ <polygon+ points={cageState.points.map((p) => `${p.x},${p.y}`).join(' ')}+ fill={+ cageState.phase === 'edit'+ ? 'rgba(251, 191, 36, 0.05)'+ : 'rgba(34, 211, 238, 0.03)'+ }+ stroke={cageState.phase === 'edit' ? '#fbbf24' : '#22d3ee'}+ strokeWidth={1.7 * invZoom}+ strokeDasharray={+ cageState.phase === 'edit'+ ? `${5 * invZoom} ${3 * invZoom}`+ : undefined+ }+ />+ {/* Interactive Cage Edges (Insert vertex in Edit mode, Drag edge in Deform mode) */}+ {!isSpaceDown &&+ cageState.points.map((pt, i) => {+ const next = cageState.points[(i + 1) % cageState.points.length];+ return (+ <line+ key={`cage-edge-${pt.id}`}+ x1={pt.x}+ y1={pt.y}+ x2={next.x}+ y2={next.y}+ stroke="transparent"+ strokeWidth={12 * invZoom}+ style={{+ pointerEvents: 'stroke',+ cursor: cageState.phase === 'edit' ? 'copy' : 'move',+ }}+ onPointerDown={(e) => handleCageEdgePointerDown(i, e)}+ />+ );+ })}+ </>+ ) : (+ <>+ <polyline+ points={cageState.points.map((p) => `${p.x},${p.y}`).join(' ')}+ fill="none"+ stroke="#fbbf24"+ strokeWidth={1.7 * invZoom}+ />+ {hoverDocPt && (+ <line+ x1={cageState.points[cageState.points.length - 1].x}+ y1={cageState.points[cageState.points.length - 1].y}+ x2={hoverDocPt.x}+ y2={hoverDocPt.y}+ stroke="#fbbf24"+ strokeOpacity={0.75}+ strokeWidth={1.3 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}+ </>+ )}+ </>+ )}</svg>{/* Perspective Corner Pin Control Handles */}@@ -652,12 +1527,148 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({/>)))}++ {/* Puppet Warp Joint Pins & Selected Pin Rotation Ring */}+ {mode === 'puppet' &&+ puppetPins.map((pin, idx) => {+ const isSelected = session.puppet?.selectedPinId === pin.id;+ const rotRad = (pin.rotation * Math.PI) / 180;+ const ringRadiusPx = 22;+ const knobX = Math.cos(rotRad) * ringRadiusPx;+ const knobY = Math.sin(rotRad) * ringRadiusPx;++ return (+ <div+ key={pin.id}+ data-testid={`puppet-pin-${idx}`}+ className="absolute z-34 pointer-events-none"+ style={{+ left: `${pin.x}px`,+ top: `${pin.y}px`,+ transform: `scale(${invZoom})`,+ transformOrigin: '0 0',+ }}+ >+ {/* Rotation Ring & Handle around Selected Pin */}+ {isSelected && (+ <>+ <div+ className="absolute rounded-full border border-dashed border-amber-300/80 pointer-events-none"+ style={{+ left: `${-ringRadiusPx}px`,+ top: `${-ringRadiusPx}px`,+ width: `${ringRadiusPx * 2}px`,+ height: `${ringRadiusPx * 2}px`,+ }}+ />+ <div+ data-testid={`puppet-pin-rotate-${idx}`}+ onPointerDown={(e) => startRotatePuppetPin(pin, e)}+ onDoubleClick={(e) => {+ e.stopPropagation();+ handleResetPinRotation(pin.id);+ }}+ title={`Drag to rotate joint (${Math.round(pin.rotation)}°, Shift snaps 15°, double-click resets)`}+ className="absolute w-2.5 h-2.5 rounded-full bg-amber-400 border border-[#161616] shadow-md cursor-alias hover:scale-125 transition-transform pointer-events-auto"+ style={{+ left: `${knobX}px`,+ top: `${knobY}px`,+ transform: 'translate(-50%, -50%)',+ }}+ />+ {Math.abs(pin.rotation) >= 0.5 && (+ <div+ className="absolute px-1 py-0.5 rounded bg-[#161616]/90 border border-amber-400/40 text-amber-300 font-mono text-[9px] whitespace-nowrap pointer-events-none"+ style={{+ left: '0px',+ top: `${-ringRadiusPx - 14}px`,+ transform: `translateX(-50%) scale(${flipX ? -1 : 1}, ${flipY ? -1 : 1})`,+ }}+ >+ {pin.rotation > 0 ? `+${Math.round(pin.rotation)}°` : `${Math.round(pin.rotation)}°`}+ </div>+ )}+ </>+ )}++ {/* Interactive Pin Core Handle */}+ <div+ onPointerDown={(e) => startDragPuppetPin(pin, e)}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ handleDeletePuppetPin(pin.id);+ }}+ title={`Pin #${idx + 1} · Drag to move · Alt+Drag or ring to rotate · Right-click or Del to remove`}+ className={`absolute rounded-full shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform pointer-events-auto flex items-center justify-center ${+ isSelected+ ? 'w-3.5 h-3.5 bg-amber-400 border-2 border-white ring-2 ring-amber-400/40'+ : 'w-3 h-3 bg-cyan-400 border-2 border-[#141414] ring-1 ring-white/80'+ }`}+ style={{+ left: '0px',+ top: '0px',+ transform: 'translate(-50%, -50%)',+ }}+ >+ <div className="w-1 h-1 rounded-full bg-[#141414]" />+ </div>+ </div>+ );+ })}++ {/* Cage Transform Vertex Handles */}+ {mode === 'cage' &&+ cageState &&+ cageState.points.map((pt, idx) => {+ const isSelected = cageState.selectedPointId === pt.id;+ const isCloseTarget = !cageState.closed && idx === 0 && cageState.points.length >= 3;+ return (+ <div+ key={pt.id}+ data-testid={`cage-vertex-${idx}`}+ onPointerDown={(e) => startDragCageVertex(pt, idx, e)}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ handleDeleteCagePoint(pt.id);+ }}+ title={+ isCloseTarget+ ? 'Click to close cage & begin deforming'+ : cageState.phase === 'edit'+ ? `Cage Vertex ${idx + 1} · Drag to shape cage · Right-click to remove`+ : `Cage Vertex ${idx + 1} · Drag to warp`+ }+ className={`absolute z-34 rounded-full border-2 shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform pointer-events-auto ${+ isCloseTarget+ ? 'bg-emerald-400 border-white ring-2 ring-emerald-400/50'+ : cageState.phase === 'edit'+ ? isSelected+ ? 'bg-amber-300 border-white'+ : 'bg-amber-400 border-[#161616]'+ : isSelected+ ? 'bg-cyan-300 border-white ring-2 ring-cyan-400/40'+ : 'bg-white border-cyan-500'+ }`}+ style={{+ left: `${pt.x}px`,+ top: `${pt.y}px`,+ width: `${isCloseTarget ? 12 : 10}px`,+ height: `${isCloseTarget ? 12 : 10}px`,+ transform: `translate(-50%, -50%) scale(${invZoom})`,+ transformOrigin: 'center',+ }}+ />+ );+ })}</>)}{/* 3. Floating Transform Toolbar (Pinned below transform boundary) */}<div- className="absolute z-40 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl px-1.5 py-1 flex items-center space-x-1.5 whitespace-nowrap select-none text-xs"+ data-testid="transform-toolbar"+ className="absolute z-40 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl px-1.5 py-1 flex flex-col items-center gap-1 whitespace-nowrap select-none text-xs"style={{left: `${nonAffineBounds.minX + nonAffineBounds.width / 2}px`,top: `${nonAffineBounds.maxY}px`,@@ -666,124 +1677,406 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({}}onPointerDown={(e) => e.stopPropagation()}>- {/* Mode Switchers */}- <div className="flex items-center space-x-0.5 bg-[#161616] p-0.5 rounded border border-white/[0.06]">+ {/* Row 1: Mode Switchers + Apply / Cancel + Flip / Reset */}+ <div className="flex items-center space-x-1.5">+ <div className="flex items-center space-x-0.5 bg-[#161616] p-0.5 rounded border border-white/[0.06]">+ <button+ type="button"+ onClick={() => handleSwitchMode('affine')}+ title="Free Transform (Affine Scale & Rotate)"+ className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${+ mode === 'affine'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Free+ </button>++ <button+ type="button"+ onClick={() => handleSwitchMode('perspective')}+ title="Perspective Quad (4-Point Homography)"+ className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${+ mode === 'perspective'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Perspective+ </button>++ <button+ type="button"+ onClick={() => handleSwitchMode('mesh')}+ title="Mesh Warp (Catmull-Rom Bicubic Lattice)"+ className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${+ mode === 'mesh'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Mesh+ </button>++ <button+ type="button"+ data-testid="transform-mode-puppet"+ onClick={() => handleSwitchMode('puppet')}+ title="Puppet Warp (Place joint pins to bend limbs, tilt head & adjust cloak folds)"+ className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${+ mode === 'puppet'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Puppet+ </button>++ <button+ type="button"+ data-testid="transform-mode-cage"+ onClick={() => handleSwitchMode('cage')}+ title="Cage Transform (Deform artwork inside an editable polygon cage)"+ className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${+ mode === 'cage'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ Cage+ </button>+ </div>++ <div className="w-px h-4 bg-white/[0.08]" />++ {/* Apply */}<button- onClick={() => handleSwitchMode('affine')}- title="Free Transform (Affine Scale & Rotate)"- className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${- mode === 'affine'- ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'- }`}+ type="button"+ onClick={onApply}+ title="Apply Transform (Enter)"+ className="px-2.5 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-[11px] font-medium cursor-pointer transition-opacity"+ >+ Apply+ </button>++ {/* Cancel */}+ <button+ type="button"+ onClick={onCancel}+ title="Cancel Transform (Esc)"+ className="px-2 py-1 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-[11px] cursor-pointer transition-colors">- Free+ Cancel</button>+ <div className="w-px h-4 bg-white/[0.08]" />++ {/* Flip Horizontal */}<button- onClick={() => handleSwitchMode('perspective')}- title="Perspective Quad (4-Point Homography)"- className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${- mode === 'perspective'- ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ type="button"+ onClick={handleFlipH}+ title="Flip Horizontal"+ className={`p-1 rounded transition-colors cursor-pointer ${+ session.flipH+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>- Perspective+ <FlipHorizontal className="w-3.5 h-3.5" /></button>+ {/* Flip Vertical */}<button- onClick={() => handleSwitchMode('mesh')}- title="Mesh Warp (Catmull-Rom Bezier Lattice)"- className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${- mode === 'mesh'- ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ type="button"+ onClick={handleFlipV}+ title="Flip Vertical"+ className={`p-1 rounded transition-colors cursor-pointer ${+ session.flipV+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>- Mesh+ <FlipVertical className="w-3.5 h-3.5" />+ </button>++ {/* Reset */}+ <button+ type="button"+ onClick={handleReset}+ title="Reset Transform"+ className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ >+ <RotateCcw className="w-3.5 h-3.5" /></button></div>- {/* Mesh Grid Density Selector (when in mesh mode) */}+ {/* Row 2: Mesh Grid Density */}{mode === 'mesh' && (- <>- <div className="w-px h-4 bg-white/[0.08]" />- <div className="flex items-center space-x-1 text-[11px] text-[#8a8a8a]">- <span>Grid</span>- {[3, 4, 5, 6, 8].map((size) => (+ <div className="flex items-center space-x-1 pt-0.5 border-t border-white/[0.06] w-full justify-center text-[11px] text-[#8a8a8a]">+ <span>Grid</span>+ {[3, 4, 5, 6, 8].map((size) => (+ <button+ type="button"+ key={size}+ onClick={() => handleChangeMeshGrid(size)}+ className={`px-1.5 py-0.5 rounded cursor-pointer transition-colors ${+ (session.meshCols || 4) === size+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] font-medium'+ : 'hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {size}x{size}+ </button>+ ))}+ </div>+ )}++ {/* Row 2: Puppet Warp Controls */}+ {mode === 'puppet' && (+ <div className="flex items-center space-x-1.5 pt-0.5 border-t border-white/[0.06] w-full justify-center text-[10px] text-[#8a8a8a]">+ {/* Rigidity */}+ <div className="flex items-center space-x-0.5 bg-[#161616] p-0.5 rounded border border-white/[0.05]">+ {(['rigid', 'normal', 'distort'] as const).map((rMode) => (<button- key={size}- onClick={() => handleChangeMeshGrid(size)}- className={`px-1 py-0.5 rounded cursor-pointer transition-colors ${- (session.meshCols || 4) === size- ? 'bg-[var(--accent-subtle)] text-[var(--accent)] font-medium'- : 'hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ type="button"+ key={rMode}+ onClick={() => handleChangePuppetRigidity(rMode)}+ title={+ rMode === 'rigid'+ ? 'Rigid (Preserves bone/limb rigidity & volume)'+ : rMode === 'normal'+ ? 'Normal (Balanced ARAP smooth bending)'+ : 'Distort (Elastic similarity stretch for cloaks & stylization)'+ }+ className={`px-1.5 py-0.5 rounded capitalize cursor-pointer transition-colors ${+ (session.puppet?.rigidity ?? 'normal') === rMode+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>- {size}x{size}+ {rMode}</button>))}</div>- </>++ {/* Density */}+ <div className="flex items-center space-x-0.5 bg-[#161616] p-0.5 rounded border border-white/[0.05]">+ {(['coarse', 'normal', 'fine'] as const).map((dMode) => (+ <button+ type="button"+ key={dMode}+ onClick={() => handleChangePuppetMeshParams(dMode, currentExpansion)}+ title={`Mesh Density: ${dMode}`}+ className={`px-1.5 py-0.5 rounded capitalize cursor-pointer transition-colors ${+ (session.puppet?.density ?? 'normal') === dMode+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {dMode === 'coarse' ? 'Low' : dMode === 'normal' ? 'Med' : 'Fine'}+ </button>+ ))}+ </div>++ {/* Expansion */}+ <div+ className="flex items-center space-x-0.5 bg-[#161616] px-1 py-0.5 rounded border border-white/[0.05]"+ title="Mesh Expansion padding around silhouette"+ >+ <span className="text-[#777]">Exp</span>+ <button+ type="button"+ onClick={() => stepExpansion(-1)}+ className="px-1 hover:text-white cursor-pointer"+ title="Decrease mesh expansion"+ >+ -+ </button>+ <span className="font-mono text-[#e5e5e5] min-w-[24px] text-center">+ {currentExpansion}px+ </span>+ <button+ type="button"+ onClick={() => stepExpansion(1)}+ className="px-1 hover:text-white cursor-pointer"+ title="Increase mesh expansion"+ >+ ++ </button>+ </div>++ {/* Toggle Mesh Wireframe */}+ <button+ type="button"+ onClick={handleTogglePuppetShowMesh}+ title="Show / Hide Mesh Wireframe"+ className={`px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer transition-colors ${+ session.puppet?.showMesh !== false+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Grid className="w-3 h-3" />+ <span>Mesh</span>+ </button>++ {/* Selected Pin Depth & Delete Controls */}+ {selectedPin && (+ <>+ <div className="w-px h-3.5 bg-white/[0.08]" />+ <div className="flex items-center space-x-0.5">+ <button+ type="button"+ onClick={() => handleAdjustPinDepth(selectedPin.id, -1)}+ title="Send Pin Depth Backward (limb behind)"+ className="p-0.5 rounded hover:bg-[#2c2c2c] hover:text-[#e5e5e5] cursor-pointer"+ >+ <ArrowDown className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => handleAdjustPinDepth(selectedPin.id, 1)}+ title="Bring Pin Depth Forward (limb in front)"+ className="p-0.5 rounded hover:bg-[#2c2c2c] hover:text-[#e5e5e5] cursor-pointer"+ >+ <ArrowUp className="w-3 h-3" />+ </button>+ {selectedPin.depth !== 0 && (+ <span className="font-mono text-[9px] text-cyan-300 px-0.5">+ Z{selectedPin.depth > 0 ? `+${selectedPin.depth}` : selectedPin.depth}+ </span>+ )}+ <button+ type="button"+ onClick={() => handleResetPinRotation(selectedPin.id)}+ title="Reset selected pin rotation to 0°"+ className="px-1 py-0.5 rounded font-mono text-[10px] hover:bg-[#2c2c2c] text-amber-300 cursor-pointer"+ >+ {Math.round(selectedPin.rotation)}°+ </button>+ <button+ type="button"+ onClick={() => handleDeletePuppetPin(selectedPin.id)}+ title="Remove Selected Pin (Del)"+ className="p-0.5 rounded text-[#8a8a8a] hover:text-rose-400 hover:bg-[#2c2c2c] cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ </>+ )}++ <div className="w-px h-3.5 bg-white/[0.08]" />++ {puppetPins.length === 0 ? (+ <span className="text-cyan-300/90 px-1">Click artwork to place joint pins</span>+ ) : (+ <div className="flex items-center space-x-1">+ <span className="font-mono text-[#cccccc]">+ {puppetPins.length} {puppetPins.length === 1 ? 'pin' : 'pins'}+ </span>+ <button+ type="button"+ onClick={handleClearPuppetPins}+ title="Clear All Pins"+ className="px-1.5 py-0.5 rounded hover:bg-[#2c2c2c] hover:text-rose-400 cursor-pointer transition-colors"+ >+ Clear+ </button>+ </div>+ )}+ </div>)}- <div className="w-px h-4 bg-white/[0.08]" />+ {/* Row 2: Cage Transform Controls */}+ {mode === 'cage' && cageState && (+ <div className="flex items-center space-x-1.5 pt-0.5 border-t border-white/[0.06] w-full justify-center text-[10px] text-[#8a8a8a]">+ <div className="flex items-center space-x-0.5 bg-[#161616] p-0.5 rounded border border-white/[0.05]">+ <button+ type="button"+ disabled={!cageState.closed && cageState.points.length < 3}+ onClick={() => handleSetCagePhase('deform')}+ title="Deform Mode: Drag cage vertices or edges to smoothly warp pixels"+ className={`px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer transition-colors disabled:opacity-40 ${+ cageState.phase === 'deform'+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ <Move className="w-3 h-3" />+ <span>Deform</span>+ </button>+ <button+ type="button"+ onClick={() => handleSetCagePhase('edit')}+ title="Edit Cage: Reshape rest cage, click edges to add points, right-click points to delete"+ className={`px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer transition-colors ${+ cageState.phase === 'edit'+ ? 'bg-amber-500/20 text-amber-300 font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ <PenTool className="w-3 h-3" />+ <span>Edit Cage</span>+ </button>+ </div>- {/* Apply */}- <button- onClick={onApply}- title="Apply Transform (Enter)"- className="px-2.5 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-[11px] font-medium cursor-pointer transition-opacity"- >- Apply- </button>-- {/* Cancel */}- <button- onClick={onCancel}- title="Cancel Transform (Esc)"- className="px-2 py-1 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-[11px] cursor-pointer transition-colors"- >- Cancel- </button>-- <div className="w-px h-4 bg-white/[0.08]" />-- {/* Flip Horizontal */}- <button- onClick={handleFlipH}- title="Flip Horizontal"- className={`p-1 rounded transition-colors cursor-pointer ${- session.flipH- ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- <FlipHorizontal className="w-3.5 h-3.5" />- </button>-- {/* Flip Vertical */}- <button- onClick={handleFlipV}- title="Flip Vertical"- className={`p-1 rounded transition-colors cursor-pointer ${- session.flipV- ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- <FlipVertical className="w-3.5 h-3.5" />- </button>-- {/* Reset */}- <button- onClick={handleReset}- title="Reset Transform"- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"- >- <RotateCcw className="w-3.5 h-3.5" />- </button>+ {!cageState.closed && (+ <button+ type="button"+ disabled={cageState.points.length < 3}+ onClick={handleCloseCage}+ title="Close Cage Polygon"+ className="px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 disabled:opacity-40 flex items-center gap-1 cursor-pointer"+ >+ <Check className="w-3 h-3" />+ <span>Close ({cageState.points.length})</span>+ </button>+ )}++ <button+ type="button"+ onClick={handleStartRedrawCage}+ title="Draw a custom polygon cage around a specific region (head, arm, cloak)"+ className="px-1.5 py-0.5 rounded hover:bg-[#2c2c2c] hover:text-[#e5e5e5] cursor-pointer transition-colors"+ >+ Redraw+ </button>++ <button+ type="button"+ onClick={handleAutoFitCage}+ title="Auto-fit tight silhouette cage around artwork"+ className="px-1.5 py-0.5 rounded hover:bg-[#2c2c2c] hover:text-[#e5e5e5] flex items-center gap-1 cursor-pointer transition-colors"+ >+ <Sparkles className="w-3 h-3" />+ <span>Auto Fit</span>+ </button>++ <button+ type="button"+ onClick={handleToggleCageMesh}+ title="Show / Hide Internal Cage Mesh"+ className={`px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer transition-colors ${+ cageState.showMesh+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Grid className="w-3 h-3" />+ <span>Mesh</span>+ </button>++ {!cageState.closed && (+ <span className="text-amber-300/90 px-1">+ {cageState.points.length < 3+ ? 'Click to place cage vertices'+ : 'Click first vertex or Close to deform'}+ </span>+ )}+ </div>+ )}</div></>);diff --git a/src/components/brushStudio/BrushStudioTabsPrimary.tsx b/src/components/brushStudio/BrushStudioTabsPrimary.tsxindex 73ade59..d47cd86 100644--- a/src/components/brushStudio/BrushStudioTabsPrimary.tsx+++ b/src/components/brushStudio/BrushStudioTabsPrimary.tsx@@ -24,6 +24,7 @@ import {} from '../../utils/proceduralBrushTips';import { getPreloadedBuiltinTipImage } from '../../utils/presetBrushes';import { PressureCurveEditor } from '../PressureCurveEditor';+import { resolveBrushCursorRotationSpec } from '../canvasArea/types';import {readImageFileAsDataUrl,StudioSegmented,@@ -129,6 +130,7 @@ export const ShapeBristlesTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch })onChange={(mode) =>onPatch({renderMode: mode,+ rotateCursor: undefined,naturalPaint:mode !== 'stamp'? { ...DEFAULT_NATURAL_PAINT_SETTINGS, ...(bs.naturalPaint || {}), enabled: true }@@ -346,7 +348,13 @@ export const ShapeBristlesTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }){ id: 'twist', label: 'Twist' },{ id: 'random', label: 'Random' },]}- onChange={(v) => onPatch({ customTipAngleDynamics: v })}+ onChange={(v) => onPatch({ customTipAngleDynamics: v, rotateCursor: undefined })}+ />+ <StudioToggle+ label="This brush rotates"+ description="Rotate the brush cursor preview to track brush direction"+ checked={resolveBrushCursorRotationSpec(bs, 'brush').enabled}+ onChange={(v) => onPatch({ rotateCursor: v })}/><div className="grid grid-cols-2 gap-2"><StudioSegmented<CspTipFlipMode>diff --git a/src/components/canvasArea/CanvasArtboardOverlays.tsx b/src/components/canvasArea/CanvasArtboardOverlays.tsxindex d498032..71c239b 100644--- a/src/components/canvasArea/CanvasArtboardOverlays.tsx+++ b/src/components/canvasArea/CanvasArtboardOverlays.tsx@@ -7,6 +7,7 @@ import { SpeechBalloonOverlay } from '../SpeechBalloonOverlay';import { Local3DContainer } from '../Local3DContainer';import { GradientOverlay } from '../GradientOverlay';import { PenPathOverlay } from '../PenPathOverlay';+import { QuickShapeOverlay } from '../QuickShapeOverlay';import { CanvasAreaProps, formatArtboardTransform } from './types';export interface CanvasArtboardOverlaysProps {@@ -77,11 +78,16 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onDeleteBalloon,frameDragPreview = null,shapeDragPreview = null,+ quickShapePreview = null,+ lassoFillPreview = null,gradientDragPreview = null,gradientMesh = null,+ gradientMeshMarqueeRect = null,+ isRotatingGradientMesh = false,gradientSettings,onApplyGradientMesh,onCancelGradientMesh,+ onStartRotateGradientMesh,retouchSettings,cloneSourceIndicator = null,penSession = null,@@ -225,7 +231,7 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({/>)}- {/* Free Transform Overlay */}+ {/* Free Transform / Perspective / Mesh / Puppet / Cage Overlay */}{transformSession?.active && (<TransformOverlaysession={transformSession}@@ -233,6 +239,7 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({rotation={liveRotation}flipX={liveFlipX}flipY={liveFlipY}+ isSpaceDown={canvasProps.isSpaceDown}onUpdateSession={onUpdateTransformSession || (() => {})}onApply={onApplyTransform || (() => {})}onCancel={onCancelTransform || (() => {})}@@ -384,6 +391,205 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({);})()}+ {/* QuickShape Interactive Hold-to-Snap Guide & Handles Overlay */}+ {quickShapePreview && (+ <QuickShapeOverlay+ dimensions={dimensions}+ zoom={liveZoom}+ rotation={liveRotation}+ flipX={liveFlipX}+ flipY={liveFlipY}+ preview={quickShapePreview}+ />+ )}++ {/* Real-Time Lasso Fill / Enclose & Fill / Paint Unfilled Area Visual Preview */}+ {lassoFillPreview && lassoFillPreview.points.length > 0 && (() => {+ const pts = lassoFillPreview.points;+ const previewMode = lassoFillPreview.mode ?? 'lasso';+ const invZoom = 1 / Math.max(0.05, liveZoom);+ const openPathD =+ `M ${pts[0].x} ${pts[0].y}` ++ pts+ .slice(1)+ .map((p) => ` L ${p.x} ${p.y}`)+ .join('');+ const closedPathD = pts.length >= 3 ? `${openPathD} Z` : '';+ const previewOpacity = Math.max(0, Math.min(1, lassoFillPreview.opacity));+ const hasSelClip = Boolean(+ selection &&+ (selection.svgPath ||+ selection.type === 'rect' ||+ (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3))+ );+ const lastPt = pts[pts.length - 1];+ const firstPt = pts[0];+ const patSize = Math.max(4, 8 * invZoom);+ const halfPat = patSize / 2;++ if (previewMode === 'paint-unfilled') {+ const strokeWidth = Math.max(2, lassoFillPreview.brushSize ?? 24);+ return (+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-30 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ <defs>+ {hasSelClip && selection && (+ <clipPath id="lasso-fill-preview-sel-clip">+ {selection.svgPath ? (+ <path d={selection.svgPath} clipRule="evenodd" />+ ) : selection.type === 'rect' ? (+ <rect+ x={selection.bounds.x}+ y={selection.bounds.y}+ width={selection.bounds.width}+ height={selection.bounds.height}+ />+ ) : selection.type === 'lasso' && selection.polygon ? (+ <polygon points={selection.polygon.map((p) => `${p.x},${p.y}`).join(' ')} />+ ) : null}+ </clipPath>+ )}+ </defs>+ {/* Uniform translucent green mask stroke (CSP Paint Unfilled Area preview) */}+ <g+ opacity={0.38}+ clipPath={hasSelClip ? 'url(#lasso-fill-preview-sel-clip)' : undefined}+ >+ {pts.length === 1 ? (+ <circle cx={pts[0].x} cy={pts[0].y} r={strokeWidth / 2} fill="#22c55e" />+ ) : (+ <path+ d={openPathD}+ fill="none"+ stroke="#22c55e"+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ )}+ </g>+ {pts.length >= 2 && (+ <path+ d={openPathD}+ fill="none"+ stroke="#86efac"+ strokeOpacity={0.75}+ strokeWidth={1.1 * invZoom}+ strokeDasharray={`${3 * invZoom} ${3 * invZoom}`}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ )}+ </svg>+ );+ }++ const isEncloseMode = previewMode === 'enclose-and-fill';+ const contourStroke = lassoFillPreview.isTransparentInk+ ? '#f87171'+ : isEncloseMode+ ? '#38bdf8'+ : '#ffffff';+ const effectiveFillOpacity = isEncloseMode+ ? lassoFillPreview.isTransparentInk+ ? 0.42+ : Math.min(0.28, Math.max(0.12, previewOpacity * 0.28))+ : previewOpacity;++ return (+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-30 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ <defs>+ {hasSelClip && selection && (+ <clipPath id="lasso-fill-preview-sel-clip">+ {selection.svgPath ? (+ <path d={selection.svgPath} clipRule="evenodd" />+ ) : selection.type === 'rect' ? (+ <rect+ x={selection.bounds.x}+ y={selection.bounds.y}+ width={selection.bounds.width}+ height={selection.bounds.height}+ />+ ) : selection.type === 'lasso' && selection.polygon ? (+ <polygon points={selection.polygon.map((p) => `${p.x},${p.y}`).join(' ')} />+ ) : null}+ </clipPath>+ )}+ {lassoFillPreview.isTransparentInk && (+ <pattern+ id="lasso-fill-erase-pattern"+ width={patSize}+ height={patSize}+ patternUnits="userSpaceOnUse"+ >+ <rect width={patSize} height={patSize} fill="rgba(255,255,255,0.45)" />+ <rect width={halfPat} height={halfPat} fill="rgba(180,180,180,0.45)" />+ <rect+ x={halfPat}+ y={halfPat}+ width={halfPat}+ height={halfPat}+ fill="rgba(180,180,180,0.45)"+ />+ </pattern>+ )}+ </defs>++ {closedPathD && (+ <path+ d={closedPathD}+ fill={+ lassoFillPreview.isTransparentInk+ ? 'url(#lasso-fill-erase-pattern)'+ : lassoFillPreview.color+ }+ fillOpacity={effectiveFillOpacity}+ clipPath={hasSelClip ? 'url(#lasso-fill-preview-sel-clip)' : undefined}+ />+ )}++ {/* Drawn freehand contour */}+ <path+ d={openPathD}+ fill="none"+ stroke="#000000"+ strokeOpacity={0.75}+ strokeWidth={2.5 * invZoom}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d={openPathD}+ fill="none"+ stroke={contourStroke}+ strokeWidth={1.3 * invZoom}+ strokeDasharray={isEncloseMode ? `${5 * invZoom} ${3 * invZoom}` : undefined}+ strokeLinecap="round"+ strokeLinejoin="round"+ />++ {/* Dashed closing segment from current cursor back to start */}+ {pts.length >= 2 && (+ <line+ x1={lastPt.x}+ y1={lastPt.y}+ x2={firstPt.x}+ y2={firstPt.y}+ stroke={contourStroke}+ strokeOpacity={0.85}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}+ </svg>+ );+ })()}+{/* Live Gradient Guide & Interactive Mesh Gradient Overlay */}{(gradientDragPreview || gradientMesh) && (<GradientOverlay@@ -393,9 +599,12 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({flipY={liveFlipY}dragPreview={gradientDragPreview}mesh={gradientMesh}+ marqueeRect={gradientMeshMarqueeRect}+ isRotatingMesh={isRotatingGradientMesh}opacity={gradientSettings?.opacity ?? 1}onApplyMesh={onApplyGradientMesh}onCancelMesh={onCancelGradientMesh}+ onStartRotateMesh={onStartRotateGradientMesh}/>)}diff --git a/src/components/canvasArea/CanvasViewportHud.tsx b/src/components/canvasArea/CanvasViewportHud.tsxindex b835001..41cd511 100644--- a/src/components/canvasArea/CanvasViewportHud.tsx+++ b/src/components/canvasArea/CanvasViewportHud.tsx@@ -22,6 +22,9 @@ export interface CanvasViewportHudProps {totalAngleDeg: number;isCustomTip: boolean;isSquare: boolean;+ isCursorRotating?: boolean;+ cursorOrientationOffsetDeg?: number;+ thicknessRatio?: number;tipOutline: TipOutline | null;isResizingBrush: boolean;resizePreviewX: number;@@ -44,6 +47,9 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({totalAngleDeg,isCustomTip,isSquare,+ isCursorRotating = false,+ cursorOrientationOffsetDeg = 0,+ thicknessRatio = 1.0,tipOutline,isResizingBrush,resizePreviewX,@@ -61,6 +67,10 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({onUpdatePerspectiveRuler,activeLockedAxis = null,isDrawing = false,+ tool = 'brush',+ fillSettings,+ liquifySettings,+ retouchSettings,brushSettings,onUpdateBrushSettings,onUndo,@@ -79,8 +89,18 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({onDeleteAnimationCel,onSelectCelLayer,isExternalFileDropActive = false,+ externalFileDropKind,} = canvasProps;+ const showCircleDirectionTick =+ isCursorRotating && !isCustomTip && !isSquare && Math.abs(thicknessRatio - 1) < 0.08;+ const tickLenSvg = Math.max(4, Math.min(28, (7 / Math.max(8, cursorWidth)) * 100));+ const tickHalfSvg = Math.max(3, Math.min(22, (5 / Math.max(8, cursorHeight)) * 100));+ const circleDirectionPath =+ cursorOrientationOffsetDeg === 90+ ? `M ${50 - tickHalfSvg} 0.5 L 50 ${0.5 - tickLenSvg} L ${50 + tickHalfSvg} 0.5`+ : `M 99.5 ${50 - tickHalfSvg} L ${99.5 + tickLenSvg} 50 L 99.5 ${50 + tickHalfSvg}`;+return (<>{/* Interactive Straight Ruler Overlay */}@@ -122,6 +142,7 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({{/* Dynamic Dual-Tone Brush Silhouette Outline Cursor (CSP / Photoshop style) */}<divref={cursorRingRef}+ data-cursor-rotating={isCursorRotating ? 'true' : 'false'}className="pointer-events-none absolute top-0 left-0 z-30 select-none"style={{display: 'none',@@ -203,6 +224,28 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({strokeWidth="1"vectorEffect="non-scaling-stroke"/>+ {showCircleDirectionTick && (+ <>+ <path+ d={circleDirectionPath}+ fill="none"+ stroke="rgba(255, 255, 255, 0.9)"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ vectorEffect="non-scaling-stroke"+ />+ <path+ d={circleDirectionPath}+ fill="none"+ stroke="rgba(0, 0, 0, 0.9)"+ strokeWidth="1"+ strokeLinecap="round"+ strokeLinejoin="round"+ vectorEffect="non-scaling-stroke"+ />+ </>+ )}</>)}</svg>@@ -279,9 +322,30 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({style={{ zIndex: 60 }}><div className="flex items-center gap-2 text-[11px] font-mono font-medium text-[#e5e5e5]">- <span>Size {brushSettings.size}px</span>- <span className="text-[#8a8a8a]">·</span>- <span>Hard {Math.round((brushSettings.hardness ?? 1.0) * 100)}%</span>+ <span>+ Size{' '}+ {tool === 'liquify' && liquifySettings+ ? liquifySettings.size+ : tool === 'retouch' && retouchSettings+ ? retouchSettings.size+ : tool === 'fill' && fillSettings?.method === 'paint-unfilled'+ ? Math.round(fillSettings.brushSize ?? 24)+ : brushSettings.size}+ px+ </span>+ {!(tool === 'fill' && fillSettings?.method === 'paint-unfilled') &&+ tool !== 'liquify' && (+ <>+ <span className="text-[#8a8a8a]">·</span>+ <span>+ Hard{' '}+ {tool === 'retouch' && retouchSettings+ ? retouchSettings.hardness+ : Math.round((brushSettings.hardness ?? 1.0) * 100)}+ %+ </span>+ </>+ )}</div></div></div>@@ -430,7 +494,11 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({className="pointer-events-none absolute inset-2 z-50 rounded-md border-2 border-dashed border-[var(--accent)] bg-[var(--accent)]/8 flex items-center justify-center"><div className="px-3.5 py-2 rounded-md bg-[#161616]/95 border border-[var(--accent)]/60 text-xs font-medium text-[#f5f5f5] shadow-xl">- Drop image to import as layer+ {externalFileDropKind === '3d-model'+ ? 'Drop 3D model (.glb, .gltf, .obj) to load'+ : externalFileDropKind === 'any-3d'+ ? 'Drop 3D model (.glb, .gltf, .obj) or image'+ : 'Drop image to import as layer'}</div></div>)}diff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.tsindex 24b7490..d0a6062 100644--- a/src/components/canvasArea/types.ts+++ b/src/components/canvasArea/types.ts@@ -7,6 +7,8 @@ import {TransformSession,TextSettings,ToolType,+ FillMethod,+ FillSettings,LiquifySettings,SpeechBalloon,SoftProofSettings,@@ -21,10 +23,15 @@ import {AnimationTimeline as AnimationTimelineType,} from '../../types/editor';import type { CloneSourceIndicator } from '../../hooks/drawing/useRetouchTool';+import type { GradientMeshMarqueeRect } from '../../hooks/drawing/useGradientTool';+import type { LassoFillPreview } from '../../hooks/drawing/useShapeAndFillTools';+import type { QuickShapePreviewState } from '../../utils/quickShapeEngine';import { ROTATE_CURSOR_CSS, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/perspective';import { SparseTileGrid } from '../../utils/tileEngine';import { ModifierAction } from '../../types/settings';+import { ExternalFileDropPayloadKind } from '../../utils/fileDropImport';+import { isNaturalPaintBrush } from '../../engine/NaturalPaintRenderer';export const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;@@ -110,6 +117,8 @@ export interface CanvasAreaProps {onBake3DSuccess?: (layer: LayerItem) => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;+ fillSettings?: FillSettings;+ onUpdateFillSettings?: (newSettings: Partial<FillSettings>) => void;primaryColor?: string;onSwapColors?: () => void;showCursorCoordinates?: boolean;@@ -123,11 +132,16 @@ export interface CanvasAreaProps {onDeleteBalloon?: () => void;frameDragPreview?: { mode: 'create' | 'divide'; start: { x: number; y: number }; end: { x: number; y: number } } | null;shapeDragPreview?: ShapeDragPreview | null;+ quickShapePreview?: QuickShapePreviewState | null;+ lassoFillPreview?: LassoFillPreview | null;gradientDragPreview?: GradientDragPreview | null;gradientMesh?: GradientMeshState | null;+ gradientMeshMarqueeRect?: GradientMeshMarqueeRect | null;+ isRotatingGradientMesh?: boolean;gradientSettings?: GradientSettings;onApplyGradientMesh?: () => void;onCancelGradientMesh?: () => void;+ onStartRotateGradientMesh?: (e: React.PointerEvent<HTMLElement>) => void;retouchSettings?: RetouchSettings;onUpdateRetouchSettings?: (newSettings: Partial<RetouchSettings>) => void;cloneSourceIndicator?: CloneSourceIndicator | null;@@ -143,11 +157,28 @@ export interface CanvasAreaProps {onDeleteAnimationCel?: (frameIndex: number) => void;onSelectCelLayer?: (layerId: string) => void;softProofSettings?: SoftProofSettings;+ valueCheckEnabled?: boolean;onViewportReady?: (viewport: HTMLDivElement) => void;activeLayerId?: string;colorMode?: CanvasColorMode;tileGrid?: SparseTileGrid;isExternalFileDropActive?: boolean;+ externalFileDropKind?: ExternalFileDropPayloadKind;+}++export type CursorRotationSource = 'none' | 'direction' | 'tilt' | 'twist';++export interface BrushCursorRotationSpec {+ /** Whether the brush cursor dynamically rotates on canvas. */+ enabled: boolean;+ /** Which input drives dynamic cursor rotation. */+ source: CursorRotationSource;+ /**+ * Static orientation offset in degrees so the tip silhouette aligns with the painted stroke+ * (e.g. +90° for Natural Paint procedural bristle tips whose bristles span horizontally along X,+ * whereas BristleRibbonEngine spreads bristles perpendicular to the stroke tangent along (-ty, tx)).+ */+ orientationOffsetDeg: number;}export interface CursorConfig {@@ -156,13 +187,160 @@ export interface CursorConfig {thicknessRatio: number;thicknessVertical: boolean;tipAngleDeg: number;+ orientationOffsetDeg: number;followDirection?: boolean;+ rotationSource: CursorRotationSource;+ naturalPaintMode?: boolean;dynamicDirDeg?: number;+ twistDeg?: number;rotation: number;flipX: boolean;flipY: boolean;}+export function normalizeAngleDeg(deg: number): number {+ let a = deg % 360;+ if (a > 180) a -= 360;+ if (a <= -180) a += 360;+ return a;+}++/**+ * Resolves whether a brush's on-canvas cursor silhouette should rotate dynamically,+ * which input drives its rotation (stroke direction, pen tilt, or barrel twist),+ * and any static orientation offset needed to match the rendered stroke geometry.+ */+export function resolveBrushCursorRotationSpec(+ bs: Partial<BrushSettings> | undefined,+ tool: ToolType+): BrushCursorRotationSpec {+ if (!bs || (tool !== 'brush' && tool !== 'decoration' && tool !== 'eraser')) {+ return { enabled: false, source: 'none', orientationOffsetDeg: 0 };+ }++ const naturalMode = isNaturalPaintBrush(bs);+ const angleDyn = bs.customTipAngleDynamics;++ let autoSource: CursorRotationSource = 'none';+ if (angleDyn === 'tilt') {+ autoSource = 'tilt';+ } else if (angleDyn === 'twist') {+ autoSource = 'twist';+ } else if (+ angleDyn === 'direction' ||+ angleDyn === 'direction-random' ||+ angleDyn === 'initial-direction'+ ) {+ autoSource = 'direction';+ } else if (naturalMode) {+ autoSource = 'direction';+ }++ // Respect explicit per-brush override from the "This brush rotates" checkbox+ if (bs.rotateCursor === false) {+ return { enabled: false, source: 'none', orientationOffsetDeg: 0 };+ }++ const enabled = bs.rotateCursor === true || autoSource !== 'none';+ if (!enabled) {+ return { enabled: false, source: 'none', orientationOffsetDeg: 0 };+ }++ const source: CursorRotationSource = autoSource !== 'none' ? autoSource : 'direction';+ const isNaturalProceduralTip =+ naturalMode &&+ source === 'direction' &&+ (!bs.bristle?.profile || bs.bristle.profile !== 'custom');+ const orientationOffsetDeg = isNaturalProceduralTip ? 90 : 0;++ return { enabled: true, source, orientationOffsetDeg };+}++export function computeEffectiveCursorAngleDeg(+ cfg: Pick<+ CursorConfig,+ 'tipAngleDeg' | 'orientationOffsetDeg' | 'followDirection' | 'dynamicDirDeg' | 'twistDeg'+ >+): number {+ return (+ cfg.tipAngleDeg ++ cfg.orientationOffsetDeg ++ (cfg.followDirection ? (cfg.dynamicDirDeg ?? 0) + (cfg.twistDeg ?? 0) : 0)+ );+}++export function computeNextDynamicCursorAngleDeg(params: {+ source: CursorRotationSource;+ currentDeg: number;+ hasCurrent: boolean;+ sdx: number;+ sdy: number;+ canvasRotationDeg: number;+ flipX: boolean;+ flipY: boolean;+ tiltX?: number;+ tiltY?: number;+ twist?: number;+}): { angleDeg: number; updated: boolean } {+ const {+ source,+ currentDeg,+ hasCurrent,+ sdx,+ sdy,+ canvasRotationDeg,+ flipX,+ flipY,+ tiltX = 0,+ tiltY = 0,+ twist = 0,+ } = params;++ if (source === 'none') {+ return { angleDeg: currentDeg, updated: false };+ }++ if (source === 'twist') {+ if (Number.isFinite(twist)) {+ return { angleDeg: normalizeAngleDeg(twist), updated: true };+ }+ return { angleDeg: currentDeg, updated: false };+ }++ if (source === 'tilt') {+ const tiltLen = Math.hypot(tiltX, tiltY);+ if (tiltLen > 3) {+ const targetDeg = (Math.atan2(tiltX, -tiltY) * 180) / Math.PI;+ if (!hasCurrent) {+ return { angleDeg: normalizeAngleDeg(targetDeg), updated: true };+ }+ const delta = normalizeAngleDeg(targetDeg - currentDeg);+ return { angleDeg: normalizeAngleDeg(currentDeg + delta * 0.65), updated: true };+ }+ return { angleDeg: currentDeg, updated: false };+ }++ // source === 'direction'+ const distSq = sdx * sdx + sdy * sdy;+ if (distSq < 9) {+ return { angleDeg: currentDeg, updated: false };+ }+ const dist = Math.sqrt(distSq);+ const rad = (-canvasRotationDeg * Math.PI) / 180;+ const c = Math.cos(rad);+ const s = Math.sin(rad);+ const cdx = (sdx * c - sdy * s) * (flipX ? -1 : 1);+ const cdy = (sdx * s + sdy * c) * (flipY ? -1 : 1);+ const targetDeg = (Math.atan2(cdy, cdx) * 180) / Math.PI;++ if (!hasCurrent) {+ return { angleDeg: normalizeAngleDeg(targetDeg), updated: true };+ }+ const delta = normalizeAngleDeg(targetDeg - currentDeg);+ const blend = Math.min(0.85, 0.35 + dist * 0.03);+ return { angleDeg: normalizeAngleDeg(currentDeg + delta * blend), updated: true };+}+export interface CursorStyleParams {isOverCanvas: boolean;isResizingBrush: boolean;@@ -173,6 +351,7 @@ export interface CursorStyleParams {isPanning: boolean;isSpaceDown: boolean;tool: ToolType;+ fillMethod?: FillMethod;}export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {@@ -253,6 +432,7 @@ export function getCursorStyle({isPanning,isSpaceDown,tool,+ fillMethod,}: CursorStyleParams): React.CSSProperties {if (isResizingBrush || heldModifierAction === 'brush-size') {return { cursor: 'ew-resize' };@@ -275,6 +455,9 @@ export function getCursorStyle({if (tool === 'text') {return { cursor: 'text' };}+ if (tool === 'fill' && fillMethod === 'paint-unfilled') {+ return { cursor: isOverCanvas ? 'none' : 'default' };+ }if (tool === 'select-rect' ||tool === 'select-lasso' ||@@ -293,7 +476,13 @@ export function getCursorStyle({if (tool === 'transform' || tool === '3d') {return { cursor: 'default' };}- if (tool === 'brush' || tool === 'eraser' || tool === 'select-pen' || tool === 'select-eraser') {+ if (+ tool === 'brush' ||+ tool === 'decoration' ||+ tool === 'eraser' ||+ tool === 'select-pen' ||+ tool === 'select-eraser'+ ) {return { cursor: isOverCanvas ? 'none' : 'default' };}return { cursor: isOverCanvas ? 'crosshair' : 'default' };diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.tsindex 7be8986..4005e42 100644--- a/src/components/canvasArea/useCanvasEffects.ts+++ b/src/components/canvasArea/useCanvasEffects.ts@@ -1,16 +1,26 @@import React, { useEffect, useRef, useState } from 'react';-import { BrushSettings, LiquifySettings, RetouchSettings, ToolType } from '../../types/editor';+import { BrushSettings, FillSettings, LiquifySettings, RetouchSettings, ToolType } from '../../types/editor';import { ModifierAction } from '../../types/settings';import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';import { computeTipStampDimensions } from '../../engine/BrushEngine';import { preloadTipImage } from '../../utils/brushStorage';-import { subscribeNativeTablet } from '../../utils/nativeTabletInput';-import { CursorConfig, formatCursorRingTransform } from './types';+import { shouldSuppressDomPointerEvent, subscribeNativeTablet } from '../../utils/nativeTabletInput';+import { isNaturalPaintBrush } from '../../engine/NaturalPaintRenderer';+import {+ computeEffectiveCursorAngleDeg,+ computeNextDynamicCursorAngleDeg,+ CursorConfig,+ formatCursorRingTransform,+ normalizeAngleDeg,+ resolveBrushCursorRotationSpec,+} from './types';export interface UseCanvasEffectsParams {viewportRef: React.RefObject<HTMLDivElement | null>;brushSettings: BrushSettings;onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;+ fillSettings?: FillSettings;+ onUpdateFillSettings?: (newSettings: Partial<FillSettings>) => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;retouchSettings?: RetouchSettings;@@ -41,6 +51,8 @@ export function useCanvasEffects({viewportRef,brushSettings,onUpdateBrushSettings,+ fillSettings,+ onUpdateFillSettings,liquifySettings,onUpdateLiquifySettings,retouchSettings,@@ -111,25 +123,28 @@ export function useCanvasEffects({setTipOutline(null);}, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);+ const isBrushOrEraser = tool === 'brush' || tool === 'decoration' || tool === 'eraser';+ const isPaintUnfilled = tool === 'fill' && fillSettings?.method === 'paint-unfilled';const isCustomTip = Boolean(- tipOutline && !brushSettings.isRibbon && (tool === 'brush' || tool === 'eraser')+ tipOutline && !brushSettings.isRibbon && isBrushOrEraser);- const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;+ const isSquare = isBrushOrEraser && brushSettings.preset === 'square-digital' && !tipOutline;const activeToolSize =tool === 'liquify' && liquifySettings? liquifySettings.size: tool === 'retouch' && retouchSettings? retouchSettings.size- : brushSettings.size;+ : isPaintUnfilled+ ? Math.max(2, Math.min(300, fillSettings?.brushSize ?? 24))+ : brushSettings.size;const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);- const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;- const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');- const tipAngleDeg = tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0;- const followDirection =- tool === 'brush' &&- (brushSettings.customTipAngleDynamics === 'direction' ||- brushSettings.customTipAngleDynamics === 'direction-random');+ const thicknessRatio = isBrushOrEraser ? (brushSettings.thickness ?? 1.0) : 1.0;+ const thicknessVertical = Boolean(brushSettings.thicknessVertical && isBrushOrEraser);+ const tipAngleDeg = isBrushOrEraser ? (brushSettings.customTipAngle ?? 0) : 0;+ const cursorRotationSpec = resolveBrushCursorRotationSpec(brushSettings, tool);+ const followDirection = cursorRotationSpec.enabled;+ const naturalPaintMode = isBrushOrEraser && isNaturalPaintBrush(brushSettings);const tipAspect =isCustomTip && tipOutline ? tipOutline.height / Math.max(1, tipOutline.width) : 1;@@ -143,9 +158,9 @@ export function useCanvasEffects({const cursorWidth = Math.max(2, tipCursorDims.width);const cursorHeight = Math.max(2, tipCursorDims.height);- // Brush tip rotation: tip angle relative to canvas + viewport canvas rotation- const totalAngleDeg = tipAngleDeg + liveRotation;const dynamicDirDegRef = useRef<number>(0);+ const hasDynamicDirRef = useRef<boolean>(false);+ const twistDegRef = useRef<number>(0);const lastDirAnchorRef = useRef<{ x: number; y: number } | null>(null);const cursorConfigRef = useRef<CursorConfig>({activeToolSize,@@ -153,8 +168,12 @@ export function useCanvasEffects({thicknessRatio,thicknessVertical,tipAngleDeg,+ orientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,followDirection,+ rotationSource: cursorRotationSpec.source,+ naturalPaintMode,dynamicDirDeg: 0,+ twistDeg: 0,rotation: liveRotation,flipX: liveFlipX,flipY: liveFlipY,@@ -165,12 +184,18 @@ export function useCanvasEffects({thicknessRatio,thicknessVertical,tipAngleDeg,+ orientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,followDirection,+ rotationSource: cursorRotationSpec.source,+ naturalPaintMode,dynamicDirDeg: dynamicDirDegRef.current,+ twistDeg: twistDegRef.current,rotation: liveRotation,flipX: liveFlipX,flipY: liveFlipY,};+ // Brush tip rotation: effective tip angle relative to canvas + viewport canvas rotation+ const totalAngleDeg = computeEffectiveCursorAngleDeg(cursorConfigRef.current) + liveRotation;const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);// Zero-latency direct DOM cursor preview element & pointer stat readout@@ -203,7 +228,19 @@ export function useCanvasEffects({};}, [showCursorCoordinates, showPressureInStatusBar]);- // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle changes while hovering+ // Reset transient direction tracking when rotation mode changes (e.g. toggling "This brush rotates" or switching brush)+ useEffect(() => {+ hasDynamicDirRef.current = false;+ lastDirAnchorRef.current = null;+ twistDegRef.current = 0;+ if (!cursorRotationSpec.enabled) {+ dynamicDirDegRef.current = 0;+ }+ cursorConfigRef.current.dynamicDirDeg = dynamicDirDegRef.current;+ cursorConfigRef.current.twistDeg = 0;+ }, [cursorRotationSpec.enabled, cursorRotationSpec.source, brushSettings.preset]);++ // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle/rotation settings change while hoveringuseEffect(() => {const ring = cursorRingRef.current;const pos = lastPointerPosRef.current;@@ -215,10 +252,19 @@ export function useCanvasEffects({cfg.rotation,cfg.flipX,cfg.flipY,- cfg.tipAngleDeg + (cfg.followDirection ? cfg.dynamicDirDeg ?? 0 : 0)+ computeEffectiveCursorAngleDeg(cfg));}- }, [tipAngleDeg, liveRotation, liveFlipX, liveFlipY]);+ }, [+ tipAngleDeg,+ cursorRotationSpec.enabled,+ cursorRotationSpec.source,+ cursorRotationSpec.orientationOffsetDeg,+ liveRotation,+ liveFlipX,+ liveFlipY,+ brushSettings.preset,+ ]);useEffect(() => {const viewport = viewportRef.current;@@ -236,45 +282,66 @@ export function useCanvasEffects({heldModifierAction === 'rotate' ||heldModifierAction === 'zoom-drag' ||(tool !== 'brush' &&+ tool !== 'decoration' &&tool !== 'eraser' &&tool !== 'liquify' &&tool !== 'retouch' &&tool !== 'select-pen' &&- tool !== 'select-eraser');+ tool !== 'select-eraser' &&+ !isPaintUnfilled);let cachedRect: DOMRect | null = viewport.getBoundingClientRect();const updateRect = () => {if (viewport) cachedRect = viewport.getBoundingClientRect();};- const showRingAtLocalPos = (x: number, y: number) => {+ const showRingAtLocalPos = (+ x: number,+ y: number,+ tiltX?: number,+ tiltY?: number,+ twist?: number+ ) => {const ring = cursorRingRef.current;if (!ring) return;const cfg = cursorConfigRef.current;- let effectiveTipAngle = cfg.tipAngleDeg;if (cfg.followDirection) {const anchor = lastDirAnchorRef.current;- if (anchor) {- const sdx = x - anchor.x;- const sdy = y - anchor.y;- if (sdx * sdx + sdy * sdy >= 16) {- const rad = (-cfg.rotation * Math.PI) / 180;- const c = Math.cos(rad);- const s = Math.sin(rad);- const cdx = (sdx * c - sdy * s) * (cfg.flipX ? -1 : 1);- const cdy = (sdx * s + sdy * c) * (cfg.flipY ? -1 : 1);- const targetDeg = (Math.atan2(cdy, cdx) * 180) / Math.PI;- let delta = targetDeg - dynamicDirDegRef.current;- while (delta > 180) delta -= 360;- while (delta < -180) delta += 360;- dynamicDirDegRef.current += delta * 0.45;- cfg.dynamicDirDeg = dynamicDirDegRef.current;+ const sdx = anchor ? x - anchor.x : 0;+ const sdy = anchor ? y - anchor.y : 0;+ if (!anchor) {+ lastDirAnchorRef.current = { x, y };+ }+ const next = computeNextDynamicCursorAngleDeg({+ source: cfg.rotationSource,+ currentDeg: dynamicDirDegRef.current,+ hasCurrent: hasDynamicDirRef.current,+ sdx,+ sdy,+ canvasRotationDeg: cfg.rotation,+ flipX: cfg.flipX,+ flipY: cfg.flipY,+ tiltX,+ tiltY,+ twist,+ });+ if (next.updated) {+ dynamicDirDegRef.current = next.angleDeg;+ hasDynamicDirRef.current = true;+ cfg.dynamicDirDeg = next.angleDeg;+ if (cfg.rotationSource === 'direction') {lastDirAnchorRef.current = { x, y };}- } else {- lastDirAnchorRef.current = { x, y };}- effectiveTipAngle = cfg.tipAngleDeg + dynamicDirDegRef.current;+ if (+ cfg.naturalPaintMode &&+ cfg.rotationSource === 'direction' &&+ twist !== undefined &&+ Number.isFinite(twist)+ ) {+ twistDegRef.current = normalizeAngleDeg(twist);+ cfg.twistDeg = twistDegRef.current;+ }}ring.style.transform = formatCursorRingTransform(x,@@ -282,7 +349,7 @@ export function useCanvasEffects({cfg.rotation,cfg.flipX,cfg.flipY,- effectiveTipAngle+ computeEffectiveCursorAngleDeg(cfg));if (ring.style.display !== 'block') {ring.style.display = 'block';@@ -303,7 +370,14 @@ export function useCanvasEffects({const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;ro?.observe(viewport);- const updateCursorRingCoords = (clientX: number, clientY: number, forceRefreshRect: boolean = false) => {+ const updateCursorRingCoords = (+ clientX: number,+ clientY: number,+ forceRefreshRect: boolean = false,+ tiltX?: number,+ tiltY?: number,+ twist?: number+ ) => {const ring = cursorRingRef.current;if (!ring) return;@@ -315,6 +389,8 @@ export function useCanvasEffects({if (x < 0 || x > cachedRect.width || y < 0 || y > cachedRect.height) {lastPointerPosRef.current = null;+ lastDirAnchorRef.current = null;+ hasDynamicDirRef.current = false;ring.style.display = 'none';return;}@@ -326,19 +402,33 @@ export function useCanvasEffects({return;}- showRingAtLocalPos(x, y);+ showRingAtLocalPos(x, y, tiltX, tiltY, twist);};const handleWindowPointerMove = (e: PointerEvent) => {- updateCursorRingCoords(e.clientX, e.clientY, false);+ if (+ (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&+ shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)+ ) {+ return;+ }+ updateCursorRingCoords(e.clientX, e.clientY, false, e.tiltX, e.tiltY, e.twist);};const handleViewportPointerEnterOrDown = (e: PointerEvent) => {- updateCursorRingCoords(e.clientX, e.clientY, true);+ if (+ (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&+ shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)+ ) {+ return;+ }+ updateCursorRingCoords(e.clientX, e.clientY, true, e.tiltX, e.tiltY, e.twist);};const handlePointerLeave = () => {lastPointerPosRef.current = null;+ lastDirAnchorRef.current = null;+ hasDynamicDirRef.current = false;if (cursorRingRef.current) {cursorRingRef.current.style.display = 'none';}@@ -357,7 +447,14 @@ export function useCanvasEffects({handlePointerLeave();return;}- updateCursorRingCoords(last.clientX, last.clientY, false);+ updateCursorRingCoords(+ last.clientX,+ last.clientY,+ false,+ last.tiltX,+ last.tiltY,+ last.twist+ );});return () => {@@ -370,7 +467,7 @@ export function useCanvasEffects({viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);viewport.removeEventListener('pointerleave', handlePointerLeave);};- }, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, hasOpenDocument]);+ }, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, isPaintUnfilled, hasOpenDocument]);// Dismiss quick palette on Escape and reset transient UI state on window blur / tab hideuseEffect(() => {@@ -418,6 +515,10 @@ export function useCanvasEffects({size: Math.max(2, Math.min(300, Math.round(pendingSize))),hardness: Math.round(pendingHardness * 100),});+ } else if (isPaintUnfilled && onUpdateFillSettings) {+ onUpdateFillSettings({+ brushSize: Math.max(2, Math.min(300, Math.round(pendingSize))),+ });} else {onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });}@@ -481,12 +582,15 @@ export function useCanvasEffects({document.body.style.cursor = '';document.body.style.userSelect = '';};- }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings, tool, setIsResizingBrush]);+ }, [isResizingBrush, isPaintUnfilled, onUpdateBrushSettings, onUpdateFillSettings, onUpdateLiquifySettings, onUpdateRetouchSettings, tool, setIsResizingBrush]);return {tipOutline,isCustomTip,isSquare,+ isCursorRotating: cursorRotationSpec.enabled,+ cursorOrientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,+ thicknessRatio,cursorWidth,cursorHeight,totalAngleDeg,diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex 2f38997..121b70c 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -2,6 +2,7 @@ import React, { useRef } from 'react';import {BrushSettings,CanvasDimensions,+ FillSettings,LiquifySettings,RetouchSettings,ToolType,@@ -19,6 +20,7 @@ export interface UseCanvasPointerHandlersParams {viewportRef: React.RefObject<HTMLDivElement | null>;dimensions: CanvasDimensions;brushSettings: BrushSettings;+ fillSettings?: FillSettings;liquifySettings?: LiquifySettings;retouchSettings?: RetouchSettings;tool: ToolType;@@ -49,6 +51,7 @@ export function useCanvasPointerHandlers({viewportRef,dimensions,brushSettings,+ fillSettings,liquifySettings,retouchSettings,tool,@@ -98,7 +101,9 @@ export function useCanvasPointerHandlers({? liquifySettings.size: tool === 'retouch' && retouchSettings? retouchSettings.size- : brushSettings.size,+ : tool === 'fill' && fillSettings?.method === 'paint-unfilled'+ ? Math.max(2, Math.min(300, fillSettings.brushSize ?? 24))+ : brushSettings.size,hardness:tool === 'retouch' && retouchSettings? retouchSettings.hardness / 100@@ -190,7 +195,8 @@ export function useCanvasPointerHandlers({allowDrawingPassThrough &&e.button === 0 &&e.altKey &&- ((tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') ||+ (tool === 'transform' ||+ (tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') ||tool === 'pen' ||tool === '3d')) {@@ -293,7 +299,7 @@ export function useCanvasPointerHandlers({// Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM// pen events AND WinTab CXO_SYSTEM-synthesized mouse events (which carry constant pressure=0.5).if (- (tool === 'brush' || tool === 'eraser') &&+ (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)) {return;@@ -310,7 +316,7 @@ export function useCanvasPointerHandlers({const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {if (- (tool === 'brush' || tool === 'eraser') &&+ (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)) {return;@@ -329,7 +335,7 @@ export function useCanvasPointerHandlers({const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {if (!(- (tool === 'brush' || tool === 'eraser') &&+ (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY))) {diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.tsindex b6d0aa0..980417a 100644--- a/src/components/canvasArea/useCompositorViewport.ts+++ b/src/components/canvasArea/useCompositorViewport.ts@@ -17,6 +17,7 @@ import {resolveEffectiveDpr,} from '../../utils/performanceManager';import {+ computeEffectiveCursorAngleDeg,CursorConfig,formatArtboardTransform,formatCursorRingTransform,@@ -48,6 +49,7 @@ export interface UseCompositorViewportParams {showCheckerboard: boolean;hasOpenDocument: boolean;softProofSettings?: SoftProofSettings;+ valueCheckEnabled?: boolean;activeLayerId?: string;brushOpacity?: number;colorMode: CanvasColorMode;@@ -80,6 +82,7 @@ export function useCompositorViewport({showCheckerboard,hasOpenDocument,softProofSettings,+ valueCheckEnabled = false,activeLayerId,brushOpacity,colorMode,@@ -176,6 +179,7 @@ export function useCompositorViewport({showCheckerboard,onionSkinFrames,softProofSettings,+ valueCheckEnabled,activeLayerId,brushOpacity: brushOpacity ?? 1.0,effectiveDraftCanvasRef,@@ -191,6 +195,7 @@ export function useCompositorViewport({showCheckerboard,onionSkinFrames,softProofSettings,+ valueCheckEnabled,activeLayerId,brushOpacity: brushOpacity ?? 1.0,effectiveDraftCanvasRef,@@ -226,6 +231,7 @@ export function useCompositorViewport({devicePixelRatio: dpr,onionSkinFrames: rp.onionSkinFrames,softProof: rp.softProofSettings,+ valueCheck: rp.valueCheckEnabled,activeLayerId: rp.activeLayerId ?? null,activeDraftLayerId: rp.activeLayerId ?? null,activeDraftCanvas: draftCanvas,@@ -290,7 +296,7 @@ export function useCompositorViewport({cam.rotation,cam.flipX,cam.flipY,- cfg.tipAngleDeg + (cfg.followDirection ? cfg.dynamicDirDeg ?? 0 : 0)+ computeEffectiveCursorAngleDeg(cfg));}}@@ -475,6 +481,7 @@ export function useCompositorViewport({showCheckerboard,onionSkinFrames,softProofSettings,+ valueCheckEnabled,activeLayerId,brushOpacity,colorMode,diff --git a/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts b/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.tsindex 679fbbb..d66d61d 100644--- a/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts+++ b/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts@@ -64,7 +64,7 @@ export function processNativeTabletBatch(cb: NativeTabletBridgeCallbacks): void {const curTool = cb.getTool();- const isBrushOrEraser = curTool === 'brush' || curTool === 'eraser';+ const isBrushOrEraser = curTool === 'brush' || curTool === 'decoration' || curTool === 'eraser';const startStrokeFromSample = (s: NativeTabletSample): boolean => {if (diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.tsindex c94f8b3..bbab8be 100644--- a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts@@ -1,5 +1,5 @@import React from 'react';-import { Point } from '../../../types/editor';+import { Point, isBrushLikeTool } from '../../../types/editor';import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';import { detectWhitePaperGround } from '../../../utils/pigmentEngine';@@ -34,6 +34,7 @@ import {renderShiftLineInitialSegment,setupDraftCanvasSurface,} from './pointerDownInitialStamp';+import { cleanupQuickShapeState } from './quickShapeController';import { NATIVE_PEN_POINTER_ID } from './nativeTabletBridge';export function runPointerDown(@@ -44,7 +45,7 @@ export function runPointerDown(_coalescedEvents?: PointerEvent[]): void {const currentTool = helpers.getTool();- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';+ const isBrushOrEraser = isBrushLikeTool(currentTool);if (!isBrushOrEraser ||params.disabled ||@@ -126,7 +127,7 @@ export function runPointerDown(const preferNativeDraftScale = Boolean(!isVectorOrMask &&- (bs.colorMixing || bs.customTipImage || bs.paperTextureImage)+ (bs.colorMixing || bs.customTipImage || bs.paperTextureImage || isNaturalPaintBrush(bs)));const draftScale = setupDraftCanvasSurface(params,@@ -162,6 +163,7 @@ export function runPointerDown(state.activePointerId = e.pointerId;params.isDrawingRef.current = true;recoveryService.setDrawingActive(true);+ cleanupQuickShapeState(state, params);const firstEvent = e.nativeEvent;const rawStartPoint = helpers.getCanvasPoint(firstEvent);diff --git a/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.tsindex c64b624..f859cbc 100644--- a/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts@@ -8,6 +8,10 @@ import {StrokeSessionState,UseBrushStrokeSessionParams,} from './types';+import {+ scheduleQuickShapeDragUpdate,+ updateQuickShapeHoldMonitor,+} from './quickShapeController';export function runPointerMove(state: StrokeSessionState,@@ -31,6 +35,31 @@ export function runPointerMove(if (!vRect) return;const dims = params.dimensionsRef.current;+ // Active QuickShape handle/corner dragging mode (before releasing the pen)+ if (state.quickShapeSession) {+ const nativeEvt = e.nativeEvent;+ screenToCanvasInto(+ nativeEvt.clientX,+ nativeEvt.clientY,+ vRect,+ params.panRef.current,+ params.zoomRef.current,+ params.rotationRef.current,+ dims,+ state.scratchDocCoord,+ params.flipXRef.current,+ params.flipYRef.current+ );+ const qx = state.scratchDocCoord.x;+ const qy = state.scratchDocCoord.y;+ const dragInfo = { x: qx, y: qy, shiftKey: e.shiftKey, altKey: e.altKey };+ state.quickShapeLastPointerPos = dragInfo;+ scheduleQuickShapeDragUpdate(state, params, helpers, dragInfo);+ helpers.dispatchPointerStat(qx, qy, state.lastQueuedPressure);+ params.onCollabCursorMoveRef.current?.(qx, qy, true, helpers.getTool());+ return;+ }+const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =coalescedEvents ??extEvent.coalescedEvents ??@@ -71,6 +100,9 @@ export function runPointerMove(let lastQueuedY = 0;let lastQueuedPressure = state.lastQueuedPressure;let hasQueued = false;+ let lastSampledDocX = state.lastProcessedPoint.x;+ let lastSampledDocY = state.lastProcessedPoint.y;+ let hasSampledDoc = false;// Ensure monotonic, evenly spaced timestamps across same-timestamp coalesced hardware bursts// (common in WebView2 / Chromium getCoalescedEvents and Windows Ink / WinTab bursts).@@ -160,6 +192,10 @@ export function runPointerMove(cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;}+ lastSampledDocX = cx;+ lastSampledDocY = cy;+ hasSampledDoc = true;+if (state.hasLastProcessedPoint &&Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&@@ -208,6 +244,18 @@ export function runPointerMove(params.onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, helpers.getTool());}+ if (hasSampledDoc) {+ updateQuickShapeHoldMonitor(+ state,+ params,+ helpers,+ lastSampledDocX,+ lastSampledDocY,+ isShiftKey,+ isAltOverride+ );+ }+if ((pipeline.getPendingCount() > 0 || state.latestPredicted !== null) &&state.drawRafId === nulldiff --git a/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.tsindex c28cd68..c7edf20 100644--- a/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts@@ -82,8 +82,10 @@ export interface DirectDraftCommitParams {expressWhite: boolean;};selMaskOpts: {- mask: NonNullable<CanvasSelection['mask']>;+ mask: Uint8Array | null;bounds: CanvasSelection['bounds'];+ maskWidth?: number;+ maskHeight?: number;} | null;isEraser: boolean;isBgEraser: boolean;diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.tsindex 494482f..e163472 100644--- a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts@@ -24,6 +24,12 @@ import {syncDualBrushRegionToDraft,syncStrokePaperTextureRegionToDraft,} from './strokeHelpers';+import {+ cleanupQuickShapeState,+ clearQuickShapeHoldTimer,+ flushPendingQuickShapeDrag,+} from './quickShapeController';+import { getQuickShapeLabel } from '../../../utils/quickShapeEngine';export function runPointerUp(state: StrokeSessionState,@@ -50,7 +56,19 @@ export function runPointerUp(cancelAnimationFrame(state.drawRafId);state.drawRafId = null;}- helpers.flushPendingPoints(true);+ clearQuickShapeHoldTimer(state);++ const isQuickShape = state.quickShapeSession !== null;+ const quickShapeKind = state.quickShapeSession?.currentShape.kind ?? null;+ if (isQuickShape) {+ if (state.quickShapeRafId !== null) {+ cancelAnimationFrame(state.quickShapeRafId);+ state.quickShapeRafId = null;+ }+ flushPendingQuickShapeDrag(state, params, helpers);+ } else {+ helpers.flushPendingPoints(true);+ }const bs = helpers.getBrushSettings();const dims = params.dimensionsRef.current;@@ -87,44 +105,48 @@ export function runPointerUp(let addedFlickPoints = false;const tailSegments: CubicBezierSegment[] = [];- pipeline.finalizeStroke(e.nativeEvent?.timeStamp || e.timeStamp || performance.now(), {- enableFlickTaper,- dirtyPadExtra: tailPadExtra,- onPoint: (sample) => {- addedFlickPoints = true;- state.allStrokePoints.push({- x: sample.x,- y: sample.y,- pressure: sample.pressure,- width: sample.width,- tiltX: sample.tiltX,- tiltY: sample.tiltY,- twist: sample.twist,- timestamp: sample.timestamp,- isCorner: sample.isCorner,- });- },- onSegment: (seg) => {- tailSegments.push({- p0: { ...seg.p0 },- c1: { ...seg.c1 },- c2: { ...seg.c2 },- p3: { ...seg.p3 },- });- const segPad = Math.ceil(- Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32- );- const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;- const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;- const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;- const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;- pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);- helpers.markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);- },- });+ if (!isQuickShape) {+ pipeline.finalizeStroke(e.nativeEvent?.timeStamp || e.timeStamp || performance.now(), {+ enableFlickTaper,+ dirtyPadExtra: tailPadExtra,+ onPoint: (sample) => {+ addedFlickPoints = true;+ state.allStrokePoints.push({+ x: sample.x,+ y: sample.y,+ pressure: sample.pressure,+ width: sample.width,+ tiltX: sample.tiltX,+ tiltY: sample.tiltY,+ twist: sample.twist,+ timestamp: sample.timestamp,+ isCorner: sample.isCorner,+ });+ },+ onSegment: (seg) => {+ tailSegments.push({+ p0: { ...seg.p0 },+ c1: { ...seg.c1 },+ c2: { ...seg.c2 },+ p3: { ...seg.p3 },+ });+ const segPad = Math.ceil(+ Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32+ );+ const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;+ const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;+ const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;+ const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;+ pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);+ helpers.markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);+ },+ });+ }const pDirty = pipeline.dirtyRect;- const mergedDirty = state.dirtyRect+ const mergedDirty = isQuickShape+ ? state.dirtyRect+ : state.dirtyRect? {minX: Math.min(state.dirtyRect.minX,@@ -168,6 +190,7 @@ export function runPointerUp(bs.taper.minSizeRatio !== undefined));const shouldTaper =+ !isQuickShape &&hasActiveTaper &&(Boolean(bs.taper?.useIn) ||(Boolean(bs.taper?.useOut) && (!addedFlickPoints || hasCspArcLengthTaper)));@@ -275,6 +298,9 @@ export function runPointerUp(grid,mergedDirty,strokeId: state.currentStrokeId,+ labelOverride: quickShapeKind+ ? `QuickShape: ${getQuickShapeLabel(quickShapeKind)}`+ : undefined,pushHistoryStep: params.pushHistoryStep,});} else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {@@ -291,7 +317,9 @@ export function runPointerUp(if (clampedBakeRect) {const strokeIdForHistory = state.currentStrokeId || undefined;- const label = resolveStrokeHistoryLabel(bs, currentTool, isMonochrome);+ const label = quickShapeKind+ ? `QuickShape: ${getQuickShapeLabel(quickShapeKind)}`+ : resolveStrokeHistoryLabel(bs, currentTool, isMonochrome);const dirtyRect = clampedBakeRect;const toolForHistory: StrokeHistoryToolType =currentTool === 'eraser' ? 'eraser' : isPencil ? 'pencil' : 'brush';@@ -304,7 +332,7 @@ export function runPointerUp(commitMaskModeStroke({canvas: maskCanvas,dirtyRect,- bs,+ bs: isQuickShape ? { ...bs, postCorrection: 0, taper: undefined } : bs,strokeColor,isEraser,currentTool,@@ -338,6 +366,7 @@ export function runPointerUp(isMonochrome,hasWetEdge,shouldTaper,+ isQuickShape,exitSpeed,strokeColor,allPoints,@@ -445,6 +474,7 @@ export function runPointerUp(state.ribbonSession = null;state.snapSession.endStroke();state.straightSnapSession.endStroke();+ cleanupQuickShapeState(state, params);helpers.emitConstraintAxisChange(null);if (params.isMaskModeRef.current) {diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.tsindex ee2ec47..65a9e68 100644--- a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts@@ -24,6 +24,7 @@ import {import { isRibbonBrush } from '../../../engine/RibbonBrushEngine';import { LayerPixelSampler } from '../../../utils/colorMixingEngine';import { detectWhitePaperGround } from '../../../utils/pigmentEngine';+import { buildStrokeSelectionMask } from '../../../utils/selectionUtils';import {DraftCanvasElement,PushHistoryStepFn,@@ -65,6 +66,7 @@ export interface CommitRasterStrokeParams {isMonochrome: boolean;hasWetEdge: boolean;shouldTaper: boolean;+ isQuickShape?: boolean;exitSpeed?: number;strokeColor: string;allPoints: Point[];@@ -99,6 +101,7 @@ export function commitRasterStrokeToTiles(isMonochrome,hasWetEdge,shouldTaper,+ isQuickShape = false,exitSpeed,strokeColor,allPoints,@@ -132,9 +135,15 @@ export function commitRasterStrokeToTiles(expressWhite: activeLayer?.monoExpressWhite ?? true,}: undefined;- const selMaskOpts = activeSelection?.mask- ? { mask: activeSelection.mask, bounds: activeSelection.bounds }- : null;+ const selMaskOpts =+ activeSelection?.mask && activeSelection.maskWidth && activeSelection.maskHeight+ ? {+ mask: activeSelection.mask,+ bounds: activeSelection.bounds,+ maskWidth: activeSelection.maskWidth,+ maskHeight: activeSelection.maskHeight,+ }+ : null;const pigmentStrength = resolveStrokePigmentStrength(bs,isEraser,@@ -150,7 +159,8 @@ export function commitRasterStrokeToTiles(const draftOriginX = draftDocRect ? Math.round(draftDocRect.x) : 0;const draftOriginY = draftDocRect ? Math.round(draftDocRect.y) : 0;const canDirectDraftCommit = Boolean(- draftCanvas &&+ !isQuickShape &&+ draftCanvas &&draftCtx &&Math.abs(draftScale - 1.0) < 1e-6 &&draftDocRect &&@@ -198,6 +208,7 @@ export function commitRasterStrokeToTiles(string,{ format: TileFormat; data: Uint8Array | null }>();+ const natSelMaskOpts = buildStrokeSelectionMask(activeSelection, dirtyRect, dims);const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);for (let i = 0; i < spans.length; i++) {const sp = spans[i];@@ -219,7 +230,7 @@ export function commitRasterStrokeToTiles(pigmentStrength,pigmentWhiteGround,monochrome: monoOpts,- selectionMask: selMaskOpts,+ selectionMask: natSelMaskOpts,snapshotOut: beforeSnapshot,suppressNotify: true,});@@ -296,10 +307,12 @@ export function commitRasterStrokeToTiles(isMonochrome,isEraser);- const bakeBs: BrushSettings =- effectiveOpacitySensor && !bs.opacitySensor+ const bakeBs: BrushSettings = {+ ...(effectiveOpacitySensor && !bs.opacitySensor? { ...bs, opacitySensor: effectiveOpacitySensor }- : bs;+ : bs),+ ...(isQuickShape ? { postCorrection: 0, taper: undefined } : {}),+ };const allowGpuMonoBake =isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;const bakeSampler =diff --git a/src/hooks/drawing/brushStrokeSession/quickShapeController.ts b/src/hooks/drawing/brushStrokeSession/quickShapeController.tsnew file mode 100644index 0000000..83962a4--- /dev/null+++ b/src/hooks/drawing/brushStrokeSession/quickShapeController.ts@@ -0,0 +1,397 @@+import { BrushSettings, isPaintTool } from '../../../types/editor';+import { get2DContext } from '../../../utils/canvasUtils';+import {+ buildSecondaryBrushSettings,+ renderCompleteStroke,+ resolveDualBrushConfig,+} from '../../../engine/BrushEngine';+import { useUiStore } from '../../../stores';+import {+ QUICK_SHAPE_HOLD_MS,+ QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX,+ QUICK_SHAPE_MIN_STROKE_LENGTH_DOC,+ QuickShapeGeometry,+ buildQuickShapePreview,+ computeQuickShapeBounds,+ createQuickShapeSession,+ extractQuickShapeStrokeStyle,+ playQuickShapeSnapClick,+ recognizeQuickShape,+ sampleQuickShapePoints,+ updateQuickShapeFromDrag,+} from '../../../utils/quickShapeEngine';+import { DraftCanvasElement, applySelectionCanvasClip } from '../types';+import { resetAndClearOffscreenDraftCanvas } from './strokeHelpers';+import {+ StrokeSessionHelpers,+ StrokeSessionState,+ UseBrushStrokeSessionParams,+} from './types';++export function isQuickShapeEligible(+ state: StrokeSessionState,+ helpers: Pick<StrokeSessionHelpers, 'getTool'>+): boolean {+ if (!useUiStore.getState().appSettings.quickShapeEnabled) return false;+ if (!isPaintTool(helpers.getTool())) return false;+ if (state.isShiftLineStroke) return false;+ if (state.straightSnapSession.isActive()) return false;+ if (state.snapSession.getActiveAxis() !== null) return false;+ return true;+}++export function clearQuickShapeHoldTimer(state: StrokeSessionState): void {+ if (state.quickShapeHoldTimer !== null) {+ clearTimeout(state.quickShapeHoldTimer);+ state.quickShapeHoldTimer = null;+ }+}++export function cleanupQuickShapeState(+ state: StrokeSessionState,+ params: Pick<UseBrushStrokeSessionParams, 'onQuickShapePreviewChangeRef'>+): void {+ clearQuickShapeHoldTimer(state);+ if (state.quickShapeRafId !== null) {+ cancelAnimationFrame(state.quickShapeRafId);+ state.quickShapeRafId = null;+ }+ if (state.quickShapeKeyCleanup) {+ state.quickShapeKeyCleanup();+ state.quickShapeKeyCleanup = null;+ }+ const hadSession = state.quickShapeSession !== null;+ state.quickShapeSession = null;+ state.quickShapeHoldAnchor = null;+ state.quickShapeRawTravelDist = 0;+ state.quickShapeLastPointerPos = null;+ state.quickShapePendingDrag = null;+ if (hadSession) {+ params.onQuickShapePreviewChangeRef?.current?.(null);+ }+}++/**+ * Renders the current QuickShape onto the live draft canvas with the artist's active brush+ * and updates `state.allStrokePoints`, `state.dirtyRect`, and `state.touchedTiles`.+ */+export function renderQuickShapeToDraftCanvas(+ state: StrokeSessionState,+ params: UseBrushStrokeSessionParams,+ helpers: StrokeSessionHelpers,+ shape: QuickShapeGeometry+): void {+ const session = state.quickShapeSession;+ if (!session) return;++ const shapePoints = sampleQuickShapePoints(shape, session.style);+ state.allStrokePoints = shapePoints;++ const dims = params.dimensionsRef.current;+ const bs = helpers.getBrushSettings();+ const currentTool = helpers.getTool();+ const currentLayerId = params.activeLayerIdRef.current;+ const activeLayer = params.layersRef.current?.find((l) => l.id === currentLayerId);+ const mode = params.colorModeRef.current;+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';+ const isMonochrome = mode === 'monochrome' || isMonoLayer;+ const strokeColor = helpers.resolveStrokeColor(bs, false, false, isMonochrome, mode);+ const maskCanvas = params.getActiveMaskCanvas();++ const bounds = computeQuickShapeBounds(shape);+ const dualCfg = resolveDualBrushConfig(bs);+ const dualSecInfo = dualCfg ? buildSecondaryBrushSettings(bs, dualCfg) : null;+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0, dualCfg?.scatter ?? 0);+ const maxBrushDim = Math.max(session.style.width, bs.size || 10, dualSecInfo?.settings.size || 0);+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;+ const blurMargin = (1 - strokeHardness) * (maxBrushDim * 1.5);+ const pad = Math.max(32, Math.ceil(maxBrushDim * (2.8 + scatterFactor * 2) + blurMargin + 32));++ state.dirtyRect = {+ minX: Math.max(0, Math.floor(bounds.minX - pad)),+ minY: Math.max(0, Math.floor(bounds.minY - pad)),+ maxX: Math.min(dims.width, Math.ceil(bounds.maxX + pad)),+ maxY: Math.min(dims.height, Math.ceil(bounds.maxY + pad)),+ };+ state.touchedTiles.clear();+ helpers.markTouchedTiles(+ state.dirtyRect.minX,+ state.dirtyRect.minY,+ state.dirtyRect.maxX,+ state.dirtyRect.maxY+ );++ const draftCanvas = params.effectiveDraftCanvasRef?.current as+ | DraftCanvasElement+ | null+ | undefined;+ if (!draftCanvas) return;+ const draftCtx = get2DContext(draftCanvas);+ if (!draftCtx) return;++ if (draftCanvas.__clipSaved) {+ try {+ draftCtx.restore();+ } catch {+ // Ignore restore underflow+ }+ draftCanvas.__clipSaved = false;+ }++ const draftScale = draftCanvas.__draftScale ?? 1.0;+ const docRect = draftCanvas.__draftDocRect;+ const visMinX = docRect ? docRect.x : 0;+ const visMinY = docRect ? docRect.y : 0;++ draftCtx.resetTransform();+ draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);+ draftCtx.setTransform(+ draftScale,+ 0,+ 0,+ draftScale,+ -visMinX * draftScale,+ -visMinY * draftScale+ );+ draftCtx.save();+ draftCanvas.__clipSaved = true;+ draftCtx.beginPath();+ draftCtx.rect(0, 0, dims.width, dims.height);+ draftCtx.clip();+ applySelectionCanvasClip(draftCtx, params.selectionRef.current);++ const effectiveOpacitySensor = helpers.resolveEffectiveOpacitySensor(bs, isMonochrome, false);+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);+ const allowGpuMono =+ isMonochrome && (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false;+ const draftBs: BrushSettings = {+ ...bs,+ ...(effectiveOpacitySensor && !bs.opacitySensor+ ? { opacitySensor: effectiveOpacitySensor }+ : {}),+ opacity: 1.0,+ isTransparentInk: false,+ wetEdge: 0,+ brushCombineMode: undefined,+ postCorrection: 0,+ taper: undefined,+ antiAlias: liveAA ?? bs.antiAlias,+ color: bs.isTransparentInk ? '#000000' : strokeColor,+ };++ renderCompleteStroke(+ draftCtx,+ shapePoints,+ draftBs,+ currentTool,+ isMonochrome ? 'monochrome' : mode,+ false,+ maskCanvas || undefined,+ false,+ state.layerPixelSampler || undefined,+ allowGpuMono+ );++ draftCanvas.__draftHasContent = true;+ draftCanvas.__draftFrameDirtyRect = null;+ draftCanvas.__draftForceFullUpload = true;+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;+ params.activeTileGridRef.current.notifyChange(true);+}++/**+ * Attempts to snap the current freehand stroke into a QuickShape after the stylus dwell timer fires.+ */+export function tryActivateQuickShape(+ state: StrokeSessionState,+ params: UseBrushStrokeSessionParams,+ helpers: StrokeSessionHelpers+): boolean {+ state.quickShapeHoldTimer = null;+ if (!params.isDrawingRef.current || state.quickShapeSession) return false;+ if (!isQuickShapeEligible(state, helpers)) return false;++ // Flush any buffered samples so recognition sees the full stroke+ if (state.drawRafId !== null) {+ cancelAnimationFrame(state.drawRafId);+ state.drawRafId = null;+ }+ helpers.flushPendingPoints(true);++ const zoom = Math.max(0.1, params.zoomRef.current || 1.0);+ const holdToleranceDoc = QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX / zoom;+ const recognition = recognizeQuickShape(state.allStrokePoints, holdToleranceDoc);+ if (!recognition) return false;++ // Soft click acoustic & tactile feedback+ playQuickShapeSnapClick();++ helpers.clearPredictedCanvas();+ // Clean up incremental live-stroke state; QuickShape renders & commits via renderCompleteStroke+ if (state.naturalPaintSession) {+ state.naturalPaintSession.finishAndDispose();+ state.naturalPaintSession = null;+ }+ state.ribbonSession = null;+ state.dualSecondaryRibbonSession = null;+ resetAndClearOffscreenDraftCanvas(state.rawDraftCanvas as DraftCanvasElement | null);+ resetAndClearOffscreenDraftCanvas(state.dualPrimaryCanvas as DraftCanvasElement | null);+ resetAndClearOffscreenDraftCanvas(state.dualSecondaryCanvas as DraftCanvasElement | null);+ state.frameGpuDabs.length = 0;+ state.dualFrameSecondaryGpuDabs.length = 0;++ const bs = helpers.getBrushSettings();+ const style = extractQuickShapeStrokeStyle(state.allStrokePoints, bs.size || 10);+ const lastPt = state.allStrokePoints[state.allStrokePoints.length - 1];+ const snapPenPos = state.quickShapeLastPointerPos+ ? { x: state.quickShapeLastPointerPos.x, y: state.quickShapeLastPointerPos.y }+ : { x: lastPt.x, y: lastPt.y };++ const session = createQuickShapeSession(recognition.shape, snapPenPos, style);+ state.quickShapeSession = session;++ // Apply initial modifier state if Shift or Alt is already held at snap time+ if (+ state.quickShapeLastPointerPos &&+ (state.quickShapeLastPointerPos.shiftKey || state.quickShapeLastPointerPos.altKey)+ ) {+ updateQuickShapeFromDrag(+ session,+ snapPenPos,+ {+ shiftKey: state.quickShapeLastPointerPos.shiftKey,+ altKey: state.quickShapeLastPointerPos.altKey,+ },+ zoom+ );+ }++ // Listen for Shift / Alt modifier toggles and Escape cancel while pen is held down+ if (typeof window !== 'undefined') {+ const handleKeyChange = (ev: KeyboardEvent) => {+ if (!state.quickShapeSession || !params.isDrawingRef.current) return;+ if (ev.type === 'keydown' && ev.key === 'Escape') {+ ev.preventDefault();+ ev.stopPropagation();+ helpers.abortActiveStroke();+ return;+ }+ if (ev.key === 'Shift' || ev.key === 'Alt') {+ const pos = state.quickShapeLastPointerPos ?? {+ x: state.quickShapeSession.snapPenPos.x,+ y: state.quickShapeSession.snapPenPos.y,+ shiftKey: false,+ altKey: false,+ };+ const nextPos = {+ x: pos.x,+ y: pos.y,+ shiftKey: ev.shiftKey,+ altKey: ev.altKey,+ };+ state.quickShapeLastPointerPos = nextPos;+ scheduleQuickShapeDragUpdate(state, params, helpers, nextPos);+ }+ };+ window.addEventListener('keydown', handleKeyChange, true);+ window.addEventListener('keyup', handleKeyChange, true);+ state.quickShapeKeyCleanup = () => {+ window.removeEventListener('keydown', handleKeyChange, true);+ window.removeEventListener('keyup', handleKeyChange, true);+ };+ }++ renderQuickShapeToDraftCanvas(state, params, helpers, session.currentShape);+ params.onQuickShapePreviewChangeRef?.current?.(buildQuickShapePreview(session));+ return true;+}++/**+ * Updates the spatial dwell anchor and arms/resets the ~350ms hold timer during freehand drawing.+ * Tolerates minor stylus micro-jitter inside `QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX` without resetting.+ */+export function updateQuickShapeHoldMonitor(+ state: StrokeSessionState,+ params: UseBrushStrokeSessionParams,+ helpers: StrokeSessionHelpers,+ cx: number,+ cy: number,+ shiftKey: boolean,+ altKey: boolean+): void {+ const prevPos = state.quickShapeLastPointerPos;+ if (prevPos) {+ state.quickShapeRawTravelDist += Math.hypot(cx - prevPos.x, cy - prevPos.y);+ } else if (state.allStrokePoints.length > 0) {+ const p0 = state.allStrokePoints[0];+ state.quickShapeRawTravelDist += Math.hypot(cx - p0.x, cy - p0.y);+ }+ state.quickShapeLastPointerPos = { x: cx, y: cy, shiftKey, altKey };++ if (state.quickShapeSession) return;+ if (!isQuickShapeEligible(state, helpers)) {+ clearQuickShapeHoldTimer(state);+ state.quickShapeHoldAnchor = null;+ return;+ }++ // Require sufficient stroke extent before arming hold detection+ const approxLen = Math.max(state.strokeTotalDistance, state.quickShapeRawTravelDist);+ if (approxLen < QUICK_SHAPE_MIN_STROKE_LENGTH_DOC) {+ clearQuickShapeHoldTimer(state);+ state.quickShapeHoldAnchor = { x: cx, y: cy };+ return;+ }++ const zoom = Math.max(0.1, params.zoomRef.current || 1.0);+ const holdToleranceDoc = QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX / zoom;+ const anchor = state.quickShapeHoldAnchor;++ if (!anchor || Math.hypot(cx - anchor.x, cy - anchor.y) > holdToleranceDoc) {+ state.quickShapeHoldAnchor = { x: cx, y: cy };+ clearQuickShapeHoldTimer(state);+ state.quickShapeHoldTimer = setTimeout(() => {+ tryActivateQuickShape(state, params, helpers);+ }, QUICK_SHAPE_HOLD_MS);+ } else if (state.quickShapeHoldTimer === null) {+ state.quickShapeHoldTimer = setTimeout(() => {+ tryActivateQuickShape(state, params, helpers);+ }, QUICK_SHAPE_HOLD_MS);+ }+}++export function flushPendingQuickShapeDrag(+ state: StrokeSessionState,+ params: UseBrushStrokeSessionParams,+ helpers: StrokeSessionHelpers+): void {+ state.quickShapeRafId = null;+ const session = state.quickShapeSession;+ const pending = state.quickShapePendingDrag;+ state.quickShapePendingDrag = null;+ if (!session || !pending || !params.isDrawingRef.current) return;++ const zoom = Math.max(0.1, params.zoomRef.current || 1.0);+ const nextShape = updateQuickShapeFromDrag(+ session,+ { x: pending.x, y: pending.y },+ { shiftKey: pending.shiftKey, altKey: pending.altKey },+ zoom+ );+ renderQuickShapeToDraftCanvas(state, params, helpers, nextShape);+ params.onQuickShapePreviewChangeRef?.current?.(buildQuickShapePreview(session));+}++export function scheduleQuickShapeDragUpdate(+ state: StrokeSessionState,+ params: UseBrushStrokeSessionParams,+ helpers: StrokeSessionHelpers,+ drag: { x: number; y: number; shiftKey: boolean; altKey: boolean }+): void {+ state.quickShapePendingDrag = drag;+ if (state.quickShapeRafId === null) {+ state.quickShapeRafId = requestAnimationFrame(() => {+ flushPendingQuickShapeDrag(state, params, helpers);+ });+ }+}diff --git a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts b/src/hooks/drawing/brushStrokeSession/strokeHelpers.tsindex ea3d24f..ba38a5e 100644--- a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts+++ b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts@@ -161,12 +161,37 @@ export function resetAndClearOffscreenDraftCanvas(export function abortActiveStrokeSession(params: Pick<UseBrushStrokeSessionParams,- 'isDrawingRef' | 'effectiveDraftCanvasRef' | 'activeTileGridRef' | 'interactionRef'+ | 'isDrawingRef'+ | 'effectiveDraftCanvasRef'+ | 'activeTileGridRef'+ | 'interactionRef'+ | 'onQuickShapePreviewChangeRef'>,state: StrokeSessionState,clearPredictedCanvas: () => void,emitConstraintAxisChange: (axis: ConstraintAxis | null) => void): void {+ if (state.quickShapeHoldTimer !== null) {+ clearTimeout(state.quickShapeHoldTimer);+ state.quickShapeHoldTimer = null;+ }+ if (state.quickShapeRafId !== null) {+ cancelAnimationFrame(state.quickShapeRafId);+ state.quickShapeRafId = null;+ }+ if (state.quickShapeKeyCleanup) {+ state.quickShapeKeyCleanup();+ state.quickShapeKeyCleanup = null;+ }+ const hadQuickShape = state.quickShapeSession !== null;+ state.quickShapeSession = null;+ state.quickShapeHoldAnchor = null;+ state.quickShapeRawTravelDist = 0;+ state.quickShapeLastPointerPos = null;+ state.quickShapePendingDrag = null;+ if (hadQuickShape) {+ params.onQuickShapePreviewChangeRef?.current?.(null);+ }if (!params.isDrawingRef.current) return;if (state.drawRafId !== null) {cancelAnimationFrame(state.drawRafId);diff --git a/src/hooks/drawing/brushStrokeSession/types.ts b/src/hooks/drawing/brushStrokeSession/types.tsindex 12dee21..a0aed72 100644--- a/src/hooks/drawing/brushStrokeSession/types.ts+++ b/src/hooks/drawing/brushStrokeSession/types.ts@@ -21,6 +21,7 @@ import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngimport { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../../types/perspective';import { PerspectiveSnapSession } from '../../../utils/perspectiveSnapping';import { StraightRulerSnapSession } from '../../../utils/straightRulerMath';+import { QuickShapePreviewState, QuickShapeSession } from '../../../utils/quickShapeEngine';import { LastStrokeEndState, PushHistoryStepFn } from '../types';export interface UseBrushStrokeSessionParams {@@ -53,6 +54,9 @@ export interface UseBrushStrokeSessionParams {onActiveConstraintAxisChangeRef: React.MutableRefObject<((axis: ConstraintAxis | null) => void) | undefined>;+ onQuickShapePreviewChangeRef?: React.MutableRefObject<+ ((preview: QuickShapePreviewState | null) => void) | undefined+ >;onUpdateLayerThumbnail: (layerId: string) => void;onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;onCollabStrokeStartRef: React.MutableRefObject<@@ -192,6 +196,14 @@ export interface StrokeSessionState {statRaf: number | null;pendingStat: { x: number | null; y: number | null; pressure: number } | null;cachedViewportRect: DOMRect | null;+ quickShapeHoldTimer: ReturnType<typeof setTimeout> | null;+ quickShapeHoldAnchor: { x: number; y: number } | null;+ quickShapeRawTravelDist: number;+ quickShapeLastPointerPos: { x: number; y: number; shiftKey: boolean; altKey: boolean } | null;+ quickShapeSession: QuickShapeSession | null;+ quickShapeRafId: number | null;+ quickShapePendingDrag: { x: number; y: number; shiftKey: boolean; altKey: boolean } | null;+ quickShapeKeyCleanup: (() => void) | null;}export function createInitialStrokeSessionState(): StrokeSessionState {@@ -251,6 +263,14 @@ export function createInitialStrokeSessionState(): StrokeSessionState {statRaf: null,pendingStat: null,cachedViewportRect: null,+ quickShapeHoldTimer: null,+ quickShapeHoldAnchor: null,+ quickShapeRawTravelDist: 0,+ quickShapeLastPointerPos: null,+ quickShapeSession: null,+ quickShapeRafId: null,+ quickShapePendingDrag: null,+ quickShapeKeyCleanup: null,};}diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.tsindex a071fe8..57863fa 100644--- a/src/hooks/drawing/useBrushStrokeSession.ts+++ b/src/hooks/drawing/useBrushStrokeSession.ts@@ -84,6 +84,7 @@ export function useBrushStrokeSession(predictedCanvasRef,activeTileGridRef,onActiveConstraintAxisChangeRef,+ onQuickShapePreviewChangeRef,} = params;const paramsRef = useRef<UseBrushStrokeSessionParams>(params);@@ -166,6 +167,22 @@ export function useBrushStrokeSession(if (state.drawRafId !== null) {cancelAnimationFrame(state.drawRafId);}+ if (state.quickShapeHoldTimer !== null) {+ clearTimeout(state.quickShapeHoldTimer);+ state.quickShapeHoldTimer = null;+ }+ if (state.quickShapeRafId !== null) {+ cancelAnimationFrame(state.quickShapeRafId);+ state.quickShapeRafId = null;+ }+ if (state.quickShapeKeyCleanup) {+ state.quickShapeKeyCleanup();+ state.quickShapeKeyCleanup = null;+ }+ if (state.quickShapeSession) {+ state.quickShapeSession = null;+ paramsRef.current.onQuickShapePreviewChangeRef?.current?.(null);+ }recoveryService.setDrawingActive(false);};}, [viewportRef, disabled, activeSessionId]);@@ -184,7 +201,13 @@ export function useBrushStrokeSession(const abortActiveStroke = useCallback(() => {abortActiveStrokeSession(- { isDrawingRef, effectiveDraftCanvasRef, activeTileGridRef, interactionRef },+ {+ isDrawingRef,+ effectiveDraftCanvasRef,+ activeTileGridRef,+ interactionRef,+ onQuickShapePreviewChangeRef,+ },sessionStateRef.current!,clearPredictedCanvas,emitConstraintAxisChange@@ -203,6 +226,7 @@ export function useBrushStrokeSession(emitConstraintAxisChange,interactionRef,isDrawingRef,+ onQuickShapePreviewChangeRef,]);const getCanvasPoint = useCallback(diff --git a/src/hooks/drawing/useGradientTool.ts b/src/hooks/drawing/useGradientTool.tsindex 7c49c96..5aa06e6 100644--- a/src/hooks/drawing/useGradientTool.ts+++ b/src/hooks/drawing/useGradientTool.ts@@ -11,7 +11,14 @@ import type {import {constrainGradientEndpoint,createDefaultGradientMesh,+ getGradientMeshCentroid,+ getSelectedMeshNodeIndices,renderGradientToTileGrid,+ rotateGradientMeshFromBase,+ selectGradientMeshNodesInRect,+ setGradientMeshSelection,+ toggleGradientMeshNodeSelection,+ updateGradientMeshNodes,} from '../../utils/gradientEngine';import { documentStore } from '../../utils/documentStore';import { TileFormat } from '../../utils/tileEngine';@@ -19,6 +26,13 @@ import { multiplayerService } from '../../services/multiplayerService';import { interactiveToolBridge, toolStoreActions, useToolStore } from '../../stores';import type { PushHistoryStepFn } from './types';+export interface GradientMeshMarqueeRect {+ x: number;+ y: number;+ width: number;+ height: number;+}+export interface UseGradientToolParams {dimensions: CanvasDimensions;colorMode: CanvasColorMode;@@ -37,11 +51,15 @@ export interface UseGradientToolParams {export interface UseGradientToolResult {gradientDragPreview: GradientDragPreview | null;gradientMesh: GradientMeshState | null;+ gradientMeshMarqueeRect: GradientMeshMarqueeRect | null;+ isRotatingGradientMesh: boolean;setGradientMesh: React.Dispatch<React.SetStateAction<GradientMeshState | null>>;handleInitGradientMesh: () => void;handleApplyGradientMesh: () => void;handleCancelGradientMesh: () => void;handleUpdateMeshNode: (index: number, patch: { color?: string; opacity?: number }) => void;+ handleUpdateMeshNodes: (indices: number[], patch: { color?: string; opacity?: number }) => void;+ handleStartRotateGradientMesh: (e: React.PointerEvent<HTMLElement>) => void;handleGradientPointerDown: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;handleGradientPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;handleGradientPointerUp: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;@@ -62,6 +80,9 @@ export function useGradientTool({showToast,}: UseGradientToolParams): UseGradientToolResult {const [gradientDragPreview, setGradientDragPreview] = useState<GradientDragPreview | null>(null);+ const [gradientMeshMarqueeRect, setGradientMeshMarqueeRect] =+ useState<GradientMeshMarqueeRect | null>(null);+ const [isRotatingGradientMesh, setIsRotatingGradientMesh] = useState<boolean>(false);const gradientMesh = useToolStore((s) => s.activeGradientMesh);const setGradientMesh: React.Dispatch<React.SetStateAction<GradientMeshState | null>> =useCallback((updater) => {@@ -69,11 +90,40 @@ export function useGradientTool({}, []);const dragRef = useRef<{ start: Point2D; end: Point2D; type: 'linear' | 'radial' } | null>(null);- const draggingMeshNodeRef = useRef<number | null>(null);+ const draggingMeshNodesRef = useRef<{+ clickedIdx: number;+ startPt: Point2D;+ basePositions: Array<{ idx: number; x: number; y: number }>;+ wasAlreadyMultiSelected: boolean;+ moved: boolean;+ } | null>(null);+ const meshMarqueeRef = useRef<{+ start: Point2D;+ end: Point2D;+ additive: boolean;+ } | null>(null);const meshRectDragRef = useRef<{ start: Point2D; end: Point2D } | null>(null);+ const rotateCleanupRef = useRef<(() => void) | null>(null);const gradientMeshRef = useRef<GradientMeshState | null>(null);gradientMeshRef.current = gradientMesh;+ const stopMeshRotation = useCallback(() => {+ if (rotateCleanupRef.current) {+ rotateCleanupRef.current();+ rotateCleanupRef.current = null;+ }+ setIsRotatingGradientMesh(false);+ }, []);++ useEffect(() => {+ return () => {+ if (rotateCleanupRef.current) {+ rotateCleanupRef.current();+ rotateCleanupRef.current = null;+ }+ };+ }, []);+const canPaintActiveLayer = useCallback((): boolean => {if (!activeLayer ||@@ -152,6 +202,7 @@ export function useGradientTool({}updateLayerThumbnail(activeLayerId, true);}+ stopMeshRotation();setGradientMesh(null);}, [activeLayer?.alphaLocked,@@ -162,26 +213,86 @@ export function useGradientTool({pushHistoryStep,resolveLayerFormat,selection,+ setGradientMesh,+ stopMeshRotation,updateLayerThumbnail,]);const handleCancelGradientMesh = useCallback(() => {+ stopMeshRotation();dragRef.current = null;- draggingMeshNodeRef.current = null;+ draggingMeshNodesRef.current = null;+ meshMarqueeRef.current = null;meshRectDragRef.current = null;+ setGradientMeshMarqueeRect(null);setGradientDragPreview(null);setGradientMesh(null);- }, []);+ }, [setGradientMesh, stopMeshRotation]);const handleUpdateMeshNode = useCallback((index: number, patch: { color?: string; opacity?: number }) => {- setGradientMesh((prev) => {- if (!prev || index < 0 || index >= prev.nodes.length) return prev;- const nextNodes = prev.nodes.map((n, i) => (i === index ? { ...n, ...patch } : n));- return { ...prev, nodes: nextNodes };- });+ setGradientMesh((prev) => (prev ? updateGradientMeshNodes(prev, [index], patch) : prev));+ },+ [setGradientMesh]+ );++ const handleUpdateMeshNodes = useCallback(+ (indices: number[], patch: { color?: string; opacity?: number }) => {+ setGradientMesh((prev) => (prev ? updateGradientMeshNodes(prev, indices, patch) : prev));},- []+ [setGradientMesh]+ );++ const handleStartRotateGradientMesh = useCallback(+ (e: React.PointerEvent<HTMLElement>) => {+ e.preventDefault();+ e.stopPropagation();+ const mesh = gradientMeshRef.current;+ if (!mesh || mesh.nodes.length === 0) return;++ stopMeshRotation();++ const pivot = getGradientMeshCentroid(mesh);+ const startPt = getCanvasCoords(e);+ const startAngleRad = Math.atan2(startPt.y - pivot.y, startPt.x - pivot.x);+ const basePositions = mesh.nodes.map((n) => ({ x: n.x, y: n.y }));+ const baseRotationDeg = mesh.rotationDeg ?? 0;++ setIsRotatingGradientMesh(true);++ const onMove = (ev: PointerEvent) => {+ const curPt = getCanvasCoords(ev);+ const curAngleRad = Math.atan2(curPt.y - pivot.y, curPt.x - pivot.x);+ let deltaDeg = ((curAngleRad - startAngleRad) * 180) / Math.PI;+ if (ev.shiftKey) {+ const snappedTotal = Math.round((baseRotationDeg + deltaDeg) / 15) * 15;+ deltaDeg = snappedTotal - baseRotationDeg;+ }+ setGradientMesh((prev) =>+ prev+ ? rotateGradientMeshFromBase(basePositions, baseRotationDeg, prev, deltaDeg, pivot)+ : prev+ );+ };++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onEnd);+ window.removeEventListener('pointercancel', onEnd);+ };++ const onEnd = () => {+ cleanup();+ rotateCleanupRef.current = null;+ setIsRotatingGradientMesh(false);+ };++ rotateCleanupRef.current = cleanup;+ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onEnd);+ window.addEventListener('pointercancel', onEnd);+ },+ [getCanvasCoords, setGradientMesh, stopMeshRotation]);// Clear preview / mesh when switching away from gradient tool or changing away from mesh type@@ -193,12 +304,14 @@ export function useGradientTool({if (prevTool === 'gradient' && s.tool !== 'gradient') {handleCancelGradientMesh();} else if (prevType === 'mesh' && s.gradientSettings.type !== 'mesh') {+ stopMeshRotation();+ setGradientMeshMarqueeRect(null);setGradientMesh(null);}prevTool = s.tool;prevType = s.gradientSettings.type;});- }, [handleCancelGradientMesh]);+ }, [handleCancelGradientMesh, setGradientMesh, stopMeshRotation]);// Register bridge callbacks so ToolPropertyInspector can invoke mesh actions without prop drillinguseEffect(() => {@@ -256,10 +369,52 @@ export function useGradientTool({}}if (hitIdx >= 0) {- draggingMeshNodeRef.current = hitIdx;- setGradientMesh((prev) => (prev ? { ...prev, selectedNodeIndex: hitIdx } : prev));+ if (e.shiftKey || e.ctrlKey || e.metaKey) {+ setGradientMesh((prev) =>+ prev ? toggleGradientMeshNodeSelection(prev, hitIdx) : prev+ );+ return true;+ }+ const currentSelected = getSelectedMeshNodeIndices(mesh);+ const isAlreadySelected = currentSelected.includes(hitIdx);+ if (isAlreadySelected && currentSelected.length > 1) {+ setGradientMesh((prev) =>+ prev ? setGradientMeshSelection(prev, currentSelected, hitIdx) : prev+ );+ draggingMeshNodesRef.current = {+ clickedIdx: hitIdx,+ startPt: pt,+ basePositions: currentSelected.map((idx) => ({+ idx,+ x: mesh.nodes[idx].x,+ y: mesh.nodes[idx].y,+ })),+ wasAlreadyMultiSelected: true,+ moved: false,+ };+ } else {+ setGradientMesh((prev) =>+ prev ? setGradientMeshSelection(prev, [hitIdx], hitIdx) : prev+ );+ draggingMeshNodesRef.current = {+ clickedIdx: hitIdx,+ startPt: pt,+ basePositions: [{ idx: hitIdx, x: mesh.nodes[hitIdx].x, y: mesh.nodes[hitIdx].y }],+ wasAlreadyMultiSelected: false,+ moved: false,+ };+ }return true;}++ // When a mesh already exists, dragging on empty canvas selects multiple vertices via marquee+ meshMarqueeRef.current = {+ start: pt,+ end: pt,+ additive: e.shiftKey || e.ctrlKey || e.metaKey,+ };+ setGradientMeshMarqueeRect({ x: pt.x, y: pt.y, width: 0, height: 0 });+ return true;}// Start dragging a new mesh bounding box (or click to initialize default bounds)meshRectDragRef.current = { start: pt, end: pt };@@ -285,7 +440,7 @@ export function useGradientTool({});return true;},- [canPaintActiveLayer, zoomRef]+ [canPaintActiveLayer, setGradientMesh, zoomRef]);const handleGradientPointerMove = useCallback(@@ -293,19 +448,42 @@ export function useGradientTool({const { tool, gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();if (tool !== 'gradient') return false;- if (draggingMeshNodeRef.current !== null && gradientMeshRef.current) {+ if (draggingMeshNodesRef.current && gradientMeshRef.current) {const pt = getCanvasCoords(e);- const nodeIdx = draggingMeshNodeRef.current;+ const drag = draggingMeshNodesRef.current;+ const dx = pt.x - drag.startPt.x;+ const dy = pt.y - drag.startPt.y;+ if (Math.hypot(dx, dy) >= 2) {+ drag.moved = true;+ }+ const posMap = new Map<number, { x: number; y: number }>();+ for (const bp of drag.basePositions) {+ posMap.set(bp.idx, { x: bp.x + dx, y: bp.y + dy });+ }setGradientMesh((prev) => {- if (!prev || nodeIdx < 0 || nodeIdx >= prev.nodes.length) return prev;- const nextNodes = prev.nodes.map((n, i) =>- i === nodeIdx ? { ...n, x: pt.x, y: pt.y } : n- );+ if (!prev) return prev;+ const nextNodes = prev.nodes.map((n, i) => {+ const movedPos = posMap.get(i);+ return movedPos ? { ...n, x: movedPos.x, y: movedPos.y } : n;+ });return { ...prev, nodes: nextNodes };});return true;}+ if (meshMarqueeRef.current) {+ const pt = getCanvasCoords(e);+ meshMarqueeRef.current.end = pt;+ const s = meshMarqueeRef.current.start;+ setGradientMeshMarqueeRect({+ x: Math.min(s.x, pt.x),+ y: Math.min(s.y, pt.y),+ width: Math.abs(pt.x - s.x),+ height: Math.abs(pt.y - s.y),+ });+ return true;+ }+if (meshRectDragRef.current) {const pt = getCanvasCoords(e);meshRectDragRef.current.end = pt;@@ -342,7 +520,7 @@ export function useGradientTool({return false;},- [getCanvasCoords]+ [getCanvasCoords, setGradientMesh]);const handleGradientPointerUp = useCallback(@@ -358,8 +536,38 @@ export function useGradientTool({// Ignore capture release errors}- if (draggingMeshNodeRef.current !== null) {- draggingMeshNodeRef.current = null;+ if (draggingMeshNodesRef.current) {+ const drag = draggingMeshNodesRef.current;+ draggingMeshNodesRef.current = null;+ if (drag.wasAlreadyMultiSelected && !drag.moved) {+ setGradientMesh((prev) =>+ prev ? setGradientMeshSelection(prev, [drag.clickedIdx], drag.clickedIdx) : prev+ );+ }+ return true;+ }++ if (meshMarqueeRef.current) {+ const marquee = meshMarqueeRef.current;+ meshMarqueeRef.current = null;+ setGradientMeshMarqueeRect(null);+ const w = Math.abs(pt.x - marquee.start.x);+ const h = Math.abs(pt.y - marquee.start.y);+ if (w < 4 && h < 4) {+ if (!marquee.additive) {+ setGradientMesh((prev) => (prev ? setGradientMeshSelection(prev, [], null) : prev));+ }+ } else {+ const rect = {+ x: Math.min(marquee.start.x, pt.x),+ y: Math.min(marquee.start.y, pt.y),+ width: w,+ height: h,+ };+ setGradientMesh((prev) =>+ prev ? selectGradientMeshNodesInRect(prev, rect, marquee.additive) : prev+ );+ }return true;}@@ -430,6 +638,7 @@ export function useGradientTool({pushHistoryStep,resolveLayerFormat,selection,+ setGradientMesh,updateLayerThumbnail,]);@@ -437,11 +646,15 @@ export function useGradientTool({return {gradientDragPreview,gradientMesh,+ gradientMeshMarqueeRect,+ isRotatingGradientMesh,setGradientMesh,handleInitGradientMesh,handleApplyGradientMesh,handleCancelGradientMesh,handleUpdateMeshNode,+ handleUpdateMeshNodes,+ handleStartRotateGradientMesh,handleGradientPointerDown,handleGradientPointerMove,handleGradientPointerUp,diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.tsindex 5bd5a7b..76ba8d4 100644--- a/src/hooks/drawing/useSelectionTools.ts+++ b/src/hooks/drawing/useSelectionTools.ts@@ -8,6 +8,7 @@ import {LayerItem,LayerTreeDelta,TileDelta,+ TransformMode,TransformSession,} from '../../types/editor';import { documentStore } from '../../utils/documentStore';@@ -39,6 +40,7 @@ import {import {renderPerspectiveQuad,renderMeshWarp,+ renderDeformedTriangles,createDefaultPerspectiveQuad,createDefaultMeshPoints,computeMeshSubdivisions,@@ -49,8 +51,24 @@ import {processAffineTransformChunks,processPerspectiveTransformChunks,processMeshWarpTransformChunks,+ processDeformedTrianglesTransformChunks,type PixelBuffer,} from '../../utils/transformEngine';+import {+ releaseTransformSessionCanvases,+ switchTransformSessionMode,+} from '../../utils/transformModeTransition';+import {+ ensurePuppetMesh,+ getDeformedMeshBounds,+ isPuppetDeformed,+ solvePuppetDeformation,+} from '../../utils/puppetWarpEngine';+import {+ createInitialCageState,+ evaluateCageMesh,+ isCageDeformed,+} from '../../utils/cageWarpEngine';import { get2DContext, getCanvasCompositeOperation } from '../../utils/canvasUtils';import { useToolStore, toolStoreActions } from '../../stores';import { PushHistoryStepFn } from './types';@@ -78,6 +96,49 @@ function computeTransformDestRect(const sb = getMeshSurfaceBounds(session.meshPoints, 6);includePt(sb.minX, sb.minY);includePt(sb.maxX, sb.maxY);+ } else if (session.mode === 'puppet') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const sw = session.sourcePixels?.width ?? session.sourceCanvas.width;+ const sh = session.sourcePixels?.height ?? session.sourceCanvas.height;+ const pMesh = ensurePuppetMesh(session.puppet, session.sourcePixels, sw, sh, quad);+ const solved = solvePuppetDeformation(+ pMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ const pb = getDeformedMeshBounds(solved.x, solved.y);+ includePt(pb.minX, pb.minY);+ includePt(pb.maxX, pb.maxY);+ } else if (session.mode === 'cage') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const sw = session.sourcePixels?.width ?? session.sourceCanvas.width;+ const sh = session.sourcePixels?.height ?? session.sourceCanvas.height;+ const cageState =+ session.cage ?? createInitialCageState(session.sourcePixels, sw, sh, quad);+ const evalRes = evaluateCageMesh(sw, sh, quad, cageState, false);+ const cb = getDeformedMeshBounds(evalRes.deformedX, evalRes.deformedY);+ includePt(cb.minX, cb.minY);+ includePt(cb.maxX, cb.maxY);} else {const cx = session.x + session.width / 2;const cy = session.y + session.height / 2;@@ -180,6 +241,119 @@ function compositeTransformedIntoTileGrid() {return destRect;}+ } else if (session.mode === 'puppet') {+ if (!isPuppetDeformed(session.puppet)) {+ processAffineTransformChunks(+ resolvedPixels,+ {+ x: session.x,+ y: session.y,+ width: session.width,+ height: session.height,+ rotation: session.rotation,+ flipH: session.flipH,+ flipV: session.flipV,+ },+ destRect,+ CHUNK,+ commitChunk+ );+ return destRect;+ }+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const pMesh = ensurePuppetMesh(+ session.puppet,+ session.sourcePixels ?? resolvedPixels,+ resolvedPixels.width,+ resolvedPixels.height,+ quad+ );+ const solved = solvePuppetDeformation(+ pMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ if (+ processDeformedTrianglesTransformChunks(+ resolvedPixels,+ solved.x,+ solved.y,+ pMesh.uvX,+ pMesh.uvY,+ pMesh.triangles,+ destRect,+ CHUNK,+ commitChunk,+ solved.triOrder+ )+ ) {+ return destRect;+ }+ } else if (session.mode === 'cage') {+ if (!isCageDeformed(session.cage)) {+ processAffineTransformChunks(+ resolvedPixels,+ {+ x: session.x,+ y: session.y,+ width: session.width,+ height: session.height,+ rotation: session.rotation,+ flipH: session.flipH,+ flipV: session.flipV,+ },+ destRect,+ CHUNK,+ commitChunk+ );+ return destRect;+ }+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const cageState =+ session.cage ??+ createInitialCageState(resolvedPixels, resolvedPixels.width, resolvedPixels.height, quad);+ const evalRes = evaluateCageMesh(+ resolvedPixels.width,+ resolvedPixels.height,+ quad,+ cageState,+ true+ );+ if (+ processDeformedTrianglesTransformChunks(+ resolvedPixels,+ evalRes.deformedX,+ evalRes.deformedY,+ evalRes.uvX,+ evalRes.uvY,+ evalRes.triangles,+ destRect,+ CHUNK,+ commitChunk+ )+ ) {+ return destRect;+ }} else {processAffineTransformChunks(resolvedPixels,@@ -240,6 +414,71 @@ function compositeTransformedIntoTileGrid(true);renderMeshWarp(cCtx, sourceCanvas, session.meshPoints, subPerCell);+ } else if (session.mode === 'puppet') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const pMesh = ensurePuppetMesh(+ session.puppet,+ session.sourcePixels,+ sourceCanvas.width,+ sourceCanvas.height,+ quad+ );+ const solved = solvePuppetDeformation(+ pMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ renderDeformedTriangles(+ cCtx,+ sourceCanvas,+ solved.x,+ solved.y,+ pMesh.uvX,+ pMesh.uvY,+ pMesh.triangles,+ solved.triOrder+ );+ } else if (session.mode === 'cage') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const cageState =+ session.cage ??+ createInitialCageState(session.sourcePixels, sourceCanvas.width, sourceCanvas.height, quad);+ const evalRes = evaluateCageMesh(+ sourceCanvas.width,+ sourceCanvas.height,+ quad,+ cageState,+ true+ );+ renderDeformedTriangles(+ cCtx,+ sourceCanvas,+ evalRes.deformedX,+ evalRes.deformedY,+ evalRes.uvX,+ evalRes.uvY,+ evalRes.triangles+ );} else {const midX = session.x + session.width / 2;const midY = session.y + session.height / 2;@@ -315,7 +554,7 @@ export interface UseSelectionToolsResult {handleFeatherSelection: (radius?: number) => void;handleInvertSelection: () => void;handleSelectAll: () => void;- handleStartTransform: () => void;+ handleStartTransform: (initialMode?: TransformMode) => void;handleApplyTransform: () => void;handleCancelTransform: () => void;handleSelectionPointerDown: (@@ -1032,8 +1271,25 @@ export function useSelectionTools({showToast('Selected All (Ctrl+A)');}, [dimensions, showToast]);- const handleStartTransform = useCallback(() => {- if (transformSession?.active) return;+ const handleStartTransform = useCallback((initialMode?: TransformMode) => {+ const requestedMode: TransformMode =+ initialMode === 'affine' ||+ initialMode === 'perspective' ||+ initialMode === 'mesh' ||+ initialMode === 'puppet' ||+ initialMode === 'cage'+ ? initialMode+ : 'affine';++ if (transformSession?.active) {+ if (initialMode && requestedMode !== transformSession.mode) {+ setTransformSession((prev) => (prev ? switchTransformSessionMode(prev, requestedMode) : null));+ }+ return;+ }++ const finalizeSession = (base: TransformSession): TransformSession =>+ requestedMode === 'affine' ? base : switchTransformSessionMode(base, requestedMode);flushPendingHistoryTasks?.();const grid = getGrid();@@ -1059,7 +1315,7 @@ export function useSelectionTools({floatCanvas.height,0);- setTransformSession({+ setTransformSession(finalizeSession({active: true,layerId: targetLayerId,sourceCanvas: floatCanvas,@@ -1078,7 +1334,7 @@ export function useSelectionTools({meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),- });+ }));setSelection(null);toolStoreActions.setToolRaw('transform');return;@@ -1175,7 +1431,7 @@ export function useSelectionTools({compositeCanvas.height,0);- setTransformSession({+ setTransformSession(finalizeSession({active: true,layerId: primaryLayerId,layerIds: liftedLayerIds,@@ -1202,7 +1458,7 @@ export function useSelectionTools({meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),- });+ }));setSelection(null);toolStoreActions.setToolRaw('transform');return;@@ -1234,7 +1490,7 @@ export function useSelectionTools({floatCanvas.height,0);- setTransformSession({+ setTransformSession(finalizeSession({active: true,layerId: targetLayerId,sourceCanvas: floatCanvas,@@ -1253,7 +1509,7 @@ export function useSelectionTools({meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),- });+ }));setSelection(null);} else if (targetLayers.length > 1) {let minX = Infinity;@@ -1330,7 +1586,7 @@ export function useSelectionTools({const primaryLayerId = liftedLayerIds[0];const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);- setTransformSession({+ setTransformSession(finalizeSession({active: true,layerId: primaryLayerId,layerIds: liftedLayerIds,@@ -1353,7 +1609,7 @@ export function useSelectionTools({meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),- });+ }));} else {const targetLayerId = targetLayers[0].id;const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');@@ -1377,7 +1633,7 @@ export function useSelectionTools({updateLayerThumbnail(targetLayerId, true);const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);- setTransformSession({+ setTransformSession(finalizeSession({active: true,layerId: targetLayerId,sourceCanvas,@@ -1397,7 +1653,7 @@ export function useSelectionTools({meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),- });+ }));}toolStoreActions.setToolRaw('transform');}, [@@ -1479,14 +1735,24 @@ export function useSelectionTools({for (const d of tileDeltas) {allTileDeltas.push(d);}- releaseTemporaryCanvas(sCanvas);updateLayerThumbnail(lId, true);}+ const modeLabel =+ transformSession.mode === 'puppet'+ ? 'Puppet Warp'+ : transformSession.mode === 'cage'+ ? 'Cage Transform'+ : transformSession.mode === 'mesh'+ ? 'Mesh Warp'+ : transformSession.mode === 'perspective'+ ? 'Perspective Transform'+ : 'Free Transform';+if (allTileDeltas.length > 0) {pushHistoryStep('transform',- `Free Transform (${transformSession.layerIds.length} layers)`,+ `${modeLabel} (${transformSession.layerIds.length} layers)`,null,null,transformSession.layerIds[0],@@ -1495,7 +1761,7 @@ export function useSelectionTools({);}- releaseTemporaryCanvas(transformSession.sourceCanvas);+ releaseTransformSessionCanvases(transformSession);grid.notifyChange(true);setTransformSession(null);toolStoreActions.selectTool('brush');@@ -1520,11 +1786,22 @@ export function useSelectionTools({resolveMonoOpts(targetLayerId, targetFormat));+ const singleModeLabel =+ transformSession.mode === 'puppet'+ ? 'Puppet Warp'+ : transformSession.mode === 'cage'+ ? 'Cage Transform'+ : transformSession.mode === 'mesh'+ ? 'Mesh Warp'+ : transformSession.mode === 'perspective'+ ? 'Perspective Transform'+ : 'Free Transform';+const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, targetLayerId);if (tileDeltas.length > 0) {pushHistoryStep('transform',- 'Free Transform',+ singleModeLabel,null,null,targetLayerId,@@ -1533,7 +1810,7 @@ export function useSelectionTools({);}- releaseTemporaryCanvas(transformSession.sourceCanvas);+ releaseTransformSessionCanvases(transformSession);grid.notifyChange(true);updateLayerThumbnail(targetLayerId, true);setTransformSession(null);@@ -1557,12 +1834,7 @@ export function useSelectionTools({grid.restoreLayerSnapshot(lId, beforeSnap, true);updateLayerThumbnail(lId, true);}- if (transformSession.layerSourceCanvases) {- for (const sCanvas of transformSession.layerSourceCanvases.values()) {- releaseTemporaryCanvas(sCanvas);- }- }- releaseTemporaryCanvas(transformSession.sourceCanvas);+ releaseTransformSessionCanvases(transformSession);grid.notifyChange(true);setTransformSession(null);toolStoreActions.selectTool('brush');@@ -1573,7 +1845,7 @@ export function useSelectionTools({grid.restoreLayerSnapshot(transformSession.layerId, transformSession.beforeTileSnapshot, false);updateLayerThumbnail(transformSession.layerId, true);}- releaseTemporaryCanvas(transformSession.sourceCanvas);+ releaseTransformSessionCanvases(transformSession);setTransformSession(null);toolStoreActions.selectTool('brush');}, [transformSession, getGrid, updateLayerThumbnail]);diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.tsindex b2ff24c..3d7e6bc 100644--- a/src/hooks/drawing/useShapeAndFillTools.ts+++ b/src/hooks/drawing/useShapeAndFillTools.ts@@ -19,6 +19,10 @@ import {executeFloodFillOnTileGridAsync,executeLassoFillOnTileGrid,} from '../../utils/floodFill';+import {+ executeEncloseAndFillOnTileGrid,+ executePaintUnfilledAreaOnTileGrid,+} from '../../utils/smartLineFill';import {LiquifySubStep,LiquifyWarpField,@@ -56,6 +60,15 @@ export interface FrameDragPreview {end: Point2D;}+export interface LassoFillPreview {+ points: Point2D[];+ color: string;+ opacity: number;+ isTransparentInk: boolean;+ mode?: 'lasso' | 'enclose-and-fill' | 'paint-unfilled';+ brushSize?: number;+}+export interface UseShapeAndFillToolsParams {dimensions: CanvasDimensions;colorMode: CanvasColorMode;@@ -97,6 +110,7 @@ export interface UseShapeAndFillToolsResult {setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;frameDragPreview: FrameDragPreview | null;shapeDragPreview: ShapeDragPreview | null;+ lassoFillPreview: LassoFillPreview | null;openLayerForEditing: (layer: LayerItem) => boolean;isPipetteSamplingRef: React.MutableRefObject<boolean>;handleSampleColor: (pt: { x: number; y: number }) => void;@@ -170,10 +184,12 @@ export function useShapeAndFillTools({const [editingBalloonLayerId, setEditingBalloonLayerId] = useState<string | null>(null);const [frameDragPreview, setFrameDragPreview] = useState<FrameDragPreview | null>(null);const [shapeDragPreview, setShapeDragPreview] = useState<ShapeDragPreview | null>(null);+ const [lassoFillPreview, setLassoFillPreview] = useState<LassoFillPreview | null>(null);const isPipetteSamplingRef = useRef<boolean>(false);const liquifyPersistentRef = useRef<PersistentLiquifyWarpSession | null>(null);const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);+ const activeSmartFillModeRef = useRef<'lasso' | 'enclose-and-fill' | 'paint-unfilled' | null>(null);const frameStartRef = useRef<{ x: number; y: number } | null>(null);const shapeDragRef = useRef<{start: { x: number; y: number };@@ -233,6 +249,41 @@ export function useShapeAndFillTools({};}, [shapeDragPreview]);+ // Cancel active Lasso / Smart Line Fill drag on Escape or when switching tool/method+ useEffect(() => {+ const cancelLassoFill = () => {+ if (lassoFillPointsRef.current.length > 0 || activeSmartFillModeRef.current !== null) {+ lassoFillPointsRef.current = [];+ activeSmartFillModeRef.current = null;+ setLassoFillPreview(null);+ }+ };+ const unsub = useToolStore.subscribe(() => {+ const s = useToolStore.getState();+ const activeMode = activeSmartFillModeRef.current;+ if (+ s.tool !== 'fill' ||+ (activeMode !== null && s.fillSettings.method !== activeMode) ||+ (s.fillSettings.method !== 'lasso' &&+ s.fillSettings.method !== 'enclose-and-fill' &&+ s.fillSettings.method !== 'paint-unfilled')+ ) {+ cancelLassoFill();+ }+ });+ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape' && lassoFillPointsRef.current.length > 0) {+ ev.preventDefault();+ cancelLassoFill();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => {+ unsub();+ window.removeEventListener('keydown', onKeyDown);+ };+ }, []);+const openLayerForEditing = useCallback((layer: LayerItem): boolean => {if (layer.locked) {@@ -644,13 +695,35 @@ export function useShapeAndFillTools({return true;}- if (fillSettings.method === 'lasso') {+ if (+ fillSettings.method === 'lasso' ||+ fillSettings.method === 'enclose-and-fill' ||+ fillSettings.method === 'paint-unfilled'+ ) {+ const isTransparentInk = useToolStore.getState().isTransparentColor;+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');+ if (fillSettings.method === 'paint-unfilled' && isTransparentInk && !isBg) {+ showToast?.('Switch off Transparent Ink (C) to paint unfilled areas');+ return true;+ }try {(e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);} catch {// Ignore capture errors in synthetic events}+ activeSmartFillModeRef.current = fillSettings.method;lassoFillPointsRef.current = [pt];+ setLassoFillPreview({+ points: [pt],+ color: primaryColor,+ opacity: Math.max(0, Math.min(1, fillSettings.opacity ?? 1)),+ isTransparentInk,+ mode: fillSettings.method,+ brushSize:+ fillSettings.method === 'paint-unfilled'+ ? Math.max(2, Math.min(300, fillSettings.brushSize ?? 24))+ : undefined,+ });return true;}@@ -921,10 +994,30 @@ export function useShapeAndFillTools({if (tool === 'fill' &&- fillSettings.method === 'lasso' &&+ (fillSettings.method === 'lasso' ||+ fillSettings.method === 'enclose-and-fill' ||+ fillSettings.method === 'paint-unfilled') &&lassoFillPointsRef.current.length > 0) {- lassoFillPointsRef.current.push(getCanvasCoords(e));+ const pt = getCanvasCoords(e);+ const pts = lassoFillPointsRef.current;+ const last = pts[pts.length - 1];+ const minSpacing = fillSettings.method === 'paint-unfilled' ? 1.0 : 1.5;+ if (!last || Math.hypot(pt.x - last.x, pt.y - last.y) >= minSpacing) {+ pts.push(pt);+ const ts = useToolStore.getState();+ setLassoFillPreview({+ points: [...pts],+ color: ts.primaryColor,+ opacity: Math.max(0, Math.min(1, ts.fillSettings.opacity ?? 1)),+ isTransparentInk: ts.isTransparentColor,+ mode: fillSettings.method,+ brushSize:+ fillSettings.method === 'paint-unfilled'+ ? Math.max(2, Math.min(300, ts.fillSettings.brushSize ?? 24))+ : undefined,+ });+ }return true;}@@ -1093,16 +1186,24 @@ export function useShapeAndFillTools({if (tool === 'fill' &&- fillSettings.method === 'lasso' &&- lassoFillPointsRef.current.length >= 3+ (fillSettings.method === 'lasso' ||+ fillSettings.method === 'enclose-and-fill' ||+ fillSettings.method === 'paint-unfilled') &&+ lassoFillPointsRef.current.length > 0) {try {(e.currentTarget as HTMLElement)?.releasePointerCapture?.(e.pointerId);} catch {// Ignore release errors}+ const activeMethod = activeSmartFillModeRef.current ?? fillSettings.method;const pts = [...lassoFillPointsRef.current];lassoFillPointsRef.current = [];+ activeSmartFillModeRef.current = null;+ setLassoFillPreview(null);+ if (activeMethod !== 'paint-unfilled' && pts.length < 3) {+ return true;+ }flushPendingHistoryTasks?.();if (!activeLayerId ||@@ -1115,6 +1216,11 @@ export function useShapeAndFillTools({}const grid = documentStore.getActiveTileGrid();+ if (activeLayer.alphaLocked && !grid.hasLayerTiles(activeLayerId)) {+ showToast?.('Alpha Lock is enabled on an empty layer');+ return true;+ }+const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');const isMono =!isBg && (colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome');@@ -1124,22 +1230,77 @@ export function useShapeAndFillTools({: null;const isTransparentInk = useToolStore.getState().isTransparentColor;const effectiveFillColor = isTransparentInk ? 'rgba(0,0,0,0)' : primaryColor;+ const fillOpacity = Math.max(0, Math.min(1, fillSettings.opacity ?? 1));- const res = executeLassoFillOnTileGrid({- grid,- targetLayerId: activeLayerId,- dimensions,- polygon: pts,- fillColorHex: effectiveFillColor,- targetFormat,- alphaLocked: Boolean(activeLayer.alphaLocked),- selectionMask: selMask,- });+ let res: { dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] };+ let historyLabel: string;++ if (activeMethod === 'enclose-and-fill') {+ res = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: activeLayerId,+ layers,+ dimensions,+ polygon: pts,+ fillColorHex: effectiveFillColor,+ tolerance: fillSettings.tolerance ?? 32,+ referMode: fillSettings.smartReferMode ?? 'refer-reference',+ targetMode: fillSettings.encloseTarget ?? 'all-enclosed',+ targetFormat,+ options: {+ closeGap: fillSettings.smartCloseGap ?? 10,+ areaScale: fillSettings.smartAreaScale ?? 1,+ antiAlias: fillSettings.antiAlias ?? true,+ selectionMask: selMask,+ alphaLocked: Boolean(activeLayer.alphaLocked),+ opacity: fillOpacity,+ },+ });+ historyLabel = isTransparentInk ? 'Enclose & Erase' : 'Enclose & Fill';+ if (!res.modified) {+ showToast?.('No closed outline found — try increasing Close Gap or check Reference Layer');+ }+ } else if (activeMethod === 'paint-unfilled') {+ res = executePaintUnfilledAreaOnTileGrid({+ grid,+ targetLayerId: activeLayerId,+ layers,+ dimensions,+ strokePoints: pts,+ brushSize: Math.max(2, Math.min(300, fillSettings.brushSize ?? 24)),+ fillColorHex: effectiveFillColor,+ tolerance: fillSettings.tolerance ?? 32,+ referMode: fillSettings.smartReferMode ?? 'refer-reference',+ targetFormat,+ options: {+ closeGap: fillSettings.smartCloseGap ?? 10,+ areaScale: fillSettings.smartAreaScale ?? 1,+ antiAlias: fillSettings.antiAlias ?? true,+ selectionMask: selMask,+ alphaLocked: Boolean(activeLayer.alphaLocked),+ opacity: fillOpacity,+ },+ });+ historyLabel = 'Paint Unfilled Area';+ } else {+ res = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: activeLayerId,+ dimensions,+ polygon: pts,+ fillColorHex: effectiveFillColor,+ targetFormat,+ alphaLocked: Boolean(activeLayer.alphaLocked),+ selectionMask: selMask,+ opacity: fillOpacity,+ });+ historyLabel = isTransparentInk ? 'Lasso Erase' : 'Lasso Fill';+ }if (res.modified && res.tileDeltas.length > 0) {pushHistoryStep('fill',- isTransparentInk ? 'Lasso Erase' : 'Lasso Fill',+ historyLabel,null,null,activeLayerId,@@ -1283,6 +1444,7 @@ export function useShapeAndFillTools({setActiveBalloon,frameDragPreview,shapeDragPreview,+ lassoFillPreview,openLayerForEditing,isPipetteSamplingRef,handleSampleColor,diff --git a/src/hooks/drawing/useVectorDrawing.ts b/src/hooks/drawing/useVectorDrawing.tsindex c543c60..ceec704 100644--- a/src/hooks/drawing/useVectorDrawing.ts+++ b/src/hooks/drawing/useVectorDrawing.ts@@ -38,6 +38,7 @@ export interface CommitVectorStrokeArgs {grid: SparseTileGrid;mergedDirty: { minX: number; minY: number; maxX: number; maxY: number } | null;strokeId: string | null;+ labelOverride?: string;pushHistoryStep: PushHistoryStepFn;}@@ -54,6 +55,7 @@ export function commitVectorStrokeOrErase({grid,mergedDirty,strokeId,+ labelOverride,pushHistoryStep,}: CommitVectorStrokeArgs): VectorStroke | undefined {const knots: VectorKnot[] = allPoints.map((pt, idx) => ({@@ -187,7 +189,7 @@ export function commitVectorStrokeOrErase({pushHistoryStep(isPencil ? 'pencil' : 'brush',- bs.brushName || (isPencil ? 'Vector Pencil' : 'Vector Pen'),+ labelOverride || bs.brushName || (isPencil ? 'Vector Pencil' : 'Vector Pen'),null,null,currentLayerId,diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsxindex 8f95c77..8654c94 100644--- a/src/hooks/useAppMenuSections.tsx+++ b/src/hooks/useAppMenuSections.tsx@@ -9,6 +9,7 @@ import {LayerItem,MenuSection,SoftProofSettings,+ TransformMode,isFolderLikeLayer,} from '../types/editor';import { PerspectiveRuler, StraightRuler } from '../types/perspective';@@ -29,6 +30,7 @@ import {documentStoreActions,toolStoreActions,uiStoreActions,+ useDocumentStore,useToolStore,useWorkspaceStore,workspaceStoreActions,@@ -78,7 +80,7 @@ export interface UseAppMenuSectionsParams {handleTriggerPasteFromFile: () => void;handleDeleteSelectedLayer: () => void;handleClearActiveLayer: () => void;- handleStartTransform: () => void;+ handleStartTransform: (initialMode?: TransformMode) => void;handleDeselect: () => void;handleFillSelectionColor: () => void;handleOpenTonalModal: (type: TonalCorrectionType) => void;@@ -110,6 +112,7 @@ export interface UseAppMenuSectionsParams {zoomIn: () => void;zoomOut: () => void;resetZoomAndCenter: () => void;+ resetZoomTo100: () => void;resetRotation: () => void;toggleFlipHorizontal: () => void;toggleFlipVertical: () => void;@@ -187,6 +190,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiozoomIn,zoomOut,resetZoomAndCenter,+ resetZoomTo100,resetRotation,toggleFlipHorizontal,toggleFlipVertical,@@ -203,9 +207,12 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioconst activePreset = useWorkspaceStore((s) => s.activePreset);const workspaceLayout = useWorkspaceStore((s) => s.layout);const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);+ const quickBrushPanelVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);const showDocumentTabs = useWorkspaceStore((s) => s.showDocumentTabs);const showCommandBar = useWorkspaceStore((s) => s.showCommandBar);+ const navigatorPreviewMode = useWorkspaceStore((s) => s.navigatorPreviewMode);+ const valueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);const visiblePanels = useMemo(() => listVisiblePanelIds(workspaceLayout), [workspaceLayout]);return useMemo(@@ -414,7 +421,20 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiolabel: 'Free Transform',shortcut: 'Ctrl+T',disabled: !hasOpenDocument,- onClick: handleStartTransform,+ onClick: () => handleStartTransform('affine'),+ },+ {+ id: 'edit-puppet-warp',+ label: 'Puppet Warp',+ shortcut: 'Ctrl+Shift+T',+ disabled: !hasOpenDocument,+ onClick: () => handleStartTransform('puppet'),+ },+ {+ id: 'edit-cage-transform',+ label: 'Cage Transform',+ disabled: !hasOpenDocument,+ onClick: () => handleStartTransform('cage'),},{id: 'edit-deselect',@@ -1087,6 +1107,13 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiodisabled: !hasOpenDocument,onClick: resetZoomAndCenter,},+ {+ id: 'view-zoom-100',+ label: 'Reset Zoom to 100%',+ shortcut: 'Ctrl+1',+ disabled: !hasOpenDocument,+ onClick: resetZoomTo100,+ },{id: 'view-reset-rotation',label: 'Reset Rotation',@@ -1117,6 +1144,53 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiodisabled: !hasOpenDocument || (!flipX && !flipY),onClick: resetViewFlip,},+ { id: 'view-div-value-check', label: '', divider: true },+ {+ id: 'view-value-check',+ label: 'Value Check (Live B/W)',+ shortcut: 'Shift+Y',+ checked: valueCheckEnabled,+ disabled: !hasOpenDocument,+ onClick: () => {+ const enabled = documentStoreActions.toggleValueCheck();+ showToast(enabled ? 'Value Check (Live B/W): ON' : 'Value Check (Live B/W): OFF');+ },+ },+ {+ id: 'view-navigator-preview-mode',+ label: 'Navigator Preview Mode',+ disabled: !hasOpenDocument,+ submenu: [+ {+ id: 'view-nav-mode-color',+ label: 'Color',+ checked: navigatorPreviewMode === 'color',+ onClick: () => {+ workspaceStoreActions.setNavigatorPreviewMode('color');+ showToast('Navigator Preview: Color');+ },+ },+ {+ id: 'view-nav-mode-bw',+ label: 'Live B/W Tone Preview',+ checked: navigatorPreviewMode === 'bw',+ onClick: () => {+ workspaceStoreActions.setNavigatorPreviewMode('bw');+ showToast('Navigator Preview: Live B/W Tone');+ },+ },+ {+ id: 'view-nav-mode-split',+ label: 'Split View (Color | B/W)',+ shortcut: 'Alt+Shift+Y',+ checked: navigatorPreviewMode === 'split',+ onClick: () => {+ workspaceStoreActions.setNavigatorPreviewMode('split');+ showToast('Navigator Preview: Split View (Color | B/W)');+ },+ },+ ],+ },{ id: 'view-div-ruler', label: '', divider: true },{id: 'view-straight-ruler',@@ -1351,6 +1425,13 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiochecked: !palettesHidden,onClick: () => workspaceStoreActions.togglePalettesHidden(),},+ {+ id: 'window-toggle-quick-brushes',+ label: 'Quick-Access Brush Panel',+ shortcut: 'Shift+B',+ checked: quickBrushPanelVisible,+ onClick: () => workspaceStoreActions.toggleQuickBrushPanelVisible(),+ },{ id: 'window-div-palettes', label: '', divider: true },...ALL_DOCK_PANEL_IDS.map((pid) => ({id: `window-panel-${pid}`,@@ -1475,7 +1556,9 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioisTimelapseRecording,isWebtoonMode,layers,+ navigatorPreviewMode,palettesHidden,+ quickBrushPanelVisible,perspectiveRuler,straightRuler,redo,@@ -1483,6 +1566,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioresetRotation,resetViewFlip,resetZoomAndCenter,+ resetZoomTo100,selection,showCommandBar,showDocumentTabs,@@ -1497,6 +1581,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiotoggleLayerMask,toggleMaskLinked,toggleTone,+ valueCheckEnabled,visiblePanels,zoomIn,zoomOut,diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.tsindex 0a3cc40..4fe9028 100644--- a/src/hooks/useCanvasDrawing.ts+++ b/src/hooks/useCanvasDrawing.ts@@ -1,10 +1,11 @@-import { useRef, useEffect, useCallback } from 'react';+import { useRef, useEffect, useCallback, useState } from 'react';import {LastStrokeEndState,UseCanvasDrawingProps,useBrushStrokeSession,useDrawingHistory,} from './drawing';+import type { QuickShapePreviewState } from '../utils/quickShapeEngine';export type { UseCanvasDrawingProps, PushHistoryStepFn } from './drawing';@@ -53,6 +54,11 @@ export function useCanvasDrawing({const isDrawingRef = useRef(false);const lastStrokeEndRef = useRef<LastStrokeEndState | null>(null);const abortActiveStrokeRef = useRef<() => void>(() => {});+ const [quickShapePreview, setQuickShapePreview] = useState<QuickShapePreviewState | null>(null);+ const onQuickShapePreviewChangeRef = useRef<+ ((preview: QuickShapePreviewState | null) => void) | undefined+ >(setQuickShapePreview);+ onQuickShapePreviewChangeRef.current = setQuickShapePreview;const fallbackPanRef = useRef(pan);const fallbackZoomRef = useRef(zoom);@@ -73,6 +79,7 @@ export function useCanvasDrawing({const activeLayerVisibleRef = useRef(activeLayerVisible);const dimensionsRef = useRef(dimensions);const selectionRef = useRef(selection);+ selectionRef.current = selection;const isMaskModeRef = useRef(isMaskMode);const layersRef = useRef(layers);const onApplyLayerTreeDeltaRef = useRef(onApplyLayerTreeDelta);@@ -196,6 +203,7 @@ export function useCanvasDrawing({rulerRef,straightRulerRef,onActiveConstraintAxisChangeRef,+ onQuickShapePreviewChangeRef,onUpdateLayerThumbnail,onUpdateMaskThumbnailRef,onCollabStrokeStartRef,@@ -230,6 +238,7 @@ export function useCanvasDrawing({clearCanvas: history.clearCanvas,resetHistory: history.resetHistory,selectiveUndo: history.selectiveUndo,+ quickShapePreview,cursorPos: null as { x: number; y: number } | null,currentPressure: 0,isHovering: false,diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.tsindex 075005a..218cda5 100644--- a/src/hooks/useCanvasNavigation.ts+++ b/src/hooks/useCanvasNavigation.ts@@ -2,7 +2,10 @@ import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'import { CanvasDimensions } from '../types/editor';import { toolStoreActions, useToolStore, useUiStore } from '../stores';import { stepBrushSizePreset } from '../utils/brushPresetManager';-import { resolveHeldKeyModifierAction } from '../utils/shortcutManager';+import {+ detectShortcutPlatform,+ resolveHeldKeyModifierAction,+} from '../utils/shortcutManager';export const MIN_ZOOM = 0.01; // 1%export const MAX_ZOOM = 32.0; // 3200%@@ -667,6 +670,10 @@ export function useCanvasNavigation({zoomToViewportCenter(target);}, [zoomToViewportCenter]);+ const resetZoomTo100 = useCallback(() => {+ setZoomLive(1.0, true);+ }, [setZoomLive]);+const startPan = useCallback((e: React.PointerEvent | PointerEvent) => {e.preventDefault();@@ -1102,6 +1109,18 @@ export function useCanvasNavigation({Math.min(500, Math.round(stepBrushSizePreset(toolState.liquifySettings.size, dir))));toolStoreActions.updateLiquifySettings({ size: nextSize });+ } else if (+ toolState.tool === 'fill' &&+ toolState.fillSettings.method === 'paint-unfilled'+ ) {+ const nextSize = Math.max(+ 2,+ Math.min(+ 300,+ Math.round(stepBrushSizePreset(toolState.fillSettings.brushSize ?? 24, dir))+ )+ );+ toolStoreActions.updateFillSettings({ brushSize: nextSize });} else {const nextSize = stepBrushSizePreset(toolState.brushSettings.size, dir);toolStoreActions.updateBrushSettings({ size: nextSize });@@ -1175,9 +1194,15 @@ export function useCanvasNavigation({return;}+ const isMac = detectShortcutPlatform() === 'mac';const nextShift = e.key === 'Shift' ? true : Boolean(e.shiftKey);- const nextCtrl =- e.key === 'Control' || e.key === 'Meta' ? true : Boolean(e.ctrlKey || e.metaKey);+ const nextCtrl = isMac+ ? e.key === 'Control' || e.key === 'Meta'+ ? true+ : Boolean(e.ctrlKey || e.metaKey)+ : e.key === 'Control'+ ? true+ : Boolean(e.ctrlKey);const nextAlt = e.key === 'Alt' ? true : Boolean(e.altKey);syncModifierState(nextShift, nextCtrl, nextAlt);@@ -1192,9 +1217,15 @@ export function useCanvasNavigation({};const handleKeyUp = (e: KeyboardEvent) => {+ const isMac = detectShortcutPlatform() === 'mac';const nextShift = e.key === 'Shift' ? false : Boolean(e.shiftKey);- const nextCtrl =- e.key === 'Control' || e.key === 'Meta' ? false : Boolean(e.ctrlKey || e.metaKey);+ const nextCtrl = isMac+ ? e.key === 'Control' || e.key === 'Meta'+ ? false+ : Boolean(e.ctrlKey || e.metaKey)+ : e.key === 'Control'+ ? false+ : Boolean(e.ctrlKey);const nextAlt = e.key === 'Alt' ? false : Boolean(e.altKey);syncModifierState(nextShift, nextCtrl, nextAlt);@@ -1317,6 +1348,7 @@ export function useCanvasNavigation({zoomOut,zoomToViewportCenter,resetZoomAndCenter,+ resetZoomTo100,resetRotation,rotateBy,toggleFlipHorizontal,diff --git a/src/hooks/useExternalFileDrop.ts b/src/hooks/useExternalFileDrop.tsindex f42836f..5d08e59 100644--- a/src/hooks/useExternalFileDrop.ts+++ b/src/hooks/useExternalFileDrop.ts@@ -1,13 +1,20 @@import { useCallback, useEffect, useRef, useState } from 'react';import {+ ExternalDropZoneKind,+ ExternalFileDropPayloadKind,ExternalFileDropTarget,LayerInsertTarget,MAX_DROPPED_IMAGE_FILES,+ filterDropped3DModelFiles,+ filterDropped3DModelPaths,filterDroppedImageFiles,filterDroppedImagePaths,+ inferHtml5DragPayloadKind,isExternalFileDrag,isSameDropTarget,+ isSupported3DModelExtension,isSupportedImageExtension,+ readTauriDropped3DModelFile,readTauriDroppedImageFile,resolveDropZoneAtPoint,resolveDropZoneFromElement,@@ -19,28 +26,57 @@ interface TauriWindow extends Window {export interface UseExternalFileDropOptions {enabled: boolean;+ is3DModeActive?: boolean;importImageFileAsLayer: (file: File,insertTarget?: LayerInsertTarget) => Promise<{ id: string; name: string }>;+ import3DModelFile?: (file: File) => void | Promise<void>;onMarkDirty: () => void;showToast: (message: string) => void;}export interface UseExternalFileDropResult {activeDropTarget: ExternalFileDropTarget | null;- importDroppedFiles: (files: Iterable<File>, target?: LayerInsertTarget) => Promise<number>;+ importDroppedFiles: (+ files: Iterable<File>,+ target?: LayerInsertTarget,+ dropZone?: ExternalDropZoneKind+ ) => Promise<number>;+}++function applyPayloadKindToTarget(+ resolved: ExternalFileDropTarget | null,+ payloadKind: ExternalFileDropPayloadKind | null+): ExternalFileDropTarget | null {+ if (!resolved || !payloadKind) return null;+ if (payloadKind === '3d-model') {+ if (resolved.zone === 'layers') return null;+ return { ...resolved, payloadKind: '3d-model' };+ }+ if (payloadKind === 'image') {+ if (resolved.zone === '3d-stage') return null;+ return { ...resolved, payloadKind: 'image' };+ }+ if (resolved.zone === 'layers') {+ return { ...resolved, payloadKind: 'image' };+ }+ return { ...resolved, payloadKind: 'any-3d' };}export function useExternalFileDrop({enabled,+ is3DModeActive = false,importImageFileAsLayer,+ import3DModelFile,onMarkDirty,showToast,}: UseExternalFileDropOptions): UseExternalFileDropResult {const [activeDropTarget, setActiveDropTarget] = useState<ExternalFileDropTarget | null>(null);const activeDropTargetRef = useRef<ExternalFileDropTarget | null>(null);- const tauriDragHasImagesRef = useRef<boolean>(true);+ const tauriDragPayloadKindRef = useRef<ExternalFileDropPayloadKind | null>(null);+ const is3DModeActiveRef = useRef<boolean>(is3DModeActive);+ is3DModeActiveRef.current = is3DModeActive;const updateDropTarget = useCallback((next: ExternalFileDropTarget | null) => {if (isSameDropTarget(activeDropTargetRef.current, next)) return;@@ -49,15 +85,50 @@ export function useExternalFileDrop({}, []);const importDroppedFiles = useCallback(- async (rawFiles: Iterable<File>, target?: LayerInsertTarget): Promise<number> => {+ async (+ rawFiles: Iterable<File>,+ target?: LayerInsertTarget,+ dropZone?: ExternalDropZoneKind+ ): Promise<number> => {+ const fileList = Array.from(rawFiles);++ if (import3DModelFile && dropZone !== 'layers') {+ const model3D = filterDropped3DModelFiles(fileList);+ if (model3D.accepted.length > 0) {+ try {+ await import3DModelFile(model3D.accepted[0]);+ return 1;+ } catch (err) {+ console.warn('Dropped 3D model import failed:', err);+ showToast('Failed to import dropped 3D model.');+ return 0;+ }+ }+ if (model3D.oversizedCount > 0) {+ showToast('3D model exceeds 250 MB limit.');+ return 0;+ }+ }++ if (dropZone === '3d-stage') {+ if (fileList.length > 0) {+ showToast('Unsupported file type. Drop a .glb, .gltf, or .obj 3D model.');+ }+ return 0;+ }+const { accepted, rejectedCount, oversizedCount, truncatedCount } =- filterDroppedImageFiles(rawFiles);+ filterDroppedImageFiles(fileList);if (accepted.length === 0) {if (oversizedCount > 0) {showToast('Image exceeds 100 MB limit.');} else if (rejectedCount > 0) {- showToast('Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.');+ showToast(+ is3DModeActiveRef.current+ ? 'Unsupported file type. Drop .glb, .gltf, .obj 3D models or PNG, JPG, WebP, GIF, BMP, SVG images.'+ : 'Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.'+ );}return 0;}@@ -102,15 +173,45 @@ export function useExternalFileDrop({return importedNames.length;},- [importImageFileAsLayer, onMarkDirty, showToast]+ [import3DModelFile, importImageFileAsLayer, onMarkDirty, showToast]);const importDroppedPaths = useCallback(- async (paths: readonly string[], target?: LayerInsertTarget): Promise<number> => {+ async (+ paths: readonly string[],+ target?: LayerInsertTarget,+ dropZone?: ExternalDropZoneKind+ ): Promise<number> => {+ if (import3DModelFile && dropZone !== 'layers') {+ const model3DPaths = filterDropped3DModelPaths(paths);+ if (model3DPaths.accepted.length > 0) {+ try {+ const modelFile = await readTauriDropped3DModelFile(model3DPaths.accepted[0]);+ await import3DModelFile(modelFile);+ return 1;+ } catch (err) {+ console.warn('Failed to read or load dropped 3D model file:', err);+ showToast('Failed to read dropped 3D model file.');+ return 0;+ }+ }+ }++ if (dropZone === '3d-stage') {+ if (paths.length > 0) {+ showToast('Unsupported file type. Drop a .glb, .gltf, or .obj 3D model.');+ }+ return 0;+ }+const { accepted, rejectedCount, truncatedCount } = filterDroppedImagePaths(paths);if (accepted.length === 0) {if (rejectedCount > 0) {- showToast('Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.');+ showToast(+ is3DModeActiveRef.current+ ? 'Unsupported file type. Drop .glb, .gltf, .obj 3D models or PNG, JPG, WebP, GIF, BMP, SVG images.'+ : 'Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.'+ );}return 0;}@@ -172,7 +273,7 @@ export function useExternalFileDrop({return importedNames.length;},- [importImageFileAsLayer, onMarkDirty, showToast]+ [import3DModelFile, importImageFileAsLayer, onMarkDirty, showToast]);// Clear highlight whenever feature disables (e.g., switching to Home view or closing doc)@@ -203,7 +304,9 @@ export function useExternalFileDrop({}e.preventDefault();- const resolved = resolveFromDragEvent(e);+ const rawResolved = resolveFromDragEvent(e);+ const payloadKind = inferHtml5DragPayloadKind(e.dataTransfer, is3DModeActiveRef.current);+ const resolved = applyPayloadKindToTarget(rawResolved, payloadKind);if (e.dataTransfer) {e.dataTransfer.dropEffect = resolved ? 'copy' : 'none';}@@ -239,10 +342,14 @@ export function useExternalFileDrop({const files = e.dataTransfer?.files;if (!files || files.length === 0) return;- void importDroppedFiles(Array.from(files), {- targetLayerId: resolved.targetLayerId,- position: resolved.position,- });+ void importDroppedFiles(+ Array.from(files),+ {+ targetLayerId: resolved.targetLayerId,+ position: resolved.position,+ },+ resolved.zone+ );};window.addEventListener('dragover', handleDragOver);@@ -276,35 +383,57 @@ export function useExternalFileDrop({if (cancelled) return;const payload = event.payload;if (payload.type === 'enter') {- tauriDragHasImagesRef.current =- payload.paths.length === 0 || payload.paths.some(isSupportedImageExtension);- if (!tauriDragHasImagesRef.current) {+ if (payload.paths.length === 0) {+ tauriDragPayloadKindRef.current = is3DModeActiveRef.current ? 'any-3d' : 'image';+ } else if (import3DModelFile && payload.paths.some(isSupported3DModelExtension)) {+ tauriDragPayloadKindRef.current = '3d-model';+ } else if (payload.paths.some(isSupportedImageExtension)) {+ tauriDragPayloadKindRef.current = 'image';+ } else {+ tauriDragPayloadKindRef.current = null;+ }++ if (!tauriDragPayloadKindRef.current) {updateDropTarget(null);return;}const pt = toLogicalPoint(payload.position);- updateDropTarget(resolveDropZoneAtPoint(pt.x, pt.y));+ updateDropTarget(+ applyPayloadKindToTarget(+ resolveDropZoneAtPoint(pt.x, pt.y),+ tauriDragPayloadKindRef.current+ )+ );} else if (payload.type === 'over') {- if (!tauriDragHasImagesRef.current) {+ if (!tauriDragPayloadKindRef.current) {updateDropTarget(null);return;}const pt = toLogicalPoint(payload.position);- updateDropTarget(resolveDropZoneAtPoint(pt.x, pt.y));+ updateDropTarget(+ applyPayloadKindToTarget(+ resolveDropZoneAtPoint(pt.x, pt.y),+ tauriDragPayloadKindRef.current+ )+ );} else if (payload.type === 'leave') {- tauriDragHasImagesRef.current = true;+ tauriDragPayloadKindRef.current = null;updateDropTarget(null);} else if (payload.type === 'drop') {- tauriDragHasImagesRef.current = true;+ tauriDragPayloadKindRef.current = null;const pt = toLogicalPoint(payload.position);const resolved =resolveDropZoneAtPoint(pt.x, pt.y) ?? activeDropTargetRef.current;updateDropTarget(null);if (!resolved || payload.paths.length === 0) return;- void importDroppedPaths(payload.paths, {- targetLayerId: resolved.targetLayerId,- position: resolved.position,- });+ void importDroppedPaths(+ payload.paths,+ {+ targetLayerId: resolved.targetLayerId,+ position: resolved.position,+ },+ resolved.zone+ );}});if (cancelled) {@@ -321,7 +450,7 @@ export function useExternalFileDrop({cancelled = true;unlisten?.();};- }, [enabled, importDroppedPaths, updateDropTarget]);+ }, [enabled, import3DModelFile, importDroppedPaths, updateDropTarget]);return {activeDropTarget,diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.tsindex 25b249e..653381f 100644--- a/src/services/multiplayerService.ts+++ b/src/services/multiplayerService.ts@@ -125,6 +125,7 @@ const TOOL_TYPES_LIST: ToolType[] = ['gradient','retouch','pen',+ 'decoration',];export const DEEP_LINK_SCHEME = 'inkstudio:';diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.tsindex e8ffb38..dbcc8f3 100644--- a/src/services/recoveryService.ts+++ b/src/services/recoveryService.ts@@ -11,6 +11,7 @@ import {VectorStroke,LayerItem,CanvasColorMode,+ InkTimelapseMetadata,} from '../types/editor';import {globalTileGrid,@@ -137,6 +138,7 @@ export interface DocumentManifest {activeLayerId: string;timestamp: number;workTimeMs?: number;+ timelapse?: InkTimelapseMetadata | null;}export interface CrashedSessionInfo {diff --git a/src/stores/index.ts b/src/stores/index.tsindex b7cbddd..1314e5d 100644--- a/src/stores/index.ts+++ b/src/stores/index.ts@@ -41,6 +41,9 @@ export type {export { useWorkspaceStore, workspaceStoreActions } from './useWorkspaceStore';export type { WorkspaceStoreState } from './useWorkspaceStore';+export { useSubToolGroupStore, subToolGroupStoreActions } from './useSubToolGroupStore';+export type { SubToolGroupStoreState } from './useSubToolGroupStore';+export { useSubViewStore, subViewStoreActions } from './useSubViewStore';export type { SubViewStoreState, SubViewImageItem, SubViewTransform } from './useSubViewStore';diff --git a/src/stores/use3DStore.ts b/src/stores/use3DStore.tsindex 54c02d2..ee2ec31 100644--- a/src/stores/use3DStore.ts+++ b/src/stores/use3DStore.ts@@ -9,6 +9,7 @@ import {Tool3DMode,} from '../utils/tool3DRules';import { PosePresetName } from '../utils/mannequin3D';+import { Primitive3DType } from '../utils/primitives3D';import { LTConversionSettings } from '../types/editor';export interface Model3DTransformState {@@ -32,7 +33,8 @@ export interface Scene3DStoreState {snapEnabled: boolean;isReferenceVisible: boolean;loadedModelName: string | null;- modelKind: 'none' | 'imported';+ modelKind: 'none' | 'imported' | 'primitive';+ activePrimitiveType: Primitive3DType | null;isMannequinActive: boolean;activeIKHandle: string | null;showIKHandles: boolean;@@ -69,6 +71,7 @@ const createInitial3DState = (): Scene3DStoreState => ({isReferenceVisible: true,loadedModelName: null,modelKind: 'none',+ activePrimitiveType: null,isMannequinActive: false,activeIKHandle: null,showIKHandles: true,@@ -122,12 +125,14 @@ export const store3DActions = {setLoadedModel(loadedModelName: string | null,- modelKind: 'none' | 'imported',- isMannequinActive: boolean+ modelKind: 'none' | 'imported' | 'primitive',+ isMannequinActive: boolean,+ activePrimitiveType: Primitive3DType | null = null): void {use3DStore.setState({loadedModelName,modelKind,+ activePrimitiveType: modelKind === 'primitive' ? activePrimitiveType : null,isMannequinActive,activeIKHandle: null,});@@ -226,6 +231,7 @@ export const store3DActions = {use3DStore.setState({loadedModelName: null,modelKind: 'none',+ activePrimitiveType: null,isMannequinActive: false,activeIKHandle: null,isBaking: false,@@ -245,6 +251,7 @@ export const store3DActions = {export interface Scene3DCommandBridge {triggerFilePicker?: () => void;loadFile?: (file: File) => void;+ createPrimitive?: (type: Primitive3DType) => void;applyNumericTransform?: (next: Model3DTransformState) => void;applyTransformDelta?: (mode: Tool3DMode, dx: number, dy: number, snap?: boolean) => void;rotateModelYaw?: (degrees: number) => void;diff --git a/src/stores/useDocumentStore.ts b/src/stores/useDocumentStore.tsindex 81ef34f..963c3e1 100644--- a/src/stores/useDocumentStore.ts+++ b/src/stores/useDocumentStore.ts@@ -28,6 +28,7 @@ export interface DocumentStoreState {activeEditTarget: 'layer' | 'mask';savedFileInfo: SavedFileInfo | null;softProofSettings: SoftProofSettings;+ valueCheckEnabled: boolean;animationTimeline: AnimationTimeline | null;perspectiveRuler: PerspectiveRuler | null;straightRuler: StraightRuler | null;@@ -44,6 +45,7 @@ const createInitialDocumentState = (): DocumentStoreState => ({activeEditTarget: 'layer',savedFileInfo: null,softProofSettings: { ...DEFAULT_SOFT_PROOF_SETTINGS },+ valueCheckEnabled: false,animationTimeline: null,perspectiveRuler: null,straightRuler: null,@@ -125,6 +127,16 @@ export const documentStoreActions = {}));},+ toggleValueCheck(): boolean {+ const next = !useDocumentStore.getState().valueCheckEnabled;+ useDocumentStore.setState({ valueCheckEnabled: next });+ return next;+ },++ setValueCheckEnabled(valueCheckEnabled: boolean): void {+ useDocumentStore.setState({ valueCheckEnabled });+ },+setAnimationTimeline(animationTimeline: AnimationTimeline | null): void {useDocumentStore.setState({ animationTimeline });},diff --git a/src/stores/useSubToolGroupStore.ts b/src/stores/useSubToolGroupStore.tsnew file mode 100644index 0000000..eb14582--- /dev/null+++ b/src/stores/useSubToolGroupStore.ts@@ -0,0 +1,483 @@+import { BrushPresetId } from '../types/editor';+import { createStore } from './createStore';+import {+ ActiveDecorationSubToolTab,+ ActiveSubToolGroupTab,+ BrushGroupOverridesMap,+ BuiltinGroupOrdersMap,+ BuiltinTargetGroupId,+ CustomSubToolGroup,+ SubToolGroupIconId,+ SubToolGroupScope,+ createSubToolGroupId,+ getFactoryGroupIdForBrush,+ isBuiltinTargetGroupId,+ isDecorationCustomGroup,+ loadSubToolGroupsState,+ normalizeBrushIdForGroup,+ saveSubToolGroupsState,+} from '../utils/subToolGroups';++export interface SubToolGroupStoreState {+ groups: CustomSubToolGroup[];+ activeTab: ActiveSubToolGroupTab;+ activeDecorationTab: ActiveDecorationSubToolTab;+ brushGroupOverrides: BrushGroupOverridesMap;+ builtinGroupOrders: BuiltinGroupOrdersMap;+}++const createInitialSubToolGroupState = (): SubToolGroupStoreState => {+ const loaded = loadSubToolGroupsState();+ return {+ groups: loaded.groups,+ activeTab: loaded.activeTab,+ activeDecorationTab: loaded.activeDecorationTab ?? 'all',+ brushGroupOverrides: loaded.brushGroupOverrides ?? {},+ builtinGroupOrders: loaded.builtinGroupOrders ?? {},+ };+};++export const useSubToolGroupStore = createStore<SubToolGroupStoreState>(+ createInitialSubToolGroupState+);++function persistCurrentState(): void {+ const s = useSubToolGroupStore.getState();+ saveSubToolGroupsState({+ version: 1,+ groups: s.groups,+ activeTab: s.activeTab,+ activeDecorationTab: s.activeDecorationTab,+ brushGroupOverrides: s.brushGroupOverrides,+ builtinGroupOrders: s.builtinGroupOrders,+ });+}++function stripBrushFromBuiltinOrders(+ orders: BuiltinGroupOrdersMap,+ normBrushId: BrushPresetId,+ keepGroupId?: BuiltinTargetGroupId+): BuiltinGroupOrdersMap {+ let mutated = false;+ const next: BuiltinGroupOrdersMap = { ...orders };+ for (const [gid, list] of Object.entries(orders) as Array<+ [BuiltinTargetGroupId, BrushPresetId[] | undefined]+ >) {+ if (!list || gid === keepGroupId) continue;+ const filtered = list.filter((id) => id !== normBrushId);+ if (filtered.length !== list.length) {+ mutated = true;+ if (filtered.length > 0) next[gid] = filtered;+ else delete next[gid];+ }+ }+ return mutated ? next : orders;+}++function stripBrushFromCustomGroups(+ groups: CustomSubToolGroup[],+ normBrushId: BrushPresetId,+ keepGroupId?: string+): CustomSubToolGroup[] {+ return groups.map((g) => {+ if (g.id === keepGroupId) return g;+ const filtered = g.brushIds.filter((id) => id !== normBrushId);+ if (filtered.length === g.brushIds.length) return g;+ return {+ ...g,+ brushIds: filtered,+ lastActiveBrushId:+ g.lastActiveBrushId && filtered.includes(g.lastActiveBrushId)+ ? g.lastActiveBrushId+ : filtered[0],+ };+ });+}++export const subToolGroupStoreActions = {+ setActiveTab(tab: ActiveSubToolGroupTab): void {+ useSubToolGroupStore.setState({ activeTab: tab });+ persistCurrentState();+ },++ setActiveDecorationTab(tab: ActiveDecorationSubToolTab): void {+ useSubToolGroupStore.setState({ activeDecorationTab: tab });+ persistCurrentState();+ },++ createGroup(options: {+ name?: string;+ color?: string | null;+ icon?: SubToolGroupIconId;+ toolScope?: SubToolGroupScope;+ initialBrushIds?: BrushPresetId[];+ selectTab?: boolean;+ } = {}): CustomSubToolGroup {+ const prev = useSubToolGroupStore.getState();+ const isDecoScope = options.toolScope === 'decoration';+ const sameScopeCount = prev.groups.filter((g) =>+ isDecoScope ? isDecorationCustomGroup(g) : !isDecorationCustomGroup(g)+ ).length;+ const cleanName =+ options.name && options.name.trim().length > 0+ ? options.name.trim().slice(0, 32)+ : `Custom Group ${sameScopeCount + 1}`;++ const initialClean: BrushPresetId[] = [];+ const initialSet = new Set<string>();+ for (const rawId of options.initialBrushIds ?? []) {+ const norm = normalizeBrushIdForGroup(rawId);+ if (norm && !initialSet.has(norm)) {+ initialSet.add(norm);+ initialClean.push(norm);+ }+ }++ const newGroup: CustomSubToolGroup = {+ id: createSubToolGroupId(),+ name: cleanName,+ color: options.color ?? null,+ icon: options.icon ?? 'folder',+ ...(isDecoScope ? { toolScope: 'decoration' as const } : {}),+ brushIds: initialClean,+ lastActiveBrushId: initialClean[0],+ createdAt: Date.now(),+ };++ let nextOverrides = prev.brushGroupOverrides;+ let nextBuiltinOrders = prev.builtinGroupOrders;+ let updatedExisting = prev.groups;++ if (initialSet.size > 0) {+ nextOverrides = { ...prev.brushGroupOverrides };+ for (const id of initialClean) {+ delete nextOverrides[id];+ nextBuiltinOrders = stripBrushFromBuiltinOrders(nextBuiltinOrders, id);+ updatedExisting = stripBrushFromCustomGroups(updatedExisting, id);+ }+ }++ useSubToolGroupStore.setState({+ groups: [...updatedExisting, newGroup],+ activeTab: !isDecoScope && options.selectTab !== false ? newGroup.id : prev.activeTab,+ activeDecorationTab:+ isDecoScope && options.selectTab !== false ? newGroup.id : prev.activeDecorationTab,+ brushGroupOverrides: nextOverrides,+ builtinGroupOrders: nextBuiltinOrders,+ });+ persistCurrentState();+ return newGroup;+ },++ renameGroup(groupId: string, newName: string): void {+ const trimmed = newName.trim().slice(0, 32);+ if (!trimmed) return;+ useSubToolGroupStore.setState((prev) => ({+ groups: prev.groups.map((g) => (g.id === groupId ? { ...g, name: trimmed } : g)),+ }));+ persistCurrentState();+ },++ updateGroupAppearance(+ groupId: string,+ patch: { color?: string | null; icon?: SubToolGroupIconId }+ ): void {+ useSubToolGroupStore.setState((prev) => ({+ groups: prev.groups.map((g) => (g.id === groupId ? { ...g, ...patch } : g)),+ }));+ persistCurrentState();+ },++ deleteGroup(groupId: string): void {+ useSubToolGroupStore.setState((prev) => {+ const groups = prev.groups.filter((g) => g.id !== groupId);+ const activeTab = prev.activeTab === groupId ? 'all' : prev.activeTab;+ const activeDecorationTab =+ prev.activeDecorationTab === groupId ? 'all' : prev.activeDecorationTab;+ return { groups, activeTab, activeDecorationTab };+ });+ persistCurrentState();+ },++ moveGroup(groupId: string, direction: -1 | 1): void {+ useSubToolGroupStore.setState((prev) => {+ const idx = prev.groups.findIndex((g) => g.id === groupId);+ if (idx < 0) return prev;+ const targetScope = isDecorationCustomGroup(prev.groups[idx]);+ let swapIdx = idx + direction;+ while (+ swapIdx >= 0 &&+ swapIdx < prev.groups.length &&+ isDecorationCustomGroup(prev.groups[swapIdx]) !== targetScope+ ) {+ swapIdx += direction;+ }+ if (swapIdx < 0 || swapIdx >= prev.groups.length) return prev;+ const copy = [...prev.groups];+ const [moved] = copy.splice(idx, 1);+ copy.splice(swapIdx, 0, moved);+ return { groups: copy };+ });+ persistCurrentState();+ },++ reorderGroup(draggedGroupId: string, targetGroupId: string): void {+ if (!draggedGroupId || !targetGroupId || draggedGroupId === targetGroupId) return;+ useSubToolGroupStore.setState((prev) => {+ const fromIdx = prev.groups.findIndex((g) => g.id === draggedGroupId);+ const toIdx = prev.groups.findIndex((g) => g.id === targetGroupId);+ if (fromIdx < 0 || toIdx < 0) return prev;+ const copy = [...prev.groups];+ const [moved] = copy.splice(fromIdx, 1);+ copy.splice(toIdx, 0, moved);+ return { groups: copy };+ });+ persistCurrentState();+ },++ /**+ * Moves ANY brush (built-in or custom) into ANY target group — whether a user Custom SubTool Group+ * OR a built-in group ('pen', 'sketch', 'brush', 'blend', 'natural-paint', 'custom').+ */+ moveBrushToGroup(+ presetId: BrushPresetId,+ targetGroupId: string,+ insertIndex?: number,+ existingTargetOrder?: readonly BrushPresetId[]+ ): boolean {+ const norm = normalizeBrushIdForGroup(presetId);+ if (!norm) return false;+ const state = useSubToolGroupStore.getState();++ // Case 1: Target is a built-in / Imported group+ if (isBuiltinTargetGroupId(targetGroupId)) {+ const nextGroups = stripBrushFromCustomGroups(state.groups, norm);+ const nextOverrides: BrushGroupOverridesMap = { ...state.brushGroupOverrides };+ const factoryGroup = getFactoryGroupIdForBrush(norm);+ if (targetGroupId === factoryGroup) {+ delete nextOverrides[norm];+ } else {+ nextOverrides[norm] = targetGroupId;+ }++ let nextBuiltinOrders = stripBrushFromBuiltinOrders(+ state.builtinGroupOrders,+ norm,+ targetGroupId+ );+ const baseList = existingTargetOrder+ ? existingTargetOrder+ .map((id) => normalizeBrushIdForGroup(id))+ .filter((id): id is BrushPresetId => Boolean(id && id !== norm))+ : (nextBuiltinOrders[targetGroupId] ?? []).filter((id) => id !== norm);++ if (insertIndex !== undefined && Number.isFinite(insertIndex)) {+ const clamped = Math.max(0, Math.min(baseList.length, Math.round(insertIndex)));+ baseList.splice(clamped, 0, norm);+ nextBuiltinOrders = { ...nextBuiltinOrders, [targetGroupId]: baseList };+ } else if (existingTargetOrder || nextBuiltinOrders[targetGroupId]) {+ baseList.push(norm);+ nextBuiltinOrders = { ...nextBuiltinOrders, [targetGroupId]: baseList };+ }++ useSubToolGroupStore.setState({+ groups: nextGroups,+ brushGroupOverrides: nextOverrides,+ builtinGroupOrders: nextBuiltinOrders,+ });+ persistCurrentState();+ return true;+ }++ // Case 2: Target is a Custom SubTool Group+ if (!state.groups.some((g) => g.id === targetGroupId)) return false;++ const nextOverrides: BrushGroupOverridesMap = { ...state.brushGroupOverrides };+ delete nextOverrides[norm];+ const nextBuiltinOrders = stripBrushFromBuiltinOrders(state.builtinGroupOrders, norm);++ const nextGroups = state.groups.map((g) => {+ const without = g.brushIds.filter((id) => id !== norm);+ if (g.id !== targetGroupId) {+ if (without.length === g.brushIds.length) return g;+ return {+ ...g,+ brushIds: without,+ lastActiveBrushId:+ g.lastActiveBrushId && without.includes(g.lastActiveBrushId)+ ? g.lastActiveBrushId+ : without[0],+ };+ }+ const nextIds = [...without];+ if (insertIndex !== undefined && Number.isFinite(insertIndex)) {+ const clamped = Math.max(0, Math.min(nextIds.length, Math.round(insertIndex)));+ nextIds.splice(clamped, 0, norm);+ } else {+ nextIds.push(norm);+ }+ return {+ ...g,+ brushIds: nextIds,+ lastActiveBrushId: g.lastActiveBrushId ?? norm,+ };+ });++ useSubToolGroupStore.setState({+ groups: nextGroups,+ brushGroupOverrides: nextOverrides,+ builtinGroupOrders: nextBuiltinOrders,+ });+ persistCurrentState();+ return true;+ },++ /**+ * Moves & places `draggedBrushId` right before or after `targetBrushId` inside ANY group+ * (custom SubTool group OR built-in / Imported section).+ */+ reorderBrushInGroup(+ groupId: string,+ draggedBrushId: BrushPresetId,+ targetBrushId: BrushPresetId,+ position?: 'before' | 'after',+ visibleGroupBrushIds?: readonly BrushPresetId[]+ ): void {+ const fromId = normalizeBrushIdForGroup(draggedBrushId);+ const toId = normalizeBrushIdForGroup(targetBrushId);+ if (!fromId || !toId || fromId === toId) return;++ const state = useSubToolGroupStore.getState();++ // Case 1: Built-in / Imported group+ if (isBuiltinTargetGroupId(groupId)) {+ const currentOrder = (visibleGroupBrushIds ?? state.builtinGroupOrders[groupId] ?? [])+ .map((id) => normalizeBrushIdForGroup(id))+ .filter((id): id is BrushPresetId => Boolean(id));+ const origFromIdx = currentOrder.indexOf(fromId);+ const origToIdx = currentOrder.indexOf(toId);+ const without = currentOrder.filter((id) => id !== fromId);+ const adjustedToIdx = without.indexOf(toId);+ let insertIdx: number;+ if (adjustedToIdx < 0) {+ insertIdx = without.length;+ } else if (position === 'before') {+ insertIdx = adjustedToIdx;+ } else if (position === 'after') {+ insertIdx = adjustedToIdx + 1;+ } else {+ insertIdx = origFromIdx >= 0 && origFromIdx < origToIdx ? adjustedToIdx + 1 : adjustedToIdx;+ }+ subToolGroupStoreActions.moveBrushToGroup(fromId, groupId, insertIdx, currentOrder);+ return;+ }++ // Case 2: Custom group+ const targetGroup = state.groups.find((g) => g.id === groupId);+ if (!targetGroup) return;+ const origFromIdx = targetGroup.brushIds.indexOf(fromId);+ const origToIdx = targetGroup.brushIds.indexOf(toId);+ if (origToIdx < 0) return;++ const without = targetGroup.brushIds.filter((id) => id !== fromId);+ const adjustedToIdx = without.indexOf(toId);+ let insertIdx: number;+ if (adjustedToIdx < 0) {+ insertIdx = without.length;+ } else if (position === 'before') {+ insertIdx = adjustedToIdx;+ } else if (position === 'after') {+ insertIdx = adjustedToIdx + 1;+ } else {+ insertIdx = origFromIdx >= 0 && origFromIdx < origToIdx ? adjustedToIdx + 1 : adjustedToIdx;+ }++ subToolGroupStoreActions.moveBrushToGroup(fromId, groupId, insertIdx);+ },++ /**+ * Removes a brush from all custom groups AND clears any built-in group override,+ * returning it to its original factory section (or cleaning up on brush deletion).+ */+ removeBrushFromAllGroups(presetId: BrushPresetId): boolean {+ const norm = normalizeBrushIdForGroup(presetId);+ if (!norm) return false;+ const prev = useSubToolGroupStore.getState();++ let changed = false;+ const nextGroups = prev.groups.map((g) => {+ const filtered = g.brushIds.filter((id) => id !== norm && id !== presetId);+ if (filtered.length === g.brushIds.length) return g;+ changed = true;+ return {+ ...g,+ brushIds: filtered,+ lastActiveBrushId:+ g.lastActiveBrushId && filtered.includes(g.lastActiveBrushId)+ ? g.lastActiveBrushId+ : filtered[0],+ };+ });++ const nextOverrides = { ...prev.brushGroupOverrides };+ if (Object.prototype.hasOwnProperty.call(nextOverrides, norm)) {+ delete nextOverrides[norm];+ changed = true;+ }+ if (Object.prototype.hasOwnProperty.call(nextOverrides, presetId)) {+ delete nextOverrides[presetId];+ changed = true;+ }++ const nextOrders = stripBrushFromBuiltinOrders(prev.builtinGroupOrders, norm);+ if (nextOrders !== prev.builtinGroupOrders) {+ changed = true;+ }++ if (changed) {+ useSubToolGroupStore.setState({+ groups: nextGroups,+ brushGroupOverrides: nextOverrides,+ builtinGroupOrders: nextOrders,+ });+ persistCurrentState();+ }+ return changed;+ },++ recordActiveBrush(presetId: BrushPresetId): void {+ const norm = normalizeBrushIdForGroup(presetId);+ if (!norm) return;+ const state = useSubToolGroupStore.getState();+ const owner = state.groups.find((g) => g.brushIds.includes(norm));+ if (!owner || owner.lastActiveBrushId === norm) return;+ useSubToolGroupStore.setState({+ groups: state.groups.map((g) =>+ g.id === owner.id ? { ...g, lastActiveBrushId: norm } : g+ ),+ });+ persistCurrentState();+ },++ reloadFromStorage(): void {+ const loaded = loadSubToolGroupsState();+ useSubToolGroupStore.setState({+ groups: loaded.groups,+ activeTab: loaded.activeTab,+ activeDecorationTab: loaded.activeDecorationTab ?? 'all',+ brushGroupOverrides: loaded.brushGroupOverrides ?? {},+ builtinGroupOrders: loaded.builtinGroupOrders ?? {},+ });+ },++ resetAllGroups(): void {+ useSubToolGroupStore.setState({+ groups: [],+ activeTab: 'all',+ activeDecorationTab: 'all',+ brushGroupOverrides: {},+ builtinGroupOrders: {},+ });+ persistCurrentState();+ },+};diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.tsindex 580fbae..0dbf196 100644--- a/src/stores/useToolStore.ts+++ b/src/stores/useToolStore.ts@@ -18,16 +18,31 @@ import {Point2D,} from '../types/editor';import { DEFAULT_SHAPE_SETTINGS } from '../utils/shapeEngine';-import { DEFAULT_GRADIENT_SETTINGS } from '../utils/gradientEngine';+import {+ DEFAULT_GRADIENT_SETTINGS,+ getSelectedMeshNodeIndices,+ invertGradientMeshSelection,+ rotateGradientMeshVertices,+ selectAllGradientMeshNodes,+ setGradientMeshRotation,+ setGradientMeshSelection,+ updateGradientMeshNodes,+} from '../utils/gradientEngine';import { DEFAULT_RETOUCH_SETTINGS } from '../utils/retouchEngine';import {saveBrushSettingsDebounced,getEffectiveBrushSettings,getActivePresetId,saveActivePresetId,+ getActiveDecorationPresetId,+ saveActiveDecorationPresetId,ERASER_PRESET_ID,DEFAULT_BRUSH_PRESET_ID,} from '../utils/brushPresetManager';+import {+ DEFAULT_DECORATION_PRESET_ID,+ prewarmDecorationBrushAssets,+} from '../utils/presetBrushes';import { enforceColorMode } from '../utils/colorUtils';import { safeLocalStorageSetItem } from '../utils/safeStorage';import { createStore } from './createStore';@@ -45,8 +60,12 @@ export interface QuickModifiersState {export interface ToolStoreState {tool: ToolType;activePresetId: BrushPresetId;+ activeBrushPresetId: BrushPresetId;+ activeDecorationPresetId: BrushPresetId;+ lastPaintTool: 'brush' | 'decoration';brushSettings: BrushSettings;lastBrushSettings: BrushSettings | null;+ lastDecorationSettings: BrushSettings | null;primaryColor: string;secondaryColor: string;isTransparentColor: boolean;@@ -199,11 +218,16 @@ function loadInitialPenSettings(): PenToolSettings {const createInitialToolState = (): ToolStoreState => {const { presetId, brushSettings } = createInitialBrushSettings();+ const decorationPresetId = getActiveDecorationPresetId();return {tool: 'brush',activePresetId: presetId,+ activeBrushPresetId: presetId,+ activeDecorationPresetId: decorationPresetId,+ lastPaintTool: 'brush',brushSettings,lastBrushSettings: brushSettings,+ lastDecorationSettings: null,primaryColor: '#000000',secondaryColor: '#ffffff',isTransparentColor: false,@@ -223,6 +247,12 @@ const createInitialToolState = (): ToolStoreState => {fillSettings: {method: 'refer-all',tolerance: 32,+ opacity: 1,+ smartReferMode: 'refer-reference',+ encloseTarget: 'all-enclosed',+ smartCloseGap: 10,+ smartAreaScale: 1,+ brushSize: 24,},textSettings: {text: '',@@ -285,11 +315,11 @@ function isValidBrushPresetId(presetId?: string | null): presetId is BrushPreset}function resolveBrushPresetId(state: ToolStoreState): BrushPresetId {- if (isValidBrushPresetId(state.activePresetId)) {- return state.activePresetId;+ if (isValidBrushPresetId(state.activeBrushPresetId)) {+ return state.activeBrushPresetId;}- if (isValidBrushPresetId(state.brushSettings.preset)) {- return state.brushSettings.preset;+ if (state.tool !== 'decoration' && isValidBrushPresetId(state.activePresetId)) {+ return state.activePresetId;}if (isValidBrushPresetId(state.lastBrushSettings?.preset)) {return state.lastBrushSettings.preset;@@ -297,14 +327,37 @@ function resolveBrushPresetId(state: ToolStoreState): BrushPresetId {return getActivePresetId();}+function resolveDecorationPresetId(state: ToolStoreState): BrushPresetId {+ if (isValidBrushPresetId(state.activeDecorationPresetId)) {+ return state.activeDecorationPresetId;+ }+ if (state.tool === 'decoration' && isValidBrushPresetId(state.activePresetId)) {+ return state.activePresetId;+ }+ if (isValidBrushPresetId(state.lastDecorationSettings?.preset)) {+ return state.lastDecorationSettings.preset;+ }+ return getActiveDecorationPresetId() || DEFAULT_DECORATION_PRESET_ID;+}++function resolveCurrentPaintPresetId(state: ToolStoreState): BrushPresetId {+ if (state.tool === 'decoration') {+ return resolveDecorationPresetId(state);+ }+ return resolveBrushPresetId(state);+}+function buildRestoredBrushSettings(state: ToolStoreState,- presetId: BrushPresetId+ presetId: BrushPresetId,+ snapshotOverride?: BrushSettings | null): BrushSettings {const effective = getEffectiveBrushSettings(presetId);+ const candidateSnapshot =+ snapshotOverride !== undefined ? snapshotOverride : state.lastBrushSettings;const snapshot =- state.lastBrushSettings && state.lastBrushSettings.preset === presetId- ? state.lastBrushSettings+ candidateSnapshot && candidateSnapshot.preset === presetId+ ? candidateSnapshot: null;// If getEffectiveBrushSettings couldn't resolve a custom brush from storage/cache@@ -348,16 +401,30 @@ export const toolStoreActions = {}if (prevTool === newTool) return;- if (newTool === 'eraser') {- const preservedPresetId = resolveBrushPresetId(state);- const preservedBrushSettings = isValidBrushPresetId(state.brushSettings.preset)+ const savedBrushSettings =+ prevTool === 'brush' && isValidBrushPresetId(state.brushSettings.preset)? state.brushSettings: state.lastBrushSettings;+ const savedDecoSettings =+ prevTool === 'decoration' && isValidBrushPresetId(state.brushSettings.preset)+ ? state.brushSettings+ : state.lastDecorationSettings;+ const nextLastPaintTool: 'brush' | 'decoration' =+ prevTool === 'decoration'+ ? 'decoration'+ : prevTool === 'brush'+ ? 'brush'+ : state.lastPaintTool;++ if (newTool === 'eraser') {+ const preservedPresetId = resolveCurrentPaintPresetId(state);const eraserSettings = getEffectiveBrushSettings(ERASER_PRESET_ID);useToolStore.setState({tool: newTool,activePresetId: preservedPresetId,- lastBrushSettings: preservedBrushSettings,+ lastPaintTool: nextLastPaintTool,+ lastBrushSettings: savedBrushSettings,+ lastDecorationSettings: savedDecoSettings,brushSettings: {...state.brushSettings,...eraserSettings,@@ -370,25 +437,72 @@ export const toolStoreActions = {return;}- const activePreset = resolveBrushPresetId(state);+ if (newTool === 'decoration') {+ prewarmDecorationBrushAssets();+ const decoPreset = resolveDecorationPresetId(state);+ const restoredDeco = buildRestoredBrushSettings(state, decoPreset, savedDecoSettings);+ const resolvedDecoId = (restoredDeco.preset || decoPreset) as BrushPresetId;+ useToolStore.setState({+ tool: 'decoration',+ activePresetId: resolvedDecoId,+ activeDecorationPresetId: resolvedDecoId,+ lastPaintTool: 'decoration',+ brushSettings: restoredDeco,+ lastBrushSettings: savedBrushSettings,+ lastDecorationSettings: restoredDeco,+ });+ return;+ }++ if (newTool === 'brush') {+ const brushPreset = resolveBrushPresetId(state);+ const restoredBrush = buildRestoredBrushSettings(state, brushPreset, savedBrushSettings);+ const resolvedBrushId = (restoredBrush.preset || brushPreset) as BrushPresetId;+ useToolStore.setState({+ tool: 'brush',+ activePresetId: resolvedBrushId,+ activeBrushPresetId: resolvedBrushId,+ lastPaintTool: 'brush',+ brushSettings: restoredBrush,+ lastBrushSettings: restoredBrush,+ lastDecorationSettings: savedDecoSettings,+ });+ return;+ }+const needsBrushRestore =prevTool === 'eraser' ||state.brushSettings.preset === ERASER_PRESET_ID ||- state.brushSettings.preset === 'eraser' ||- (newTool === 'brush' && state.brushSettings.preset !== activePreset);+ state.brushSettings.preset === 'eraser';if (needsBrushRestore) {- const restoredBrush = buildRestoredBrushSettings(state, activePreset);+ const targetIsDeco = nextLastPaintTool === 'decoration';+ const activePreset = targetIsDeco+ ? resolveDecorationPresetId(state)+ : resolveBrushPresetId(state);+ const restored = buildRestoredBrushSettings(+ state,+ activePreset,+ targetIsDeco ? savedDecoSettings : savedBrushSettings+ );+ const resolvedId = (restored.preset || activePreset) as BrushPresetId;useToolStore.setState({tool: newTool,- activePresetId: (restoredBrush.preset || activePreset) as BrushPresetId,- brushSettings: restoredBrush,- lastBrushSettings: restoredBrush,+ activePresetId: resolvedId,+ lastPaintTool: nextLastPaintTool,+ brushSettings: restored,+ lastBrushSettings: targetIsDeco ? savedBrushSettings : restored,+ lastDecorationSettings: targetIsDeco ? restored : savedDecoSettings,});return;}- useToolStore.setState({ tool: newTool });+ useToolStore.setState({+ tool: newTool,+ lastPaintTool: nextLastPaintTool,+ lastBrushSettings: savedBrushSettings,+ lastDecorationSettings: savedDecoSettings,+ });},setToolRaw(tool: ToolType): void {@@ -398,25 +512,40 @@ export const toolStoreActions = {updateBrushSettings(newSettings: Partial<BrushSettings>): void {const state = useToolStore.getState();const isEraser = state.tool === 'eraser';+ const isDeco = state.tool === 'decoration';const next: BrushSettings = { ...state.brushSettings, ...newSettings };const nextValidPreset = isValidBrushPresetId(next.preset) ? next.preset : null;const targetPresetId = isEraser? ERASER_PRESET_ID- : nextValidPreset || resolveBrushPresetId(state);+ : nextValidPreset || resolveCurrentPaintPresetId(state);saveBrushSettingsDebounced(targetPresetId, next);- if (!isEraser && nextValidPreset && state.tool === 'brush') {- saveActivePresetId(nextValidPreset);+ if (!isEraser && nextValidPreset) {+ if (isDeco) {+ saveActiveDecorationPresetId(nextValidPreset);+ } else if (state.tool === 'brush') {+ saveActivePresetId(nextValidPreset);+ }}useToolStore.setState({brushSettings: next,activePresetId:- !isEraser && nextValidPreset && state.tool === 'brush'+ !isEraser && nextValidPreset && (state.tool === 'brush' || isDeco)? nextValidPreset: state.activePresetId,+ activeBrushPresetId:+ !isEraser && nextValidPreset && state.tool === 'brush'+ ? nextValidPreset+ : state.activeBrushPresetId,+ activeDecorationPresetId:+ !isEraser && nextValidPreset && isDeco+ ? nextValidPreset+ : state.activeDecorationPresetId,lastBrushSettings:- !isEraser && nextValidPreset ? next : state.lastBrushSettings,+ !isEraser && !isDeco && nextValidPreset ? next : state.lastBrushSettings,+ lastDecorationSettings:+ !isEraser && isDeco && nextValidPreset ? next : state.lastDecorationSettings,});},@@ -434,6 +563,7 @@ export const toolStoreActions = {const effective = enforceColorMode(color, mode);const state = useToolStore.getState();const isEraser = state.tool === 'eraser';+ const isDeco = state.tool === 'decoration';const nextBrush: BrushSettings = {...state.brushSettings,@@ -444,7 +574,7 @@ export const toolStoreActions = {? ERASER_PRESET_ID: isValidBrushPresetId(nextBrush.preset)? nextBrush.preset- : resolveBrushPresetId(state);+ : resolveCurrentPaintPresetId(state);saveBrushSettingsDebounced(targetPresetId, nextBrush);const nextRecent = commit@@ -454,19 +584,40 @@ export const toolStoreActions = {].slice(0, 14): state.recentColors;+ let nextActiveGradientMesh = state.activeGradientMesh;+ if (+ state.tool === 'gradient' &&+ state.gradientSettings.type === 'mesh' &&+ state.activeGradientMesh+ ) {+ const selectedMeshIndices = getSelectedMeshNodeIndices(state.activeGradientMesh);+ if (selectedMeshIndices.length > 0) {+ nextActiveGradientMesh = updateGradientMeshNodes(+ state.activeGradientMesh,+ selectedMeshIndices,+ { color: effective }+ );+ }+ }+useToolStore.setState({primaryColor: effective,isTransparentColor: false,brushSettings: nextBrush,lastBrushSettings:- !isEraser && isValidBrushPresetId(nextBrush.preset)+ !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)? nextBrush: state.lastBrushSettings,+ lastDecorationSettings:+ !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)+ ? nextBrush+ : state.lastDecorationSettings,recentColors: nextRecent,+ activeGradientMesh: nextActiveGradientMesh,});if (isEraser) {- toolStoreActions.selectTool('brush');+ toolStoreActions.selectTool(state.lastPaintTool || 'brush');}},@@ -475,6 +626,7 @@ export const toolStoreActions = {const effective = enforceColorMode(color, mode);const state = useToolStore.getState();const isEraser = state.tool === 'eraser';+ const isDeco = state.tool === 'decoration';const nextBrush: BrushSettings = {...state.brushSettings,@@ -484,7 +636,7 @@ export const toolStoreActions = {? ERASER_PRESET_ID: isValidBrushPresetId(nextBrush.preset)? nextBrush.preset- : resolveBrushPresetId(state);+ : resolveCurrentPaintPresetId(state);saveBrushSettingsDebounced(targetPresetId, nextBrush);const nextRecent = commit@@ -498,9 +650,13 @@ export const toolStoreActions = {secondaryColor: effective,brushSettings: nextBrush,lastBrushSettings:- !isEraser && isValidBrushPresetId(nextBrush.preset)+ !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)? nextBrush: state.lastBrushSettings,+ lastDecorationSettings:+ !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)+ ? nextBrush+ : state.lastDecorationSettings,recentColors: nextRecent,});},@@ -509,6 +665,7 @@ export const toolStoreActions = {const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;const state = useToolStore.getState();const isEraser = state.tool === 'eraser';+ const isDeco = state.tool === 'decoration';const prevPrimary = state.primaryColor;const effectivePrimary = enforceColorMode(state.secondaryColor, mode);const nextBrush: BrushSettings = {@@ -521,7 +678,7 @@ export const toolStoreActions = {? ERASER_PRESET_ID: isValidBrushPresetId(nextBrush.preset)? nextBrush.preset- : resolveBrushPresetId(state);+ : resolveCurrentPaintPresetId(state);saveBrushSettingsDebounced(targetPresetId, nextBrush);const nextRecent = [@@ -537,20 +694,25 @@ export const toolStoreActions = {isTransparentColor: false,brushSettings: nextBrush,lastBrushSettings:- !isEraser && isValidBrushPresetId(nextBrush.preset)+ !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)? nextBrush: state.lastBrushSettings,+ lastDecorationSettings:+ !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)+ ? nextBrush+ : state.lastDecorationSettings,recentColors: nextRecent,});if (isEraser) {- toolStoreActions.selectTool('brush');+ toolStoreActions.selectTool(state.lastPaintTool || 'brush');}},toggleTransparentColor(): boolean {const state = useToolStore.getState();const isEraser = state.tool === 'eraser';+ const isDeco = state.tool === 'decoration';const next = !state.isTransparentColor;const nextBrush: BrushSettings = {...state.brushSettings,@@ -560,16 +722,20 @@ export const toolStoreActions = {? ERASER_PRESET_ID: isValidBrushPresetId(nextBrush.preset)? nextBrush.preset- : resolveBrushPresetId(state);+ : resolveCurrentPaintPresetId(state);saveBrushSettingsDebounced(targetPresetId, nextBrush);useToolStore.setState({isTransparentColor: next,brushSettings: nextBrush,lastBrushSettings:- !isEraser && isValidBrushPresetId(nextBrush.preset)+ !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)? nextBrush: state.lastBrushSettings,+ lastDecorationSettings:+ !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)+ ? nextBrush+ : state.lastDecorationSettings,});return next;},@@ -674,15 +840,58 @@ export const toolStoreActions = {},updateActiveGradientMeshNode(index: number, patch: { color?: string; opacity?: number }): void {+ toolStoreActions.updateActiveGradientMeshNodes([index], patch);+ },++ updateActiveGradientMeshNodes(+ indices: readonly number[],+ patch: { color?: string; opacity?: number }+ ): void {useToolStore.setState((prev) => {const mesh = prev.activeGradientMesh;- if (!mesh || index < 0 || index >= mesh.nodes.length) return prev;- return {- activeGradientMesh: {- ...mesh,- nodes: mesh.nodes.map((n, i) => (i === index ? { ...n, ...patch } : n)),- },- };+ if (!mesh || indices.length === 0) return prev;+ const updated = updateGradientMeshNodes(mesh, indices, patch);+ return updated === mesh ? prev : { activeGradientMesh: updated };+ });+ },++ rotateActiveGradientMesh(deltaDeg: number): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh) return prev;+ return { activeGradientMesh: rotateGradientMeshVertices(mesh, deltaDeg) };+ });+ },++ setActiveGradientMeshRotation(targetDeg: number): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh) return prev;+ return { activeGradientMesh: setGradientMeshRotation(mesh, targetDeg) };+ });+ },++ selectAllActiveGradientMeshNodes(): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh) return prev;+ return { activeGradientMesh: selectAllGradientMeshNodes(mesh) };+ });+ },++ clearActiveGradientMeshSelection(): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh) return prev;+ return { activeGradientMesh: setGradientMeshSelection(mesh, []) };+ });+ },++ invertActiveGradientMeshSelection(): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh) return prev;+ return { activeGradientMesh: invertGradientMeshSelection(mesh) };});},diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.tsindex db7d9f4..7bd0bcc 100644--- a/src/stores/useUiStore.ts+++ b/src/stores/useUiStore.ts@@ -4,6 +4,7 @@ import { CrashedSessionInfo } from '../services/recoveryService';import { TonalCorrectionType, ProcessingBounds, TileHistogramMap } from '../utils/tonalEngine';import type { TileSnapshotEntry } from '../utils/tileEngine';import { performanceManager } from '../utils/performanceManager';+import { applyInterfaceScale } from '../utils/interfaceScale';import { safeLocalStorageSetItem, setStorageQuotaNotifier } from '../utils/safeStorage';import { createStore } from './createStore';import { useUpdaterStore } from './useUpdaterStore';@@ -161,6 +162,7 @@ function readStoredNumber(key: string, fallback: number): number {const createInitialUiState = (): UiStoreState => {const initialSettings = loadAppSettings();performanceManager.applySettings(initialSettings);+ void applyInterfaceScale(initialSettings.interfaceScale);return {appView: 'workspace',leftPanelWidth: readStoredNumber('ink_left_panel_width_v3', 118),@@ -261,6 +263,7 @@ export const uiStoreActions = {updateAppSettings(newSettings: AppSettings): void {performanceManager.applySettings(newSettings);+ void applyInterfaceScale(newSettings.interfaceScale);useUiStore.setState({ appSettings: newSettings });saveAppSettings(newSettings);},diff --git a/src/stores/useWorkspaceStore.ts b/src/stores/useWorkspaceStore.tsindex bb75621..ab53ae9 100644--- a/src/stores/useWorkspaceStore.ts+++ b/src/stores/useWorkspaceStore.ts@@ -1,20 +1,31 @@+import { BrushPresetId } from '../types/editor';import {CommandActionId,DockPanelId,+ NavigatorPreviewMode,PersistedWorkspaceState,QuickAccessItem,QuickAccessViewMode,+ QuickBrushPanelOrientation,+ QuickBrushPanelState,WorkspaceLayout,WorkspacePresetId,} from '../types/workspace';+import {+ clampNavigatorSplitRatio,+ DEFAULT_NAVIGATOR_SPLIT_RATIO,+ nextNavigatorPreviewMode,+} from '../utils/valueCheck';import {DEFAULT_COMMAND_BAR_IDS,DEFAULT_QUICK_ACCESS_ITEMS,+ DEFAULT_QUICK_BRUSH_IDS,DetachPanelOptions,MovePanelTarget,bringFloatingPanelToFrontInLayout,cloneLayout,closeFloatingPanelInLayout,+ createDefaultQuickBrushPanelState,detachPanelToFloatingInLayout,dockFloatingPanelInLayout,getPresetLayout,@@ -33,6 +44,7 @@ import {toggleGroupCollapsedInLayout,togglePanelInLayout,} from '../utils/workspacePresets';+import { migrateLegacyPresetId } from '../utils/brushPresetManager';import { createStore } from './createStore';import { useUiStore } from './useUiStore';@@ -44,10 +56,13 @@ export interface WorkspaceStoreState {openPopover: { colId: string; panelId: DockPanelId } | null;quickAccessItems: QuickAccessItem[];quickAccessViewMode: QuickAccessViewMode;+ quickBrushPanel: QuickBrushPanelState;commandBarIds: CommandActionId[];showStatusBar: boolean;showDocumentTabs: boolean;showCommandBar: boolean;+ navigatorPreviewMode: NavigatorPreviewMode;+ navigatorSplitRatio: number;migratedPanels?: DockPanelId[];}@@ -61,10 +76,13 @@ const createInitialWorkspaceState = (): WorkspaceStoreState => {openPopover: null,quickAccessItems: loaded.quickAccessItems,quickAccessViewMode: loaded.quickAccessViewMode,+ quickBrushPanel: loaded.quickBrushPanel ?? createDefaultQuickBrushPanelState(),commandBarIds: loaded.commandBarIds,showStatusBar: loaded.showStatusBar,showDocumentTabs: loaded.showDocumentTabs,showCommandBar: loaded.showCommandBar,+ navigatorPreviewMode: loaded.navigatorPreviewMode ?? 'color',+ navigatorSplitRatio: loaded.navigatorSplitRatio ?? DEFAULT_NAVIGATOR_SPLIT_RATIO,migratedPanels: loaded.migratedPanels,};};@@ -80,10 +98,13 @@ function persistCurrentWorkspace(): void {savedCustomLayout: s.savedCustomLayout,quickAccessItems: s.quickAccessItems,quickAccessViewMode: s.quickAccessViewMode,+ quickBrushPanel: s.quickBrushPanel,commandBarIds: s.commandBarIds,showStatusBar: s.showStatusBar,showDocumentTabs: s.showDocumentTabs,showCommandBar: s.showCommandBar,+ navigatorPreviewMode: s.navigatorPreviewMode,+ navigatorSplitRatio: s.navigatorSplitRatio,migratedPanels: s.migratedPanels,};saveWorkspaceState(payload);@@ -457,4 +478,180 @@ export const workspaceStoreActions = {useWorkspaceStore.setState({ showCommandBar: show });persistCurrentWorkspace();},++ setNavigatorPreviewMode(mode: NavigatorPreviewMode): void {+ useWorkspaceStore.setState({ navigatorPreviewMode: mode });+ persistCurrentWorkspace();+ },++ cycleNavigatorPreviewMode(): NavigatorPreviewMode {+ const next = nextNavigatorPreviewMode(useWorkspaceStore.getState().navigatorPreviewMode);+ useWorkspaceStore.setState({ navigatorPreviewMode: next });+ persistCurrentWorkspace();+ return next;+ },++ setNavigatorSplitRatio(ratio: number, persist = true): void {+ const clamped = clampNavigatorSplitRatio(ratio);+ useWorkspaceStore.setState({ navigatorSplitRatio: clamped });+ if (persist) persistCurrentWorkspace();+ },++ // Quick-Access Brush Panel customization & persistence+ setQuickBrushPanelVisible(visible: boolean): void {+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: { ...prev.quickBrushPanel, visible },+ }));+ persistCurrentWorkspace();+ },++ toggleQuickBrushPanelVisible(): boolean {+ const next = !useWorkspaceStore.getState().quickBrushPanel.visible;+ workspaceStoreActions.setQuickBrushPanelVisible(next);+ return next;+ },++ updateQuickBrushPanelSettings(+ patch: Partial<Omit<QuickBrushPanelState, 'brushIds'>>+ ): void {+ useWorkspaceStore.setState((prev) => {+ const merged: QuickBrushPanelState = {+ ...prev.quickBrushPanel,+ ...patch,+ };+ if (patch.opacity !== undefined) {+ merged.opacity = Math.max(0.4, Math.min(1, Math.round(patch.opacity * 100) / 100));+ }+ if (patch.title !== undefined) {+ merged.title = patch.title.slice(0, 28);+ }+ return { quickBrushPanel: merged };+ });+ persistCurrentWorkspace();+ },++ setQuickBrushPanelPosition(+ position: { x: number; y: number } | null,+ persist = true+ ): void {+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: {+ ...prev.quickBrushPanel,+ position: position ? { x: Math.round(position.x), y: Math.round(position.y) } : null,+ },+ }));+ if (persist) persistCurrentWorkspace();+ },++ toggleQuickBrushPanelLocked(): boolean {+ const next = !useWorkspaceStore.getState().quickBrushPanel.locked;+ workspaceStoreActions.updateQuickBrushPanelSettings({ locked: next });+ return next;+ },++ toggleQuickBrushPanelOrientation(): QuickBrushPanelOrientation {+ const current = useWorkspaceStore.getState().quickBrushPanel.orientation;+ const next: QuickBrushPanelOrientation = current === 'vertical' ? 'horizontal' : 'vertical';+ workspaceStoreActions.updateQuickBrushPanelSettings({ orientation: next });+ return next;+ },++ addQuickBrush(presetId: BrushPresetId): boolean {+ const resolved = migrateLegacyPresetId(presetId);+ if (!resolved) return false;+ const existing = useWorkspaceStore.getState().quickBrushPanel.brushIds;+ if (existing.includes(resolved)) return false;+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: {+ ...prev.quickBrushPanel,+ brushIds: [...prev.quickBrushPanel.brushIds, resolved],+ },+ }));+ persistCurrentWorkspace();+ return true;+ },++ removeQuickBrush(presetId: BrushPresetId): void {+ const resolved = migrateLegacyPresetId(presetId);+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: {+ ...prev.quickBrushPanel,+ brushIds: prev.quickBrushPanel.brushIds.filter(+ (id) => id !== presetId && id !== resolved+ ),+ },+ }));+ persistCurrentWorkspace();+ },++ toggleQuickBrush(presetId: BrushPresetId): boolean {+ const resolved = migrateLegacyPresetId(presetId);+ const existing = useWorkspaceStore.getState().quickBrushPanel.brushIds;+ if (existing.includes(resolved) || existing.includes(presetId)) {+ workspaceStoreActions.removeQuickBrush(resolved);+ return false;+ }+ workspaceStoreActions.addQuickBrush(resolved);+ return true;+ },++ moveQuickBrush(presetId: BrushPresetId, direction: -1 | 1): void {+ const resolved = migrateLegacyPresetId(presetId);+ useWorkspaceStore.setState((prev) => {+ const list = prev.quickBrushPanel.brushIds;+ const idx = list.indexOf(resolved);+ const nextIdx = idx + direction;+ if (idx < 0 || nextIdx < 0 || nextIdx >= list.length) return prev;+ const copy = [...list];+ const [moved] = copy.splice(idx, 1);+ copy.splice(nextIdx, 0, moved);+ return {+ quickBrushPanel: { ...prev.quickBrushPanel, brushIds: copy },+ };+ });+ persistCurrentWorkspace();+ },++ reorderQuickBrush(draggedId: BrushPresetId, targetId: BrushPresetId): void {+ const fromId = migrateLegacyPresetId(draggedId);+ const toId = migrateLegacyPresetId(targetId);+ if (!fromId || !toId || fromId === toId) return;+ useWorkspaceStore.setState((prev) => {+ const list = prev.quickBrushPanel.brushIds;+ const fromIdx = list.indexOf(fromId);+ const toIdx = list.indexOf(toId);+ if (fromIdx < 0 || toIdx < 0) return prev;+ const copy = [...list];+ const [moved] = copy.splice(fromIdx, 1);+ copy.splice(toIdx, 0, moved);+ return {+ quickBrushPanel: { ...prev.quickBrushPanel, brushIds: copy },+ };+ });+ persistCurrentWorkspace();+ },++ clearQuickBrushes(): void {+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: { ...prev.quickBrushPanel, brushIds: [] },+ }));+ persistCurrentWorkspace();+ },++ resetQuickBrushPanelItems(): void {+ useWorkspaceStore.setState((prev) => ({+ quickBrushPanel: {+ ...prev.quickBrushPanel,+ brushIds: [...DEFAULT_QUICK_BRUSH_IDS],+ },+ }));+ persistCurrentWorkspace();+ },++ resetQuickBrushPanel(): void {+ useWorkspaceStore.setState({+ quickBrushPanel: createDefaultQuickBrushPanelState(),+ });+ persistCurrentWorkspace();+ },};diff --git a/src/types/editor.ts b/src/types/editor.tsindex 754c6bd..401b086 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -27,6 +27,7 @@ export type {export type ToolType =| 'brush'+ | 'decoration'| 'eraser'| 'pipette'| 'transform'@@ -48,6 +49,14 @@ export type ToolType =| 'liquify'| '3d';+export function isPaintTool(tool: ToolType): boolean {+ return tool === 'brush' || tool === 'decoration';+}++export function isBrushLikeTool(tool: ToolType): boolean {+ return tool === 'brush' || tool === 'decoration' || tool === 'eraser';+}+export interface Point {x: number;y: number;@@ -60,7 +69,15 @@ export interface Point {isCorner?: boolean;}-export type BrushCategory = 'pen' | 'sketch' | 'brush' | 'blend' | 'natural-paint';+export type DecorationCategory = 'deco-background' | 'deco-clothing' | 'deco-effect';++export type BrushCategory =+ | 'pen'+ | 'sketch'+ | 'brush'+ | 'blend'+ | 'natural-paint'+ | DecorationCategory;export type BrushRenderMode = 'stamp' | 'bristle-ribbon' | 'bristle-hybrid';@@ -425,6 +442,7 @@ export interface CspBrush {angle: number;angleDynamics?: CspAngleDynamicsMode;rotationRandomScale?: number; // 0.0 to 1.0+ rotateCursor?: boolean; // Optional per-brush override for rotating brush outline cursorflipH?: CspTipFlipMode;flipV?: CspTipFlipMode;antiAlias?: number; // 0: none/binary, 1: low, 2: mid, 3: high@@ -572,6 +590,7 @@ export interface BrushSettings {customTipAngle?: number;customTipAngleDynamics?: CspAngleDynamicsMode;customTipRotationRandomScale?: number;+ rotateCursor?: boolean; // Optional per-brush override for rotating brush outline cursorisColorTip?: boolean;isDualToneTip?: boolean;brushName?: string; // Custom display name@@ -743,7 +762,16 @@ export interface LiquifySettings {multiLayer?: boolean;}-export type FillMethod = 'refer-all' | 'refer-active' | 'refer-reference' | 'lasso';+export type FillMethod =+ | 'refer-all'+ | 'refer-active'+ | 'refer-reference'+ | 'lasso'+ | 'enclose-and-fill'+ | 'paint-unfilled';++export type SmartFillReferMode = 'refer-reference' | 'refer-all' | 'active';+export type SmartFillTargetMode = 'all-enclosed' | 'unfilled-only';export interface FillSettings {method: FillMethod;@@ -751,6 +779,17 @@ export interface FillSettings {closeGap?: number; // 0 - 20 px (CSP Close Gap)areaScale?: number; // -20 to +20 px (CSP Area Scaling)antiAlias?: boolean; // Anti-aliasing edge smoothing & spill guard+ opacity?: number; // 0.01 - 1.0 (Lasso Fill / Smart Fill opacity)+ /** Reference source for Smart Line Fill (Enclose & Fill / Paint Unfilled Area) */+ smartReferMode?: SmartFillReferMode;+ /** Target area filter for Enclose & Fill ('all-enclosed' | 'unfilled-only') */+ encloseTarget?: SmartFillTargetMode;+ /** Close Gap in px for Smart Line Fill (0 - 40, defaults to 10px for sketchy line art) */+ smartCloseGap?: number;+ /** Area Scaling in px for Smart Line Fill (-20 to +20, defaults to +1px) */+ smartAreaScale?: number;+ /** Brush diameter in px for Paint Unfilled Area (2 - 300) */+ brushSize?: number;}export interface TextSettings {@@ -851,7 +890,76 @@ export interface Point2D {y: number;}-export type TransformMode = 'affine' | 'perspective' | 'mesh';+export type TransformMode = 'affine' | 'perspective' | 'mesh' | 'puppet' | 'cage';++export type PuppetRigidityMode = 'rigid' | 'normal' | 'distort';+export type PuppetMeshDensity = 'coarse' | 'normal' | 'fine';++export interface PuppetPin {+ id: string;+ /** Pin rest position in document coordinates (before puppet deformation) */+ restX: number;+ restY: number;+ /** Pin current deformed position in document coordinates */+ x: number;+ y: number;+ /** Optional joint rotation offset in degrees */+ rotation: number;+ /** Stacking depth priority for overlapping limbs/folds (higher draws on top) */+ depth: number;+}++export interface PuppetMeshData {+ /** Source canvas dimensions the rest mesh was generated for */+ sourceWidth: number;+ sourceHeight: number;+ /** Rest vertex positions in source-local pixel coords */+ restLocalX: Float32Array;+ restLocalY: Float32Array;+ /** Rest vertex positions in document coordinates */+ restWorldX: Float32Array;+ restWorldY: Float32Array;+ /** Normalized source texture UVs */+ uvX: Float32Array;+ uvY: Float32Array;+ /** Triangle vertex index triplets (length = triangleCount * 3) */+ triangles: Uint32Array;+ /** Unique undirected mesh edges as vertex index pairs (length = edgeCount * 2) */+ edges: Uint32Array;+ /** Connected component ID per vertex */+ componentId: Int32Array;+ componentCount: number;+ density: PuppetMeshDensity;+ expansion: number;+}++export interface PuppetWarpState {+ pins: PuppetPin[];+ selectedPinId: string | null;+ rigidity: PuppetRigidityMode;+ density: PuppetMeshDensity;+ expansion: number;+ showMesh: boolean;+ mesh?: PuppetMeshData;+}++export interface CagePoint {+ id: string;+ /** Cage vertex rest position in document coordinates */+ restX: number;+ restY: number;+ /** Cage vertex deformed position in document coordinates */+ x: number;+ y: number;+}++export interface CageTransformState {+ points: CagePoint[];+ closed: boolean;+ phase: 'edit' | 'deform';+ selectedPointId: string | null;+ showMesh: boolean;+}export interface CanvasSelection {type: 'rect' | 'lasso' | 'wand' | 'mask';@@ -878,6 +986,8 @@ export interface TransformSession {layerId: string;sourceCanvas: HTMLCanvasElement;sourcePixels?: { data: Uint8ClampedArray; width: number; height: number };+ originalSourceCanvas?: HTMLCanvasElement;+ originalSourcePixels?: { data: Uint8ClampedArray; width: number; height: number };beforeImageData?: ImageData;beforeTileSnapshot?: Map<string, TileSnapshotEntry>;bounds: { x: number; y: number; width: number; height: number };@@ -894,9 +1004,14 @@ export interface TransformSession {meshCols?: number;meshRows?: number;meshPoints?: Point2D[][];+ puppet?: PuppetWarpState;+ cage?: CageTransformState;layerIds?: string[];layerSourceCanvases?: Map<string, HTMLCanvasElement>;layerSourcePixels?: Map<string, { data: Uint8ClampedArray; width: number; height: number }>;+ originalLayerSourceCanvases?: Map<string, HTMLCanvasElement>;+ originalLayerSourcePixels?: Map<string, { data: Uint8ClampedArray; width: number; height: number }>;+ retiredCanvases?: HTMLCanvasElement[];layerBeforeImages?: Map<string, ImageData>;layerBeforeSnapshots?: Map<string, Map<string, TileSnapshotEntry>>;}@@ -1304,12 +1419,33 @@ export interface NewCanvasOptions {defaultFrequency?: number;}+export interface InkTimelapseFrameMetadata {+ index: number;+ path: string;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: number;+}++export interface InkTimelapseFrameData {+ index: number;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: Uint8Array;+}+export interface InkTimelapseMetadata {enabled: boolean;frameCount: number;+ nextIndex?: number;fps?: number;resolution?: '720p' | '1080p';aspectRatio?: 'original' | '16:9' | '9:16' | '1:1';+ frames?: InkTimelapseFrameMetadata[];}export interface LoadedDocument {@@ -1322,6 +1458,7 @@ export interface LoadedDocument {perspectiveRuler?: PerspectiveRuler | null;animationTimeline?: AnimationTimeline | null;timelapse?: InkTimelapseMetadata | null;+ timelapseFrames?: InkTimelapseFrameData[];previewDataUrl?: string;/** Persisted active work time in milliseconds (restored from .ink, .sora, .psd/.psb). */workTimeMs?: number;diff --git a/src/types/settings.ts b/src/types/settings.tsindex f779d1f..a21071a 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -1,5 +1,9 @@import { CanvasColorMode } from './editor';import { safeLocalStorageSetItem } from '../utils/safeStorage';+import {+ DEFAULT_INTERFACE_SCALE,+ clampInterfaceScale,+} from '../utils/interfaceScale';export type AnchorPosition =| 'center'@@ -73,7 +77,7 @@ export function getAccentContrastColor(hex: string): string {return luminance > 0.55 ? '#161616' : '#e5e5e5';}-export type ShortcutCategory = 'Tools' | 'Menu' | 'Canvas View' | 'Layer' | 'Edit';+export type ShortcutCategory = 'Tools' | 'Sub Tools' | 'Menu' | 'Canvas View' | 'Layer' | 'Edit';export type ShortcutOverrides = Record<string, string>;@@ -199,6 +203,7 @@ export interface AppSettings {modernAccent: ModernAccentColor;modernCustomColor: string;uiTone?: 'slate' | 'oled' | 'charcoal';+ interfaceScale: number;showCheckerboard: boolean;showCursorCoordinates: boolean;showPressureInStatusBar: boolean;@@ -216,6 +221,7 @@ export interface AppSettings {defaultStabilization: number;usePressureByDefault: boolean;smoothingEnabled: boolean;+ quickShapeEnabled: boolean;maxHistorySteps: number;// Shortcuts, Modifier Keys & Pen Pressure Calibration@@ -262,6 +268,7 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {modernAccent: 'neutral',modernCustomColor: DEFAULT_ACCENT_HEX,uiTone: 'charcoal',+ interfaceScale: DEFAULT_INTERFACE_SCALE,showCheckerboard: true,showCursorCoordinates: true,showPressureInStatusBar: true,@@ -277,6 +284,7 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {defaultStabilization: 0,usePressureByDefault: true,smoothingEnabled: true,+ quickShapeEnabled: false,maxHistorySteps: 50,shortcuts: {},@@ -462,6 +470,7 @@ export function loadAppSettings(): AppSettings {const validTone: 'slate' | 'oled' | 'charcoal' = ['slate', 'oled', 'charcoal'].includes(parsed.uiTone)? parsed.uiTone: 'charcoal';+ const validInterfaceScale: number = clampInterfaceScale(parsed.interfaceScale);const validAutoOptimizePerformance: boolean =typeof parsed.autoOptimizePerformance === 'boolean'? parsed.autoOptimizePerformance@@ -482,6 +491,10 @@ export function loadAppSettings(): AppSettings {typeof parsed.maxHistorySteps === 'number' && Number.isFinite(parsed.maxHistorySteps)? Math.max(10, Math.min(200, Math.round(parsed.maxHistorySteps))): DEFAULT_APP_SETTINGS.maxHistorySteps;+ const validQuickShapeEnabled: boolean =+ typeof parsed.quickShapeEnabled === 'boolean'+ ? parsed.quickShapeEnabled+ : DEFAULT_APP_SETTINGS.quickShapeEnabled;const validUndoRamSteps: number =typeof parsed.undoRamSteps === 'number' && Number.isFinite(parsed.undoRamSteps)? Math.max(4, Math.min(50, Math.round(parsed.undoRamSteps)))@@ -601,6 +614,8 @@ export function loadAppSettings(): AppSettings {modernAccent: validAccent,modernCustomColor: validCustomColor,uiTone: validTone,+ interfaceScale: validInterfaceScale,+ quickShapeEnabled: validQuickShapeEnabled,maxHistorySteps: validMaxHistorySteps,collabSignalingUrl: validCollabSignalingUrl,collabTurnUrl: validCollabTurnUrl,diff --git a/src/types/workspace.ts b/src/types/workspace.tsindex eda2da3..213c8aa 100644--- a/src/types/workspace.ts+++ b/src/types/workspace.ts@@ -75,14 +75,19 @@ export type CommandActionId =| 'merge-down'| 'flip-h'| 'flip-v'+ | 'value-check'| 'reset-zoom'+ | 'zoom-100'| 'reset-rotation'| 'transform'| 'deselect'| 'toggle-palettes'+ | 'toggle-quick-brushes'| 'swap-colors'| 'transparent-ink';+export type NavigatorPreviewMode = 'color' | 'bw' | 'split';+export type QuickAccessItemKind = 'command' | 'tool' | 'color' | 'brush';export interface QuickAccessItem {@@ -97,6 +102,33 @@ export interface QuickAccessItem {export type QuickAccessViewMode = 'grid' | 'list';+export type QuickBrushPanelOrientation = 'vertical' | 'horizontal';+export type QuickBrushTileSize = 'compact' | 'medium' | 'large';+export type QuickBrushPreviewStyle = 'tip' | 'stroke';++export interface QuickBrushPanelState {+ visible: boolean;+ orientation: QuickBrushPanelOrientation;+ /** Fixed viewport coordinates once dragged, or null for automatic canvas-edge anchoring */+ position: { x: number; y: number } | null;+ locked: boolean;+ /** Keep visible when all other palettes are hidden via Tab */+ keepVisibleWhenPalettesHidden: boolean;+ tileSize: QuickBrushTileSize;+ /** Number of columns (vertical mode) or rows (horizontal mode) */+ columns: 1 | 2;+ previewStyle: QuickBrushPreviewStyle;+ showNames: boolean;+ showTitle: boolean;+ title: string;+ showCategoryColors: boolean;+ /** Panel surface opacity between 0.4 and 1.0 */+ opacity: number;+ /** Show an extra quick Hide/Show All UI (Tab) button directly on the quick brush bar */+ showHideUiButton: boolean;+ brushIds: BrushPresetId[];+}+export interface PersistedWorkspaceState {version: 1;activePreset: WorkspacePresetId;@@ -104,10 +136,13 @@ export interface PersistedWorkspaceState {savedCustomLayout: WorkspaceLayout | null;quickAccessItems: QuickAccessItem[];quickAccessViewMode: QuickAccessViewMode;+ quickBrushPanel?: QuickBrushPanelState;commandBarIds: CommandActionId[];showStatusBar: boolean;showDocumentTabs: boolean;showCommandBar: boolean;+ navigatorPreviewMode?: NavigatorPreviewMode;+ navigatorSplitRatio?: number;migratedPanels?: DockPanelId[];}@@ -300,6 +335,7 @@ export const COMMAND_CATALOG: CommandCatalogEntry[] = [{ id: 'redo', label: 'Redo', shortLabel: 'Redo', shortcut: 'Ctrl+Y' },{ id: 'flip-h', label: 'Flip Horizontal', shortLabel: 'Flip H', shortcut: 'Shift+H' },{ id: 'flip-v', label: 'Flip Vertical', shortLabel: 'Flip V', shortcut: 'Shift+V' },+ { id: 'value-check', label: 'Value Check (Live B/W)', shortLabel: 'Value', shortcut: 'Shift+Y' },{ id: 'clear-layer', label: 'Clear Layer', shortLabel: 'Clear' },{ id: 'merge-down', label: 'Merge Down', shortLabel: 'Merge' },{ id: 'new-layer', label: 'New Layer', shortLabel: 'New Lyr', shortcut: 'Ctrl+Shift+N' },@@ -307,10 +343,12 @@ export const COMMAND_CATALOG: CommandCatalogEntry[] = [{ id: 'transform', label: 'Free Transform', shortLabel: 'Transf', shortcut: 'Ctrl+T' },{ id: 'deselect', label: 'Deselect', shortLabel: 'Desel', shortcut: 'Ctrl+D' },{ id: 'reset-zoom', label: 'Reset Zoom', shortLabel: 'Fit', shortcut: 'Ctrl+0' },+ { id: 'zoom-100', label: 'Reset Zoom to 100%', shortLabel: '100%', shortcut: 'Ctrl+1' },{ id: 'reset-rotation', label: 'Reset Rotation', shortLabel: '0°', shortcut: 'Ctrl+Alt+0' },{ id: 'swap-colors', label: 'Swap Colors', shortLabel: 'Swap', shortcut: 'X' },{ id: 'transparent-ink', label: 'Transparent Ink', shortLabel: 'Transp', shortcut: 'C' },{ id: 'toggle-palettes', label: 'Hide/Show Palettes', shortLabel: 'Palettes', shortcut: 'Tab' },+ { id: 'toggle-quick-brushes', label: 'Quick Brush Panel', shortLabel: 'Brushes', shortcut: 'Shift+B' },];export const WORKSPACE_PRESET_LABELS: Record<WorkspacePresetId, string> = {diff --git a/src/utils/__tests__/brushCursorRotation.test.ts b/src/utils/__tests__/brushCursorRotation.test.tsnew file mode 100644index 0000000..819219c--- /dev/null+++ b/src/utils/__tests__/brushCursorRotation.test.ts@@ -0,0 +1,348 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ computeEffectiveCursorAngleDeg,+ computeNextDynamicCursorAngleDeg,+ formatCursorRingTransform,+ normalizeAngleDeg,+ resolveBrushCursorRotationSpec,+} from '../../components/canvasArea/types';+import { BUILTIN_BRUSHES, getBuiltinBrushConfig } from '../presetBrushes';+import {+ getEffectiveBrushSettings,+ resetBrushSettingsCache,+ saveBrushSettingsImmediately,+} from '../brushPresetManager';+import {+ buildExportableBrush,+ parseInkbFile,+ serializeInkbBrush,+} from '../inkbBrushFormat';+import type { BrushSettings, CspBrush } from '../../types/editor';++function createMemoryStorage(): Storage {+ const store = new Map<string, string>();+ return {+ get length() {+ return store.size;+ },+ clear() {+ store.clear();+ },+ getItem(key: string) {+ return store.has(key) ? store.get(key)! : null;+ },+ key(index: number) {+ return Array.from(store.keys())[index] ?? null;+ },+ removeItem(key: string) {+ store.delete(key);+ },+ setItem(key: string, value: string) {+ store.set(key, String(value));+ },+ };+}++function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;+}++describe('Rotating Brush Cursor & "This brush rotates" Setting', () => {+ beforeEach(() => {+ (globalThis as any).localStorage = createMemoryStorage();+ resetBrushSettingsCache();+ });++ it('auto-enables rotating cursor for all rake brushes and other rotating built-in presets', () => {+ // 1. Natural Paint Dry Bristle Rake (bristle-ribbon): rotates with +90° perpendicular alignment+ const natRake = getBuiltinBrushConfig('dry-bristle-rake')!;+ expect(resolveBrushCursorRotationSpec(natRake, 'brush')).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 90,+ });++ // 2. All Natural Paint bristle-ribbon / bristle-hybrid presets rotate perpendicular to stroke+ const naturalPresets = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint');+ expect(naturalPresets.length).toBeGreaterThan(0);+ for (const def of naturalPresets) {+ const cfg = getBuiltinBrushConfig(def.id)!;+ const spec = resolveBrushCursorRotationSpec(cfg, 'brush');+ expect(spec.enabled, `Natural Paint brush ${def.id} should rotate`).toBe(true);+ expect(spec.source).toBe('direction');+ expect(spec.orientationOffsetDeg).toBe(90);+ }++ // 3. Brush & Blend Rake presets (stamp directional brushes): rotate with 0° offset+ const paintRake = getBuiltinBrushConfig('dry-bristle-rake-paint')!;+ expect(resolveBrushCursorRotationSpec(paintRake, 'brush')).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 0,+ });++ const blendRake = getBuiltinBrushConfig('blend-rake-hair')!;+ expect(resolveBrushCursorRotationSpec(blendRake, 'brush')).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 0,+ });++ // 4. Other directional stamp brushes auto-rotate+ for (const id of [+ 'thick-oil-impasto',+ 'fine-detail-filbert',+ 'blend-oil-bristle',+ 'blend-matte-chalk',+ 'blend-canvas-scumble',+ 'blend-fingertip',+ 'pencil-6b-8b',+ 'standard-chalk',+ ]) {+ const cfg = getBuiltinBrushConfig(id)!;+ expect(resolveBrushCursorRotationSpec(cfg, 'brush').enabled, `${id} should rotate`).toBe(true);+ }++ // 5. Fixed / non-directional brushes do NOT auto-rotate+ for (const id of [+ 'g-pen',+ 'calligraphy',+ 'oil-flat-alla-prima',+ 'concept-matte-chalk',+ 'silky-portrait-round',+ 'soft-glaze-airbrush',+ 'real-g-pen',+ 'textured-pen',+ 'charcoal-pencil',+ 'blend-velvet-soft',+ ]) {+ const cfg = getBuiltinBrushConfig(id)!;+ expect(resolveBrushCursorRotationSpec(cfg, 'brush').enabled, `${id} should not auto-rotate`).toBe(+ false+ );+ }+ });++ it('auto-detects initial-direction, pen tilt, and barrel twist angle dynamics', () => {+ expect(+ resolveBrushCursorRotationSpec({ customTipAngleDynamics: 'initial-direction' }, 'brush')+ ).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 0,+ });++ expect(resolveBrushCursorRotationSpec({ customTipAngleDynamics: 'tilt' }, 'brush')).toEqual({+ enabled: true,+ source: 'tilt',+ orientationOffsetDeg: 0,+ });++ expect(resolveBrushCursorRotationSpec({ customTipAngleDynamics: 'twist' }, 'brush')).toEqual({+ enabled: true,+ source: 'twist',+ orientationOffsetDeg: 0,+ });+ });++ it('respects explicit per-brush rotateCursor ("This brush rotates") overrides and tool gating', () => {+ const natRake = getBuiltinBrushConfig('dry-bristle-rake')!;+ expect(resolveBrushCursorRotationSpec({ ...natRake, rotateCursor: false }, 'brush')).toEqual({+ enabled: false,+ source: 'none',+ orientationOffsetDeg: 0,+ });++ const gPen = getBuiltinBrushConfig('g-pen')!;+ expect(resolveBrushCursorRotationSpec({ ...gPen, rotateCursor: true }, 'brush')).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 0,+ });++ expect(resolveBrushCursorRotationSpec({ ...gPen, rotateCursor: true }, 'eraser')).toEqual({+ enabled: true,+ source: 'direction',+ orientationOffsetDeg: 0,+ });++ // Non-brush/eraser tools never activate brush cursor rotation+ expect(resolveBrushCursorRotationSpec({ ...natRake, rotateCursor: true }, 'fill').enabled).toBe(+ false+ );+ expect(resolveBrushCursorRotationSpec({ ...natRake, rotateCursor: true }, 'liquify').enabled).toBe(+ false+ );+ });++ it('aligns Natural Paint rake teeth perpendicular to stroke direction across rightward, downward, rotated, and flipped viewports', () => {+ // Moving right (0°): horizontal rake tip must rotate to 90° (vertical row of teeth across rightward stroke)+ const moveRight = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 15,+ sdy: 0,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ });+ expect(moveRight.updated).toBe(true);+ expect(moveRight.angleDeg).toBeCloseTo(0, 4);+ expect(+ computeEffectiveCursorAngleDeg({+ tipAngleDeg: 0,+ orientationOffsetDeg: 90,+ followDirection: true,+ dynamicDirDeg: moveRight.angleDeg,+ })+ ).toBeCloseTo(90, 4);++ // Moving down (+90°): horizontal rake tip rotates to 180° (horizontal row of teeth across downward stroke)+ const moveDown = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 0,+ sdy: 15,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ });+ expect(moveDown.updated).toBe(true);+ expect(moveDown.angleDeg).toBeCloseTo(90, 4);+ expect(+ computeEffectiveCursorAngleDeg({+ tipAngleDeg: 0,+ orientationOffsetDeg: 90,+ followDirection: true,+ dynamicDirDeg: moveDown.angleDeg,+ })+ ).toBeCloseTo(180, 4);++ // Viewport rotated 45° and user moves right on screen (0° screen -> -45° canvas)+ const rotatedMove = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 20,+ sdy: 0,+ canvasRotationDeg: 45,+ flipX: false,+ flipY: false,+ });+ expect(rotatedMove.angleDeg).toBeCloseTo(-45, 4);++ // Horizontally flipped viewport (flipX = true) and user moves up-right (+10, -10) -> canvas (-10, -10) = -135°+ const flippedMove = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 10,+ sdy: -10,+ canvasRotationDeg: 0,+ flipX: true,+ flipY: false,+ });+ expect(flippedMove.angleDeg).toBeCloseTo(-135, 4);+ const transform = formatCursorRingTransform(+ 100,+ 100,+ 0,+ true,+ false,+ computeEffectiveCursorAngleDeg({+ tipAngleDeg: 0,+ orientationOffsetDeg: 90,+ followDirection: true,+ dynamicDirDeg: flippedMove.angleDeg,+ })+ );+ expect(transform).toContain('scale(-1, 1) rotate(-45deg)');+ });++ it('rejects tiny sub-3px jitter, wraps cleanly across +-180deg, and supports tilt & twist inputs', () => {+ const jitter = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 42,+ hasCurrent: true,+ sdx: 1.5,+ sdy: -1.5,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ });+ expect(jitter.updated).toBe(false);+ expect(jitter.angleDeg).toBe(42);++ // Wrap across +-180°: from +170° toward -170° should step positively past 180°, never jump backward through 0°+ const wrap = computeNextDynamicCursorAngleDeg({+ source: 'direction',+ currentDeg: 170,+ hasCurrent: true,+ sdx: Math.cos((-170 * Math.PI) / 180) * 10,+ sdy: Math.sin((-170 * Math.PI) / 180) * 10,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ });+ expect(wrap.updated).toBe(true);+ expect(Math.abs(normalizeAngleDeg(wrap.angleDeg - 180))).toBeLessThan(15);++ // Pen tilt azimuth matches BrushEngine: atan2(tiltX, -tiltY)+ const tilt = computeNextDynamicCursorAngleDeg({+ source: 'tilt',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 0,+ sdy: 0,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ tiltX: 25,+ tiltY: 0,+ });+ expect(tilt.updated).toBe(true);+ expect(tilt.angleDeg).toBeCloseTo(90, 4);++ // Barrel twist+ const twist = computeNextDynamicCursorAngleDeg({+ source: 'twist',+ currentDeg: 0,+ hasCurrent: false,+ sdx: 0,+ sdy: 0,+ canvasRotationDeg: 0,+ flipX: false,+ flipY: false,+ twist: 215,+ });+ expect(twist.updated).toBe(true);+ expect(twist.angleDeg).toBeCloseTo(-145, 4);+ });++ it('persists rotateCursor per brush, clears manual override back to auto, and round-trips through .inkb', () => {+ saveBrushSettingsImmediately('dry-bristle-rake', { rotateCursor: false });+ let eff = getEffectiveBrushSettings('dry-bristle-rake');+ expect(eff.rotateCursor).toBe(false);+ expect(resolveBrushCursorRotationSpec(eff, 'brush').enabled).toBe(false);++ // Clearing override with explicit undefined returns to auto-detected rotating state+ saveBrushSettingsImmediately('dry-bristle-rake', { rotateCursor: undefined });+ eff = getEffectiveBrushSettings('dry-bristle-rake');+ expect(eff.rotateCursor).toBeUndefined();+ expect(resolveBrushCursorRotationSpec(eff, 'brush').enabled).toBe(true);++ // Enabling on a fixed brush persists and survives .inkb export/import round-trip+ saveBrushSettingsImmediately('oil-flat-alla-prima', { rotateCursor: true });+ const exported: CspBrush = buildExportableBrush('oil-flat-alla-prima', [], {+ preset: 'oil-flat-alla-prima',+ rotateCursor: true,+ } as Partial<BrushSettings>);+ expect(exported.rotateCursor).toBe(true);++ const bytes = serializeInkbBrush(exported);+ const parsed = parseInkbFile(toArrayBuffer(bytes), 'Oil Flat.inkb');+ expect(parsed.rotateCursor).toBe(true);+ });+});diff --git a/src/utils/__tests__/changelog.test.ts b/src/utils/__tests__/changelog.test.tsindex db5321d..a08ae38 100644--- a/src/utils/__tests__/changelog.test.ts+++ b/src/utils/__tests__/changelog.test.ts@@ -8,12 +8,36 @@ import {} from '../changelog';describe('changelog parser', () => {- it('parses bundled CHANGELOG.md including v1.0.4, v1.0.3, v1.0.2, and v1.0.1 sections', () => {+ it('parses bundled CHANGELOG.md including v1.1.0, v1.0.4, v1.0.3, v1.0.2, and v1.0.1 sections', () => {const entries = getChangelogEntries();- expect(entries.length).toBeGreaterThanOrEqual(4);+ expect(entries.length).toBeGreaterThanOrEqual(5);const latest = getChangelogForVersion();- expect(latest?.version).toBe('1.0.4');+ expect(latest?.version).toBe('1.1.0');++ const v110 = getChangelogForVersion('1.1.0');+ expect(v110).toBeDefined();+ expect(v110?.version).toBe('1.1.0');+ expect(v110?.sections.map((s) => s.title)).toEqual([+ 'New',+ 'Improvements',+ 'Bug Fixes',+ ]);+ expect(v110?.sections[0].items).toContain(+ 'Added an Interface Size setting (60%–200%) in Preferences -> Appearance to make menus and panels smaller or larger'+ );+ expect(v110?.sections[0].items).toContain(+ 'Added a "This brush rotates" checkbox in Brush Tip settings and Brush Studio so you can easily turn cursor rotation on or off for any brush'+ );+ expect(v110?.sections[0].items).toContain(+ 'Added an interactive Color | B/W Split View in the Navigator (`Alt+Shift+Y`)'+ );+ expect(v110?.sections[1].items).toContain(+ 'Time-lapse recordings are now saved directly inside `.ink` files and automatically resume right where you left off when you reopen your artwork'+ );+ expect(v110?.sections[2].items).toContain(+ 'Fixed Natural Paint brushes not drawing properly inside regular Lasso and other active selections'+ );const v104 = getChangelogForVersion('1.0.4');expect(v104).toBeDefined();diff --git a/src/utils/__tests__/decorationToolGroup.test.tsx b/src/utils/__tests__/decorationToolGroup.test.tsxnew file mode 100644index 0000000..1322797--- /dev/null+++ b/src/utils/__tests__/decorationToolGroup.test.tsx@@ -0,0 +1,561 @@+// @ts-expect-error node built-in available in vitest runtime without @types/node+import fs from 'node:fs';+// @ts-expect-error node built-in available in vitest runtime without @types/node+import path from 'node:path';+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ ALL_BUILTIN_BRUSHES,+ BUILTIN_BRUSHES,+ DECORATION_BRUSHES,+ DECORATION_BRUSH_SECTIONS,+ DEFAULT_DECORATION_PRESET_ID,+ getBuiltinBrushConfig,+ isDecorationPresetId,+} from '../presetBrushes';+import {+ DEFAULT_COMMANDS,+ buildSubToolShortcutCommands,+} from '../shortcutManager';+import {+ activateSubToolGroup,+ activateSubToolPreset,+ stepSubTool,+ stepSubToolGroup,+} from '../subToolNavigation';+import { activateQuickBrush, resolveQuickBrush } from '../quickBrushUtils';+import {+ subToolGroupStoreActions,+ toolStoreActions,+ useSubToolGroupStore,+ useToolStore,+} from '../../stores';+import { SubToolList } from '../../components/SubToolList';+import { ToolStrip } from '../../components/ToolStrip';++// Minimal DOM shim matching subToolGroupsAndShortcuts.test.tsx+class MiniNode {+ nodeType: number;+ parentNode: MiniEl | null = null;+ childNodes: MiniNode[] = [];+ constructor(nodeType: number) {+ this.nodeType = nodeType;+ }+ get firstChild() {+ return this.childNodes[0] ?? null;+ }+ get lastChild() {+ return this.childNodes[this.childNodes.length - 1] ?? null;+ }+ get nextSibling(): MiniNode | null {+ if (!this.parentNode) return null;+ const i = this.parentNode.childNodes.indexOf(this);+ return i >= 0 ? (this.parentNode.childNodes[i + 1] ?? null) : null;+ }+ get previousSibling(): MiniNode | null {+ if (!this.parentNode) return null;+ const i = this.parentNode.childNodes.indexOf(this);+ return i > 0 ? (this.parentNode.childNodes[i - 1] ?? null) : null;+ }+ get textContent(): string {+ return this.childNodes.map((c) => c.textContent).join('');+ }+ set textContent(v: string) {+ this.childNodes = v ? [new MiniText(String(v))] : [];+ for (const c of this.childNodes) c.parentNode = this as unknown as MiniEl;+ }+}++class MiniText extends MiniNode {+ data: string;+ constructor(data: string) {+ super(3);+ this.data = data;+ }+ get nodeValue() {+ return this.data;+ }+ set nodeValue(v: string) {+ this.data = String(v);+ }+ override get textContent() {+ return this.data;+ }+}++class MiniEl extends MiniNode {+ tagName: string;+ nodeName: string;+ attributes = new Map<string, string>();+ style: Record<string, string> = {};+ listeners = new Map<string, Set<EventListener>>();+ className = '';+ disabled = false;+ type = '';+ value = '';+ ownerDocument: unknown = null;++ constructor(tag: string) {+ super(1);+ this.tagName = tag.toUpperCase();+ this.nodeName = this.tagName;+ }+ appendChild<T extends MiniNode>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }+ removeChild<T extends MiniNode>(child: T): T {+ const i = this.childNodes.indexOf(child);+ if (i >= 0) {+ this.childNodes.splice(i, 1);+ child.parentNode = null;+ }+ return child;+ }+ insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ if (!ref) {+ this.childNodes.push(child);+ return child;+ }+ const i = this.childNodes.indexOf(ref);+ if (i >= 0) this.childNodes.splice(i, 0, child);+ else this.childNodes.push(child);+ return child;+ }+ setAttribute(k: string, v: string) {+ this.attributes.set(k, String(v));+ if (k === 'class') this.className = String(v);+ }+ getAttribute(k: string): string | null {+ return this.attributes.get(k) ?? null;+ }+ removeAttribute(k: string) {+ this.attributes.delete(k);+ }+ addEventListener(type: string, fn: EventListener) {+ if (!this.listeners.has(type)) this.listeners.set(type, new Set());+ this.listeners.get(type)!.add(fn);+ }+ removeEventListener(type: string, fn: EventListener) {+ this.listeners.get(type)?.delete(fn);+ }+ dispatchEvent(ev: { type: string; target?: unknown; currentTarget?: unknown; bubbles?: boolean; stopPropagation?: () => void; preventDefault?: () => void }) {+ let stopped = false;+ ev.target = ev.target ?? this;+ ev.preventDefault = ev.preventDefault ?? (() => {});+ ev.stopPropagation = () => {+ stopped = true;+ };+ let cur: MiniEl | null = this;+ while (cur && !stopped) {+ ev.currentTarget = cur;+ const set = cur.listeners.get(ev.type);+ if (set) {+ for (const fn of [...set]) fn(ev as unknown as Event);+ }+ if (!ev.bubbles) break;+ cur = cur.parentNode;+ }+ return true;+ }+ closest(sel: string): MiniEl | null {+ const tags = sel.split(',').map((s) => s.trim().toUpperCase());+ let cur: MiniEl | null = this;+ while (cur) {+ if (tags.includes(cur.tagName)) return cur;+ cur = cur.parentNode;+ }+ return null;+ }+ contains(node: MiniNode | null): boolean {+ let cur: MiniNode | null = node;+ while (cur) {+ if (cur === this) return true;+ cur = cur.parentNode;+ }+ return false;+ }+ getBoundingClientRect() {+ return { left: 0, top: 0, right: 100, bottom: 20, width: 100, height: 20, x: 0, y: 0 };+ }+ focus() {}+ getContext() {+ return null;+ }+ querySelectorAll(sel: string): MiniEl[] {+ const out: MiniEl[] = [];+ const attrMatch = sel.match(/^\[([^=\]]+)(?:="([^"]*)")?\]$/);+ const walk = (n: MiniNode) => {+ if (n instanceof MiniEl) {+ if (attrMatch) {+ const val = n.getAttribute(attrMatch[1]);+ if (attrMatch[2] !== undefined ? val === attrMatch[2] : val !== null) {+ out.push(n);+ }+ }+ }+ for (const c of n.childNodes) walk(c);+ };+ walk(this);+ return out;+ }+ querySelector(sel: string): MiniEl | null {+ return this.querySelectorAll(sel)[0] ?? null;+ }+}++function installMiniDom() {+ const docListeners = new Map<string, Set<EventListener>>();+ const winListeners = new Map<string, Set<EventListener>>();+ const body = new MiniEl('body');+ const html = new MiniEl('html');+ html.appendChild(body);+ const doc: Record<string, unknown> = {+ nodeType: 9,+ nodeName: '#document',+ documentElement: html,+ body,+ activeElement: body,+ defaultView: null,+ createElement: (tag: string) => {+ const el = new MiniEl(tag);+ el.ownerDocument = doc;+ return el;+ },+ createElementNS: (_ns: string, tag: string) => {+ const el = new MiniEl(tag);+ el.ownerDocument = doc;+ return el;+ },+ createTextNode: (t: string) => {+ const tn = new MiniText(t);+ (tn as unknown as { ownerDocument: unknown }).ownerDocument = doc;+ return tn;+ },+ createComment: (t: string) => new MiniText(t),+ addEventListener: (t: string, fn: EventListener) => {+ if (!docListeners.has(t)) docListeners.set(t, new Set());+ docListeners.get(t)!.add(fn);+ },+ removeEventListener: (t: string, fn: EventListener) => {+ docListeners.get(t)?.delete(fn);+ },+ querySelector: (sel: string) => body.querySelector(sel),+ querySelectorAll: (sel: string) => body.querySelectorAll(sel),+ };+ body.ownerDocument = doc;+ html.ownerDocument = doc;++ const store = new Map<string, string>();+ const ls = {+ getItem: (k: string) => store.get(k) ?? null,+ setItem: (k: string, v: string) => {+ store.set(k, String(v));+ },+ removeItem: (k: string) => {+ store.delete(k);+ },+ clear: () => store.clear(),+ };++ class MiniIFrame extends MiniEl {}+ const win: Record<string, unknown> = {+ document: doc,+ innerWidth: 1280,+ innerHeight: 800,+ localStorage: ls,+ HTMLElement: MiniEl,+ HTMLIFrameElement: MiniIFrame,+ Node: MiniNode,+ addEventListener: (t: string, fn: EventListener) => {+ if (!winListeners.has(t)) winListeners.set(t, new Set());+ winListeners.get(t)!.add(fn);+ },+ removeEventListener: (t: string, fn: EventListener) => {+ winListeners.get(t)?.delete(fn);+ },+ dispatchEvent: (ev: Event) => {+ for (const fn of [...(winListeners.get(ev.type) ?? [])]) fn(ev);+ return true;+ },+ IS_REACT_ACT_ENVIRONMENT: true,+ };+ doc.defaultView = win;++ (globalThis as unknown as Record<string, unknown>).document = doc;+ (globalThis as unknown as Record<string, unknown>).window = win;+ (globalThis as unknown as Record<string, unknown>).localStorage = ls;+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ (globalThis as unknown as Record<string, unknown>).HTMLElement = MiniEl;+ (globalThis as unknown as Record<string, unknown>).HTMLIFrameElement = MiniIFrame;+ (globalThis as unknown as Record<string, unknown>).Node = MiniNode;+ return { doc, body, win, ls };+}++function invokeReactClick(el: MiniEl | null) {+ if (!el) throw new Error('Expected element to click');+ const key = Object.keys(el).find((k) => k.startsWith('__reactProps$'));+ const props = key ? ((el as unknown as Record<string, unknown>)[key] as Record<string, unknown>) : null;+ const onClick = props?.onClick;+ if (typeof onClick !== 'function') {+ throw new Error(`Expected onClick handler on <${el.tagName}>`);+ }+ (onClick as (e: unknown) => void)({+ preventDefault: () => {},+ stopPropagation: () => {},+ currentTarget: el,+ target: el,+ });+}++describe('Decoration tool group (CSP-style)', () => {+ let root: Root | null = null;+ let container: MiniEl | null = null;++ beforeEach(() => {+ installMiniDom();+ subToolGroupStoreActions.resetAllGroups();+ toolStoreActions.selectTool('brush');+ activateSubToolPreset('g-pen');+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root!.unmount();+ });+ root = null;+ }+ container = null;+ });++ it('includes all 26 decoration brushes across Background, Clothing, and Effect with valid PNG assets', () => {+ expect(DECORATION_BRUSH_SECTIONS.map((s) => s.label)).toEqual([+ 'Background',+ 'Clothing',+ 'Effect',+ ]);+ expect(DECORATION_BRUSHES).toHaveLength(26);++ const byCat = {+ 'deco-background': DECORATION_BRUSHES.filter((b) => b.category === 'deco-background'),+ 'deco-clothing': DECORATION_BRUSHES.filter((b) => b.category === 'deco-clothing'),+ 'deco-effect': DECORATION_BRUSHES.filter((b) => b.category === 'deco-effect'),+ };+ expect(byCat['deco-background']).toHaveLength(4);+ expect(byCat['deco-clothing']).toHaveLength(18);+ expect(byCat['deco-effect']).toHaveLength(4);++ // Clothing brushes are all CSP ribbons+ for (const b of byCat['deco-clothing']) {+ expect(b.settings.isRibbon).toBe(true);+ }++ // Verify multi-tip counts and every PNG asset exists on disk+ // @ts-expect-error process is available in vitest runtime without @types/node+ const publicDir = path.resolve(process.cwd(), 'public');+ for (const b of DECORATION_BRUSHES) {+ expect(isDecorationPresetId(b.id)).toBe(true);+ expect(b.staticTips && b.staticTips.length > 0).toBe(true);+ for (const tip of b.staticTips!) {+ const diskPath = path.join(publicDir, tip.assetPath);+ expect(fs.existsSync(diskPath), `Missing tip asset: ${diskPath}`).toBe(true);+ const bytes = fs.readFileSync(diskPath);+ // PNG magic header+ expect(bytes[0]).toBe(0x89);+ expect(bytes[1]).toBe(0x50);+ expect(bytes[2]).toBe(0x4e);+ expect(bytes[3]).toBe(0x47);+ }++ const cfg = getBuiltinBrushConfig(b.id);+ expect(cfg).not.toBeNull();+ expect(cfg!.customTipDataUrl).toBeTruthy();+ if (b.staticTips!.length > 1) {+ expect(cfg!.subTips?.length).toBe(b.staticTips!.length);+ }+ }++ expect(getBuiltinBrushConfig('deco-building')?.subTips?.length).toBe(13);+ expect(getBuiltinBrushConfig('deco-building')?.isDualToneTip).toBe(true);+ expect(getBuiltinBrushConfig('deco-roses')?.subTips?.length).toBe(8);+ expect(getBuiltinBrushConfig('deco-bloodstain')?.subTips?.length).toBe(7);+ expect(getBuiltinBrushConfig('deco-cloud')?.spray?.enabled).toBe(true);++ // Brush tool list remains cleanly separated from Decoration brushes+ expect(BUILTIN_BRUSHES.some((b) => isDecorationPresetId(b.id))).toBe(false);+ expect(ALL_BUILTIN_BRUSHES.length).toBe(BUILTIN_BRUSHES.length + DECORATION_BRUSHES.length);+ });++ it('remembers Brush and Decoration active presets independently when switching tools', () => {+ activateSubToolPreset('real-g-pen');+ expect(useToolStore.getState().tool).toBe('brush');+ expect(useToolStore.getState().activePresetId).toBe('real-g-pen');++ // Switch to Decoration tool -> loads default Decoration brush+ toolStoreActions.selectTool('decoration');+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe(DEFAULT_DECORATION_PRESET_ID);++ // Pick Roses inside Decoration+ activateSubToolPreset('deco-roses');+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe('deco-roses');++ // Switch back to Brush -> restores Real G-Pen+ toolStoreActions.selectTool('brush');+ expect(useToolStore.getState().tool).toBe('brush');+ expect(useToolStore.getState().activePresetId).toBe('real-g-pen');++ // Switch back to Decoration -> restores Roses+ toolStoreActions.selectTool('decoration');+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe('deco-roses');++ // Switch to Eraser then pick a color -> returns to Decoration (last paint tool)+ toolStoreActions.selectTool('eraser');+ expect(useToolStore.getState().tool).toBe('eraser');+ toolStoreActions.setPrimaryColor('#ff3366');+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe('deco-roses');+ });++ it('cycles Decoration subtools and groups cleanly with stepSubTool / stepSubToolGroup', () => {+ toolStoreActions.selectTool('decoration');+ activateSubToolPreset('deco-building');++ const next = stepSubTool(1);+ expect(next?.presetId).toBe('deco-cloud');+ expect(useToolStore.getState().tool).toBe('decoration');++ const grp1 = stepSubToolGroup(1);+ expect(grp1?.groupId).toBe('deco-background');+ const grp2 = stepSubToolGroup(1);+ expect(grp2?.groupId).toBe('deco-clothing');+ expect(useSubToolGroupStore.getState().activeDecorationTab).toBe('deco-clothing');+ expect(useToolStore.getState().activePresetId).toBe('deco-star-lace');++ const grp3 = activateSubToolGroup('deco-effect');+ expect(grp3?.groupName).toBe('Effect');+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe('deco-bloodstain');+ });++ it('registers Decoration tool and all 26 decoration brushes in ShortcutManager and Quick Brushes', async () => {+ expect(DEFAULT_COMMANDS.some((c) => c.id === 'tool.decoration' && c.toolId === 'decoration')).toBe(true);++ const dynamic = buildSubToolShortcutCommands([], []);+ for (const b of DECORATION_BRUSHES) {+ expect(dynamic.some((c) => c.subToolPresetId === b.id)).toBe(true);+ }++ const resolved = resolveQuickBrush('deco-cherry', []);+ expect(resolved).not.toBeNull();+ expect(resolved!.name).toBe('Cherry');+ expect(resolved!.category).toBe('deco-effect');++ await activateQuickBrush(resolved!, []);+ expect(useToolStore.getState().tool).toBe('decoration');+ expect(useToolStore.getState().activePresetId).toBe('deco-cherry');+ });++ it('renders Decoration button in ToolStrip and Decoration-scoped tabs/brushes in SubToolList', () => {+ const body = (document as unknown as { body: MiniEl }).body;+ container = document.createElement('div') as unknown as MiniEl;+ body.appendChild(container);+ root = createRoot(container as unknown as Element);++ act(() => {+ root!.render(+ <div>+ <ToolStrip />+ <SubToolList customBrushes={[]} setCustomBrushes={() => {}} />+ </div>+ );+ });++ const decoBtn = container.querySelector('[data-testid="toolstrip-decoration-btn"]');+ expect(decoBtn).not.toBeNull();+ // Initially in Brush mode -> Brush tab bar shown, Decoration tab bar hidden+ expect(container.querySelector('[data-testid="subtool-group-tab-bar"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-decoration-tab-bar"]')).toBeNull();++ // Click Decoration tool in ToolStrip+ act(() => {+ invokeReactClick(decoBtn);+ });++ expect(useToolStore.getState().tool).toBe('decoration');+ expect(container.querySelector('[data-testid="subtool-decoration-tab-bar"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-group-tab-deco-background"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-group-tab-deco-effect"]')).not.toBeNull();++ // All 26 decoration brush rows visible in All view+ for (const b of DECORATION_BRUSHES) {+ expect(container.querySelector(`[data-testid="subtool-row-${b.id}"]`)).not.toBeNull();+ }++ // Filter to Clothing tab -> only the 18 clothing brushes visible+ const clothingTab = container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]');+ act(() => {+ invokeReactClick(clothingTab);+ });+ expect(container.querySelector('[data-testid="subtool-row-deco-star-lace"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-row-deco-building"]')).toBeNull();+ expect(container.querySelector('[data-testid="subtool-row-deco-roses"]')).toBeNull();++ // "+ Group" button is available in Decoration mode too+ const createGroupBtn = container.querySelector('[data-testid="subtool-create-group-btn"]');+ expect(createGroupBtn).not.toBeNull();+ act(() => {+ invokeReactClick(createGroupBtn);+ });+ expect(container.querySelector('[data-testid="subtool-create-group-form"]')).not.toBeNull();+ const confirmBtn = container.querySelector('[data-testid="subtool-create-group-confirm"]');+ act(() => {+ invokeReactClick(confirmBtn);+ });++ const createdGroups = useSubToolGroupStore.getState().groups;+ expect(createdGroups).toHaveLength(1);+ expect(createdGroups[0].toolScope).toBe('decoration');+ expect(useSubToolGroupStore.getState().activeDecorationTab).toBe(createdGroups[0].id);+ expect(container.querySelector(`[data-testid="subtool-group-tab-${createdGroups[0].id}"]`)).not.toBeNull();++ // Move a Decoration brush into the new Decoration custom group & verify persistence+ act(() => {+ subToolGroupStoreActions.moveBrushToGroup('deco-roses', createdGroups[0].id);+ });+ expect(container.querySelector('[data-testid="subtool-row-deco-roses"]')).not.toBeNull();++ // Switching back to Brush mode hides Decoration-scoped custom groups+ const brushBtn = container.querySelector('[data-testid="toolstrip-brush-btn"]');+ act(() => {+ invokeReactClick(brushBtn);+ });+ expect(container.querySelector(`[data-testid="subtool-group-tab-${createdGroups[0].id}"]`)).toBeNull();++ // Reloading from storage preserves toolScope & activeDecorationTab+ subToolGroupStoreActions.reloadFromStorage();+ expect(useSubToolGroupStore.getState().groups[0].toolScope).toBe('decoration');+ expect(useSubToolGroupStore.getState().activeDecorationTab).toBe(createdGroups[0].id);+ });++ it('routes canvas pointerDown/Move/Up to the brush stroke engine when Decoration tool is active', () => {+ const appSource = fs.readFileSync(+ // @ts-expect-error process is available in vitest runtime without @types/node+ path.resolve(process.cwd(), 'src/App.tsx'),+ 'utf-8'+ );+ // Regression guard: App.tsx must dispatch pointerDown, pointerMove, and pointerUp+ // to drawing.handlePointer* for 'decoration' just like 'brush' and 'eraser'.+ const matches = appSource.match(/tool === 'brush' \|\| tool === 'decoration' \|\| tool === 'eraser'/g);+ expect(matches?.length).toBeGreaterThanOrEqual(3);+ });+});diff --git a/src/utils/__tests__/fileDropImport.test.ts b/src/utils/__tests__/fileDropImport.test.tsindex a408fe3..bd765de 100644--- a/src/utils/__tests__/fileDropImport.test.ts+++ b/src/utils/__tests__/fileDropImport.test.ts@@ -1,13 +1,20 @@import { describe, it, expect } from 'vitest';import {+ MAX_DROPPED_3D_MODEL_BYTES,MAX_DROPPED_IMAGE_BYTES,MAX_DROPPED_IMAGE_FILES,extractFilenameFromPath,+ filterDropped3DModelFiles,+ filterDropped3DModelPaths,filterDroppedImageFiles,filterDroppedImagePaths,+ get3DModelMimeTypeForFilename,getMimeTypeForFilename,+ inferHtml5DragPayloadKind,isExternalFileDrag,isSameDropTarget,+ isSupported3DModelExtension,+ isSupported3DModelFile,isSupportedImageExtension,isSupportedImageFile,resolveDropZoneFromElement,@@ -234,5 +241,93 @@ describe('fileDropImport utilities', () => {{ zone: 'layers', targetLayerId: 'folder-1', position: 'above' })).toBe(false);++ const stage3DEl = makeEl({ dropZone: '3d-stage' });+ expect(resolveDropZoneFromElement(stage3DEl as unknown as Element, 40)).toEqual({+ zone: '3d-stage',+ });++ expect(+ isSameDropTarget(+ { zone: 'canvas', payloadKind: '3d-model' },+ { zone: 'canvas', payloadKind: 'image' }+ )+ ).toBe(false);+ });++ it('validates and filters 3D model files and paths (.glb, .gltf, .obj) for drag-and-drop', () => {+ for (const valid of [+ 'character.glb',+ 'SCENE.GLTF',+ 'prop.obj',+ 'C:\\Models\\mecha_v2.GLB',+ '/home/artist/assets/bust.obj',+ ]) {+ expect(isSupported3DModelExtension(valid)).toBe(true);+ }++ for (const bad of ['photo.png', 'model.fbx', 'archive.zip', '.glb', 'noext', '']) {+ expect(isSupported3DModelExtension(bad)).toBe(false);+ }++ expect(get3DModelMimeTypeForFilename('hero.glb')).toBe('model/gltf-binary');+ expect(get3DModelMimeTypeForFilename('hero.gltf')).toBe('model/gltf+json');+ expect(get3DModelMimeTypeForFilename('hero.obj')).toBe('text/plain');++ const glb = makeFakeFile('hero.glb', 2048, 'model/gltf-binary');+ const obj = makeFakeFile('cube.obj', 512, '');+ const empty = makeFakeFile('empty.glb', 0, 'model/gltf-binary');+ const oversized = makeFakeFile('huge.glb', MAX_DROPPED_3D_MODEL_BYTES + 1, 'model/gltf-binary');+ const png = makeFakeFile('ref.png', 1024, 'image/png');++ expect(isSupported3DModelFile(glb)).toBe(true);+ expect(isSupported3DModelFile(obj)).toBe(true);+ expect(isSupported3DModelFile(png)).toBe(false);++ const res = filterDropped3DModelFiles([glb, obj, empty, oversized, png]);+ expect(res.accepted.map((f) => f.name)).toEqual(['hero.glb']);+ expect(res.rejectedCount).toBe(2);+ expect(res.oversizedCount).toBe(1);+ expect(res.truncatedCount).toBe(1);++ const pathRes = filterDropped3DModelPaths([+ 'C:\\models\\bad\0.glb',+ 'C:\\models\\ref.png',+ 'C:\\models\\first.glb',+ 'C:\\models\\second.obj',+ ]);+ expect(pathRes.accepted).toEqual(['C:\\models\\first.glb']);+ expect(pathRes.rejectedCount).toBe(2);+ expect(pathRes.truncatedCount).toBe(1);+ });++ it('infers HTML5 drag payload kind accurately in 3D mode vs 2D mode', () => {+ const glbFile = makeFakeFile('mesh.glb', 256, 'model/gltf-binary');+ const pngFile = makeFakeFile('pic.png', 256, 'image/png');++ expect(+ inferHtml5DragPayloadKind({ files: [glbFile] } as unknown as DataTransfer, false)+ ).toBe('3d-model');+ expect(+ inferHtml5DragPayloadKind({ files: [pngFile] } as unknown as DataTransfer, true)+ ).toBe('image');+ expect(+ inferHtml5DragPayloadKind(+ { files: [], items: [{ kind: 'file', type: '' }] } as unknown as DataTransfer,+ true+ )+ ).toBe('any-3d');+ expect(+ inferHtml5DragPayloadKind(+ { files: [], items: [{ kind: 'file', type: 'image/png' }] } as unknown as DataTransfer,+ true+ )+ ).toBe('image');+ expect(+ inferHtml5DragPayloadKind(+ { files: [], items: [{ kind: 'file', type: '' }] } as unknown as DataTransfer,+ false+ )+ ).toBe('image');});});diff --git a/src/utils/__tests__/folderMergeAndTransform.test.tsx b/src/utils/__tests__/folderMergeAndTransform.test.tsxindex f5c1980..cf7d186 100644--- a/src/utils/__tests__/folderMergeAndTransform.test.tsx+++ b/src/utils/__tests__/folderMergeAndTransform.test.tsx@@ -963,4 +963,163 @@ describe('End-to-End Folder Merge and Folder Transform with SparseTileGrid & Undexpect(grid.getPixelRGBA('sel-b', 85, 85)).toEqual([0, 0, 255, 255]);expect(pushHistorySpy).toHaveBeenCalledTimes(1);});++ it('commits Puppet Warp and Cage Transform on multi-layer folders into SparseTileGrid with atomic Undo/Redo', async () => {+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 160, height: 160 };++ const layers: LayerItem[] = [+ makeLayer('char-folder', { name: 'Character', type: 'folder' }),+ makeLayer('char-line', { name: 'Lineart', parentId: 'char-folder' }),+ makeLayer('char-fill', { name: 'Color', parentId: 'char-folder' }),+ ];++ // Vertical arm/bar at x=40..60, y=20..100 on both layers (different colors)+ paintRect(grid, 'char-line', 45, 20, 10, 80, 20, 20, 20, 255);+ paintRect(grid, 'char-fill', 40, 20, 20, 80, 220, 90, 60, 255);++ let selApi: ReturnType<typeof useSelectionTools> | null = null;+ let historyApi: ReturnType<typeof useDrawingHistory> | null = null;+ const historyLabels: string[] = [];++ function Harness() {+ const dimsRef = useRef(dims);+ const activeLayerIdRef = useRef('char-folder');+ const colorModeRef = useRef<'color' | 'grayscale' | 'monochrome'>('color');+ const layersRef = useRef<LayerItem[] | undefined>(layers);+ const updateMaskRef = useRef<((id: string) => void) | undefined>(undefined);+ const isDrawingRef = useRef(false);+ const lastStrokeEndRef = useRef(null);+ const abortRef = useRef(() => {});++ const history = useDrawingHistory({+ tileGrid: grid,+ activeLayerId: 'char-folder',+ activeLayerLocked: false,+ dimensions: dims,+ dimensionsRef: dimsRef,+ activeLayerIdRef,+ colorModeRef,+ layersRef,+ onUpdateLayerThumbnail: () => {},+ onUpdateMaskThumbnailRef: updateMaskRef,+ isDrawingRef,+ lastStrokeEndRef,+ abortActiveStrokeRef: abortRef,+ });++ const wrappedPush: typeof history.pushHistoryStep = (...args) => {+ historyLabels.push(args[1]);+ history.pushHistoryStep(...args);+ };++ selApi = useSelectionTools({+ dimensions: dims,+ colorMode: 'color',+ layers,+ activeLayer: layers[0],+ activeLayerId: 'char-folder',+ selectedLayerIds: ['char-folder'],+ tileGrid: grid,+ updateLayerThumbnail: () => {},+ pushHistoryStep: wrappedPush,+ showToast: () => {},+ });+ historyApi = history;+ return null;+ }++ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ // 1. Start directly in Puppet Warp mode+ act(() => {+ selApi!.handleStartTransform('puppet');+ });+ expect(selApi!.transformSession?.active).toBe(true);+ expect(selApi!.transformSession?.mode).toBe('puppet');+ expect(selApi!.transformSession?.puppet?.mesh).toBeDefined();++ // Place 2 joint pins: anchor bottom (50, 90) and bend top (50, 25) -> (80, 25)+ act(() => {+ selApi!.setTransformSession((prev) =>+ prev?.puppet+ ? {+ ...prev,+ puppet: {+ ...prev.puppet,+ pins: [+ { id: 'base', restX: 50, restY: 90, x: 50, y: 90, rotation: 0, depth: 0 },+ { id: 'tip', restX: 50, restY: 25, x: 80, y: 25, rotation: 0, depth: 0 },+ ],+ },+ }+ : prev+ );+ });++ // Apply Puppet Warp+ act(() => {+ selApi!.handleApplyTransform();+ });+ expect(selApi!.transformSession).toBeNull();+ expect(historyLabels[0]).toBe('Puppet Warp (2 layers)');++ // Bent top tip near (80, 25) now has opaque pixels on BOTH char-line and char-fill!+ expect(grid.getPixelRGBA('char-fill', 80, 25)[3]).toBeGreaterThan(200);+ expect(grid.getPixelRGBA('char-line', 80, 25)[3]).toBeGreaterThan(200);+ // Original unbent top (50, 25) was moved away+ expect(grid.getPixelRGBA('char-fill', 50, 25)[3]).toBe(0);+ // Anchored bottom (50, 90) stayed put+ expect(grid.getPixelRGBA('char-fill', 50, 90)[3]).toBe(255);++ // Undo restores exact original straight bar on both layers+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex - 1);+ });+ expect(grid.getPixelRGBA('char-fill', 50, 25)[3]).toBe(255);+ expect(grid.getPixelRGBA('char-line', 50, 25)[3]).toBe(255);+ expect(grid.getPixelRGBA('char-fill', 80, 25)[3]).toBe(0);++ // 2. Start directly in Cage Transform mode, drag top cage vertices right by +25px, and Apply+ act(() => {+ selApi!.handleStartTransform('cage');+ });+ expect(selApi!.transformSession?.mode).toBe('cage');+ expect(selApi!.transformSession?.cage?.closed).toBe(true);++ act(() => {+ selApi!.setTransformSession((prev) =>+ prev?.cage+ ? {+ ...prev,+ cage: {+ ...prev.cage,+ points: prev.cage.points.map((pt) =>+ pt.restY < 45 ? { ...pt, x: pt.restX + 25 } : pt+ ),+ },+ }+ : prev+ );+ });++ act(() => {+ selApi!.handleApplyTransform();+ });+ expect(selApi!.transformSession).toBeNull();+ expect(historyLabels[1]).toBe('Cage Transform (2 layers)');+ expect(grid.getPixelRGBA('char-fill', 70, 25)[3]).toBeGreaterThan(200);+ expect(grid.getPixelRGBA('char-line', 70, 25)[3]).toBeGreaterThan(200);+ expect(grid.getPixelRGBA('char-line', 50, 25)[3]).toBe(0);++ // Undo restores exact original straight bar again+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex - 1);+ });+ expect(grid.getPixelRGBA('char-line', 50, 25)[3]).toBe(255);+ expect(grid.getPixelRGBA('char-line', 70, 25)[3]).toBe(0);+ });});diff --git a/src/utils/__tests__/gradientEngine.test.ts b/src/utils/__tests__/gradientEngine.test.tsindex fc90b74..1582626 100644--- a/src/utils/__tests__/gradientEngine.test.ts+++ b/src/utils/__tests__/gradientEngine.test.ts@@ -1,14 +1,25 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeEach } from 'vitest';import {DEFAULT_GRADIENT_SETTINGS,constrainGradientEndpoint,createDefaultGradientMesh,+ getGradientMeshCentroid,+ getSelectedMeshNodeIndices,+ invertGradientMeshSelection,rasterizeMeshGradientToRgba,renderGradientToTileGrid,resolveGradientStops,+ rotateGradientMeshFromBase,+ rotateGradientMeshVertices,sampleGradientStops,+ selectAllGradientMeshNodes,+ selectGradientMeshNodesInRect,+ setGradientMeshRotation,+ toggleGradientMeshNodeSelection,+ updateGradientMeshNodes,} from '../gradientEngine';import { SparseTileGrid } from '../tileEngine';+import { toolStoreActions, useToolStore } from '../../stores';describe('Gradient Engine (Linear / Radial / Mesh)', () => {it('interpolates multi-stop RGBA colors with clamp, repeat, reflect, and reverse', () => {@@ -181,4 +192,159 @@ describe('Gradient Engine (Linear / Radial / Mesh)', () => {expect(res.modified).toBe(true);expect(grid.getPixelRGBA('layer-mesh', 40, 40)[0]).toBeGreaterThan(220);});++ describe('Gradient Mesh simultaneous rotation & multi-vertex color editing', () => {+ beforeEach(() => {+ toolStoreActions.setActiveGradientMesh(null);+ toolStoreActions.selectTool('brush');+ toolStoreActions.updateGradientSettings({ type: 'linear' });+ });++ it('rotates all mesh vertices simultaneously around centroid without drift and renders rotated colors', () => {+ const base = createDefaultGradientMesh(+ { x: 0, y: 0, width: 64, height: 64 },+ 3,+ 3,+ '#ff0000',+ '#00ff00'+ );+ base.nodes[0].color = '#ff0000'; // top-left (0, 0)+ base.nodes[2].color = '#00ff00'; // top-right (64, 0)+ base.nodes[6].color = '#0000ff'; // bottom-left (0, 64)+ base.nodes[8].color = '#ffff00'; // bottom-right (64, 64)++ const origCentroid = getGradientMeshCentroid(base);+ expect(origCentroid.x).toBeCloseTo(32, 5);+ expect(origCentroid.y).toBeCloseTo(32, 5);++ // Rotate all vertices +90° simultaneously+ const rot90 = rotateGradientMeshVertices(base, 90);+ expect(rot90.rotationDeg).toBeCloseTo(90, 5);+ const rotCentroid = getGradientMeshCentroid(rot90);+ expect(rotCentroid.x).toBeCloseTo(32, 5);+ expect(rotCentroid.y).toBeCloseTo(32, 5);+ // (0, 0) around (32, 32) rotated +90° -> (64, 0); (64, 64) -> (0, 64)+ expect(rot90.nodes[0].x).toBeCloseTo(64, 4);+ expect(rot90.nodes[0].y).toBeCloseTo(0, 4);+ expect(rot90.nodes[8].x).toBeCloseTo(0, 4);+ expect(rot90.nodes[8].y).toBeCloseTo(64, 4);+ // Center node stays at centroid+ expect(rot90.nodes[4].x).toBeCloseTo(32, 4);+ expect(rot90.nodes[4].y).toBeCloseTo(32, 4);++ // rotateGradientMeshFromBase gives exact angle from initial positions without drift+ const basePositions = base.nodes.map((n) => ({ x: n.x, y: n.y }));+ const rot180 = rotateGradientMeshFromBase(basePositions, 0, base, 180, origCentroid);+ expect(rot180.rotationDeg).toBeCloseTo(180, 5);+ expect(rot180.nodes[0].x).toBeCloseTo(64, 4);+ expect(rot180.nodes[0].y).toBeCloseTo(64, 4);++ // Rasterizing 180°-rotated mesh places red node (originally top-left) at bottom-right+ const buf = rasterizeMeshGradientToRgba(rot180, 0, 0, 64, 64, 1, 1, false, 6);+ const brOff = (61 * 64 + 61) * 4;+ expect(buf[brOff]).toBeGreaterThan(200);+ expect(buf[brOff + 1]).toBeLessThan(60);+ expect(buf[brOff + 2]).toBeLessThan(60);++ // Setting absolute rotation back to 0° restores original positions+ const restored = setGradientMeshRotation(rot90, 0);+ expect(restored.rotationDeg).toBeCloseTo(0, 5);+ expect(restored.nodes[0].x).toBeCloseTo(0, 4);+ expect(restored.nodes[0].y).toBeCloseTo(0, 4);+ expect(restored.nodes[8].x).toBeCloseTo(64, 4);+ expect(restored.nodes[8].y).toBeCloseTo(64, 4);+ });++ it('multi-selects vertices via toggle, marquee rect, select-all, and invert, and batch-updates colors and opacity', () => {+ let mesh = createDefaultGradientMesh(+ { x: 10, y: 10, width: 100, height: 100 },+ 3,+ 3,+ '#111111',+ '#222222'+ );+ expect(getSelectedMeshNodeIndices(mesh)).toEqual([0]);++ // Toggle vertices 2 and 4 into multi-selection+ mesh = toggleGradientMeshNodeSelection(mesh, 2);+ mesh = toggleGradientMeshNodeSelection(mesh, 4);+ expect(getSelectedMeshNodeIndices(mesh)).toEqual([0, 2, 4]);+ expect(mesh.selectedNodeIndex).toBe(4);++ // Batch-update color & opacity on all 3 selected vertices simultaneously+ const recolored = updateGradientMeshNodes(mesh, getSelectedMeshNodeIndices(mesh), {+ color: '#ff00aa',+ opacity: 0.4,+ });+ for (const idx of [0, 2, 4]) {+ expect(recolored.nodes[idx].color).toBe('#ff00aa');+ expect(recolored.nodes[idx].opacity).toBeCloseTo(0.4, 5);+ }+ // Unselected vertices remain unchanged+ expect(recolored.nodes[1].color).not.toBe('#ff00aa');+ expect(recolored.nodes[1].opacity).toBe(1);++ // Marquee box selection around top row (y = 10, x in [10, 110])+ const topRowSel = selectGradientMeshNodesInRect(recolored, {+ x: 0,+ y: 0,+ width: 120,+ height: 30,+ });+ expect(getSelectedMeshNodeIndices(topRowSel)).toEqual([0, 1, 2]);++ // Additive marquee box adds bottom-right corner (index 8 at x=110, y=110)+ const additiveSel = selectGradientMeshNodesInRect(+ topRowSel,+ { x: 95, y: 95, width: 30, height: 30 },+ true+ );+ expect(getSelectedMeshNodeIndices(additiveSel)).toEqual([0, 1, 2, 8]);++ // Invert selection & select all+ const inverted = invertGradientMeshSelection(additiveSel);+ expect(getSelectedMeshNodeIndices(inverted)).toEqual([3, 4, 5, 6, 7]);+ const allSelected = selectAllGradientMeshNodes(inverted);+ expect(getSelectedMeshNodeIndices(allSelected)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+ });++ it('synchronizes store actions and primary color changes across all selected mesh vertices', () => {+ const mesh = createDefaultGradientMesh(+ { x: 0, y: 0, width: 100, height: 100 },+ 2,+ 2,+ '#000000',+ '#ffffff'+ );+ toolStoreActions.selectTool('gradient');+ toolStoreActions.updateGradientSettings({ type: 'mesh' });+ toolStoreActions.setActiveGradientMesh(mesh);++ // Select all 4 vertices via store action+ toolStoreActions.selectAllActiveGradientMeshNodes();+ expect(getSelectedMeshNodeIndices(useToolStore.getState().activeGradientMesh!)).toEqual([+ 0, 1, 2, 3,+ ]);++ // Picking a new primary color applies to ALL selected vertices simultaneously+ toolStoreActions.setPrimaryColor('#22cc88');+ const afterColor = useToolStore.getState().activeGradientMesh!;+ for (const node of afterColor.nodes) {+ expect(node.color).toBe('#22cc88');+ }++ // Store rotation action rotates all vertices simultaneously+ toolStoreActions.rotateActiveGradientMesh(90);+ const afterRot = useToolStore.getState().activeGradientMesh!;+ expect(afterRot.rotationDeg).toBeCloseTo(90, 5);+ expect(afterRot.nodes[0].x).toBeCloseTo(100, 4);+ expect(afterRot.nodes[0].y).toBeCloseTo(0, 4);++ // Reset rotation via setActiveGradientMeshRotation(0)+ toolStoreActions.setActiveGradientMeshRotation(0);+ const afterReset = useToolStore.getState().activeGradientMesh!;+ expect(afterReset.nodes[0].x).toBeCloseTo(0, 4);+ expect(afterReset.nodes[0].y).toBeCloseTo(0, 4);+ });+ });});diff --git a/src/utils/__tests__/hostModal.test.tsx b/src/utils/__tests__/hostModal.test.tsxindex efbaa44..417236a 100644--- a/src/utils/__tests__/hostModal.test.tsx+++ b/src/utils/__tests__/hostModal.test.tsx@@ -426,4 +426,60 @@ describe('HostModal WebRTC P2P default & hierarchy', () => {}));});++ it('exposes Interface Size (60%–200%) controls in SettingsModal Appearance tab', async () => {+ const onUpdateSettings = vi.fn();+ const onShowToast = vi.fn();++ await act(async () => {+ root.render(+ <SettingsModal+ isOpen={true}+ onClose={vi.fn()}+ settings={{+ ...DEFAULT_APP_SETTINGS,+ interfaceScale: 100,+ }}+ onUpdateSettings={onUpdateSettings}+ onShowToast={onShowToast}+ />+ );+ });++ const section = findByTestId(container, 'settings-interface-size-section');+ expect(section).toBeDefined();++ const preset60 = findByTestId(container, 'settings-interface-scale-preset-60')!;+ const preset200 = findByTestId(container, 'settings-interface-scale-preset-200')!;+ const incBtn = findByTestId(container, 'settings-interface-scale-inc')!;+ const resetBtn = findByTestId(container, 'settings-interface-scale-reset')!;++ await act(async () => {+ clickElement(preset200);+ });+ expect(onUpdateSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({ interfaceScale: 200 })+ );++ await act(async () => {+ clickElement(preset60);+ });+ expect(onUpdateSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({ interfaceScale: 60 })+ );++ await act(async () => {+ clickElement(incBtn);+ });+ expect(onUpdateSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({ interfaceScale: 65 })+ );++ await act(async () => {+ clickElement(resetBtn);+ });+ expect(onUpdateSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({ interfaceScale: 100 })+ );+ });});diff --git a/src/utils/__tests__/interfaceScaleAndZoomReset.test.ts b/src/utils/__tests__/interfaceScaleAndZoomReset.test.tsnew file mode 100644index 0000000..9962fe4--- /dev/null+++ b/src/utils/__tests__/interfaceScaleAndZoomReset.test.ts@@ -0,0 +1,207 @@+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';+import {+ DEFAULT_INTERFACE_SCALE,+ MAX_INTERFACE_SCALE,+ MIN_INTERFACE_SCALE,+ applyInterfaceScale,+ clampInterfaceScale,+ getActiveNativeWebviewZoom,+ resetInterfaceScaleState,+} from '../interfaceScale';+import {+ DEFAULT_APP_SETTINGS,+ loadAppSettings,+ saveAppSettings,+} from '../../types/settings';+import {+ adjustTabletSamplesForWebviewZoom,+ NativeTabletSample,+} from '../nativeTabletInput';+import {+ DEFAULT_COMMANDS,+ ShortcutManager,+ findShortcutConflicts,+ matchesKeyboardEvent,+} from '../shortcutManager';+import { COMMAND_CATALOG } from '../../types/workspace';+import { executeWorkspaceCommand, isCommandDisabled, WorkspaceCommandHandlers } from '../../components/CommandBar';++describe('Interface Size (60%–200%) settings & application', () => {+ const prevDocument = (globalThis as any).document;+ const prevLocalStorage = (globalThis as any).localStorage;++ beforeEach(() => {+ resetInterfaceScaleState();+ const storage: Record<string, string> = {};+ (globalThis as any).localStorage = {+ getItem: (k: string) => storage[k] ?? null,+ setItem: (k: string, v: string) => {+ storage[k] = String(v);+ },+ removeItem: (k: string) => {+ delete storage[k];+ },+ clear: () => {+ Object.keys(storage).forEach((k) => delete storage[k]);+ },+ };+ });++ afterEach(() => {+ resetInterfaceScaleState();+ (globalThis as any).document = prevDocument;+ (globalThis as any).localStorage = prevLocalStorage;+ });++ it('clamps interface scale cleanly to [60, 200] with 100 default', () => {+ expect(MIN_INTERFACE_SCALE).toBe(60);+ expect(MAX_INTERFACE_SCALE).toBe(200);+ expect(DEFAULT_INTERFACE_SCALE).toBe(100);++ expect(clampInterfaceScale(60)).toBe(60);+ expect(clampInterfaceScale(200)).toBe(200);+ expect(clampInterfaceScale(125)).toBe(125);+ expect(clampInterfaceScale(124.6)).toBe(125);+ expect(clampInterfaceScale(25)).toBe(60);+ expect(clampInterfaceScale(350)).toBe(200);+ expect(clampInterfaceScale(NaN)).toBe(100);+ expect(clampInterfaceScale('150')).toBe(100);+ expect(clampInterfaceScale(undefined)).toBe(100);+ });++ it('persists and sanitizes interfaceScale in AppSettings', () => {+ expect(loadAppSettings().interfaceScale).toBe(100);++ saveAppSettings({ ...DEFAULT_APP_SETTINGS, interfaceScale: 135 });+ expect(loadAppSettings().interfaceScale).toBe(135);++ localStorage.setItem('ink_studio_app_settings', JSON.stringify({ interfaceScale: 40 }));+ expect(loadAppSettings().interfaceScale).toBe(60);++ localStorage.setItem('ink_studio_app_settings', JSON.stringify({ interfaceScale: 260 }));+ expect(loadAppSettings().interfaceScale).toBe(200);++ localStorage.setItem('ink_studio_app_settings', JSON.stringify({ interfaceScale: 'invalid' }));+ expect(loadAppSettings().interfaceScale).toBe(100);+ });++ it('applies CSS zoom and custom properties on documentElement in web mode', async () => {+ const attrs = new Map<string, string>();+ const props = new Map<string, string>();+ const styleObj: Record<string, any> = {+ zoom: '',+ setProperty: (k: string, v: string) => props.set(k, v),+ };+ (globalThis as any).document = {+ documentElement: {+ setAttribute: (k: string, v: string) => attrs.set(k, v),+ style: styleObj,+ },+ };++ expect(await applyInterfaceScale(150)).toBe(150);+ expect(attrs.get('data-ui-scale')).toBe('150');+ expect(props.get('--ui-scale')).toBe('1.5');+ expect(styleObj.zoom).toBe('1.5');+ expect(getActiveNativeWebviewZoom()).toBe(1);++ expect(await applyInterfaceScale(60)).toBe(60);+ expect(attrs.get('data-ui-scale')).toBe('60');+ expect(props.get('--ui-scale')).toBe('0.6');+ expect(styleObj.zoom).toBe('0.6');++ // Clamps out-of-range inputs+ expect(await applyInterfaceScale(999)).toBe(200);+ expect(styleObj.zoom).toBe('2');++ // Clears CSS zoom at default 100%+ expect(await applyInterfaceScale(100)).toBe(100);+ expect(attrs.get('data-ui-scale')).toBe('100');+ expect(props.get('--ui-scale')).toBe('1');+ expect(styleObj.zoom).toBe('');+ });++ it('converts native tablet coordinates inversely by active WebView zoom factor', () => {+ const mkSample = (x: number, y: number): NativeTabletSample => ({+ clientX: x,+ clientY: y,+ pressure: 0.75,+ tiltX: 0,+ tiltY: 0,+ twist: 0,+ timestamp: 100,+ buttons: 1,+ phase: 2,+ backend: 1,+ });++ const at150 = adjustTabletSamplesForWebviewZoom([mkSample(600, 300)], 1.5);+ expect(at150[0].clientX).toBeCloseTo(400, 5);+ expect(at150[0].clientY).toBeCloseTo(200, 5);++ const at60 = adjustTabletSamplesForWebviewZoom([mkSample(600, 300)], 0.6);+ expect(at60[0].clientX).toBeCloseTo(1000, 5);+ expect(at60[0].clientY).toBeCloseTo(500, 5);++ const at100 = adjustTabletSamplesForWebviewZoom([mkSample(600, 300)], 1.0);+ expect(at100[0].clientX).toBe(600);+ expect(at100[0].clientY).toBe(300);+ });+});++describe('Reset Zoom to 100% command (canvas zoom level, distinct from interface size)', () => {+ it('registers view.zoomActualSize in DEFAULT_COMMANDS with Ctrl+1 and no conflicts', () => {+ const cmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.zoomActualSize');+ expect(cmd).toBeDefined();+ expect(cmd!.label).toBe('Reset Zoom to 100%');+ expect(cmd!.category).toBe('Canvas View');+ expect(cmd!.defaultShortcut).toBe('Ctrl+1');++ expect(findShortcutConflicts('view.zoomActualSize', 'Ctrl+1', {})).toHaveLength(0);++ // Matches both top-row Digit1 and Numpad1+ expect(matchesKeyboardEvent({ key: '1', code: 'Digit1', ctrlKey: true }, 'Ctrl+1')).toBe(true);+ expect(matchesKeyboardEvent({ key: '1', code: 'Numpad1', ctrlKey: true }, 'Ctrl+1')).toBe(true);+ expect(matchesKeyboardEvent({ key: '0', code: 'Digit0', ctrlKey: true }, 'Ctrl+1')).toBe(false);++ // Dispatches independently of view.resetZoom (Ctrl+0)+ const mgr = new ShortcutManager(DEFAULT_COMMANDS);+ const onFit = vi.fn();+ const on100 = vi.fn();+ mgr.registerHandler('view.resetZoom', onFit);+ mgr.registerHandler('view.zoomActualSize', on100);++ const match100 = mgr.matchEvent({ key: '1', code: 'Digit1', ctrlKey: true });+ expect(match100?.id).toBe('view.zoomActualSize');+ mgr.executeCommand(match100!.id);+ expect(on100).toHaveBeenCalledTimes(1);+ expect(onFit).not.toHaveBeenCalled();+ });++ it('exposes zoom-100 in COMMAND_CATALOG and dispatches onResetZoomTo100', () => {+ const entry = COMMAND_CATALOG.find((c) => c.id === 'zoom-100');+ expect(entry).toBeDefined();+ expect(entry!.label).toBe('Reset Zoom to 100%');+ expect(entry!.shortLabel).toBe('100%');+ expect(entry!.shortcut).toBe('Ctrl+1');++ const onResetZoom = vi.fn();+ const onResetZoomTo100 = vi.fn();+ const handlers: WorkspaceCommandHandlers = {+ canUndo: false,+ canRedo: false,+ onUndo: vi.fn(),+ onRedo: vi.fn(),+ onResetZoom,+ onResetZoomTo100,+ hasOpenDocument: true,+ };++ expect(isCommandDisabled('zoom-100', handlers)).toBe(false);+ expect(isCommandDisabled('zoom-100', { ...handlers, hasOpenDocument: false })).toBe(true);++ executeWorkspaceCommand('zoom-100', handlers);+ expect(onResetZoomTo100).toHaveBeenCalledTimes(1);+ expect(onResetZoom).not.toHaveBeenCalled();+ });+});diff --git a/src/utils/__tests__/mode3DPrimitivesAndDrop.test.tsx b/src/utils/__tests__/mode3DPrimitivesAndDrop.test.tsxnew file mode 100644index 0000000..13f7e10--- /dev/null+++ b/src/utils/__tests__/mode3DPrimitivesAndDrop.test.tsx@@ -0,0 +1,436 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { Csp3DToolbar } from '../../components/Csp3DToolbar';+import { Tool3DPropertyInspector } from '../../components/Tool3DPropertyInspector';+import { useExternalFileDrop, UseExternalFileDropResult } from '../../hooks/useExternalFileDrop';+import {+ documentStoreActions,+ scene3DBridge,+ store3DActions,+ uiStoreActions,+} from '../../stores';+import { Primitive3DType } from '../primitives3D';++class TestTextNode {+ public nodeType = 3;+ public nodeName = '#text';+ public parentNode: TestElement | null = null;+ constructor(+ public nodeValue: string,+ public ownerDocument: TestDocument+ ) {}+}++class TestElement extends EventTarget {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public parentNode: TestElement | null = null;+ public childNodes: Array<TestElement | TestTextNode> = [];+ public style: Record<string, string> = {};+ public attributes = new Map<string, string>();+ public dataset: Record<string, string> = {};+ public value = '';+ public disabled = false;+ public type = '';+ public className = '';++ constructor(+ tag: string,+ public ownerDocument: TestDocument+ ) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = this.nodeName;+ }++ appendChild<T extends TestElement | TestTextNode>(child: T): T {+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ removeChild<T extends TestElement | TestTextNode>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) this.childNodes.splice(idx, 1);+ child.parentNode = null;+ return child;+ }++ insertBefore<T extends TestElement | TestTextNode>(+ child: T,+ ref: TestElement | TestTextNode | null+ ): T {+ child.parentNode = this;+ const idx = ref ? this.childNodes.indexOf(ref) : -1;+ if (idx >= 0) this.childNodes.splice(idx, 0, child);+ else this.childNodes.push(child);+ return child;+ }++ setAttribute(name: string, val: string) {+ const str = String(val);+ this.attributes.set(name, str);+ if (name.startsWith('data-')) {+ const camel = name+ .slice(5)+ .replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());+ this.dataset[camel] = str;+ }+ if (name === 'type') this.type = str;+ if (name === 'value') this.value = str;+ }++ removeAttribute(name: string) {+ this.attributes.delete(name);+ if (name.startsWith('data-')) {+ const camel = name+ .slice(5)+ .replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());+ delete this.dataset[camel];+ }+ }++ getAttribute(name: string): string | null {+ return this.attributes.has(name) ? this.attributes.get(name)! : null;+ }++ closest(selector: string): TestElement | null {+ let cur: TestElement | null = this;+ while (cur) {+ if (selector === '[data-drop-zone]' && cur.dataset.dropZone !== undefined) return cur;+ if (selector === '[data-layer-id]' && cur.dataset.layerId !== undefined) return cur;+ if (+ selector === '[data-testid="sub-view-panel"]' &&+ cur.dataset.testid === 'sub-view-panel'+ ) {+ return cur;+ }+ cur = cur.parentNode;+ }+ return null;+ }++ getBoundingClientRect(): DOMRect {+ return {+ top: 0,+ left: 0,+ bottom: 200,+ right: 200,+ width: 200,+ height: 200,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ } as DOMRect;+ }++ get textContent(): string {+ return this.childNodes+ .map((c) => (c instanceof TestTextNode ? c.nodeValue : c.textContent))+ .join('');+ }++ set textContent(v: string) {+ this.childNodes = [];+ if (v) this.appendChild(new TestTextNode(v, this.ownerDocument));+ }++ override dispatchEvent(event: Event): boolean {+ const path: EventTarget[] = [];+ let cur: TestElement | null = this;+ while (cur) {+ path.push(cur);+ cur = cur.parentNode;+ }+ path.push(this.ownerDocument);+ if (this.ownerDocument.defaultView && this.ownerDocument.defaultView instanceof EventTarget) {+ path.push(this.ownerDocument.defaultView);+ }++ Object.defineProperty(event, 'target', { value: this, configurable: true });+ for (const node of path) {+ Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });+ EventTarget.prototype.dispatchEvent.call(node, event);+ if (event.cancelBubble) break;+ }+ return !event.defaultPrevented;+ }+}++class TestDocument extends EventTarget {+ public nodeType = 9;+ public activeElement: TestElement | null = null;+ public defaultView: unknown = null;+ public documentElement: TestElement;+ public body: TestElement;+ public hitElement: TestElement | null = null;++ constructor() {+ super();+ this.documentElement = new TestElement('html', this);+ this.body = new TestElement('body', this);+ this.documentElement.appendChild(this.body);+ }++ createElement(tag: string) {+ return new TestElement(tag, this);+ }++ createElementNS(_ns: string, tag: string) {+ return new TestElement(tag, this);+ }++ createTextNode(text: string) {+ return new TestTextNode(text, this);+ }++ createComment() {+ return new TestTextNode('', this);+ }++ elementFromPoint(_x: number, _y: number) {+ return this.hitElement;+ }+}++function findByTestId(root: TestElement, testId: string): TestElement | null {+ if (root.getAttribute('data-testid') === testId) return root;+ for (const child of root.childNodes) {+ if (child instanceof TestElement) {+ const found = findByTestId(child, testId);+ if (found) return found;+ }+ }+ return null;+}++describe('3D Mode Primitives UI & Drag-and-Drop 3D Model Import', () => {+ const origWindow = (globalThis as Record<string, unknown>).window;+ const origDocument = (globalThis as Record<string, unknown>).document;+ const origHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const origHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const origElement = (globalThis as Record<string, unknown>).Element;+ const origNode = (globalThis as Record<string, unknown>).Node;+ const origActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ let doc: TestDocument;+ let win: EventTarget;+ let container: TestElement;+ let root: Root;++ beforeEach(() => {+ class HTMLIFrameElementShim extends TestElement {}+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ doc = new TestDocument();+ win = Object.assign(new EventTarget(), {+ document: doc,+ innerWidth: 1280,+ innerHeight: 800,+ devicePixelRatio: 1,+ navigator: {},+ Node: TestElement,+ HTMLElement: TestElement,+ HTMLIFrameElement: HTMLIFrameElementShim,+ Element: TestElement,+ });+ doc.defaultView = win;+ (globalThis as Record<string, unknown>).document = doc;+ (globalThis as Record<string, unknown>).window = win;+ (globalThis as Record<string, unknown>).Element = TestElement;+ (globalThis as Record<string, unknown>).HTMLElement = TestElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = HTMLIFrameElementShim;+ (globalThis as Record<string, unknown>).Node = TestElement;++ container = doc.createElement('div');+ doc.body.appendChild(container);+ root = createRoot(container as unknown as HTMLElement);+ store3DActions.resetSceneMeta();+ });++ afterEach(async () => {+ await act(async () => {+ root.unmount();+ });+ scene3DBridge.createPrimitive = undefined;+ uiStoreActions.set3DLayerOpen(false, null);+ documentStoreActions.setDocuments([]);+ documentStoreActions.setActiveDocumentId(null);+ (globalThis as Record<string, unknown>).window = origWindow;+ (globalThis as Record<string, unknown>).document = origDocument;+ (globalThis as Record<string, unknown>).HTMLElement = origHTMLElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = origHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = origElement;+ (globalThis as Record<string, unknown>).Node = origNode;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = origActEnv;+ });++ it('opens Primitives popover in Csp3DToolbar and creates all 5 primitive shapes', () => {+ const onCreatePrimitive = vi.fn();++ act(() => {+ root.render(+ <Csp3DToolbar+ is3DToolActive={true}+ onActivate3DTool={() => {}}+ onDirectDrag={() => {}}+ onDirectDragEnd={() => {}}+ onTriggerImport={() => {}}+ onCreatePrimitive={onCreatePrimitive}+ onSnapToGround={() => {}}+ onUndo={() => {}}+ onRedo={() => {}}+ onOpenLTModal={() => {}}+ onBakeTo2D={() => {}}+ onClose={() => {}}+ />+ );+ });++ const shapes: Primitive3DType[] = ['cube', 'sphere', 'capsule', 'cylinder', 'pyramid'];+ for (const shape of shapes) {+ const trigger = findByTestId(container, 'toolbar-3d-primitives-btn');+ expect(trigger).not.toBeNull();+ act(() => {+ trigger!.dispatchEvent(new Event('click', { bubbles: true }));+ });+ const btn = findByTestId(container, `toolbar-3d-primitive-${shape}`);+ expect(btn).not.toBeNull();+ act(() => {+ btn!.dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(findByTestId(container, 'toolbar-3d-primitives-popover')).toBeNull();+ }++ expect(onCreatePrimitive.mock.calls.map((c) => c[0])).toEqual(shapes);+ });++ it('triggers scene3DBridge.createPrimitive for every primitive in Tool3DPropertyInspector', () => {+ const createSpy = vi.fn();+ scene3DBridge.createPrimitive = createSpy;+ documentStoreActions.setDocuments([+ {+ id: 'doc-1',+ name: 'Test',+ dimensions: { width: 800, height: 600, dpi: 300 },+ colorMode: 'color',+ layers: [],+ activeLayerId: '',+ },+ ]);+ documentStoreActions.setActiveDocumentId('doc-1');+ uiStoreActions.set3DLayerOpen(true);++ act(() => {+ root.render(<Tool3DPropertyInspector />);+ });++ const shapes: Primitive3DType[] = ['cube', 'sphere', 'capsule', 'cylinder', 'pyramid'];+ for (const shape of shapes) {+ const btn = findByTestId(container, `inspector-3d-primitive-${shape}`);+ expect(btn).not.toBeNull();+ act(() => {+ btn!.dispatchEvent(new Event('click', { bubbles: true }));+ });+ }++ expect(createSpy.mock.calls.map((c) => c[0])).toEqual(shapes);+ });++ it('imports dropped .glb/.obj models in 3D mode via HTML5 drag-and-drop without affecting image layer drops', async () => {+ const importImageFileAsLayer = vi.fn(async (file: File) => ({ id: 'l-1', name: file.name }));+ const import3DModelFile = vi.fn();+ const onMarkDirty = vi.fn();+ const showToast = vi.fn();++ const hookState: { current: UseExternalFileDropResult | null } = { current: null };+ function Harness() {+ hookState.current = useExternalFileDrop({+ enabled: true,+ is3DModeActive: true,+ importImageFileAsLayer,+ import3DModelFile,+ onMarkDirty,+ showToast,+ });+ return null;+ }++ const canvasZone = doc.createElement('main');+ canvasZone.setAttribute('data-drop-zone', 'canvas');+ doc.body.appendChild(canvasZone);++ const layersZone = doc.createElement('aside');+ layersZone.setAttribute('data-drop-zone', 'layers');+ doc.body.appendChild(layersZone);++ act(() => {+ root.render(<Harness />);+ });++ // 1. Dragging a .glb file over canvas highlights with payloadKind: '3d-model'+ const glbFile = new File([new Uint8Array([1, 2, 3, 4])], 'hero.glb', {+ type: 'model/gltf-binary',+ });+ doc.hitElement = canvasZone;+ const dragOverCanvas = new Event('dragover', { bubbles: true, cancelable: true });+ Object.defineProperty(dragOverCanvas, 'clientX', { value: 100 });+ Object.defineProperty(dragOverCanvas, 'clientY', { value: 100 });+ Object.defineProperty(dragOverCanvas, 'dataTransfer', {+ value: { types: ['Files'], files: [glbFile], dropEffect: 'none' },+ });++ act(() => {+ canvasZone.dispatchEvent(dragOverCanvas);+ });+ expect(hookState.current?.activeDropTarget).toEqual({ zone: 'canvas', payloadKind: '3d-model' });++ // 2. Dragging a .glb file over layers panel clears highlight (3D models don't insert into layer rows)+ doc.hitElement = layersZone;+ const dragOverLayers = new Event('dragover', { bubbles: true, cancelable: true });+ Object.defineProperty(dragOverLayers, 'clientX', { value: 100 });+ Object.defineProperty(dragOverLayers, 'clientY', { value: 100 });+ Object.defineProperty(dragOverLayers, 'dataTransfer', {+ value: { types: ['Files'], files: [glbFile], dropEffect: 'none' },+ });+ act(() => {+ layersZone.dispatchEvent(dragOverLayers);+ });+ expect(hookState.current?.activeDropTarget).toBeNull();++ // 3. Dropping a .glb file on canvas calls import3DModelFile and NOT importImageFileAsLayer+ doc.hitElement = canvasZone;+ const drop3DEvent = new Event('drop', { bubbles: true, cancelable: true });+ Object.defineProperty(drop3DEvent, 'clientX', { value: 100 });+ Object.defineProperty(drop3DEvent, 'clientY', { value: 100 });+ Object.defineProperty(drop3DEvent, 'dataTransfer', {+ value: { types: ['Files'], files: [glbFile] },+ });+ await act(async () => {+ canvasZone.dispatchEvent(drop3DEvent);+ await Promise.resolve();+ });+ expect(import3DModelFile).toHaveBeenCalledTimes(1);+ expect(import3DModelFile).toHaveBeenCalledWith(glbFile);+ expect(importImageFileAsLayer).not.toHaveBeenCalled();++ // 4. Dropping a .png image on canvas while in 3D mode still imports as a 2D layer+ const pngFile = new File([new Uint8Array([137, 80, 78, 71])], 'ref.png', {+ type: 'image/png',+ });+ const dropImgEvent = new Event('drop', { bubbles: true, cancelable: true });+ Object.defineProperty(dropImgEvent, 'clientX', { value: 100 });+ Object.defineProperty(dropImgEvent, 'clientY', { value: 100 });+ Object.defineProperty(dropImgEvent, 'dataTransfer', {+ value: { types: ['Files'], files: [pngFile] },+ });+ await act(async () => {+ canvasZone.dispatchEvent(dropImgEvent);+ await Promise.resolve();+ });+ expect(importImageFileAsLayer).toHaveBeenCalledTimes(1);+ expect(onMarkDirty).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/utils/__tests__/primitives3D.test.ts b/src/utils/__tests__/primitives3D.test.tsnew file mode 100644index 0000000..5092567--- /dev/null+++ b/src/utils/__tests__/primitives3D.test.ts@@ -0,0 +1,89 @@+import { describe, it, expect, beforeEach } from 'vitest';+import * as THREE from 'three';+import {+ PRIMITIVE_3D_ITEMS,+ Primitive3DType,+ createPrimitive3DGeometry,+ createPrimitive3DObject,+} from '../primitives3D';+import { store3DActions, use3DStore } from '../../stores';++describe('3D Primitives Builder & Store Integration', () => {+ beforeEach(() => {+ store3DActions.resetSceneMeta();+ });++ it('exposes cube, sphere, capsule, cylinder, and pyramid primitives', () => {+ expect(PRIMITIVE_3D_ITEMS.map((p) => p.type)).toEqual([+ 'cube',+ 'sphere',+ 'capsule',+ 'cylinder',+ 'pyramid',+ ]);+ });++ it.each<Primitive3DType>(['cube', 'sphere', 'capsule', 'cylinder', 'pyramid'])(+ 'creates a valid floor-aligned %s primitive mesh ready for shading and shadows',+ (type) => {+ const { group, mesh, displayName } = createPrimitive3DObject(type);++ expect(displayName.length).toBeGreaterThan(0);+ expect(group.children).toContain(mesh);+ expect(mesh.isMesh).toBe(true);+ expect(mesh.castShadow).toBe(true);+ expect(mesh.receiveShadow).toBe(true);+ expect(mesh.userData.hasCustomMaterial).toBe(false);+ expect(mesh.userData.primitiveType).toBe(type);+ expect(mesh.userData.origGeometry).toBe(mesh.geometry);+ expect(mesh.userData.origMaterial).toBe(mesh.material);++ const posAttr = mesh.geometry.getAttribute('position');+ const normAttr = mesh.geometry.getAttribute('normal');+ expect(posAttr).toBeDefined();+ expect(posAttr.count).toBeGreaterThan(0);+ expect(normAttr).toBeDefined();+ expect(normAttr.count).toBe(posAttr.count);++ group.updateMatrixWorld(true);+ const box = new THREE.Box3().setFromObject(group);+ const center = new THREE.Vector3();+ const size = new THREE.Vector3();+ box.getCenter(center);+ box.getSize(size);++ expect(box.min.y).toBeCloseTo(0, 4);+ expect(center.x).toBeCloseTo(0, 4);+ expect(center.z).toBeCloseTo(0, 4);+ expect(size.x).toBeGreaterThan(0.5);+ expect(size.y).toBeGreaterThan(0.5);+ expect(size.z).toBeGreaterThan(0.5);++ mesh.geometry.dispose();+ (mesh.material as THREE.Material).dispose();+ }+ );++ it('builds pyramid with flat non-indexed normals so triangular facets remain crisp', () => {+ const geom = createPrimitive3DGeometry('pyramid');+ expect(geom.index).toBeNull();+ expect(geom.getAttribute('normal')).toBeDefined();+ geom.dispose();+ });++ it('tracks active primitive kind in use3DStore and clears it when switching to an imported model', () => {+ store3DActions.setLoadedModel('Capsule', 'primitive', false, 'capsule');+ expect(use3DStore.getState().loadedModelName).toBe('Capsule');+ expect(use3DStore.getState().modelKind).toBe('primitive');+ expect(use3DStore.getState().activePrimitiveType).toBe('capsule');++ store3DActions.setLoadedModel('hero.glb', 'imported', false);+ expect(use3DStore.getState().modelKind).toBe('imported');+ expect(use3DStore.getState().activePrimitiveType).toBeNull();++ store3DActions.setLoadedModel('Pyramid', 'primitive', false, 'pyramid');+ store3DActions.resetSceneMeta();+ expect(use3DStore.getState().modelKind).toBe('none');+ expect(use3DStore.getState().activePrimitiveType).toBeNull();+ });+});diff --git a/src/utils/__tests__/puppetAndCageWarp.test.ts b/src/utils/__tests__/puppetAndCageWarp.test.tsnew file mode 100644index 0000000..ddbe5ae--- /dev/null+++ b/src/utils/__tests__/puppetAndCageWarp.test.ts@@ -0,0 +1,770 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import type { Point2D, PuppetPin, TransformSession } from '../../types/editor';+import {+ buildPuppetMesh,+ createInitialPuppetState,+ getDeformedMeshBounds,+ isPuppetDeformed,+ mapDeformedPointToPuppetRest,+ solvePuppetDeformation,+} from '../puppetWarpEngine';+import {+ buildAutoCagePoints,+ computeMeanValueWeights,+ createInitialCageState,+ evaluateCageMesh,+ isCageDeformed,+ isPointInPolygon,+} from '../cageWarpEngine';+import {+ createDefaultMeshPoints,+ createDefaultPerspectiveQuad,+ processDeformedTrianglesTransformChunks,+ rasterizeTrianglesCpuLanczos3,+} from '../transformEngine';+import {+ flipTransformSession,+ releaseTransformSessionCanvases,+ resetTransformSession,+ switchTransformSessionMode,+} from '../transformModeTransition';++class MockImageData {+ data: Uint8ClampedArray;+ width: number;+ height: number;+ constructor(dataOrW: Uint8ClampedArray | number, widthOrH: number, height?: number) {+ if (typeof dataOrW === 'number') {+ this.width = dataOrW;+ this.height = widthOrH;+ this.data = new Uint8ClampedArray(this.width * this.height * 4);+ } else {+ this.data = dataOrW;+ this.width = widthOrH;+ this.height = height ?? Math.floor(dataOrW.length / (4 * widthOrH));+ }+ }+}++class MockCanvas {+ private _w = 0;+ private _h = 0;+ pixels = new Uint8ClampedArray(0);+ released = false;++ get width() {+ return this._w;+ }+ set width(v: number) {+ this._w = Math.max(0, Math.floor(v));+ if (this._w === 0) this.released = true;+ this.pixels = new Uint8ClampedArray(this._w * this._h * 4);+ }+ get height() {+ return this._h;+ }+ set height(v: number) {+ this._h = Math.max(0, Math.floor(v));+ if (this._h === 0) this.released = true;+ this.pixels = new Uint8ClampedArray(this._w * this._h * 4);+ }++ getContext(type: string) {+ if (type !== '2d') return null;+ const self = this;+ return {+ createImageData(w: number, h: number) {+ return new MockImageData(w, h);+ },+ putImageData(img: MockImageData, dx = 0, dy = 0) {+ for (let y = 0; y < img.height; y++) {+ const ty = dy + y;+ if (ty < 0 || ty >= self._h) continue;+ for (let x = 0; x < img.width; x++) {+ const tx = dx + x;+ if (tx < 0 || tx >= self._w) continue;+ const sOff = (y * img.width + x) * 4;+ const dOff = (ty * self._w + tx) * 4;+ self.pixels[dOff] = img.data[sOff];+ self.pixels[dOff + 1] = img.data[sOff + 1];+ self.pixels[dOff + 2] = img.data[sOff + 2];+ self.pixels[dOff + 3] = img.data[sOff + 3];+ }+ }+ },+ getImageData(sx: number, sy: number, sw: number, sh: number) {+ const out = new Uint8ClampedArray(sw * sh * 4);+ for (let y = 0; y < sh; y++) {+ const py = sy + y;+ if (py < 0 || py >= self._h) continue;+ for (let x = 0; x < sw; x++) {+ const px = sx + x;+ if (px < 0 || px >= self._w) continue;+ const sOff = (py * self._w + px) * 4;+ const dOff = (y * sw + x) * 4;+ out[dOff] = self.pixels[sOff];+ out[dOff + 1] = self.pixels[sOff + 1];+ out[dOff + 2] = self.pixels[sOff + 2];+ out[dOff + 3] = self.pixels[sOff + 3];+ }+ }+ return new MockImageData(out, sw, sh);+ },+ };+ }+}++function makePaintedBuffer(+ w: number,+ h: number,+ painter: (x: number, y: number) => [number, number, number, number]+): { canvas: HTMLCanvasElement; pixels: { data: Uint8ClampedArray; width: number; height: number } } {+ const canvas = new MockCanvas();+ canvas.width = w;+ canvas.height = h;+ const data = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const [r, g, b, a] = painter(x, y);+ const off = (y * w + x) * 4;+ data[off] = r;+ data[off + 1] = g;+ data[off + 2] = b;+ data[off + 3] = a;+ }+ }+ canvas.pixels.set(data);+ return {+ canvas: canvas as unknown as HTMLCanvasElement,+ pixels: { data, width: w, height: h },+ };+}++function makeSession(+ x: number,+ y: number,+ w: number,+ h: number,+ painter: (px: number, py: number) => [number, number, number, number]+): TransformSession {+ const { canvas, pixels } = makePaintedBuffer(w, h, painter);+ const quad = createDefaultPerspectiveQuad(x, y, w, h, 0);+ return {+ active: true,+ layerId: 'layer-1',+ sourceCanvas: canvas,+ sourcePixels: pixels,+ bounds: { x, y, width: w, height: h },+ x,+ y,+ width: w,+ height: h,+ rotation: 0,+ flipH: false,+ flipV: false,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ };+}++/** Paints a stylized character silhouette (head, neck, torso, right arm separated from torso by gap) */+function paintCharacterSilhouette(x: number, y: number): [number, number, number, number] {+ // Head circle centered at (100, 35), r=20+ if (Math.hypot(x - 100, y - 35) <= 20) return [240, 200, 175, 255];+ // Neck: x in [92..108], y in [50..66]+ if (x >= 92 && x <= 108 && y >= 50 && y <= 66) return [230, 185, 160, 255];+ // Torso: x in [76..124], y in [64..160]+ if (x >= 76 && x <= 124 && y >= 64 && y <= 160) return [70, 95, 190, 255];+ // Shoulder bridge to right arm: x in [120..158], y in [66..84]+ if (x >= 120 && x <= 158 && y >= 66 && y <= 84) return [190, 70, 90, 255];+ // Hanging right arm: x in [142..158], y in [66..158] (18px clear gap from torso at x=125..141!)+ if (x >= 142 && x <= 158 && y >= 66 && y <= 158) return [210, 75, 95, 255];+ return [0, 0, 0, 0];+}++describe('Puppet Warp ARAP Engine', () => {+ it('builds a silhouette-conforming equilateral mesh respecting density and separating disconnected islands', () => {+ const { pixels } = makePaintedBuffer(200, 200, (x, y) => {+ // Main character silhouette + floating detached sparkle at (25, 25)+ if (Math.hypot(x - 25, y - 25) <= 8) return [255, 230, 80, 255];+ return paintCharacterSilhouette(x, y);+ });+ const quad = createDefaultPerspectiveQuad(0, 0, 200, 200, 0);++ const coarse = buildPuppetMesh(pixels, 200, 200, quad, 'coarse', 4);+ const normal = buildPuppetMesh(pixels, 200, 200, quad, 'normal', 4);+ const fine = buildPuppetMesh(pixels, 200, 200, quad, 'fine', 4);++ expect(coarse.restWorldX.length).toBeLessThan(normal.restWorldX.length);+ expect(normal.restWorldX.length).toBeLessThan(fine.restWorldX.length);+ expect(normal.triangles.length).toBeGreaterThan(30);+ expect(normal.componentCount).toBe(2); // Main character + floating sparkle+ });++ it('produces exact identity with 0 pins or unmoved pins, and exact rigid transform with 1 pin', () => {+ const { pixels } = makePaintedBuffer(200, 200, paintCharacterSilhouette);+ const quad = createDefaultPerspectiveQuad(10, 20, 200, 200, 0);+ const mesh = buildPuppetMesh(pixels, 200, 200, quad, 'normal', 4);++ // 0 pins -> exact identity+ const res0 = solvePuppetDeformation(mesh, [], 'normal');+ for (let i = 0; i < mesh.restWorldX.length; i++) {+ expect(res0.x[i]).toBe(mesh.restWorldX[i]);+ expect(res0.y[i]).toBe(mesh.restWorldY[i]);+ }++ // 1 pin moved by (+30, -15) and rotated 90 deg -> exact rigid motion+ const pin1: PuppetPin = {+ id: 'p1',+ restX: 110,+ restY: 120,+ x: 140,+ y: 105,+ rotation: 90,+ depth: 0,+ };+ const res1 = solvePuppetDeformation(mesh, [pin1], 'normal');+ for (let i = 0; i < mesh.restWorldX.length; i++) {+ const dx = mesh.restWorldX[i] - pin1.restX;+ const dy = mesh.restWorldY[i] - pin1.restY;+ // 90 deg CW in y-down: (dx, dy) -> (-dy, dx)+ expect(res1.x[i]).toBeCloseTo(pin1.x - dy, 3);+ expect(res1.y[i]).toBeCloseTo(pin1.y + dx, 3);+ }+ });++ it('articulates 6 character joint pins smoothly, isolates limbs across transparent gaps, and preserves rigidity', () => {+ const { pixels } = makePaintedBuffer(200, 200, paintCharacterSilhouette);+ const quad = createDefaultPerspectiveQuad(0, 0, 200, 200, 0);+ const mesh = buildPuppetMesh(pixels, 200, 200, quad, 'normal', 3);++ // Place 6 joint pins: head, neck, torso-hip, shoulder, elbow, wrist+ const pins: PuppetPin[] = [+ { id: 'head', restX: 100, restY: 32, x: 100, y: 32, rotation: 0, depth: 0 },+ { id: 'neck', restX: 100, restY: 58, x: 100, y: 58, rotation: 0, depth: 0 },+ { id: 'hip', restX: 100, restY: 145, x: 100, y: 145, rotation: 0, depth: 0 },+ { id: 'shoulder', restX: 148, restY: 75, x: 148, y: 75, rotation: 0, depth: 0 },+ { id: 'elbow', restX: 150, restY: 112, x: 150, y: 112, rotation: 0, depth: 0 },+ // Bend the wrist outward to the right & up by (+30, -15)+ { id: 'wrist', restX: 150, restY: 150, x: 180, y: 135, rotation: 0, depth: 0 },+ ];++ const solvedNormal = solvePuppetDeformation(mesh, pins, 'normal');+ const solvedRigid = solvePuppetDeformation(mesh, pins, 'rigid');+ const solvedDistort = solvePuppetDeformation(mesh, pins, 'distort');++ // Helper: find nearest mesh vertex to (x, y)+ const nearestVertex = (qx: number, qy: number) => {+ let best = 0;+ let bestD = Infinity;+ for (let i = 0; i < mesh.restWorldX.length; i++) {+ const d = Math.hypot(mesh.restWorldX[i] - qx, mesh.restWorldY[i] - qy);+ if (d < bestD) {+ bestD = d;+ best = i;+ }+ }+ return best;+ };++ // 1. Wrist vertex moved strongly toward target (+30, -15)+ const wristV = nearestVertex(150, 150);+ expect(solvedNormal.x[wristV] - mesh.restWorldX[wristV]).toBeGreaterThan(22);+ expect(solvedNormal.y[wristV] - mesh.restWorldY[wristV]).toBeLessThan(-10);++ // 2. Adjacent lower-right torso (118, 145) across the transparent gap stayed anchored!+ const torsoEdgeV = nearestVertex(118, 145);+ const torsoDrift = Math.hypot(+ solvedNormal.x[torsoEdgeV] - mesh.restWorldX[torsoEdgeV],+ solvedNormal.y[torsoEdgeV] - mesh.restWorldY[torsoEdgeV]+ );+ expect(torsoDrift).toBeLessThan(1.5);++ // 3. Head stayed anchored while arm moved+ const headV = nearestVertex(100, 32);+ const headDrift = Math.hypot(+ solvedNormal.x[headV] - mesh.restWorldX[headV],+ solvedNormal.y[headV] - mesh.restWorldY[headV]+ );+ expect(headDrift).toBeLessThan(1.0);++ // 4. Rigid mode preserves triangle edge lengths better than Distort under stretch+ const stretchPins = pins.map((p) =>+ p.id === 'wrist' ? { ...p, x: 150, y: 185 } : p+ );+ const rigidStretch = solvePuppetDeformation(mesh, stretchPins, 'rigid');+ const distortStretch = solvePuppetDeformation(mesh, stretchPins, 'distort');++ // Measure average triangle area scale deviation on forearm triangles (x > 135, y > 110)+ const avgAreaError = (sx: Float32Array, sy: Float32Array) => {+ let errSum = 0;+ let count = 0;+ for (let t = 0; t < mesh.triangles.length; t += 3) {+ const a = mesh.triangles[t];+ const b = mesh.triangles[t + 1];+ const c = mesh.triangles[t + 2];+ const cx = (mesh.restWorldX[a] + mesh.restWorldX[b] + mesh.restWorldX[c]) / 3;+ const cy = (mesh.restWorldY[a] + mesh.restWorldY[b] + mesh.restWorldY[c]) / 3;+ if (cx < 135 || cy < 110) continue;+ const restArea = Math.abs(+ (mesh.restWorldX[b] - mesh.restWorldX[a]) * (mesh.restWorldY[c] - mesh.restWorldY[a]) -+ (mesh.restWorldY[b] - mesh.restWorldY[a]) * (mesh.restWorldX[c] - mesh.restWorldX[a])+ );+ const defArea = Math.abs(+ (sx[b] - sx[a]) * (sy[c] - sy[a]) - (sy[b] - sy[a]) * (sx[c] - sx[a])+ );+ if (restArea > 1e-4) {+ errSum += Math.abs(defArea / restArea - 1);+ count++;+ }+ }+ return count > 0 ? errSum / count : 0;+ };++ expect(avgAreaError(rigidStretch.x, rigidStretch.y)).toBeLessThan(+ avgAreaError(distortStretch.x, distortStretch.y)+ );+ expect(solvedRigid.x.length).toBe(mesh.restWorldX.length);+ expect(solvedDistort.x.length).toBe(mesh.restWorldX.length);+ });++ it('supports explicit pin rotation (head tilt), zero-jump pin placement on deformed mesh, and pin depth ordering', () => {+ const { pixels } = makePaintedBuffer(200, 200, paintCharacterSilhouette);+ const quad = createDefaultPerspectiveQuad(0, 0, 200, 200, 0);+ const mesh = buildPuppetMesh(pixels, 200, 200, quad, 'normal', 4);++ // Tilt head by +25 deg while anchoring neck & hip+ const tiltPins: PuppetPin[] = [+ { id: 'head', restX: 100, restY: 35, x: 100, y: 35, rotation: 25, depth: 2 },+ { id: 'neck', restX: 100, restY: 58, x: 100, y: 58, rotation: 0, depth: 0 },+ { id: 'hip', restX: 100, restY: 145, x: 100, y: 145, rotation: 0, depth: -1 },+ ];+ const tilted = solvePuppetDeformation(mesh, tiltPins, 'normal');++ // Top of head (100, 18) should swing rightward (+x) under positive CW rotation in y-down coords+ let topHeadV = 0;+ let bestD = Infinity;+ for (let i = 0; i < mesh.restWorldX.length; i++) {+ const d = Math.hypot(mesh.restWorldX[i] - 100, mesh.restWorldY[i] - 18);+ if (d < bestD) {+ bestD = d;+ topHeadV = i;+ }+ }+ expect(tilted.x[topHeadV] - mesh.restWorldX[topHeadV]).toBeGreaterThan(4);++ // Pin depth ordering must produce triOrder placing high-depth head triangles after low-depth hip triangles+ expect(tilted.triOrder).toBeDefined();+ const order = tilted.triOrder!;+ expect(order.length).toBe(mesh.triangles.length / 3);+ const firstTri = order[0];+ const lastTri = order[order.length - 1];+ const triY = (ti: number) => {+ const a = mesh.triangles[ti * 3];+ const b = mesh.triangles[ti * 3 + 1];+ const c = mesh.triangles[ti * 3 + 2];+ return (mesh.restWorldY[a] + mesh.restWorldY[b] + mesh.restWorldY[c]) / 3;+ };+ // Low-depth hip (y ~ 145) renders first; high-depth head (y ~ 35) renders on top (last)+ expect(triY(firstTri)).toBeGreaterThan(triY(lastTri));++ // Clicking on the already-deformed mesh maps back accurately to rest coordinates (zero jump!)+ const testX = tilted.x[topHeadV];+ const testY = tilted.y[topHeadV];+ const mapped = mapDeformedPointToPuppetRest(mesh, tilted.x, tilted.y, testX, testY);+ expect(mapped.inside).toBe(true);+ expect(mapped.restX).toBeCloseTo(mesh.restWorldX[topHeadV], 2);+ expect(mapped.restY).toBeCloseTo(mesh.restWorldY[topHeadV], 2);+ });++ it('moves unpinned floating islands rigidly with the nearest pinned limb and decouples them when pinned', () => {+ const { pixels } = makePaintedBuffer(200, 200, (x, y) => {+ // Floating hair accessory / sparkle at (45, 22) clearly separated from head (100, 35, r=20)+ if (Math.hypot(x - 45, y - 22) <= 6) return [255, 255, 200, 255];+ return paintCharacterSilhouette(x, y);+ });+ const quad = createDefaultPerspectiveQuad(0, 0, 200, 200, 0);+ const mesh = buildPuppetMesh(pixels, 200, 200, quad, 'normal', 2);+ expect(mesh.componentCount).toBe(2);++ // Move head pin right by +20px while keeping hip anchored+ const pins: PuppetPin[] = [+ { id: 'head', restX: 100, restY: 35, x: 120, y: 35, rotation: 0, depth: 0 },+ { id: 'hip', restX: 100, restY: 145, x: 100, y: 145, rotation: 0, depth: 0 },+ ];+ const solved = solvePuppetDeformation(mesh, pins, 'normal');++ // Find a vertex on the floating island near (45, 22)+ let islandV = -1;+ for (let i = 0; i < mesh.restWorldX.length; i++) {+ if (Math.hypot(mesh.restWorldX[i] - 45, mesh.restWorldY[i] - 22) < 12) {+ islandV = i;+ break;+ }+ }+ expect(islandV).toBeGreaterThanOrEqual(0);+ // Unpinned floating island follows the head rightward instead of staying stranded+ expect(solved.x[islandV] - mesh.restWorldX[islandV]).toBeGreaterThan(10);++ // Placing a pin directly on the floating island decouples it so it stays anchored at (45, 22)+ const independentPins: PuppetPin[] = [+ ...pins,+ { id: 'sparkle', restX: 45, restY: 22, x: 45, y: 22, rotation: 0, depth: 0 },+ ];+ const solvedIndep = solvePuppetDeformation(mesh, independentPins, 'normal');+ expect(Math.abs(solvedIndep.x[islandV] - mesh.restWorldX[islandV])).toBeLessThan(0.01);+ expect(Math.abs(solvedIndep.y[islandV] - mesh.restWorldY[islandV])).toBeLessThan(0.01);+ });+});++describe('Cage Transform & Mean Value Coordinates Engine', () => {+ it('satisfies partition of unity, exact linear precision, and boundary interpolation on concave polygons', () => {+ // Non-convex L-shaped polygon cage+ const concavePoly: Point2D[] = [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 100, y: 40 },+ { x: 40, y: 40 },+ { x: 40, y: 100 },+ { x: 0, y: 100 },+ ];++ const weights = new Float64Array(concavePoly.length);+ const testPoints: Point2D[] = [+ { x: 20, y: 20 },+ { x: 75, y: 20 },+ { x: 20, y: 75 },+ { x: 50, y: 0 }, // midpoint on top edge+ { x: 40, y: 40 }, // concave reflex vertex+ ];++ for (const pt of testPoints) {+ expect(isPointInPolygon(pt.x, pt.y, concavePoly)).toBe(true);+ expect(computeMeanValueWeights(pt.x, pt.y, concavePoly, weights)).toBe(true);++ let sumW = 0;+ let rx = 0;+ let ry = 0;+ for (let i = 0; i < concavePoly.length; i++) {+ sumW += weights[i];+ rx += weights[i] * concavePoly[i].x;+ ry += weights[i] * concavePoly[i].y;+ }+ expect(sumW).toBeCloseTo(1, 6);+ expect(rx).toBeCloseTo(pt.x, 5);+ expect(ry).toBeCloseTo(pt.y, 5);+ }++ // Outside point inside the concave cutout (80, 80) is correctly outside+ expect(isPointInPolygon(80, 80, concavePoly)).toBe(false);+ });++ it('auto-fits a silhouette cage containing all opaque pixels and localizes custom sub-cage warps', () => {+ const { pixels } = makePaintedBuffer(200, 200, paintCharacterSilhouette);+ const quad = createDefaultPerspectiveQuad(0, 0, 200, 200, 0);+ const autoPoints = buildAutoCagePoints(pixels, 200, 200, quad);+ expect(autoPoints.length).toBeGreaterThanOrEqual(6);++ const restPoly = autoPoints.map((p) => ({ x: p.restX, y: p.restY }));+ // Key opaque silhouette landmarks must lie strictly inside the auto-fitted cage+ expect(isPointInPolygon(100, 35, restPoly)).toBe(true); // head+ expect(isPointInPolygon(100, 155, restPoly)).toBe(true); // lower torso+ expect(isPointInPolygon(150, 150, restPoly)).toBe(true); // wrist++ // Custom sub-cage covering ONLY the top half (y: 0..80)+ const subCage = {+ points: [+ { id: 'c0', restX: 60, restY: 0, x: 60, y: 0 },+ { id: 'c1', restX: 140, restY: 0, x: 170, y: 10 }, // pull top-right corner+ { id: 'c2', restX: 140, restY: 80, x: 140, y: 80 },+ { id: 'c3', restX: 60, restY: 80, x: 60, y: 80 },+ ],+ closed: true,+ phase: 'deform' as const,+ selectedPointId: null,+ showMesh: false,+ };+ expect(isCageDeformed(subCage)).toBe(true);++ const evalRes = evaluateCageMesh(200, 200, quad, subCage, false);+ // Find vertex inside top-right of sub-cage (near 120, 20) vs outside below (near 100, 140)+ let insideMoved = false;+ let outsideDriftMax = 0;+ for (let i = 0; i < evalRes.uvX.length; i++) {+ const rx = evalRes.uvX[i] * 200;+ const ry = evalRes.uvY[i] * 200;+ const drift = Math.hypot(evalRes.deformedX[i] - rx, evalRes.deformedY[i] - ry);+ if (rx > 100 && rx < 135 && ry > 10 && ry < 40 && drift > 5) {+ insideMoved = true;+ }+ if (ry > 90) {+ outsideDriftMax = Math.max(outsideDriftMax, drift);+ }+ }+ expect(insideMoved).toBe(true);+ expect(outsideDriftMax).toBeLessThan(1e-5);+ });+});++describe('Sharpness Preservation & Anti-Ringing Lanczos-3 Triangle Rasterizer', () => {+ it('warps crisp black lineart via Puppet Warp without losing peak sharpness or producing seams', () => {+ // Crisp 4px dark vertical ink line on transparent background+ const { pixels } = makePaintedBuffer(80, 80, (x, y) =>+ x >= 38 && x <= 41 && y >= 10 && y <= 70 ? [15, 15, 20, 255] : [0, 0, 0, 0]+ );+ const quad = createDefaultPerspectiveQuad(0, 0, 80, 80, 0);+ const mesh = buildPuppetMesh(pixels, 80, 80, quad, 'normal', 4);++ // Gently tilt the top of the line by +12px while anchoring the bottom+ const pins: PuppetPin[] = [+ { id: 'top', restX: 40, restY: 14, x: 52, y: 14, rotation: 0, depth: 0 },+ { id: 'bot', restX: 40, restY: 66, x: 40, y: 66, rotation: 0, depth: 0 },+ ];+ const solved = solvePuppetDeformation(mesh, pins, 'rigid');+ const bounds = getDeformedMeshBounds(solved.x, solved.y);+ const out = rasterizeTrianglesCpuLanczos3(+ pixels,+ solved.x,+ solved.y,+ mesh.uvX,+ mesh.uvY,+ mesh.triangles,+ bounds.minX,+ bounds.minY,+ bounds.width,+ bounds.height+ );++ // Every scanline along the middle of the tilted stroke must have solid full-opacity peak+ // pixels (zero seams/holes) and crisp narrow cross-section (sharp anti-ringing Lanczos-3)+ let continuousRows = 0;+ for (let y = 20; y <= 60; y++) {+ const py = y - bounds.minY;+ if (py < 0 || py >= bounds.height) continue;+ let maxA = 0;+ let opaqueWidth = 0;+ for (let px = 0; px < bounds.width; px++) {+ const a = out[(py * bounds.width + px) * 4 + 3];+ if (a > maxA) maxA = a;+ if (a >= 128) opaqueWidth++;+ }+ if (maxA >= 250) continuousRows++;+ // Original line is 4px wide -> tilted ~12 deg should stay tight (~3..6px, not blurred wide!)+ expect(opaqueWidth).toBeGreaterThanOrEqual(3);+ expect(opaqueWidth).toBeLessThanOrEqual(7);+ }+ expect(continuousRows).toBe(41);+ });++ it('commits deformed triangles cleanly via processDeformedTrianglesTransformChunks', () => {+ const { pixels } = makePaintedBuffer(40, 40, () => [200, 40, 60, 255]);+ const quad = createDefaultPerspectiveQuad(10, 10, 40, 40, 0);+ const mesh = buildPuppetMesh(pixels, 40, 40, quad, 'coarse', 2);+ const solved = solvePuppetDeformation(+ mesh,+ [{ id: 'p1', restX: 30, restY: 30, x: 50, y: 40, rotation: 0, depth: 0 }],+ 'normal'+ );++ const dest = { x: 0, y: 0, width: 100, height: 100 };+ const out = new Uint8ClampedArray(100 * 100 * 4);+ const ok = processDeformedTrianglesTransformChunks(+ pixels,+ solved.x,+ solved.y,+ mesh.uvX,+ mesh.uvY,+ mesh.triangles,+ dest,+ 64,+ (chunk, cx, cy, cw, ch) => {+ for (let row = 0; row < ch; row++) {+ out.set(chunk.subarray(row * cw * 4, (row + 1) * cw * 4), ((cy + row) * 100 + cx) * 4);+ }+ }+ );+ expect(ok).toBe(true);+ // Moved center (50, 40) is solid red; original empty corner (5, 5) is transparent+ expect(out[(40 * 100 + 50) * 4]).toBeGreaterThan(190);+ expect(out[(40 * 100 + 50) * 4 + 3]).toBe(255);+ expect(out[(5 * 100 + 5) * 4 + 3]).toBe(0);+ });+});++describe('Transform Mode Transitions, Multi-Layer Baking, Flip & Reset for Puppet and Cage', () => {+ let prevDocument: unknown;++ beforeEach(() => {+ prevDocument = (globalThis as { document?: unknown }).document;+ (globalThis as { document?: unknown }).document = {+ createElement: () => new MockCanvas(),+ };+ });++ afterEach(() => {+ (globalThis as { document?: unknown }).document = prevDocument;+ });++ it('transitions losslessly between Free, Puppet, and Cage when undeformed, and bakes cleanly when deformed', () => {+ const base = makeSession(20, 20, 60, 60, (x, y) =>+ x >= 10 && x < 50 && y >= 10 && y < 50 ? [40, 180, 220, 255] : [0, 0, 0, 0]+ );++ // Free -> Puppet (no baking!)+ const inPuppet = switchTransformSessionMode({ ...base, x: 40, y: 30 }, 'puppet');+ expect(inPuppet.mode).toBe('puppet');+ expect(inPuppet.sourceCanvas).toBe(base.sourceCanvas);+ expect(inPuppet.puppet?.mesh).toBeDefined();+ expect(isPuppetDeformed(inPuppet.puppet)).toBe(false);++ // Unmodified Puppet -> Cage (still zero baking!)+ const inCage = switchTransformSessionMode(inPuppet, 'cage');+ expect(inCage.mode).toBe('cage');+ expect(inCage.sourceCanvas).toBe(base.sourceCanvas);+ expect(inCage.cage?.closed).toBe(true);+ expect(isCageDeformed(inCage.cage)).toBe(false);++ // Unmodified Cage -> Free recovers moved (40, 30) with zero baking!+ const backFree = switchTransformSessionMode(inCage, 'affine');+ expect(backFree.sourceCanvas).toBe(base.sourceCanvas);+ expect(backFree.x).toBe(40);+ expect(backFree.y).toBe(30);++ // Now deform Puppet and switch to Free -> must bake & expand bounds while preserving originalSourceCanvas+ const warpedPuppet: TransformSession = {+ ...inPuppet,+ puppet: {+ ...inPuppet.puppet!,+ pins: [+ { id: 'p1', restX: 60, restY: 50, x: 60, y: 50, rotation: 0, depth: 0 },+ { id: 'p2', restX: 80, restY: 70, x: 115, y: 85, rotation: 0, depth: 0 },+ ],+ },+ };+ expect(isPuppetDeformed(warpedPuppet.puppet)).toBe(true);++ const bakedFromPuppet = switchTransformSessionMode(warpedPuppet, 'affine');+ expect(bakedFromPuppet.mode).toBe('affine');+ expect(bakedFromPuppet.sourceCanvas).not.toBe(base.sourceCanvas);+ expect(bakedFromPuppet.originalSourceCanvas).toBe(base.sourceCanvas);+ expect(bakedFromPuppet.x + bakedFromPuppet.width).toBeGreaterThan(100);++ // Reset restores original unbaked sourceCanvas and original bounds (20, 20)+ const reset = resetTransformSession(bakedFromPuppet);+ expect(reset.sourceCanvas).toBe(base.sourceCanvas);+ expect(reset.x).toBe(20);+ expect(reset.y).toBe(20);+ releaseTransformSessionCanvases(reset);+ });++ it('preserves independent layers when baking a multi-layer folder Puppet Warp and supports Flip involution', () => {+ const layerA = makePaintedBuffer(50, 50, (x, y) =>+ x < 25 && y < 25 ? [255, 0, 0, 255] : [0, 0, 0, 0]+ );+ const layerB = makePaintedBuffer(50, 50, (x, y) =>+ x >= 25 && y >= 25 ? [0, 0, 255, 255] : [0, 0, 0, 0]+ );+ const preview = makePaintedBuffer(50, 50, (x, y) => {+ if (x < 25 && y < 25) return [255, 0, 0, 255];+ if (x >= 25 && y >= 25) return [0, 0, 255, 255];+ return [0, 0, 0, 0];+ });+ const quad = createDefaultPerspectiveQuad(10, 10, 50, 50, 0);+ const baseSession: TransformSession = {+ active: true,+ layerId: 'layer-a',+ layerIds: ['layer-a', 'layer-b'],+ layerSourceCanvases: new Map([+ ['layer-a', layerA.canvas],+ ['layer-b', layerB.canvas],+ ]),+ layerSourcePixels: new Map([+ ['layer-a', layerA.pixels],+ ['layer-b', layerB.pixels],+ ]),+ sourceCanvas: preview.canvas,+ sourcePixels: preview.pixels,+ bounds: { x: 10, y: 10, width: 50, height: 50 },+ x: 10,+ y: 10,+ width: 50,+ height: 50,+ rotation: 0,+ flipH: false,+ flipV: false,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ };++ const inPuppet = switchTransformSessionMode(baseSession, 'puppet');+ const posed: TransformSession = {+ ...inPuppet,+ puppet: {+ ...inPuppet.puppet!,+ pins: [+ { id: 'a', restX: 20, restY: 20, x: 20, y: 20, rotation: 10, depth: 0 },+ { id: 'b', restX: 48, restY: 48, x: 65, y: 55, rotation: 0, depth: 0 },+ ],+ },+ };++ // Flip horizontal twice is an exact involution (pins + rotation restored)+ const flippedOnce = flipTransformSession(posed, 'horizontal');+ expect(flippedOnce.flipH).toBe(true);+ expect(flippedOnce.puppet!.pins[0].rotation).toBe(-10);+ const flippedTwice = flipTransformSession(flippedOnce, 'horizontal');+ expect(flippedTwice.flipH).toBe(false);+ expect(flippedTwice.puppet!.pins[0].rotation).toBe(10);+ expect(flippedTwice.puppet!.pins[1].x).toBeCloseTo(65, 3);++ // Bake into Cage mode -> Layer A stays pure red, Layer B stays pure blue+ const inCageBaked = switchTransformSessionMode(posed, 'cage');+ expect(inCageBaked.mode).toBe('cage');+ expect(inCageBaked.cage?.closed).toBe(true);+ const bakedA = inCageBaked.layerSourcePixels!.get('layer-a')!;+ const bakedB = inCageBaked.layerSourcePixels!.get('layer-b')!;+ let aRed = 0; let aBlue = 0; let bRed = 0; let bBlue = 0;+ for (let i = 0; i < bakedA.data.length; i += 4) {+ if (bakedA.data[i + 3] > 128) {+ if (bakedA.data[i] > 150) aRed++;+ if (bakedA.data[i + 2] > 150) aBlue++;+ }+ if (bakedB.data[i + 3] > 128) {+ if (bakedB.data[i] > 150) bRed++;+ if (bakedB.data[i + 2] > 150) bBlue++;+ }+ }+ expect(aRed).toBeGreaterThan(50);+ expect(aBlue).toBe(0);+ expect(bBlue).toBeGreaterThan(50);+ expect(bRed).toBe(0);++ // Flip Cage vertically twice is an exact involution+ const cageFlip1 = flipTransformSession(inCageBaked, 'vertical');+ const cageFlip2 = flipTransformSession(cageFlip1, 'vertical');+ expect(cageFlip2.flipV).toBe(false);+ expect(cageFlip2.cage!.points[0].y).toBeCloseTo(inCageBaked.cage!.points[0].y, 3);++ releaseTransformSessionCanvases(cageFlip2);+ });++ it('initializes clean Puppet and Cage states with createInitialPuppetState and createInitialCageState', () => {+ const { pixels } = makePaintedBuffer(64, 64, () => [100, 120, 200, 255]);+ const quad = createDefaultPerspectiveQuad(0, 0, 64, 64, 0);+ const pState = createInitialPuppetState(pixels, 64, 64, quad);+ expect(pState.pins).toEqual([]);+ expect(pState.rigidity).toBe('normal');+ expect(pState.mesh?.triangles.length).toBeGreaterThan(0);++ const cState = createInitialCageState(pixels, 64, 64, quad);+ expect(cState.closed).toBe(true);+ expect(cState.phase).toBe('deform');+ expect(cState.points.length).toBeGreaterThanOrEqual(6);+ });+});diff --git a/src/utils/__tests__/quickBrushPanel.test.tsx b/src/utils/__tests__/quickBrushPanel.test.tsxnew file mode 100644index 0000000..b2f0e2e--- /dev/null+++ b/src/utils/__tests__/quickBrushPanel.test.tsx@@ -0,0 +1,609 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { COMMAND_CATALOG } from '../../types/workspace';+import { CspBrush } from '../../types/editor';+import {+ DEFAULT_QUICK_BRUSH_IDS,+ WORKSPACE_STORAGE_KEY,+ loadWorkspaceState,+ sanitizeQuickBrushPanelState,+} from '../workspacePresets';+import { DEFAULT_COMMANDS, findShortcutConflicts } from '../shortcutManager';+import { ERASER_PRESET_ID } from '../brushPresetManager';+import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';+import { useToolStore } from '../../stores/useToolStore';+import { useUiStore } from '../../stores/useUiStore';+import {+ executeWorkspaceCommand,+ isCommandActive,+ isCommandDisabled,+ WorkspaceCommandHandlers,+} from '../../components/CommandBar';+import { QuickBrushPanel } from '../../components/QuickBrushPanel';+import { SubToolList } from '../../components/SubToolList';++function createMemoryStorage(): Storage {+ const store = new Map<string, string>();+ return {+ get length() {+ return store.size;+ },+ clear() {+ store.clear();+ },+ getItem(key: string) {+ return store.has(key) ? store.get(key)! : null;+ },+ key(index: number) {+ return Array.from(store.keys())[index] ?? null;+ },+ removeItem(key: string) {+ store.delete(key);+ },+ setItem(key: string, value: string) {+ store.set(key, String(value));+ },+ };+}++class MiniText {+ nodeType = 3;+ nodeName = '#text';+ parentNode: MiniEl | null = null;+ constructor(+ public nodeValue: string,+ public ownerDocument: MiniDoc+ ) {}+}++class MiniComment {+ nodeType = 8;+ nodeName = '#comment';+ parentNode: MiniEl | null = null;+ constructor(+ public nodeValue: string,+ public ownerDocument: MiniDoc+ ) {}+}++class MiniEl extends EventTarget {+ nodeType = 1;+ nodeName: string;+ tagName: string;+ namespaceURI = 'http://www.w3.org/1999/xhtml';+ parentNode: MiniEl | null = null;+ childNodes: Array<MiniEl | MiniText | MiniComment> = [];+ style: Record<string, string> = {};+ className = '';+ disabled = false;+ checked = false;+ value = '';+ attrs = new Map<string, string>();++ constructor(+ tag: string,+ public ownerDocument: MiniDoc+ ) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ }++ get firstChild() {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((c) => (c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];+ }++ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ insertBefore<T extends MiniEl | MiniText | MiniComment>(+ node: T,+ ref: MiniEl | MiniText | MiniComment | null+ ): T {+ if (node.parentNode) node.parentNode.removeChild(node);+ node.parentNode = this;+ const idx = ref ? this.childNodes.indexOf(ref) : -1;+ if (idx >= 0) this.childNodes.splice(idx, 0, node);+ else this.childNodes.push(node);+ return node;+ }++ setAttribute(k: string, v: string) {+ this.attrs.set(k, String(v));+ }++ getAttribute(k: string): string | null {+ return this.attrs.get(k) ?? null;+ }++ removeAttribute(k: string) {+ this.attrs.delete(k);+ }++ getContext() {+ return null;+ }++ getBoundingClientRect() {+ return {+ left: 820,+ right: 900,+ top: 120,+ bottom: 520,+ width: 80,+ height: 400,+ x: 820,+ y: 120,+ toJSON: () => ({}),+ };+ }++ contains(target: unknown): boolean {+ if (target === this) return true;+ for (const c of this.childNodes) {+ if (c === target) return true;+ if (c instanceof MiniEl && c.contains(target)) return true;+ }+ return false;+ }++ findByAttr(attr: string, value: string): MiniEl | null {+ if (this.getAttribute(attr) === value) return this;+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) {+ const found = c.findByAttr(attr, value);+ if (found) return found;+ }+ }+ return null;+ }+}++interface MiniDoc {+ nodeType: number;+ nodeName: string;+ documentElement: MiniEl;+ body: MiniEl;+ activeElement: MiniEl;+ defaultView: Record<string, unknown>;+ createElement: (tag: string) => MiniEl;+ createElementNS: (_ns: string, tag: string) => MiniEl;+ createTextNode: (text: string) => MiniText;+ createComment: (text: string) => MiniComment;+ addEventListener: EventTarget['addEventListener'];+ removeEventListener: EventTarget['removeEventListener'];+ dispatchEvent: EventTarget['dispatchEvent'];+}++function installMiniDom() {+ const g = globalThis as unknown as Record<string, unknown>;+ const saved: Record<string, unknown> = {+ window: g.window,+ document: g.document,+ HTMLElement: g.HTMLElement,+ Node: g.Node,+ Element: g.Element,+ requestAnimationFrame: g.requestAnimationFrame,+ cancelAnimationFrame: g.cancelAnimationFrame,+ IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,+ };+ g.IS_REACT_ACT_ENVIRONMENT = true;++ const winTarget = new EventTarget();+ const docTarget = new EventTarget();++ const mockDoc = {+ nodeType: 9,+ nodeName: '#document',+ documentElement: null as unknown as MiniEl,+ body: null as unknown as MiniEl,+ activeElement: null as unknown as MiniEl,+ defaultView: null as unknown as Record<string, unknown>,+ createElement: (tag: string) => new MiniEl(tag, mockDoc),+ createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),+ createTextNode: (text: string) => new MiniText(text, mockDoc),+ createComment: (text: string) => new MiniComment(text, mockDoc),+ addEventListener: docTarget.addEventListener.bind(docTarget),+ removeEventListener: docTarget.removeEventListener.bind(docTarget),+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),+ } as MiniDoc;++ mockDoc.documentElement = new MiniEl('html', mockDoc);+ mockDoc.body = new MiniEl('body', mockDoc);+ mockDoc.documentElement.appendChild(mockDoc.body);+ mockDoc.activeElement = mockDoc.body;++ class MockIFrame extends MiniEl {}+ const rafMock = () => 1;+ const cancelRafMock = () => {};++ const mockWin: Record<string, unknown> = {+ innerWidth: 1440,+ innerHeight: 900,+ document: mockDoc,+ Node: MiniEl,+ Element: MiniEl,+ HTMLElement: MiniEl,+ SVGElement: MiniEl,+ HTMLIFrameElement: MockIFrame,+ Event,+ CustomEvent,+ addEventListener: winTarget.addEventListener.bind(winTarget),+ removeEventListener: winTarget.removeEventListener.bind(winTarget),+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),+ requestAnimationFrame: rafMock,+ cancelAnimationFrame: cancelRafMock,+ };+ mockDoc.defaultView = mockWin;++ g.window = mockWin;+ g.document = mockDoc;+ g.HTMLElement = MiniEl;+ g.Node = MiniEl;+ g.Element = MiniEl;+ g.requestAnimationFrame = rafMock;+ g.cancelAnimationFrame = cancelRafMock;++ const container = new MiniEl('div', mockDoc);+ mockDoc.body.appendChild(container);++ return {+ container,+ cleanup: () => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete g[k];+ else g[k] = v;+ }+ },+ };+}++function invokeReactProp(el: MiniEl | null, propName: string, eventArg?: unknown): void {+ expect(el).not.toBeNull();+ const key = Object.keys(el!).find((k) => k.startsWith('__reactProps'));+ expect(key).toBeDefined();+ const props = (el as unknown as Record<string, Record<string, (arg?: unknown) => void>>)[key!];+ expect(typeof props[propName]).toBe('function');+ props[propName](+ eventArg ?? {+ stopPropagation: () => {},+ preventDefault: () => {},+ }+ );+}++describe('Quick-Access Brush Panel State, Persistence, Shortcuts & UI', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;++ beforeEach(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useWorkspaceStore.reset();+ useToolStore.reset();+ useUiStore.reset();+ });++ afterEach(() => {+ if (prevStorage === undefined) {+ delete (globalThis as unknown as Record<string, unknown>).localStorage;+ } else {+ Object.defineProperty(globalThis, 'localStorage', {+ value: prevStorage,+ configurable: true,+ writable: true,+ });+ }+ });++ it('persists quick brush panel settings, custom order, and sanitizes corrupt/legacy values', () => {+ const initial = useWorkspaceStore.getState().quickBrushPanel;+ expect(initial.visible).toBe(true);+ expect(initial.orientation).toBe('vertical');+ expect(initial.keepVisibleWhenPalettesHidden).toBe(true);+ expect(initial.brushIds).toEqual(DEFAULT_QUICK_BRUSH_IDS);++ // Add, deduplicate, move, reorder, and customize settings+ expect(workspaceStoreActions.addQuickBrush('calligraphy')).toBe(true);+ expect(workspaceStoreActions.addQuickBrush('calligraphy')).toBe(false);+ workspaceStoreActions.reorderQuickBrush('calligraphy', 'g-pen');+ expect(useWorkspaceStore.getState().quickBrushPanel.brushIds[0]).toBe('calligraphy');++ workspaceStoreActions.moveQuickBrush('calligraphy', 1);+ expect(useWorkspaceStore.getState().quickBrushPanel.brushIds[1]).toBe('calligraphy');++ workspaceStoreActions.updateQuickBrushPanelSettings({+ orientation: 'horizontal',+ tileSize: 'large',+ columns: 2,+ previewStyle: 'stroke',+ showNames: false,+ showCategoryColors: false,+ opacity: 0.75,+ title: 'Inking Set',+ locked: true,+ showHideUiButton: true,+ });+ workspaceStoreActions.setQuickBrushPanelPosition({ x: 140, y: 88 }, true);++ // Simulate reload from localStorage+ useWorkspaceStore.reset();+ const reloaded = useWorkspaceStore.getState().quickBrushPanel;+ expect(reloaded.orientation).toBe('horizontal');+ expect(reloaded.tileSize).toBe('large');+ expect(reloaded.columns).toBe(2);+ expect(reloaded.previewStyle).toBe('stroke');+ expect(reloaded.showNames).toBe(false);+ expect(reloaded.showCategoryColors).toBe(false);+ expect(reloaded.opacity).toBe(0.75);+ expect(reloaded.title).toBe('Inking Set');+ expect(reloaded.locked).toBe(true);+ expect(reloaded.showHideUiButton).toBe(true);+ expect(reloaded.position).toEqual({ x: 140, y: 88 });+ expect(reloaded.brushIds[1]).toBe('calligraphy');++ // Sanitizer handles legacy preset IDs, duplicates, and out-of-range opacity+ const sanitized = sanitizeQuickBrushPanelState({+ orientation: 'invalid',+ tileSize: 'huge',+ columns: 99,+ opacity: 0.05,+ brushIds: ['oil-painting', 'oil-flat-alla-prima', ' ', 123],+ position: { x: NaN, y: 10 },+ });+ expect(sanitized.orientation).toBe('vertical');+ expect(sanitized.tileSize).toBe('medium');+ expect(sanitized.columns).toBe(1);+ expect(sanitized.opacity).toBe(0.4);+ expect(sanitized.position).toBeNull();+ expect(sanitized.brushIds).toEqual(['oil-flat-alla-prima']);++ // Corrupt localStorage still recovers safely+ localStorage.setItem(WORKSPACE_STORAGE_KEY, '{broken');+ const recovered = loadWorkspaceState();+ expect(recovered.quickBrushPanel?.brushIds).toEqual(DEFAULT_QUICK_BRUSH_IDS);+ });++ it('registers Shift+B shortcut without conflicts and exposes Command Bar toggle action', () => {+ const cmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.toggleQuickBrushPanel');+ expect(cmd).toBeDefined();+ expect(cmd?.defaultShortcut).toBe('Shift+B');+ expect(findShortcutConflicts('view.toggleQuickBrushPanel', 'Shift+B', {})).toHaveLength(0);++ const catalogEntry = COMMAND_CATALOG.find((c) => c.id === 'toggle-quick-brushes');+ expect(catalogEntry).toBeDefined();++ const handlers: WorkspaceCommandHandlers = {+ onUndo: () => {},+ onRedo: () => {},+ canUndo: false,+ canRedo: false,+ hasOpenDocument: false,+ };+ expect(isCommandDisabled('toggle-quick-brushes', handlers)).toBe(false);+ expect(isCommandActive('toggle-quick-brushes', handlers, false)).toBe(true);++ executeWorkspaceCommand('toggle-quick-brushes', handlers);+ expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);+ expect(isCommandActive('toggle-quick-brushes', handlers, false)).toBe(false);+ });++ describe('UI Rendering, Panel Settings, Hide-UI Behavior & SubToolList Pinning', () => {+ let dom: ReturnType<typeof installMiniDom>;+ let root: Root | null = null;++ const sampleCustomBrush: CspBrush = {+ id: 'inkb-custom-liner',+ name: 'Manga Hero Ink',+ size: 10,+ minSizeFactor: 0.1,+ flow: 1,+ opacity: 1,+ spacing: 0.05,+ hardness: 1,+ thickness: 1,+ antiAlias: 2,+ stabilization: 8,+ angle: 0,+ smoothing: true,+ usePressure: true,+ importedAt: 1700000000000,+ };++ beforeEach(() => {+ dom = installMiniDom();+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root?.unmount();+ });+ root = null;+ }+ dom.cleanup();+ });++ it('renders QuickBrushPanel, switches brushes, stays visible when UI is hidden (Tab), and updates live via Settings popover', () => {+ const renderPanel = () => {+ act(() => {+ if (!root) root = createRoot(dom.container as unknown as Element);+ root.render(<QuickBrushPanel customBrushes={[sampleCustomBrush]} />);+ });+ };++ renderPanel();++ // Panel renders vertically by default with default brushes+ let panel = dom.container.findByAttr('data-testid', 'quick-brush-panel');+ expect(panel).not.toBeNull();+ expect(panel?.getAttribute('data-orientation')).toBe('vertical');+ expect(panel?.getAttribute('data-locked')).toBe('false');++ // Clicking a brush tile selects that brush in useToolStore+ const airbrushTile = dom.container.findByAttr(+ 'data-testid',+ 'quick-brush-tile-soft-glaze-airbrush'+ );+ act(() => {+ invokeReactProp(airbrushTile, 'onClick');+ });+ expect(useToolStore.getState().tool).toBe('brush');+ expect(useToolStore.getState().activePresetId).toBe('soft-glaze-airbrush');++ // Pinning and clicking Eraser activates eraser tool+ act(() => {+ workspaceStoreActions.addQuickBrush(ERASER_PRESET_ID);+ });+ const eraserTile = dom.container.findByAttr(+ 'data-testid',+ `quick-brush-tile-${ERASER_PRESET_ID}`+ );+ act(() => {+ invokeReactProp(eraserTile, 'onClick');+ });+ expect(useToolStore.getState().tool).toBe('eraser');++ // Hiding all palettes (Tab) keeps QuickBrushPanel visible by default+ act(() => {+ workspaceStoreActions.setPalettesHidden(true);+ });+ expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).not.toBeNull();++ // Open Settings popover and switch to Horizontal + enable Hide UI button on bar+ const settingsBtn = dom.container.findByAttr('data-testid', 'quick-brush-settings-btn');+ act(() => {+ invokeReactProp(settingsBtn, 'onClick');+ });+ const body = document.body as unknown as MiniEl;+ const popover = body.findByAttr('data-testid', 'quick-brush-settings-popover');+ expect(popover).not.toBeNull();++ const horizBtn = body.findByAttr('data-testid', 'quick-brush-orient-horizontal');+ act(() => {+ invokeReactProp(horizBtn, 'onClick');+ });+ panel = dom.container.findByAttr('data-testid', 'quick-brush-panel');+ expect(panel?.getAttribute('data-orientation')).toBe('horizontal');+ expect(dom.container.findByAttr('data-testid', 'quick-brush-title-label')?.textContent).toBe(+ 'Favorites'+ );++ // Toggle Hide/Show UI button onto the bar+ const hideUiCheckbox = body.findByAttr('data-testid', 'quick-brush-toggle-hide-ui-btn');+ act(() => {+ invokeReactProp(hideUiCheckbox, 'onChange', { target: { checked: true } });+ });+ expect(dom.container.findByAttr('data-testid', 'quick-brush-hide-ui-btn')).not.toBeNull();++ // Lock button locks panel and hides tile remove buttons+ const lockBtn = dom.container.findByAttr('data-testid', 'quick-brush-lock-btn');+ act(() => {+ invokeReactProp(lockBtn, 'onClick');+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.locked).toBe(true);+ expect(dom.container.findByAttr('data-testid', 'quick-brush-remove-g-pen')).toBeNull();++ // Turning off keepVisibleWhenPalettesHidden hides panel while palettesHidden is true+ act(() => {+ workspaceStoreActions.updateQuickBrushPanelSettings({+ keepVisibleWhenPalettesHidden: false,+ });+ });+ expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).toBeNull();++ // Restoring palettes brings QuickBrushPanel back+ act(() => {+ workspaceStoreActions.setPalettesHidden(false);+ });+ expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).not.toBeNull();++ // Clicking close button hides QuickBrushPanel+ const closeBtn = dom.container.findByAttr('data-testid', 'quick-brush-close-btn');+ act(() => {+ invokeReactProp(closeBtn, 'onClick');+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);+ expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).toBeNull();+ });++ it('adds and removes builtin and custom brushes from SubToolList directly into QuickBrushPanel', () => {+ workspaceStoreActions.setQuickBrushPanelVisible(false);++ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(+ <SubToolList customBrushes={[sampleCustomBrush]} setCustomBrushes={() => {}} />+ );+ });++ // Pin a builtin brush ('calligraphy') from SubToolList — adds it AND opens the hidden Quick Brush Panel+ const pinCalligraphyBtn = dom.container.findByAttr(+ 'data-testid',+ 'subtool-quick-pin-calligraphy'+ );+ act(() => {+ invokeReactProp(pinCalligraphyBtn, 'onClick');+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).toContain('calligraphy');+ expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(true);++ // Pin an imported custom brush from SubToolList+ const pinCustomBtn = dom.container.findByAttr(+ 'data-testid',+ `subtool-quick-pin-${sampleCustomBrush.id}`+ );+ act(() => {+ invokeReactProp(pinCustomBtn, 'onClick');+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).toContain(sampleCustomBrush.id);++ // Clicking again removes the custom brush from Quick Brush Panel+ act(() => {+ invokeReactProp(+ dom.container.findByAttr('data-testid', `subtool-quick-pin-${sampleCustomBrush.id}`),+ 'onClick'+ );+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).not.toContain(+ sampleCustomBrush.id+ );++ // Header Star button toggles Quick Brush Panel visibility+ const headerToggleBtn = dom.container.findByAttr(+ 'data-testid',+ 'subtool-toggle-quick-brush-panel'+ );+ act(() => {+ invokeReactProp(headerToggleBtn, 'onClick');+ });+ expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);+ });+ });+});diff --git a/src/utils/__tests__/quickShape.test.tsx b/src/utils/__tests__/quickShape.test.tsxnew file mode 100644index 0000000..c28e2d4--- /dev/null+++ b/src/utils/__tests__/quickShape.test.tsx@@ -0,0 +1,969 @@+import React from 'react';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ DEFAULT_APP_SETTINGS,+ loadAppSettings,+ saveAppSettings,+} from '../../types/settings';+import {+ QUICK_SHAPE_HOLD_MS,+ QuickShapePreviewState,+ QuickShapeRectangle,+ QuickShapeTriangle,+ buildQuickShapePreview,+ computeArcCircle,+ createQuickShapeSession,+ extractQuickShapeStrokeStyle,+ getRectangleCorners,+ playQuickShapeSnapClick,+ recognizeQuickShape,+ sampleQuickShapePoints,+ updateQuickShapeFromDrag,+} from '../quickShapeEngine';+import { BrushSettings, LayerItem, Point } from '../../types/editor';+import { SparseTileGrid } from '../tileEngine';+import { uiStoreActions, useUiStore } from '../../stores';+import {+ StrokeSessionHelpers,+ UseBrushStrokeSessionParams,+ createInitialStrokeSessionState,+} from '../../hooks/drawing/brushStrokeSession/types';+import { runPointerDown } from '../../hooks/drawing/brushStrokeSession/pointerDownHandler';+import { runPointerMove } from '../../hooks/drawing/brushStrokeSession/pointerMoveHandler';+import { runPointerUp } from '../../hooks/drawing/brushStrokeSession/pointerUpHandler';+import { runFlushPendingPoints } from '../../hooks/drawing/brushStrokeSession/flushPendingPoints';+import {+ abortActiveStrokeSession,+ buildTouchedTileSpansFromSet,+ clearPredictedCanvasSurface,+ computeCanvasPoint,+ createLiveBrushOptions,+ markTouchedTilesInRect,+ resolveEffectiveOpacitySensorValue,+ resolveLiveAntiAliasValue,+ resolveStrokeColorValue,+} from '../../hooks/drawing/brushStrokeSession/strokeHelpers';+import { emitLiveSegmentToDraft } from '../../hooks/drawing/brushStrokeSession/liveSegmentEmitter';++function makePoint(x: number, y: number, pressure = 0.65, width = 8, t = 0): Point {+ return { x, y, pressure, width, timestamp: t };+}++// Deterministic pseudo-noise for realistic human hand-wobble tests+function wobble(idx: number, amp: number): number {+ return Math.sin(idx * 1.73) * amp * 0.65 + Math.cos(idx * 2.91) * amp * 0.35;+}++function makeFreehandLine(+ x0: number,+ y0: number,+ x1: number,+ y1: number,+ steps = 40,+ noise = 2.0+): Point[] {+ const dx = x1 - x0;+ const dy = y1 - y0;+ const len = Math.hypot(dx, dy);+ const nx = -dy / Math.max(1, len);+ const ny = dx / Math.max(1, len);+ const pts: Point[] = [];+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const w = i === 0 || i === steps ? 0 : wobble(i, noise);+ pts.push(makePoint(x0 + dx * t + nx * w, y0 + dy * t + ny * w, 0.7, 10, i * 6));+ }+ return pts;+}++function makeFreehandArc(+ cx: number,+ cy: number,+ radius: number,+ startRad: number,+ sweepRad: number,+ steps = 48,+ noise = 2.5+): Point[] {+ const pts: Point[] = [];+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const a = startRad + sweepRad * t;+ const r = radius + (i === 0 || i === steps ? 0 : wobble(i, noise));+ pts.push(makePoint(cx + Math.cos(a) * r, cy + Math.sin(a) * r, 0.6, 8, i * 6));+ }+ return pts;+}++function makeFreehandEllipse(+ cx: number,+ cy: number,+ rx: number,+ ry: number,+ rotRad: number,+ steps = 64,+ noise = 2.5,+ overshootFrac = 0.05,+ ccw = true+): Point[] {+ const cos = Math.cos(rotRad);+ const sin = Math.sin(rotRad);+ const totalAngle = Math.PI * 2 * (1 + overshootFrac) * (ccw ? 1 : -1);+ const pts: Point[] = [];+ for (let i = 0; i <= steps; i++) {+ const a = (totalAngle * i) / steps;+ const w = wobble(i, noise);+ const lx = Math.cos(a) * (rx + w);+ const ly = Math.sin(a) * (ry + w * 0.7);+ pts.push(+ makePoint(cx + lx * cos - ly * sin, cy + lx * sin + ly * cos, 0.75, 10, i * 6)+ );+ }+ return pts;+}++function makeFreehandPolygon(+ vertices: Array<{ x: number; y: number }>,+ stepsPerEdge = 24,+ noise = 2.0+): Point[] {+ const pts: Point[] = [];+ let idx = 0;+ for (let e = 0; e < vertices.length; e++) {+ const a = vertices[e];+ const b = vertices[(e + 1) % vertices.length];+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const len = Math.max(1, Math.hypot(dx, dy));+ const nx = -dy / len;+ const ny = dx / len;+ for (let s = 0; s < stepsPerEdge; s++) {+ const t = s / stepsPerEdge;+ const w = wobble(idx++, noise);+ pts.push(makePoint(a.x + dx * t + nx * w, a.y + dy * t + ny * w, 0.7, 9, idx * 6));+ }+ }+ // Close slightly near first vertex+ pts.push(makePoint(vertices[0].x + 2, vertices[0].y - 1.5, 0.7, 9, idx * 6));+ return pts;+}++describe('QuickShape Settings (disabled by default)', () => {+ beforeEach(() => {+ const storage: Record<string, string> = {};+ (globalThis as any).localStorage = {+ getItem: (k: string) => storage[k] || null,+ setItem: (k: string, v: string) => {+ storage[k] = String(v);+ },+ removeItem: (k: string) => {+ delete storage[k];+ },+ clear: () => {+ Object.keys(storage).forEach((k) => delete storage[k]);+ },+ };+ });++ it('is disabled by default and persists/sanitizes safely in AppSettings', () => {+ expect(DEFAULT_APP_SETTINGS.quickShapeEnabled).toBe(false);+ expect(loadAppSettings().quickShapeEnabled).toBe(false);++ // Legacy stored settings without quickShapeEnabled default safely to false+ localStorage.setItem('ink_studio_app_settings', JSON.stringify({ themePreset: 'modern' }));+ expect(loadAppSettings().quickShapeEnabled).toBe(false);++ // Corrupted non-boolean value falls back to false+ localStorage.setItem('ink_studio_app_settings', JSON.stringify({ quickShapeEnabled: 'yes' }));+ expect(loadAppSettings().quickShapeEnabled).toBe(false);++ // Enabling persists cleanly+ saveAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: true });+ expect(loadAppSettings().quickShapeEnabled).toBe(true);++ // Disabling persists cleanly+ saveAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: false });+ expect(loadAppSettings().quickShapeEnabled).toBe(false);+ });+});++describe('QuickShape Geometry Recognition (All 6 Shapes)', () => {+ it('recognizes freehand horizontal, vertical, and diagonal lines', () => {+ const diagLine = makeFreehandLine(80, 120, 380, 290, 40, 2.2);+ const res = recognizeQuickShape(diagLine);+ expect(res).not.toBeNull();+ expect(res!.shape.kind).toBe('line');+ if (res!.shape.kind === 'line') {+ expect(res!.shape.start.x).toBeCloseTo(80, 0);+ expect(res!.shape.start.y).toBeCloseTo(120, 0);+ expect(res!.shape.end.x).toBeCloseTo(380, 0);+ expect(res!.shape.end.y).toBeCloseTo(290, 0);+ }++ // Nearly horizontal line auto-aligns cleanly+ const horizLine = makeFreehandLine(50, 200, 350, 204, 40, 1.5);+ const resH = recognizeQuickShape(horizLine);+ expect(resH?.shape.kind).toBe('line');+ if (resH?.shape.kind === 'line') {+ expect(Math.abs(resH.shape.end.y - resH.shape.start.y)).toBeLessThan(1);+ }+ });++ it('recognizes freehand minor and major circular arcs (CW & CCW)', () => {+ const minorArc = makeFreehandArc(300, 300, 140, 0.2, Math.PI * 0.75, 48, 2.5);+ const res1 = recognizeQuickShape(minorArc);+ expect(res1).not.toBeNull();+ expect(res1!.shape.kind).toBe('arc');+ if (res1!.shape.kind === 'arc') {+ const circ = computeArcCircle(res1!.shape.start, res1!.shape.mid, res1!.shape.end);+ expect(circ).not.toBeNull();+ expect(circ!.cx).toBeCloseTo(300, -1);+ expect(circ!.cy).toBeCloseTo(300, -1);+ expect(circ!.radius).toBeCloseTo(140, -1);+ expect(Math.abs(circ!.sweep)).toBeCloseTo(Math.PI * 0.75, 1);+ }++ // Major 230 deg CW arc+ const majorArc = makeFreehandArc(400, 350, 110, 0.4, -Math.PI * 1.28, 60, 2.2);+ const res2 = recognizeQuickShape(majorArc);+ expect(res2).not.toBeNull();+ expect(res2!.shape.kind).toBe('arc');+ if (res2!.shape.kind === 'arc') {+ const circ = computeArcCircle(res2!.shape.start, res2!.shape.mid, res2!.shape.end);+ expect(circ).not.toBeNull();+ expect(Math.abs(circ!.sweep)).toBeGreaterThan(Math.PI);+ }+ });++ it('recognizes freehand circles (with wobble and slight overshoot)', () => {+ const circlePts = makeFreehandEllipse(320, 280, 120, 115, 0.3, 64, 3.0, 0.08, true);+ const res = recognizeQuickShape(circlePts);+ expect(res).not.toBeNull();+ expect(res!.shape.kind).toBe('circle');+ if (res!.shape.kind === 'circle') {+ expect(res!.shape.center.x).toBeCloseTo(320, -1);+ expect(res!.shape.center.y).toBeCloseTo(280, -1);+ expect(res!.shape.radius).toBeGreaterThan(105);+ expect(res!.shape.radius).toBeLessThan(130);+ }+ });++ it('recognizes freehand rotated ellipses without confusing them for rectangles or circles', () => {+ const rot = (28 * Math.PI) / 180;+ const ellPts = makeFreehandEllipse(400, 300, 180, 82, rot, 72, 2.5, 0.04, false);+ const res = recognizeQuickShape(ellPts);+ expect(res).not.toBeNull();+ expect(res!.shape.kind).toBe('ellipse');+ if (res!.shape.kind === 'ellipse') {+ expect(res!.shape.center.x).toBeCloseTo(400, -1);+ expect(res!.shape.center.y).toBeCloseTo(300, -1);+ expect(res!.shape.rx).toBeGreaterThan(165);+ expect(res!.shape.rx).toBeLessThan(195);+ expect(res!.shape.ry).toBeGreaterThan(70);+ expect(res!.shape.ry).toBeLessThan(95);+ expect(Math.abs(res!.shape.rotation - rot)).toBeLessThan(0.18);+ }+ });++ it('recognizes freehand equilateral and scalene triangles', () => {+ const triPts = makeFreehandPolygon(+ [+ { x: 250, y: 120 },+ { x: 420, y: 380 },+ { x: 110, y: 350 },+ ],+ 28,+ 2.5+ );+ const res = recognizeQuickShape(triPts);+ expect(res).not.toBeNull();+ expect(res!.shape.kind).toBe('triangle');+ if (res!.shape.kind === 'triangle') {+ expect(res!.shape.vertices).toHaveLength(3);+ // Every ground-truth corner should match a detected vertex within ~15px+ const expected = [+ { x: 250, y: 120 },+ { x: 420, y: 380 },+ { x: 110, y: 350 },+ ];+ for (const exp of expected) {+ const minD = Math.min(+ ...res!.shape.vertices.map((v) => Math.hypot(v.x - exp.x, v.y - exp.y))+ );+ expect(minD).toBeLessThan(18);+ }+ }+ });++ it('recognizes freehand axis-aligned rectangles, rotated rectangles, and squares', () => {+ // Axis-aligned rectangle+ const rectPts = makeFreehandPolygon(+ [+ { x: 120, y: 140 },+ { x: 440, y: 140 },+ { x: 440, y: 320 },+ { x: 120, y: 320 },+ ],+ 26,+ 2.5+ );+ const res1 = recognizeQuickShape(rectPts);+ expect(res1).not.toBeNull();+ expect(res1!.shape.kind).toBe('rectangle');+ if (res1!.shape.kind === 'rectangle') {+ expect(res1!.shape.center.x).toBeCloseTo(280, -1);+ expect(res1!.shape.center.y).toBeCloseTo(230, -1);+ expect(Math.max(res1!.shape.width, res1!.shape.height)).toBeGreaterThan(300);+ expect(Math.min(res1!.shape.width, res1!.shape.height)).toBeGreaterThan(165);+ }++ // Rotated rectangle (25 deg)+ const rot = (25 * Math.PI) / 180;+ const baseRect: QuickShapeRectangle = {+ kind: 'rectangle',+ center: { x: 350, y: 320 },+ width: 260,+ height: 150,+ rotation: rot,+ };+ const rotRectPts = makeFreehandPolygon(getRectangleCorners(baseRect), 24, 2.2);+ const res2 = recognizeQuickShape(rotRectPts);+ expect(res2).not.toBeNull();+ expect(res2!.shape.kind).toBe('rectangle');+ if (res2!.shape.kind === 'rectangle') {+ expect(res2!.shape.center.x).toBeCloseTo(350, -1);+ expect(res2!.shape.center.y).toBeCloseTo(320, -1);+ }++ // Square (should NOT be confused with a circle!)+ const sqPts = makeFreehandPolygon(+ [+ { x: 150, y: 150 },+ { x: 350, y: 150 },+ { x: 350, y: 350 },+ { x: 150, y: 350 },+ ],+ 26,+ 2.5+ );+ const resSq = recognizeQuickShape(sqPts);+ expect(resSq).not.toBeNull();+ expect(resSq!.shape.kind).toBe('rectangle');+ });++ it('rejects tiny dots, S-curves, figure-8 loops, and chaotic scribbles', () => {+ // Tiny tap+ expect(recognizeQuickShape([makePoint(100, 100), makePoint(105, 104)])).toBeNull();++ // S-curve wave+ const sCurve: Point[] = [];+ for (let i = 0; i <= 50; i++) {+ const t = i / 50;+ sCurve.push(makePoint(100 + t * 300, 250 + Math.sin(t * Math.PI * 2) * 80, 0.6, 8, i * 6));+ }+ expect(recognizeQuickShape(sCurve)).toBeNull();++ // Figure-8 self-crossing loop+ const fig8: Point[] = [];+ for (let i = 0; i <= 80; i++) {+ const a = (i / 80) * Math.PI * 2;+ fig8.push(makePoint(300 + Math.sin(a) * 140, 300 + Math.sin(2 * a) * 100, 0.6, 8, i * 6));+ }+ expect(recognizeQuickShape(fig8)).toBeNull();+ });+});++describe('QuickShape Interactive Handle & Corner Dragging', () => {+ const style = extractQuickShapeStrokeStyle([makePoint(0, 0, 0.72, 12)], 12);++ it('respects drag deadzone so lifting pen without intentional move never jumps', () => {+ const session = createQuickShapeSession(+ { kind: 'line', start: { x: 100, y: 100 }, end: { x: 300, y: 100 } },+ { x: 300, y: 100 },+ style+ );+ const updated = updateQuickShapeFromDrag(+ session,+ { x: 302, y: 101 },+ { shiftKey: false, altKey: false },+ 1.0+ );+ expect(updated).toEqual(session.initialShape);+ expect(session.hasExitedDeadzone).toBe(false);+ });++ it('drags line endpoint with Shift 15-degree snap and Alt translation', () => {+ const session = createQuickShapeSession(+ { kind: 'line', start: { x: 100, y: 100 }, end: { x: 250, y: 100 } },+ { x: 250, y: 100 },+ style+ );++ // Drag endpoint diagonally with Shift -> snaps to 45 deg+ const snapped = updateQuickShapeFromDrag(+ session,+ { x: 245, y: 242 },+ { shiftKey: true, altKey: false },+ 1.0+ );+ expect(snapped.kind).toBe('line');+ if (snapped.kind === 'line') {+ const angleDeg =+ (Math.atan2(snapped.end.y - snapped.start.y, snapped.end.x - snapped.start.x) * 180) /+ Math.PI;+ expect(angleDeg).toBeCloseTo(45, 3);+ }++ // Alt translates both endpoints together+ const moved = updateQuickShapeFromDrag(+ session,+ { x: 300, y: 140 },+ { shiftKey: false, altKey: true },+ 1.0+ );+ if (moved.kind === 'line') {+ expect(moved.start.x).toBeCloseTo(150, 3);+ expect(moved.start.y).toBeCloseTo(140, 3);+ expect(moved.end.x).toBeCloseTo(300, 3);+ expect(moved.end.y).toBeCloseTo(140, 3);+ }+ });++ it('drags arc endpoint preserving bulge and bends arc curvature with Alt', () => {+ const session = createQuickShapeSession(+ {+ kind: 'arc',+ start: { x: 100, y: 200 },+ mid: { x: 200, y: 120 },+ end: { x: 300, y: 200 },+ },+ { x: 300, y: 200 },+ style+ );++ const dragged = updateQuickShapeFromDrag(+ session,+ { x: 400, y: 200 },+ { shiftKey: false, altKey: false },+ 1.0+ );+ expect(dragged.kind).toBe('arc');+ if (dragged.kind === 'arc') {+ expect(dragged.end.x).toBeCloseTo(400, 3);+ expect(dragged.mid.x).toBeCloseTo(250, 3);+ // Bulge scaled proportionally with chord length (1.5x chord -> 1.5x sagitta = 120px above y=200 -> y=80)+ expect(dragged.mid.y).toBeCloseTo(80, 2);+ }++ const bent = updateQuickShapeFromDrag(+ session,+ { x: 300, y: 260 },+ { shiftKey: false, altKey: true },+ 1.0+ );+ expect(session.activeHandleId).toBe('mid');+ if (bent.kind === 'arc') {+ expect(bent.mid.y).toBeCloseTo(180, 3);+ }+ });++ it('drags circle radius and snaps ellipse to circle with Shift', () => {+ const cSession = createQuickShapeSession(+ { kind: 'circle', center: { x: 200, y: 200 }, radius: 80, handleAngle: 0 },+ { x: 280, y: 200 },+ style+ );+ const resized = updateQuickShapeFromDrag(+ cSession,+ { x: 340, y: 200 },+ { shiftKey: false, altKey: false },+ 1.0+ );+ if (resized.kind === 'circle') {+ expect(resized.radius).toBeCloseTo(140, 2);+ }++ const eSession = createQuickShapeSession(+ { kind: 'ellipse', center: { x: 200, y: 200 }, rx: 120, ry: 60, rotation: 0, handleAngle: 0 },+ { x: 320, y: 200 },+ style+ );+ const snappedEll = updateQuickShapeFromDrag(+ eSession,+ { x: 340, y: 200 },+ { shiftKey: true, altKey: false },+ 1.0+ );+ if (snappedEll.kind === 'ellipse') {+ expect(snappedEll.rx).toBeCloseTo(snappedEll.ry, 3);+ }+ });++ it('drags triangle corner directly while keeping other 2 corners fixed', () => {+ const tri: QuickShapeTriangle = {+ kind: 'triangle',+ vertices: [+ { x: 200, y: 100 },+ { x: 320, y: 300 },+ { x: 80, y: 300 },+ ],+ };+ // Pen stopped near corner 1 (320, 300)+ const session = createQuickShapeSession(tri, { x: 318, y: 298 }, style);+ expect(session.activeCornerIndex).toBe(1);++ const dragged = updateQuickShapeFromDrag(+ session,+ { x: 380, y: 340 },+ { shiftKey: false, altKey: false },+ 1.0+ );+ if (dragged.kind === 'triangle') {+ expect(dragged.vertices[0]).toEqual({ x: 200, y: 100 });+ expect(dragged.vertices[2]).toEqual({ x: 80, y: 300 });+ expect(dragged.vertices[1].x).toBeCloseTo(382, 2);+ expect(dragged.vertices[1].y).toBeCloseTo(342, 2);+ }+ });++ it('drags rectangle corner with opposite corner anchored and locks square with Shift', () => {+ const rect: QuickShapeRectangle = {+ kind: 'rectangle',+ center: { x: 200, y: 200 },+ width: 200,+ height: 100,+ rotation: 0,+ };+ const corners = getRectangleCorners(rect);+ // Corner 2 is bottom-right (300, 250); opposite corner 0 is top-left (100, 150)+ const session = createQuickShapeSession(rect, corners[2], style);+ expect(session.activeCornerIndex).toBe(2);++ const resized = updateQuickShapeFromDrag(+ session,+ { x: 360, y: 310 },+ { shiftKey: false, altKey: false },+ 1.0+ );+ if (resized.kind === 'rectangle') {+ const nextCorners = getRectangleCorners(resized);+ // Opposite corner 0 stays anchored at (100, 150)+ expect(nextCorners[0].x).toBeCloseTo(100, 2);+ expect(nextCorners[0].y).toBeCloseTo(150, 2);+ // Active corner 2 moves to (360, 310)+ expect(nextCorners[2].x).toBeCloseTo(360, 2);+ expect(nextCorners[2].y).toBeCloseTo(310, 2);+ expect(resized.width).toBeCloseTo(260, 2);+ expect(resized.height).toBeCloseTo(160, 2);+ }++ const squared = updateQuickShapeFromDrag(+ session,+ { x: 360, y: 310 },+ { shiftKey: true, altKey: false },+ 1.0+ );+ if (squared.kind === 'rectangle') {+ expect(squared.width).toBeCloseTo(squared.height, 2);+ expect(squared.width).toBeCloseTo(260, 2);+ }+ });++ it('samples smooth points and builds valid preview guides for all 6 shapes', () => {+ const shapes = [+ { kind: 'line' as const, start: { x: 50, y: 50 }, end: { x: 250, y: 150 } },+ { kind: 'arc' as const, start: { x: 50, y: 150 }, mid: { x: 150, y: 80 }, end: { x: 250, y: 150 } },+ { kind: 'circle' as const, center: { x: 200, y: 200 }, radius: 90, handleAngle: 0 },+ { kind: 'ellipse' as const, center: { x: 200, y: 200 }, rx: 120, ry: 60, rotation: 0.3, handleAngle: 0 },+ { kind: 'triangle' as const, vertices: [{ x: 200, y: 80 }, { x: 300, y: 260 }, { x: 100, y: 260 }] as [any, any, any] },+ { kind: 'rectangle' as const, center: { x: 200, y: 200 }, width: 180, height: 110, rotation: 0.2 },+ ];+ for (const s of shapes) {+ const pts = sampleQuickShapePoints(s, style);+ expect(pts.length).toBeGreaterThan(10);+ expect(pts[0].pressure).toBeCloseTo(style.pressure, 4);+ expect(pts[0].width).toBeCloseTo(style.width, 4);+ const sess = createQuickShapeSession(s, { x: 200, y: 200 }, style);+ const preview = buildQuickShapePreview(sess);+ expect(preview.svgPath.length).toBeGreaterThan(5);+ expect(preview.handles.length).toBeGreaterThanOrEqual(2);+ expect(preview.handles.some((h) => h.active)).toBe(true);+ }+ // Safe no-op in headless environment+ expect(() => playQuickShapeSnapClick()).not.toThrow();+ });+});++describe('QuickShape Brush Stroke Session Integration', () => {+ function createMockCanvas(w = 600, h = 600) {+ const ctx: any = {+ canvas: { width: w, height: h },+ strokeStyle: '#000000',+ fillStyle: '#000000',+ lineCap: 'round',+ lineJoin: 'round',+ lineWidth: 1,+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ imageSmoothingEnabled: true,+ save: vi.fn(),+ restore: vi.fn(),+ resetTransform: vi.fn(),+ setTransform: vi.fn(),+ getTransform: vi.fn(() => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 })),+ clearRect: vi.fn(),+ beginPath: vi.fn(),+ rect: vi.fn(),+ clip: vi.fn(),+ arc: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ bezierCurveTo: vi.fn(),+ stroke: vi.fn(),+ fill: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ scale: vi.fn(),+ drawImage: vi.fn(),+ fillRect: vi.fn(),+ setLineDash: vi.fn(),+ createImageData: (cw: number, ch: number) => ({+ width: cw,+ height: ch,+ data: new Uint8ClampedArray(cw * ch * 4),+ }),+ getImageData: vi.fn((_x: number, _y: number, cw: number, ch: number) => ({+ width: cw,+ height: ch,+ data: new Uint8ClampedArray(cw * ch * 4),+ })),+ putImageData: vi.fn(),+ };+ const canvas: any = {+ width: w,+ height: h,+ getContext: () => ctx,+ };+ ctx.canvas = canvas;+ return { canvas, ctx };+ }++ function makePointerEvent(+ clientX: number,+ clientY: number,+ opts?: {+ pointerId?: number;+ pointerType?: string;+ pressure?: number;+ shiftKey?: boolean;+ altKey?: boolean;+ timeStamp?: number;+ }+ ): React.PointerEvent<HTMLElement> {+ const nativeEvt: any = {+ pointerId: opts?.pointerId ?? 1,+ pointerType: opts?.pointerType ?? 'pen',+ button: 0,+ buttons: 1,+ clientX,+ clientY,+ pressure: opts?.pressure ?? 0.7,+ tiltX: 0,+ tiltY: 0,+ twist: 0,+ timeStamp: opts?.timeStamp ?? performance.now(),+ shiftKey: opts?.shiftKey ?? false,+ altKey: opts?.altKey ?? false,+ ctrlKey: false,+ metaKey: false,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ };+ return {+ ...nativeEvt,+ nativeEvent: nativeEvt,+ } as unknown as React.PointerEvent<HTMLElement>;+ }++ function createHarness(initialTool: 'brush' | 'eraser' = 'brush') {+ const dims = { width: 600, height: 600, dpi: 300 };+ const grid = new SparseTileGrid();+ grid.setLayerFormat('layer-1', 'color-32bit');+ grid.markLayerIngested('layer-1');++ const { canvas: draftCanvas } = createMockCanvas(600, 600);+ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Layer 1',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ },+ ];+ const brushSettings: BrushSettings = {+ size: 10,+ color: '#111111',+ opacity: 1.0,+ hardness: 1.0,+ flow: 1.0,+ spacing: 0.1,+ stabilization: 0,+ smoothing: true,+ usePressure: true,+ minSizeFactor: 0.2,+ useGpu: false,+ };++ const viewportRect = {+ left: 0,+ top: 0,+ width: 600,+ height: 600,+ right: 600,+ bottom: 600,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ } as DOMRect;++ const previewEvents: Array<QuickShapePreviewState | null> = [];+ const historyCalls: Array<{ label: string; tool: string }> = [];++ const state = createInitialStrokeSessionState();+ const params: UseBrushStrokeSessionParams = {+ disabled: false,+ activeSessionId: 'doc-1',+ viewportRef: { current: { getBoundingClientRect: () => viewportRect } as any },+ interactionRef: { current: null },+ isDrawingRef: { current: false },+ lastStrokeEndRef: { current: null },+ panRef: { current: { x: 300, y: 300 } },+ zoomRef: { current: 1.0 },+ rotationRef: { current: 0 },+ flipXRef: { current: false },+ flipYRef: { current: false },+ toolOverrideRef: { current: initialTool },+ brushSettingsOverrideRef: { current: brushSettings },+ colorModeRef: { current: 'color' },+ activeLayerIdRef: { current: 'layer-1' },+ activeLayerLockedRef: { current: false },+ activeLayerVisibleRef: { current: true },+ dimensionsRef: { current: dims },+ selectionRef: { current: null },+ isMaskModeRef: { current: false },+ layersRef: { current: layers },+ effectiveDraftCanvasRef: { current: draftCanvas },+ predictedCanvasRef: { current: null },+ activeTileGridRef: { current: grid },+ rulerRef: { current: null },+ straightRulerRef: { current: null },+ onActiveConstraintAxisChangeRef: { current: undefined },+ onQuickShapePreviewChangeRef: {+ current: (preview) => {+ previewEvents.push(preview);+ },+ },+ onUpdateLayerThumbnail: vi.fn(),+ onUpdateMaskThumbnailRef: { current: undefined },+ onCollabStrokeStartRef: { current: undefined },+ onCollabStrokeChunkRef: { current: undefined },+ onCollabStrokeFinishRef: { current: undefined },+ onCollabCursorMoveRef: { current: undefined },+ getActiveMaskCanvas: () => null,+ pushHistoryStep: (tool, label) => {+ historyCalls.push({ tool, label });+ },+ flushPendingHistoryTasks: vi.fn(),+ enqueueHistoryTask: (task) => task(),+ };++ const helpers: StrokeSessionHelpers = {+ getTool: () => params.toolOverrideRef.current!,+ getBrushSettings: () => params.brushSettingsOverrideRef.current!,+ getPredictedCanvas: () => null,+ clearPredictedCanvas: () => clearPredictedCanvasSurface(state, () => null),+ emitConstraintAxisChange: vi.fn(),+ markTouchedTiles: (x0, y0, x1, y1) =>+ markTouchedTilesInRect(dims, state.touchedTiles, x0, y0, x1, y1),+ getViewportRect: () => viewportRect,+ dispatchPointerStat: vi.fn(),+ abortActiveStroke: () =>+ abortActiveStrokeSession(params, state, () => {}, () => {}),+ getCanvasPoint: (e) =>+ computeCanvasPoint(e, params, () => viewportRect, () => brushSettings),+ resolveEffectiveOpacitySensor: resolveEffectiveOpacitySensorValue,+ resolveLiveAntiAlias: resolveLiveAntiAliasValue,+ buildTouchedTileSpans: (sx, sy, dw, dh) =>+ buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),+ buildLiveBrushOptions: (...args) => createLiveBrushOptions(state, ...args),+ resolveStrokeColor: (...args) => resolveStrokeColorValue(false, ...args),+ emitLiveSegment: (...args) => emitLiveSegmentToDraft(state, params, helpers, ...args),+ renderPredictedStroke: vi.fn(),+ flushPendingPoints: (skip) => runFlushPendingPoints(state, params, helpers, skip),+ };++ return { state, params, helpers, previewEvents, historyCalls };+ }++ let origRaf: typeof globalThis.requestAnimationFrame;+ let origCaf: typeof globalThis.cancelAnimationFrame;++ beforeEach(() => {+ vi.useFakeTimers();+ origRaf = globalThis.requestAnimationFrame;+ origCaf = globalThis.cancelAnimationFrame;+ (globalThis as any).requestAnimationFrame = (cb: FrameRequestCallback) =>+ setTimeout(() => cb(performance.now()), 16) as unknown as number;+ (globalThis as any).cancelAnimationFrame = (id: number) => clearTimeout(id as any);+ if (typeof (globalThis as any).document === 'undefined') {+ (globalThis as any).document = {+ createElement: () => createMockCanvas(256, 256).canvas,+ };+ }+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: false });+ });++ afterEach(() => {+ vi.useRealTimers();+ globalThis.requestAnimationFrame = origRaf;+ globalThis.cancelAnimationFrame = origCaf;+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: false });+ });++ it('does NOT trigger QuickShape when disabled by default even if stylus is held for 500ms', () => {+ expect(useUiStore.getState().appSettings.quickShapeEnabled).toBe(false);+ const { state, params, helpers, previewEvents, historyCalls } = createHarness('brush');++ const linePts = makeFreehandLine(100, 150, 420, 150, 24, 1.5);+ runPointerDown(state, params, helpers, makePointerEvent(linePts[0].x, linePts[0].y, { timeStamp: 10 }));+ for (let i = 1; i < linePts.length; i++) {+ runPointerMove(+ state,+ params,+ helpers,+ makePointerEvent(linePts[i].x, linePts[i].y, { timeStamp: 10 + i * 8 })+ );+ }++ vi.advanceTimersByTime(500);+ expect(state.quickShapeSession).toBeNull();+ expect(previewEvents).toHaveLength(0);++ runPointerUp(state, params, helpers, makePointerEvent(420, 150, { timeStamp: 800 }));+ expect(historyCalls).toHaveLength(1);+ expect(historyCalls[0].label).not.toContain('QuickShape');+ });++ it('snaps after ~350ms dwell with micro-jitter tolerance, supports handle drag before release, and commits single QuickShape history step', () => {+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: true });+ const { state, params, helpers, previewEvents, historyCalls } = createHarness('brush');++ const rectPts = makeFreehandPolygon(+ [+ { x: 120, y: 120 },+ { x: 320, y: 120 },+ { x: 320, y: 260 },+ { x: 120, y: 260 },+ ],+ 18,+ 1.8+ );++ runPointerDown(state, params, helpers, makePointerEvent(rectPts[0].x, rectPts[0].y, { timeStamp: 10 }));+ for (let i = 1; i < rectPts.length; i++) {+ runPointerMove(+ state,+ params,+ helpers,+ makePointerEvent(rectPts[i].x, rectPts[i].y, { timeStamp: 10 + i * 5 })+ );+ }++ // Simulate realistic stylus micro-jitter (<= 3px) during the hold window: should NOT reset timer!+ const lastPt = rectPts[rectPts.length - 1];+ vi.advanceTimersByTime(150);+ runPointerMove(state, params, helpers, makePointerEvent(lastPt.x + 1.5, lastPt.y - 1.2, { timeStamp: 600 }));+ vi.advanceTimersByTime(150);+ expect(state.quickShapeSession).toBeNull(); // Only 300ms elapsed (< 350ms)++ vi.advanceTimersByTime(QUICK_SHAPE_HOLD_MS - 290); // Crosses 350ms threshold!+ expect(state.quickShapeSession).not.toBeNull();+ expect(state.quickShapeSession!.currentShape.kind).toBe('rectangle');+ expect(previewEvents.length).toBeGreaterThanOrEqual(1);+ const snapPreview = previewEvents[previewEvents.length - 1]!;+ expect(snapPreview.shape.kind).toBe('rectangle');+ expect(snapPreview.handles).toHaveLength(4);++ // Drag the active corner outward BEFORE releasing the pen!+ const widthBeforeDrag = (state.quickShapeSession!.currentShape as QuickShapeRectangle).width;+ runPointerMove(+ state,+ params,+ helpers,+ makePointerEvent(lastPt.x - 80, lastPt.y - 40, { timeStamp: 900 })+ );+ vi.advanceTimersByTime(20); // Let rAF flush drag update++ const widthAfterDrag = (state.quickShapeSession!.currentShape as QuickShapeRectangle).width;+ expect(Math.abs(widthAfterDrag - widthBeforeDrag)).toBeGreaterThan(40);++ // Release pen -> commits cleanly with QuickShape history label and dismisses overlay preview+ runPointerUp(state, params, helpers, makePointerEvent(lastPt.x - 80, lastPt.y - 40, { timeStamp: 950 }));+ expect(state.quickShapeSession).toBeNull();+ expect(previewEvents[previewEvents.length - 1]).toBeNull();+ expect(historyCalls).toHaveLength(1);+ expect(historyCalls[0].label).toBe('QuickShape: Rectangle');+ });++ it('does NOT trigger when lifting pen early before 350ms or when using the eraser tool', () => {+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: true });++ // Early lift before 350ms+ const h1 = createHarness('brush');+ const linePts = makeFreehandLine(80, 100, 340, 100, 20, 1.5);+ runPointerDown(h1.state, h1.params, h1.helpers, makePointerEvent(linePts[0].x, linePts[0].y, { timeStamp: 10 }));+ for (let i = 1; i < linePts.length; i++) {+ runPointerMove(h1.state, h1.params, h1.helpers, makePointerEvent(linePts[i].x, linePts[i].y, { timeStamp: 10 + i * 5 }));+ }+ vi.advanceTimersByTime(150);+ runPointerUp(h1.state, h1.params, h1.helpers, makePointerEvent(340, 100, { timeStamp: 250 }));+ vi.advanceTimersByTime(500);+ expect(h1.state.quickShapeSession).toBeNull();+ expect(h1.previewEvents).toHaveLength(0);++ // Eraser tool should not trigger QuickShape+ const h2 = createHarness('eraser');+ runPointerDown(h2.state, h2.params, h2.helpers, makePointerEvent(linePts[0].x, linePts[0].y, { timeStamp: 10 }));+ for (let i = 1; i < linePts.length; i++) {+ runPointerMove(h2.state, h2.params, h2.helpers, makePointerEvent(linePts[i].x, linePts[i].y, { timeStamp: 10 + i * 5 }));+ }+ vi.advanceTimersByTime(500);+ expect(h2.state.quickShapeSession).toBeNull();+ expect(h2.previewEvents).toHaveLength(0);+ runPointerUp(h2.state, h2.params, h2.helpers, makePointerEvent(340, 100, { timeStamp: 700 }));+ });++ it('aborts cleanly without committing if stroke is aborted during active QuickShape', () => {+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: true });+ const { state, params, helpers, previewEvents, historyCalls } = createHarness('brush');++ const circlePts = makeFreehandEllipse(300, 300, 90, 90, 0, 48, 1.5, 0.04, true);+ runPointerDown(state, params, helpers, makePointerEvent(circlePts[0].x, circlePts[0].y, { timeStamp: 10 }));+ for (let i = 1; i < circlePts.length; i++) {+ runPointerMove(state, params, helpers, makePointerEvent(circlePts[i].x, circlePts[i].y, { timeStamp: 10 + i * 5 }));+ }+ vi.advanceTimersByTime(QUICK_SHAPE_HOLD_MS + 20);+ expect(state.quickShapeSession?.currentShape.kind).toBe('circle');++ helpers.abortActiveStroke();+ expect(state.quickShapeSession).toBeNull();+ expect(params.isDrawingRef.current).toBe(false);+ expect(previewEvents[previewEvents.length - 1]).toBeNull();+ expect(historyCalls).toHaveLength(0);+ });+});diff --git a/src/utils/__tests__/selectionFillScreentoneUndo.test.tsx b/src/utils/__tests__/selectionFillScreentoneUndo.test.tsxindex 5ac5fea..073f766 100644--- a/src/utils/__tests__/selectionFillScreentoneUndo.test.tsx+++ b/src/utils/__tests__/selectionFillScreentoneUndo.test.tsx@@ -11,7 +11,23 @@ import { createSelectionMask } from '../tonalEngine';import { useLayerManager } from '../../hooks/useLayerManager';import { useDrawingHistory, PushHistoryStepFn } from '../../hooks/drawing';import { isEditableTarget } from '../../components/GlobalShortcutListener';-import type { CanvasDimensions, CanvasSelection, LayerItem } from '../../types/editor';+import { SelectionOverlay } from '../../components/SelectionOverlay';+import { NaturalPaintStrokeSession } from '../../engine/NaturalPaintRenderer';+import { commitRasterStrokeToTiles } from '../../hooks/drawing/brushStrokeSession/pointerUpRasterCommit';+import {+ buildTouchedTileSpansFromSet,+ markTouchedTilesInRect,+} from '../../hooks/drawing/brushStrokeSession/strokeHelpers';+import { createInitialStrokeSessionState } from '../../hooks/drawing/brushStrokeSession/types';+import {+ DEFAULT_IMPASTO_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+ type BrushSettings,+ type CanvasDimensions,+ type CanvasSelection,+ type LayerItem,+ type Point,+} from '../../types/editor';class ShimNode extends EventTarget {nodeType = 1;@@ -22,14 +38,31 @@ class ShimNode extends EventTarget {parentNode: any = null;childNodes: any[] = [];style: Record<string, string> = {};+ attributes: Record<string, string> = {};isContentEditable = false;type = '';+ textContent = '';constructor(tag = 'DIV', doc?: any) {super();this.nodeName = tag.toUpperCase();this.tagName = this.nodeName;this.ownerDocument = doc ?? null;}+ setAttribute(name: string, value: string) {+ this.attributes[name] = String(value);+ }+ getAttribute(name: string) {+ return this.attributes[name] ?? null;+ }+ removeAttribute(name: string) {+ delete this.attributes[name];+ }+ setAttributeNS(_ns: string | null, name: string, value: string) {+ this.attributes[name] = String(value);+ }+ removeAttributeNS(_ns: string | null, name: string) {+ delete this.attributes[name];+ }appendChild(c: any) {c.parentNode = this;this.childNodes.push(c);@@ -58,6 +91,11 @@ function installDomShim() {doc.nodeType = 9;doc.activeElement = null;doc.createElement = (tag: string) => new ShimNode(tag, doc);+ doc.createElementNS = (ns: string, tag: string) => {+ const n = new ShimNode(tag, doc);+ n.namespaceURI = ns;+ return n;+ };doc.createTextNode = (txt: string) => {const n: any = new ShimNode('#text', doc);n.nodeType = 3;@@ -502,4 +540,344 @@ describe('Selection + Screentone, Fill Tool, LOD Invalidation, and Comprehensive(textInput as any).type = 'text';expect(isEditableTarget(textInput, ctrlZ)).toBe(true);});++ it('executeLassoFillOnTileGrid supports translucent opacity, partial transparent erase, and undo', () => {+ const grid = new SparseTileGrid();+ const quad = [+ { x: 20, y: 20 },+ { x: 100, y: 20 },+ { x: 100, y: 100 },+ { x: 20, y: 100 },+ ];++ // 1. Translucent 50% fill on blank layer+ const resHalf = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ dimensions: DIMS,+ polygon: quad,+ fillColorHex: '#ff0000',+ opacity: 0.5,+ });+ expect(resHalf.modified).toBe(true);+ const pxHalf = readPixel(grid, 'layer-1', 60, 60);+ expect(pxHalf[0]).toBe(255);+ expect(pxHalf[1]).toBe(0);+ expect(pxHalf[2]).toBe(0);+ expect(pxHalf[3]).toBeGreaterThanOrEqual(126);+ expect(pxHalf[3]).toBeLessThanOrEqual(129);+ // Outside polygon stays transparent+ expect(readPixel(grid, 'layer-1', 5, 5)[3]).toBe(0);++ // Undo restores clean blank layer+ grid.applyTileDeltas(resHalf.tileDeltas, 'undo');+ expect(readPixel(grid, 'layer-1', 60, 60)[3]).toBe(0);++ // 2. Translucent 50% erase (transparent ink) over opaque blue rectangle+ paintSolidRect(grid, 'layer-1', 10, 10, 120, 120, [0, 0, 255, 255]);+ const resPartialErase = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ dimensions: DIMS,+ polygon: quad,+ fillColorHex: 'rgba(0,0,0,0)',+ opacity: 0.5,+ });+ expect(resPartialErase.modified).toBe(true);+ const pxErasedHalf = readPixel(grid, 'layer-1', 60, 60);+ expect(pxErasedHalf[3]).toBeGreaterThanOrEqual(126);+ expect(pxErasedHalf[3]).toBeLessThanOrEqual(129);+ // Outside lasso stays fully opaque+ expect(readPixel(grid, 'layer-1', 12, 12)[3]).toBe(255);++ // 3. Full 100% transparent-ink erase clears pixels completely+ const resFullErase = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ dimensions: DIMS,+ polygon: quad,+ fillColorHex: 'rgba(0,0,0,0)',+ opacity: 1.0,+ });+ expect(resFullErase.modified).toBe(true);+ expect(readPixel(grid, 'layer-1', 60, 60)[3]).toBe(0);++ // 4. Zero opacity is a clean no-op+ const resZero = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ dimensions: DIMS,+ polygon: quad,+ fillColorHex: '#00ff00',+ opacity: 0,+ });+ expect(resZero.modified).toBe(false);+ expect(resZero.tileDeltas.length).toBe(0);+ });++ it('SelectionOverlay renders regular lasso selections with transparent interior (no blue fill)', () => {+ const container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ act(() => {+ root!.render(+ <SelectionOverlay+ selection={makeTriangleLasso()}+ dimensions={DIMS}+ zoom={1}+ onDeselect={() => {}}+ onTransformSelection={() => {}}+ onFillScreentone={() => {}}+ onFillColor={() => {}}+ onClearSelection={() => {}}+ onInvertSelection={() => {}}+ />+ );+ });++ const walk = (node: any, out: any[] = []): any[] => {+ out.push(node);+ for (const child of node.childNodes || []) {+ walk(child, out);+ }+ return out;+ };++ const allNodes = walk(container);+ const styleNodes = allNodes.filter((n) => n.tagName === 'STYLE');+ expect(styleNodes.length).toBeGreaterThan(0);+ const cssText = styleNodes+ .map(+ (s) =>+ (s.textContent || '') ++ (s.childNodes || [])+ .map((c: any) => c.nodeValue || '')+ .join('')+ )+ .join('\n');+ expect(cssText).toContain('fill: none;');+ expect(cssText).not.toContain('rgba(92, 225, 230');++ const pathNodes = allNodes.filter((n) => n.tagName === 'PATH');+ expect(pathNodes.length).toBe(2);+ for (const p of pathNodes) {+ expect(p.getAttribute('fill')).toBe('none');+ }+ });++ it('allows Natural Paint strokes to draw inside a regular lasso selection and clips strictly to the lasso polygon', () => {+ const grid = new SparseTileGrid();+ const lasso = makeTriangleLasso(); // triangle vertices: (40,40), (180,40), (110,180)++ const naturalBs: BrushSettings = {+ preset: 'oil-loaded-impasto',+ size: 28,+ opacity: 1,+ flow: 1,+ spacing: 0.1,+ hardness: 0.85,+ color: '#e11d48',+ minSizeFactor: 0.4,+ usePressure: false,+ smoothing: false,+ stabilization: 0,+ renderMode: 'bristle-ribbon',+ naturalPaint: {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ enabled: true,+ paintLoad: 0.95,+ dryBrush: 0.05,+ spatialMixing: false,+ },+ impasto: {+ ...DEFAULT_IMPASTO_SETTINGS,+ enabled: true,+ depth: 0.5,+ },+ };++ const state = createInitialStrokeSessionState();+ const natSession = new NaturalPaintStrokeSession(naturalBs, '#e11d48', 160, 42);+ const p0: Point = { x: 80, y: 80, pressure: 1, width: 28 };+ const p1: Point = { x: 140, y: 80, pressure: 1, width: 28 };+ const p2: Point = { x: 210, y: 80, pressure: 1, width: 28 };+ natSession.appendCubicSegment(p0, { ...p0, x: 100 }, { ...p1, x: 120 }, p1);+ natSession.appendCubicSegment(p1, { ...p1, x: 165 }, { ...p2, x: 190 }, p2);+ state.naturalPaintSession = natSession;++ const dirtyRect = { x: 40, y: 40, width: 200, height: 100 };+ markTouchedTilesInRect(DIMS, state.touchedTiles, 40, 40, 240, 140);++ const postWork = commitRasterStrokeToTiles({+ state,+ helpers: {+ markTouchedTiles: (minX, minY, maxX, maxY) =>+ markTouchedTilesInRect(DIMS, state.touchedTiles, minX, minY, maxX, maxY),+ resolveLiveAntiAlias: () => 2,+ buildLiveBrushOptions: (() => ({})) as any,+ emitLiveSegment: () => {},+ buildTouchedTileSpans: (sx, sy, dw, dh) =>+ buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),+ resolveEffectiveOpacitySensor: () => undefined,+ },+ grid,+ draftCanvas: null,+ dirtyRect,+ dims: DIMS,+ bs: naturalBs,+ currentTool: 'brush',+ currentLayerId: 'layer-nat',+ activeLayer: {+ id: 'layer-nat',+ name: 'Natural',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ activeSelection: lasso,+ effectiveMode: 'color',+ targetFormat: 'color-32bit',+ isEraser: false,+ isBgEraser: false,+ isMonochrome: false,+ hasWetEdge: false,+ shouldTaper: false,+ strokeColor: '#e11d48',+ allPoints: [p0, p1, p2],+ tailSegments: [],+ toolForHistory: 'brush',+ label: 'Natural Paint Stroke',+ strokeIdForHistory: 'stroke-nat-1',+ enqueueHistoryTask: (fn) => fn(),+ pushHistoryStep: () => {},+ });+ postWork?.();++ // Inside the regular lasso triangle along the stroke (x=110, y=80): painted!+ const insidePx = readPixel(grid, 'layer-nat', 110, 80);+ expect(insidePx[3]).toBeGreaterThan(150);+ expect(insidePx[0]).toBeGreaterThan(100);+ expect(insidePx[0]).toBeGreaterThan(insidePx[1] + 40);++ // Outside the regular lasso triangle along the exact same stroke (x=200, y=80): strictly clipped!+ expect(readPixel(grid, 'layer-nat', 200, 80)[3]).toBe(0);+ // Also outside triangle diagonal edge (x=50, y=120): untouched+ expect(readPixel(grid, 'layer-nat', 50, 120)[3]).toBe(0);+ });++ it('correctly indexes offset full-canvas selection masks away from origin for Natural Paint and standard strokes', () => {+ const grid = new SparseTileGrid();+ // Full-canvas mask with selected square at (120..180, 120..180), far from (0, 0)+ const fullMask = new Uint8Array(DIMS.width * DIMS.height);+ for (let y = 120; y < 180; y++) {+ for (let x = 120; x < 180; x++) {+ fullMask[y * DIMS.width + x] = 255;+ }+ }+ const offsetMaskSelection: CanvasSelection = {+ type: 'mask',+ bounds: { x: 120, y: 120, width: 60, height: 60 },+ mask: fullMask,+ maskWidth: DIMS.width,+ maskHeight: DIMS.height,+ };++ const naturalBs: BrushSettings = {+ preset: 'oil-loaded-impasto',+ size: 32,+ opacity: 1,+ flow: 1,+ spacing: 0.1,+ hardness: 0.85,+ color: '#2563eb',+ minSizeFactor: 0.5,+ usePressure: false,+ smoothing: false,+ stabilization: 0,+ renderMode: 'bristle-ribbon',+ naturalPaint: {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ enabled: true,+ paintLoad: 0.95,+ dryBrush: 0.05,+ spatialMixing: false,+ },+ impasto: {+ ...DEFAULT_IMPASTO_SETTINGS,+ enabled: true,+ depth: 0.4,+ },+ };++ const state = createInitialStrokeSessionState();+ const natSession = new NaturalPaintStrokeSession(naturalBs, '#2563eb', 140, 99);+ const p0: Point = { x: 90, y: 150, pressure: 1, width: 32 };+ const p1: Point = { x: 210, y: 150, pressure: 1, width: 32 };+ natSession.appendCubicSegment(p0, { ...p0, x: 130 }, { ...p1, x: 170 }, p1);+ state.naturalPaintSession = natSession;++ const dirtyRect = { x: 70, y: 110, width: 160, height: 80 };+ markTouchedTilesInRect(DIMS, state.touchedTiles, 70, 110, 230, 190);++ commitRasterStrokeToTiles({+ state,+ helpers: {+ markTouchedTiles: (minX, minY, maxX, maxY) =>+ markTouchedTilesInRect(DIMS, state.touchedTiles, minX, minY, maxX, maxY),+ resolveLiveAntiAlias: () => 2,+ buildLiveBrushOptions: (() => ({})) as any,+ emitLiveSegment: () => {},+ buildTouchedTileSpans: (sx, sy, dw, dh) =>+ buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),+ resolveEffectiveOpacitySensor: () => undefined,+ },+ grid,+ draftCanvas: null,+ dirtyRect,+ dims: DIMS,+ bs: naturalBs,+ currentTool: 'brush',+ currentLayerId: 'layer-mask-nat',+ activeLayer: {+ id: 'layer-mask-nat',+ name: 'Mask Natural',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ activeSelection: offsetMaskSelection,+ effectiveMode: 'color',+ targetFormat: 'color-32bit',+ isEraser: false,+ isBgEraser: false,+ isMonochrome: false,+ hasWetEdge: false,+ shouldTaper: false,+ strokeColor: '#2563eb',+ allPoints: [p0, p1],+ tailSegments: [],+ toolForHistory: 'brush',+ label: 'Natural Paint Offset Mask',+ strokeIdForHistory: 'stroke-nat-mask',+ enqueueHistoryTask: (fn) => fn(),+ pushHistoryStep: () => {},+ });++ // Inside offset mask (150, 150): must receive paint (previously failed with 0 alpha!)+ const insideMaskPx = readPixel(grid, 'layer-mask-nat', 150, 150);+ expect(insideMaskPx[3]).toBeGreaterThan(150);+ expect(insideMaskPx[2]).toBeGreaterThan(100);+ expect(insideMaskPx[2]).toBeGreaterThan(insideMaskPx[0] + 40);++ // Outside offset mask along stroke (95, 150 and 205, 150): must stay empty+ expect(readPixel(grid, 'layer-mask-nat', 95, 150)[3]).toBe(0);+ expect(readPixel(grid, 'layer-mask-nat', 205, 150)[3]).toBe(0);+ });});diff --git a/src/utils/__tests__/smartLineFill.test.ts b/src/utils/__tests__/smartLineFill.test.tsnew file mode 100644index 0000000..40bbc33--- /dev/null+++ b/src/utils/__tests__/smartLineFill.test.ts@@ -0,0 +1,781 @@+import { describe, it, expect } from 'vitest';+import { SparseTileGrid } from '../tileEngine';+import { CanvasDimensions, LayerItem, Point2D } from '../../types/editor';+import {+ executeEncloseAndFillOnTileGrid,+ executePaintUnfilledAreaOnTileGrid,+ rasterizePolygonMask,+ rasterizeBrushStrokeMask,+} from '../smartLineFill';+import { getCursorStyle } from '../../components/canvasArea/types';++function setPixel(+ buf: Uint8ClampedArray,+ w: number,+ x: number,+ y: number,+ rgba: [number, number, number, number]+): void {+ const off = (y * w + x) * 4;+ buf[off] = rgba[0];+ buf[off + 1] = rgba[1];+ buf[off + 2] = rgba[2];+ buf[off + 3] = rgba[3];+}++function drawRectOutline(+ buf: Uint8ClampedArray,+ w: number,+ x0: number,+ y0: number,+ x1: number,+ y1: number,+ rgba: [number, number, number, number] = [0, 0, 0, 255],+ thickness: number = 1+): void {+ for (let t = 0; t < thickness; t++) {+ for (let x = x0 + t; x <= x1 - t; x++) {+ setPixel(buf, w, x, y0 + t, rgba);+ setPixel(buf, w, x, y1 - t, rgba);+ }+ for (let y = y0 + t; y <= y1 - t; y++) {+ setPixel(buf, w, x0 + t, y, rgba);+ setPixel(buf, w, x1 - t, y, rgba);+ }+ }+}++function fillRectBuf(+ buf: Uint8ClampedArray,+ w: number,+ x0: number,+ y0: number,+ x1: number,+ y1: number,+ rgba: [number, number, number, number]+): void {+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ setPixel(buf, w, x, y, rgba);+ }+ }+}++function readPixel(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number+): [number, number, number, number] {+ const d = grid.readImageData(layerId, x, y, 1, 1).data;+ return [d[0], d[1], d[2], d[3]];+}++function makeStandardLayers(refOnLineArt: boolean = true): LayerItem[] {+ return [+ {+ id: 'layer-line',+ name: 'Line Art',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ isReference: refOnLineArt,+ parentId: null,+ },+ {+ id: 'layer-color',+ name: 'Flat Color',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: true,+ parentId: null,+ },+ ];+}++describe('Smart Line Fill (Enclose & Fill + Paint Unfilled Area)', () => {+ describe('Rasterizers', () => {+ it('rasterizePolygonMask handles simple and self-intersecting polygons deterministically', () => {+ const square: Point2D[] = [+ { x: 10, y: 10 },+ { x: 20, y: 10 },+ { x: 20, y: 20 },+ { x: 10, y: 20 },+ ];+ const mask = rasterizePolygonMask(square, 0, 0, 30, 30);+ expect(mask[15 * 30 + 15]).toBe(1);+ expect(mask[10 * 30 + 10]).toBe(1);+ expect(mask[19 * 30 + 19]).toBe(1);+ expect(mask[9 * 30 + 15]).toBe(0);+ expect(mask[20 * 30 + 15]).toBe(0);+ });++ it('rasterizeBrushStrokeMask covers single-click dabs and multi-segment strokes', () => {+ const dab = rasterizeBrushStrokeMask([{ x: 15, y: 15 }], 5, 0, 0, 30, 30);+ expect(dab[15 * 30 + 15]).toBe(1);+ expect(dab[15 * 30 + 19]).toBe(1);+ expect(dab[15 * 30 + 25]).toBe(0);++ const seg = rasterizeBrushStrokeMask(+ [+ { x: 5, y: 10 },+ { x: 25, y: 10 },+ ],+ 3,+ 0,+ 0,+ 30,+ 20+ );+ expect(seg[10 * 30 + 15]).toBe(1);+ expect(seg[12 * 30 + 15]).toBe(1);+ expect(seg[2 * 30 + 15]).toBe(0);+ });+ });++ describe('Enclose and Fill (Close & Fill)', () => {+ it('fills all closed hair strands inside Reference layer outline without affecting background or partially enclosed face', () => {+ const dims: CanvasDimensions = { width: 120, height: 120 };+ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-bg', dims.width, dims.height, 'color-32bit');++ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ // 3 distinct closed hair strands completely inside the lasso+ drawRectOutline(lineBuf, dims.width, 20, 20, 36, 44);+ drawRectOutline(lineBuf, dims.width, 42, 18, 58, 48);+ drawRectOutline(lineBuf, dims.width, 64, 22, 80, 44);+ // A large face box extending BELOW the lasso (y = 44..110) — only partially inside lasso+ drawRectOutline(lineBuf, dims.width, 24, 44, 76, 110);+ grid.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const layers = makeStandardLayers(true);++ // Loose lasso circling the 3 hair strands, cutting across the top of the face (y = 55)+ const lasso: Point2D[] = [+ { x: 10, y: 10 },+ { x: 92, y: 10 },+ { x: 92, y: 56 },+ { x: 10, y: 56 },+ ];++ const res = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#3b82f6',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { antiAlias: false },+ });++ expect(res.modified).toBe(true);+ expect(res.tileDeltas.length).toBeGreaterThan(0);++ // All 3 closed hair strands are filled blue+ expect(readPixel(grid, 'layer-color', 28, 32)).toEqual([59, 130, 246, 255]);+ expect(readPixel(grid, 'layer-color', 50, 32)).toEqual([59, 130, 246, 255]);+ expect(readPixel(grid, 'layer-color', 72, 32)).toEqual([59, 130, 246, 255]);++ // Background INSIDE the lasso (outside & between strands) is completely untouched+ expect(readPixel(grid, 'layer-color', 14, 14)[3]).toBe(0);+ expect(readPixel(grid, 'layer-color', 39, 32)[3]).toBe(0);+ expect(readPixel(grid, 'layer-color', 61, 32)[3]).toBe(0);++ // Partially enclosed face (both inside lasso at y=50 and outside at y=80) is untouched!+ expect(readPixel(grid, 'layer-color', 50, 50)[3]).toBe(0);+ expect(readPixel(grid, 'layer-color', 50, 80)[3]).toBe(0);++ // Undo & Redo via tileDeltas restore and re-apply layer-color cleanly+ grid.applyTileDeltas(res.tileDeltas, 'undo');+ expect(readPixel(grid, 'layer-color', 28, 32)[3]).toBe(0);+ grid.applyTileDeltas(res.tileDeltas, 'redo');+ expect(readPixel(grid, 'layer-color', 28, 32)).toEqual([59, 130, 246, 255]);+ });++ it('fills nested closed loops (hair highlight inside hair) and handles colored line art on transparent Reference layer', () => {+ const dims: CanvasDimensions = { width: 80, height: 80 };+ const grid = new SparseTileGrid();+ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ // Warm brown line art (not pure black)+ drawRectOutline(lineBuf, dims.width, 15, 15, 65, 65, [90, 45, 30, 255]);+ drawRectOutline(lineBuf, dims.width, 30, 30, 50, 50, [90, 45, 30, 255]);+ grid.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const res = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers: makeStandardLayers(true),+ dimensions: dims,+ polygon: [+ { x: 5, y: 5 },+ { x: 75, y: 5 },+ { x: 75, y: 75 },+ { x: 5, y: 75 },+ ],+ fillColorHex: '#ec4899',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { antiAlias: false },+ });++ expect(res.modified).toBe(true);+ expect(readPixel(grid, 'layer-color', 20, 20)).toEqual([236, 72, 153, 255]); // Outer ring+ expect(readPixel(grid, 'layer-color', 40, 40)).toEqual([236, 72, 153, 255]); // Inner loop+ expect(readPixel(grid, 'layer-color', 8, 8)[3]).toBe(0); // Background untouched+ });++ it('bridges small line gaps with closeGap without leaking and recovers sharp interior V-tips without filling exterior notches', () => {+ const dims: CanvasDimensions = { width: 80, height: 80 };+ const gridNoClose = new SparseTileGrid();+ const gridClose = new SparseTileGrid();++ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ // Closed box (20..50, 25..55) with a 2px gap in the top wall at x = 35, 36+ drawRectOutline(lineBuf, dims.width, 20, 25, 50, 55);+ setPixel(lineBuf, dims.width, 35, 25, [0, 0, 0, 0]);+ setPixel(lineBuf, dims.width, 36, 25, [0, 0, 0, 0]);++ // Sharp V-tip extending upward on left box (20..26, y = 20..25)+ setPixel(lineBuf, dims.width, 23, 20, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 22, 21, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 24, 21, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 21, 22, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 25, 22, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 21, 23, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 25, 23, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 20, 24, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 26, 24, [0, 0, 0, 255]);+ // Open the base of the V-tip into the box interior+ for (let x = 21; x <= 25; x++) {+ setPixel(lineBuf, dims.width, x, 25, [0, 0, 0, 0]);+ }++ // Exterior sharp V-notch on the right side (pointing down into x=60, open at top)+ setPixel(lineBuf, dims.width, 58, 30, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 62, 30, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 59, 31, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 61, 31, [0, 0, 0, 255]);+ setPixel(lineBuf, dims.width, 60, 32, [0, 0, 0, 255]);++ gridNoClose.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );+ gridClose.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const lasso: Point2D[] = [+ { x: 10, y: 10 },+ { x: 70, y: 10 },+ { x: 70, y: 70 },+ { x: 10, y: 70 },+ ];+ const layers = makeStandardLayers(true);++ // Without closeGap, the 2px gap connects the box interior to exterior -> box is NOT filled+ const resNoClose = executeEncloseAndFillOnTileGrid({+ grid: gridNoClose,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#ef4444',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { closeGap: 0, antiAlias: false },+ });+ expect(resNoClose.modified).toBe(false);+ expect(readPixel(gridNoClose, 'layer-color', 35, 40)[3]).toBe(0);++ // With closeGap = 4, gap is bridged -> box AND sharp interior V-tip apex (23, 21) fill!+ const resClose = executeEncloseAndFillOnTileGrid({+ grid: gridClose,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#ef4444',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { closeGap: 4, antiAlias: false },+ });+ expect(resClose.modified).toBe(true);+ expect(readPixel(gridClose, 'layer-color', 35, 40)).toEqual([239, 68, 68, 255]); // Box interior+ expect(readPixel(gridClose, 'layer-color', 23, 21)).toEqual([239, 68, 68, 255]); // Sharp V-tip apex recovered!+ expect(readPixel(gridClose, 'layer-color', 35, 20)[3]).toBe(0); // Background above gap untouched!+ expect(readPixel(gridClose, 'layer-color', 60, 31)[3]).toBe(0); // Exterior V-notch untouched!+ });++ it('expands under line art via areaScale without ever spilling into exterior background, and supports shrinking', () => {+ const dims: CanvasDimensions = { width: 64, height: 64 };+ const gridExpand = new SparseTileGrid();+ const gridShrink = new SparseTileGrid();+ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ // 3px thick black outline: x=14..16, x=44..46, y=14..16, y=44..46+ drawRectOutline(lineBuf, dims.width, 14, 14, 46, 46, [0, 0, 0, 255], 3);++ gridExpand.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );+ gridShrink.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const lasso: Point2D[] = [+ { x: 4, y: 4 },+ { x: 60, y: 4 },+ { x: 60, y: 60 },+ { x: 4, y: 60 },+ ];+ const layers = makeStandardLayers(true);++ // Extreme +6 areaScale: tucks under outline (x=15..16) but NEVER spills outside to x=13!+ executeEncloseAndFillOnTileGrid({+ grid: gridExpand,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#22c55e',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { areaScale: 6, antiAlias: false },+ });+ expect(readPixel(gridExpand, 'layer-color', 16, 30)).toEqual([34, 197, 94, 255]); // Under outline+ expect(readPixel(gridExpand, 'layer-color', 13, 30)[3]).toBe(0); // Exterior strictly protected!++ // -2 shrink: pulls 2px away from inner edge (x=17, 18 stay transparent, x=19 filled)+ executeEncloseAndFillOnTileGrid({+ grid: gridShrink,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#22c55e',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { areaScale: -2, antiAlias: false },+ });+ expect(readPixel(gridShrink, 'layer-color', 17, 30)[3]).toBe(0);+ expect(readPixel(gridShrink, 'layer-color', 18, 30)[3]).toBe(0);+ expect(readPixel(gridShrink, 'layer-color', 19, 30)).toEqual([34, 197, 94, 255]);+ });++ it('supports unfilled-only target mode, Transparent Ink erase, Reference Folders, selectionMask, and opaque paper layers', () => {+ const dims: CanvasDimensions = { width: 100, height: 100 };+ const grid = new SparseTileGrid();++ // Put line art inside a Reference Folder!+ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ drawRectOutline(lineBuf, dims.width, 15, 15, 40, 45); // Left shape (already painted skin)+ drawRectOutline(lineBuf, dims.width, 50, 15, 75, 45); // Right shape (unfilled hair)+ grid.writeImageData(+ 'line-child',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ // Pre-paint left shape skin color on target layer+ const colorBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ fillRectBuf(colorBuf, dims.width, 16, 16, 39, 44, [250, 210, 180, 255]);+ grid.writeImageData(+ 'layer-color',+ { data: colorBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const folderLayers: LayerItem[] = [+ {+ id: 'ref-folder',+ name: 'Line Art Folder',+ type: 'folder',+ visible: true,+ opacity: 1,+ blendMode: 'pass-through',+ locked: false,+ isReference: true,+ parentId: null,+ },+ {+ id: 'line-child',+ name: 'Ink',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: 'ref-folder',+ },+ {+ id: 'layer-color',+ name: 'Color',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];++ const lasso: Point2D[] = [+ { x: 5, y: 5 },+ { x: 85, y: 5 },+ { x: 85, y: 55 },+ { x: 5, y: 55 },+ ];++ // 1. unfilled-only protects already-painted left shape while filling right shape via Reference Folder+ const resUnfilled = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers: folderLayers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: '#6366f1',+ tolerance: 32,+ referMode: 'refer-reference',+ targetMode: 'unfilled-only',+ options: { antiAlias: false },+ });+ expect(resUnfilled.modified).toBe(true);+ expect(readPixel(grid, 'layer-color', 25, 30)).toEqual([250, 210, 180, 255]); // Skin preserved!+ expect(readPixel(grid, 'layer-color', 62, 30)).toEqual([99, 102, 241, 255]); // Hair filled!++ // 2. Transparent Ink erase with selectionMask erases only the selected right shape+ const selMask = new Uint8Array(dims.width * dims.height);+ for (let y = 10; y <= 50; y++) {+ for (let x = 48; x <= 80; x++) {+ selMask[y * dims.width + x] = 1;+ }+ }+ const resErase = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers: folderLayers,+ dimensions: dims,+ polygon: lasso,+ fillColorHex: 'rgba(0,0,0,0)',+ tolerance: 32,+ referMode: 'refer-reference',+ targetMode: 'all-enclosed',+ options: { selectionMask: selMask, antiAlias: false },+ });+ expect(resErase.modified).toBe(true);+ expect(readPixel(grid, 'layer-color', 62, 30)[3]).toBe(0); // Erased inside selection+ expect(readPixel(grid, 'layer-color', 25, 30)).toEqual([250, 210, 180, 255]); // Outside selection preserved++ // 3. Opaque white paper layer-bg single-layer workflow+ const bgGrid = new SparseTileGrid();+ const bgBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ bgBuf.fill(255);+ drawRectOutline(bgBuf, dims.width, 25, 25, 55, 55, [0, 0, 0, 255]);+ bgGrid.writeImageData(+ 'layer-bg',+ { data: bgBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );+ const bgLayers: LayerItem[] = [+ {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];+ const resBg = executeEncloseAndFillOnTileGrid({+ grid: bgGrid,+ targetLayerId: 'layer-bg',+ layers: bgLayers,+ dimensions: dims,+ polygon: [+ { x: 10, y: 10 },+ { x: 70, y: 10 },+ { x: 70, y: 70 },+ { x: 10, y: 70 },+ ],+ fillColorHex: '#f59e0b',+ tolerance: 32,+ referMode: 'active',+ options: { antiAlias: false },+ });+ expect(resBg.modified).toBe(true);+ expect(readPixel(bgGrid, 'layer-bg', 40, 40)).toEqual([245, 158, 11, 255]);+ expect(readPixel(bgGrid, 'layer-bg', 15, 15)).toEqual([255, 255, 255, 255]); // White background untouched+ });++ it('preserves thin semi-transparent anime pen/pencil strokes (alpha 35-65) at default tolerance and bridges 45-degree diagonal gaps', () => {+ const dims: CanvasDimensions = { width: 80, height: 80 };+ const grid = new SparseTileGrid();+ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);++ // Draw a diamond hair strand using thin tapered semi-transparent ink (alpha = 40, previously lost at thresh=70!)+ // Center (40, 40), radius 20, with a 4px diagonal gap along the top-right edge+ const faintInk: [number, number, number, number] = [0, 0, 0, 40];+ for (let t = 0; t <= 20; t++) {+ setPixel(lineBuf, dims.width, 40 - t, 20 + t, faintInk); // top-left diagonal+ setPixel(lineBuf, dims.width, 20 + t, 40 + t, faintInk); // bottom-left diagonal+ setPixel(lineBuf, dims.width, 40 + t, 60 - t, faintInk); // bottom-right diagonal+ // top-right diagonal with a gap at t = 9..12+ if (t < 9 || t > 12) {+ setPixel(lineBuf, dims.width, 40 + t, 20 + t, faintInk);+ }+ }+ grid.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const res = executeEncloseAndFillOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers: makeStandardLayers(true),+ dimensions: dims,+ polygon: [+ { x: 5, y: 5 },+ { x: 75, y: 5 },+ { x: 75, y: 75 },+ { x: 5, y: 75 },+ ],+ fillColorHex: '#38bdf8',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { closeGap: 10, areaScale: 1, antiAlias: false },+ });++ expect(res.modified).toBe(true);+ expect(readPixel(grid, 'layer-color', 40, 40)).toEqual([56, 189, 248, 255]); // Interior filled!+ expect(readPixel(grid, 'layer-color', 10, 10)[3]).toBe(0); // Exterior untouched!+ });+ });++ describe('Paint Unfilled Area (Brush)', () => {+ it('fills tiny unfilled V-tip corners and 2px outline crevices without touching background, adjacent large unfilled face, or existing paint', () => {+ const dims: CanvasDimensions = { width: 120, height: 120 };+ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-bg', dims.width, dims.height, 'color-32bit');++ // Reference layer:+ // Hair strand box (30..60, 20..70) + adjacent LARGE unfilled face (60..115, 20..115)+ const lineBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ drawRectOutline(lineBuf, dims.width, 30, 20, 60, 70);+ drawRectOutline(lineBuf, dims.width, 60, 20, 115, 115);+ grid.writeImageData(+ 'layer-line',+ { data: lineBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ // Target color layer:+ // Hair is mostly painted brown (33..59, 26..69), intentionally leaving:+ // - an unfilled top corner strip (31..59, 21..25)+ // - a narrow 2px unfilled sliver along the left outline (31..32, 21..69)+ const colorBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ fillRectBuf(colorBuf, dims.width, 33, 26, 59, 69, [139, 92, 60, 255]);+ grid.writeImageData(+ 'layer-color',+ { data: colorBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const layers = makeStandardLayers(true);++ // Brush along the top corner & left outline with a big 26px brush (deliberately overlapping+ // open background to the left/top, existing brown hair, AND the adjacent large unfilled face on the right!)+ // Use a distinct color (#ff0066) so we can prove existing brown hair is NEVER overwritten!+ const res = executePaintUnfilledAreaOnTileGrid({+ grid,+ targetLayerId: 'layer-color',+ layers,+ dimensions: dims,+ strokePoints: [+ { x: 60, y: 23 },+ { x: 32, y: 23 },+ { x: 32, y: 69 },+ ],+ brushSize: 26,+ fillColorHex: '#ff0066',+ tolerance: 32,+ referMode: 'refer-reference',+ options: { closeGap: 4, antiAlias: false },+ });++ expect(res.modified).toBe(true);+ expect(res.tileDeltas.length).toBeGreaterThan(0);++ // Top unfilled pocket filled!+ expect(readPixel(grid, 'layer-color', 45, 23)).toEqual([255, 0, 102, 255]);+ // Narrow 2px left outline sliver filled (even with closeGap = 4)!+ expect(readPixel(grid, 'layer-color', 31, 45)).toEqual([255, 0, 102, 255]);+ expect(readPixel(grid, 'layer-color', 32, 45)).toEqual([255, 0, 102, 255]);++ // Already-painted brown hair is 100% preserved (NEVER overwritten)!+ expect(readPixel(grid, 'layer-color', 35, 30)).toEqual([139, 92, 60, 255]);+ expect(readPixel(grid, 'layer-color', 45, 45)).toEqual([139, 92, 60, 255]);++ // Open background outside left/top outline (even right inside the 26px brush!) is untouched!+ expect(readPixel(grid, 'layer-color', 25, 23)[3]).toBe(0);+ expect(readPixel(grid, 'layer-color', 45, 15)[3]).toBe(0);++ // Adjacent large unfilled face (extending outside the brush stroke) is untouched!+ expect(readPixel(grid, 'layer-color', 65, 25)[3]).toBe(0);+ expect(readPixel(grid, 'layer-color', 85, 60)[3]).toBe(0);+ });++ it('supports single-click dab over tiny unfilled white corners on both transparent and opaque white paper layers', () => {+ const dims: CanvasDimensions = { width: 64, height: 64 };+ const grid = new SparseTileGrid();++ // Opaque white paper layer-bg with black box (15..45, 15..45) painted blue except a tiny 3x3 white corner at (16..18, 16..18)+ const bgBuf = new Uint8ClampedArray(dims.width * dims.height * 4);+ bgBuf.fill(255);+ drawRectOutline(bgBuf, dims.width, 15, 15, 45, 45, [0, 0, 0, 255]);+ fillRectBuf(bgBuf, dims.width, 16, 16, 44, 44, [37, 99, 235, 255]);+ // Carve out a tiny 3x3 unfilled white corner inside the top-left of the outline+ fillRectBuf(bgBuf, dims.width, 16, 16, 18, 18, [255, 255, 255, 255]);++ grid.writeImageData(+ 'layer-bg',+ { data: bgBuf, width: dims.width, height: dims.height },+ 0,+ 0,+ 'color-32bit',+ true+ );++ const layers: LayerItem[] = [+ {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];++ // Single-click dab right over the top-left corner with a 16px brush+ const res = executePaintUnfilledAreaOnTileGrid({+ grid,+ targetLayerId: 'layer-bg',+ layers,+ dimensions: dims,+ strokePoints: [{ x: 17, y: 17 }],+ brushSize: 16,+ fillColorHex: '#2563eb',+ tolerance: 24,+ referMode: 'active',+ options: { antiAlias: false },+ });++ expect(res.modified).toBe(true);+ // Tiny white corner is now filled blue!+ expect(readPixel(grid, 'layer-bg', 17, 17)).toEqual([37, 99, 235, 255]);+ // Black outline is preserved!+ expect(readPixel(grid, 'layer-bg', 15, 17)).toEqual([0, 0, 0, 255]);+ // White background outside the outline (even inside the 16px brush dab!) is preserved!+ expect(readPixel(grid, 'layer-bg', 12, 17)).toEqual([255, 255, 255, 255]);+ });+ });++ describe('Cursor behavior for Smart Line Fill modes', () => {+ it('shows brush outline cursor (cursor: none) for Paint Unfilled Area and crosshair for Enclose and Fill', () => {+ const base = {+ isOverCanvas: true,+ isResizingBrush: false,+ heldModifierAction: 'none' as const,+ isZoomDragging: false,+ isRotating: false,+ isRotateModifier: false,+ isPanning: false,+ isSpaceDown: false,+ tool: 'fill' as const,+ };++ expect(getCursorStyle({ ...base, fillMethod: 'paint-unfilled' })).toEqual({+ cursor: 'none',+ });+ expect(getCursorStyle({ ...base, fillMethod: 'enclose-and-fill' })).toEqual({+ cursor: 'crosshair',+ });+ expect(getCursorStyle({ ...base, fillMethod: 'lasso' })).toEqual({+ cursor: 'crosshair',+ });+ });+ });+});diff --git a/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsx b/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsxnew file mode 100644index 0000000..21328a6--- /dev/null+++ b/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsx@@ -0,0 +1,1181 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CspBrush } from '../../types/editor';+import { DEFAULT_APP_SETTINGS } from '../../types/settings';+import {+ DEFAULT_COMMANDS,+ SPRING_LOADED_HOLD_MS,+ ShortcutManager,+ SpringLoadedSubToolController,+ buildSubToolShortcutCommands,+ findShortcutConflicts,+ formatShortcutFromEvent,+ formatShortcutLabel,+ getSubToolCommandId,+ getSubToolGroupCommandId,+ matchesKeyboardEvent,+ normalizeShortcut,+ parseShortcut,+} from '../shortcutManager';+import {+ getOrderedSubToolIdsForTab,+ loadSubToolGroupsState,+ sanitizeSubToolGroupsState,+} from '../subToolGroups';+import {+ activateSubToolGroup,+ activateSubToolPreset,+ stepMainTool,+ stepSubTool,+ stepSubToolGroup,+} from '../subToolNavigation';+import {+ dispatchNativeOsHotkeyForTest,+ extractNativeOsHotkeyBindings,+} from '../nativeOsHotkeys';+import { resetBrushStorageCache, saveCustomBrush } from '../brushStorage';+import {+ subToolGroupStoreActions,+ toolStoreActions,+ uiStoreActions,+ useSubToolGroupStore,+ useToolStore,+ useUiStore,+} from '../../stores';+import { SubToolList } from '../../components/SubToolList';+import { GlobalShortcutListener } from '../../components/GlobalShortcutListener';+import { SettingsModal } from '../../components/SettingsModal';++// ---------------------------------------------------------------------------+// Minimal DOM shim (matches quickBrushPanel.test.tsx pattern for React 19)+// ---------------------------------------------------------------------------++class MiniNode {+ nodeType: number;+ parentNode: MiniEl | null = null;+ childNodes: MiniNode[] = [];+ constructor(nodeType: number) {+ this.nodeType = nodeType;+ }+ get firstChild() {+ return this.childNodes[0] ?? null;+ }+ get lastChild() {+ return this.childNodes[this.childNodes.length - 1] ?? null;+ }+ get nextSibling(): MiniNode | null {+ if (!this.parentNode) return null;+ const i = this.parentNode.childNodes.indexOf(this);+ return i >= 0 ? (this.parentNode.childNodes[i + 1] ?? null) : null;+ }+ get previousSibling(): MiniNode | null {+ if (!this.parentNode) return null;+ const i = this.parentNode.childNodes.indexOf(this);+ return i > 0 ? (this.parentNode.childNodes[i - 1] ?? null) : null;+ }+ get textContent(): string {+ return this.childNodes.map((c) => c.textContent).join('');+ }+ set textContent(v: string) {+ this.childNodes = v ? [new MiniText(String(v))] : [];+ for (const c of this.childNodes) c.parentNode = this as unknown as MiniEl;+ }+}++class MiniText extends MiniNode {+ data: string;+ constructor(data: string) {+ super(3);+ this.data = data;+ }+ get nodeValue() {+ return this.data;+ }+ set nodeValue(v: string) {+ this.data = String(v);+ }+ override get textContent() {+ return this.data;+ }+ override set textContent(v: string) {+ this.data = String(v);+ }+}++class MiniEl extends MiniNode {+ tagName: string;+ namespaceURI = 'http://www.w3.org/1999/xhtml';+ attributes: Record<string, string> = {};+ style: Record<string, string> = {};+ listeners: Record<string, Array<(ev: unknown) => void>> = {};+ value = '';+ checked = false;+ disabled = false;+ type = '';+ ownerDocument: unknown = null;++ constructor(tag: string) {+ super(1);+ this.tagName = tag.toUpperCase();+ }+ get nodeName() {+ return this.tagName;+ }+ get className() {+ return this.attributes.class || '';+ }+ set className(v: string) {+ this.attributes.class = v;+ }+ appendChild<T extends MiniNode>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }+ insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ const idx = ref ? this.childNodes.indexOf(ref) : -1;+ if (idx < 0) this.childNodes.push(child);+ else this.childNodes.splice(idx, 0, child);+ return child;+ }+ removeChild<T extends MiniNode>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) this.childNodes.splice(idx, 1);+ child.parentNode = null;+ return child;+ }+ contains(node: MiniNode | null): boolean {+ if (!node) return false;+ if (node === this) return true;+ return this.childNodes.some((c) => c === node || (c instanceof MiniEl && c.contains(node)));+ }+ setAttribute(k: string, v: string) {+ this.attributes[k] = String(v);+ }+ getAttribute(k: string) {+ return this.attributes[k] ?? null;+ }+ removeAttribute(k: string) {+ delete this.attributes[k];+ }+ addEventListener(type: string, fn: (ev: unknown) => void) {+ if (!this.listeners[type]) this.listeners[type] = [];+ this.listeners[type].push(fn);+ }+ removeEventListener(type: string, fn: (ev: unknown) => void) {+ if (!this.listeners[type]) return;+ this.listeners[type] = this.listeners[type].filter((f) => f !== fn);+ }+ focus() {}+ blur() {}+ getBoundingClientRect() {+ return { left: 100, top: 100, right: 260, bottom: 320, width: 160, height: 220 };+ }+ findByAttr(attr: string, value: string): MiniEl | null {+ if (this.attributes[attr] === value) return this;+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) {+ const found = c.findByAttr(attr, value);+ if (found) return found;+ }+ }+ return null;+ }+ collectByAttr(attr: string, value?: string, out: MiniEl[] = []): MiniEl[] {+ if (+ Object.prototype.hasOwnProperty.call(this.attributes, attr) &&+ (value === undefined || this.attributes[attr] === value)+ ) {+ out.push(this);+ }+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) c.collectByAttr(attr, value, out);+ }+ return out;+ }+ querySelectorAll(selector: string): MiniEl[] {+ const eqMatch = /^\[([^=\]]+)="([^"]+)"\]$/.exec(selector.trim());+ if (eqMatch) {+ return this.collectByAttr(eqMatch[1], eqMatch[2]);+ }+ const bareMatch = /^\[([^=\]]+)\]$/.exec(selector.trim());+ if (bareMatch) {+ return this.collectByAttr(bareMatch[1]);+ }+ return [];+ }+ querySelector(selector: string): MiniEl | null {+ return this.querySelectorAll(selector)[0] ?? null;+ }+ closest(selector: string): MiniEl | null {+ const tags = selector+ .split(',')+ .map((s) => s.trim().toUpperCase())+ .filter(Boolean);+ let cur: MiniEl | null = this;+ while (cur) {+ if (tags.includes(cur.tagName)) return cur;+ cur = cur.parentNode;+ }+ return null;+ }+}++function getReactProps(el: MiniEl | null): Record<string, unknown> | null {+ if (!el) return null;+ const key = Object.keys(el).find((k) => k.startsWith('__reactProps$'));+ return key ? ((el as unknown as Record<string, unknown>)[key] as Record<string, unknown>) : null;+}++function invokeReactProp(el: MiniEl | null, propName: string, eventObj: Record<string, unknown> = {}) {+ const props = getReactProps(el);+ const fn = props?.[propName];+ if (typeof fn !== 'function') {+ throw new Error(`Expected prop "${propName}" on <${el?.tagName ?? 'null'}> to be a function`);+ }+ const ev = {+ preventDefault: () => {},+ stopPropagation: () => {},+ clientX: 140,+ clientY: 160,+ currentTarget: el,+ target: el,+ ...eventObj,+ };+ return (fn as (e: unknown) => unknown)(ev);+}++function installMiniDom() {+ const winListeners = new Map<string, Array<(ev: unknown) => void>>();+ const docEl = new MiniEl('html');+ const head = new MiniEl('head');+ const body = new MiniEl('body');+ const container = new MiniEl('div');+ body.appendChild(container);+ docEl.appendChild(head);+ docEl.appendChild(body);++ const fakeDoc = {+ nodeType: 9,+ nodeName: '#document',+ documentElement: docEl,+ head,+ body,+ activeElement: body,+ defaultView: null as unknown as Record<string, unknown>,+ createElement: (tag: string) => {+ const el = new MiniEl(tag);+ el.ownerDocument = fakeDoc;+ return el;+ },+ createElementNS: (_ns: string, tag: string) => {+ const el = new MiniEl(tag);+ el.ownerDocument = fakeDoc;+ return el;+ },+ createTextNode: (t: string) => {+ const tn = new MiniText(t);+ (tn as unknown as { ownerDocument: unknown }).ownerDocument = fakeDoc;+ return tn;+ },+ createComment: (t: string) => new MiniText(t),+ querySelector: (sel: string) => body.querySelector(sel),+ querySelectorAll: (sel: string) => body.querySelectorAll(sel),+ addEventListener: () => {},+ removeEventListener: () => {},+ };++ docEl.ownerDocument = fakeDoc;+ body.ownerDocument = fakeDoc;+ container.ownerDocument = fakeDoc;++ class MiniIFrame extends MiniEl {}+ const fakeWin = {+ document: fakeDoc,+ innerWidth: 1280,+ innerHeight: 800,+ addEventListener: (type: string, fn: (ev: unknown) => void) => {+ const list = winListeners.get(type) ?? [];+ list.push(fn);+ winListeners.set(type, list);+ },+ removeEventListener: (type: string, fn: (ev: unknown) => void) => {+ const list = winListeners.get(type) ?? [];+ winListeners.set(+ type,+ list.filter((f) => f !== fn)+ );+ },+ dispatchEvent: (ev: { type: string }) => {+ const list = [...(winListeners.get(ev.type) ?? [])];+ for (const fn of list) fn(ev);+ return true;+ },+ getSelection: () => null,+ requestAnimationFrame: (cb: FrameRequestCallback) => {+ cb(0);+ return 1;+ },+ cancelAnimationFrame: () => {},+ HTMLElement: MiniEl,+ HTMLIFrameElement: MiniIFrame,+ Element: MiniEl,+ Node: MiniNode,+ };+ fakeDoc.defaultView = fakeWin;++ const g = globalThis as Record<string, unknown>;+ const prevDoc = g.document;+ const prevWin = g.window;+ const prevHtml = g.HTMLElement;+ const prevEl = g.Element;+ const prevNode = g.Node;+ const prevIframe = g.HTMLIFrameElement;+ const prevAct = g.IS_REACT_ACT_ENVIRONMENT;++ g.document = fakeDoc;+ g.window = fakeWin;+ g.HTMLElement = MiniEl;+ g.Element = MiniEl;+ g.Node = MiniNode;+ g.HTMLIFrameElement = MiniIFrame;+ g.IS_REACT_ACT_ENVIRONMENT = true;++ return {+ container,+ body,+ window: fakeWin,+ dispatchKeyDown: (ev: Partial<KeyboardEvent>) => {+ const full = {+ type: 'keydown',+ key: '',+ code: '',+ ctrlKey: false,+ metaKey: false,+ shiftKey: false,+ altKey: false,+ repeat: false,+ target: body,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ ...ev,+ };+ fakeWin.dispatchEvent(full);+ return full;+ },+ dispatchKeyUp: (ev: Partial<KeyboardEvent>) => {+ const full = {+ type: 'keyup',+ key: '',+ code: '',+ ctrlKey: false,+ metaKey: false,+ shiftKey: false,+ altKey: false,+ repeat: false,+ target: body,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ ...ev,+ };+ fakeWin.dispatchEvent(full);+ return full;+ },+ cleanup: () => {+ g.document = prevDoc;+ g.window = prevWin;+ g.HTMLElement = prevHtml;+ g.Element = prevEl;+ g.Node = prevNode;+ g.HTMLIFrameElement = prevIframe;+ g.IS_REACT_ACT_ENVIRONMENT = prevAct;+ },+ };+}++function createSampleCustomBrush(id: string, name: string): CspBrush {+ return {+ id,+ name,+ size: 14,+ minSizeFactor: 0.1,+ flow: 1,+ opacity: 1,+ spacing: 0.05,+ hardness: 1,+ thickness: 1,+ antiAlias: 2,+ stabilization: 8,+ angle: 0,+ smoothing: true,+ usePressure: true,+ importedAt: 1700000000000,+ };+}++function installLocalStorage() {+ const storage: Record<string, string> = {};+ (globalThis as unknown as { localStorage: Storage }).localStorage = {+ get length() {+ return Object.keys(storage).length;+ },+ key: (i: number) => Object.keys(storage)[i] ?? null,+ getItem: (k: string) => storage[k] ?? null,+ setItem: (k: string, v: string) => {+ storage[k] = String(v);+ },+ removeItem: (k: string) => {+ delete storage[k];+ },+ clear: () => {+ for (const k of Object.keys(storage)) delete storage[k];+ },+ };+ return storage;+}++describe('OS / Windows Key General Hotkey Support', () => {+ it('parses, normalizes, formats, and captures OS/Win/Meta key combinations independently from Ctrl', () => {+ expect(normalizeShortcut('Win + Q')).toBe('OS+Q');+ expect(normalizeShortcut('windows + shift + 1')).toBe('OS+Shift+1');+ expect(normalizeShortcut('Meta + Alt + Z')).toBe('OS+Alt+Z');+ expect(normalizeShortcut('super + [')).toBe('OS+[');+ expect(normalizeShortcut('Ctrl + Win + S')).toBe('Ctrl+OS+S');+ expect(normalizeShortcut('OS')).toBe('');+ expect(normalizeShortcut('Win')).toBe('');++ const parsed = parseShortcut('Ctrl+Win+Shift+2');+ expect(parsed).toMatchObject({+ ctrl: true,+ meta: true,+ shift: true,+ alt: false,+ key: '2',+ code: 'Digit2',+ });++ // Platform-specific display labels+ expect(formatShortcutLabel('OS+Q', 'windows')).toBe('Win + Q');+ expect(formatShortcutLabel('OS+Q', 'mac')).toBe('Cmd + Q');+ expect(formatShortcutLabel('OS+Q', 'linux')).toBe('OS + Q');+ expect(formatShortcutLabel('Ctrl+OS+Shift+E', 'windows')).toBe('Ctrl + Win + Shift + E');++ // Live KeyboardEvent recording distinguishes metaKey from ctrlKey and ignores bare Meta/OS+ expect(formatShortcutFromEvent({ key: 'Meta', code: 'MetaLeft', metaKey: true })).toBeNull();+ expect(formatShortcutFromEvent({ key: 'OS', code: 'OSLeft', metaKey: true })).toBeNull();+ expect(formatShortcutFromEvent({ key: 'q', code: 'KeyQ', metaKey: true })).toBe('OS+Q');+ expect(+ formatShortcutFromEvent({ key: 'q', code: 'KeyQ', ctrlKey: true, metaKey: true })+ ).toBe('Ctrl+OS+Q');+ });++ it('strictly separates Ctrl vs OS/Win matching on Windows/Linux while supporting macOS Cmd fallback', () => {+ expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', metaKey: true }, 'OS+Z')).toBe(true);+ expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', metaKey: true }, 'Ctrl+Z')).toBe(false);+ expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true }, 'OS+Z')).toBe(false);+ expect(+ matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: true }, 'Ctrl+OS+Z')+ ).toBe(true);+ expect(+ matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: true }, 'OS+Z')+ ).toBe(false);++ const mgr = new ShortcutManager(DEFAULT_COMMANDS);+ mgr.setOverrides({ 'edit.redo': 'OS+Z' });++ // On Windows: Ctrl+Z -> Undo, Win+Z -> Redo+ expect(+ mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: false }, undefined, 'windows')?.id+ ).toBe('edit.undo');+ expect(+ mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true }, undefined, 'windows')?.id+ ).toBe('edit.redo');++ // On macOS: explicit OS+Z wins over fallback, while unbound OS+S still falls back to Ctrl+S Save+ expect(+ mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true }, undefined, 'mac')?.id+ ).toBe('edit.redo');+ expect(+ mgr.matchEvent({ key: 's', code: 'KeyS', ctrlKey: false, metaKey: true }, undefined, 'mac')?.id+ ).toBe('file.save');+ });++ it('extracts native OS-key bindings (including numpad alt codes) across all categories', () => {+ const bindings = extractNativeOsHotkeyBindings(DEFAULT_COMMANDS, {+ 'edit.undo': 'Win+Z',+ 'view.zoomActualSize': 'OS+1',+ 'tool.brush': 'Ctrl+Win+B',+ 'tool.eraser': 'E', // non-OS, must not be extracted+ });++ expect(bindings).toContainEqual({ code: 'KeyZ', ctrl: false, shift: false, alt: false });+ expect(bindings).toContainEqual({ code: 'Digit1', ctrl: false, shift: false, alt: false });+ expect(bindings).toContainEqual({ code: 'Numpad1', ctrl: false, shift: false, alt: false });+ expect(bindings).toContainEqual({ code: 'KeyB', ctrl: true, shift: false, alt: false });+ expect(bindings.some((b) => b.code === 'KeyE')).toBe(false);+ });+});++describe('Custom SubTool Groups (CSP-style) & Instrument Navigation', () => {+ beforeEach(() => {+ installLocalStorage();+ resetBrushStorageCache();+ subToolGroupStoreActions.resetAllGroups();+ toolStoreActions.selectTool('brush');+ activateSubToolPreset('g-pen', []);+ });++ it('creates, renames, reorders, moves brushes between, and deletes custom groups with persistence', () => {+ const inking = subToolGroupStoreActions.createGroup({+ name: 'Lineart',+ color: '#818cf8',+ initialBrushIds: ['g-pen', 'real-g-pen'],+ });+ const painting = subToolGroupStoreActions.createGroup({+ name: 'Painting',+ color: '#34d399',+ initialBrushIds: ['oil-flat-alla-prima'],+ });++ expect(useSubToolGroupStore.getState().groups.map((g) => g.name)).toEqual([+ 'Lineart',+ 'Painting',+ ]);++ // Moving a brush from Lineart -> Painting removes it from Lineart (CSP single-group ownership)+ subToolGroupStoreActions.moveBrushToGroup('real-g-pen', painting.id);+ const afterMove = useSubToolGroupStore.getState().groups;+ expect(afterMove.find((g) => g.id === inking.id)?.brushIds).toEqual(['g-pen']);+ expect(afterMove.find((g) => g.id === painting.id)?.brushIds).toEqual([+ 'oil-flat-alla-prima',+ 'real-g-pen',+ ]);++ // Reorder brushes within Painting+ subToolGroupStoreActions.reorderBrushInGroup(painting.id, 'real-g-pen', 'oil-flat-alla-prima');+ expect(+ useSubToolGroupStore.getState().groups.find((g) => g.id === painting.id)?.brushIds+ ).toEqual(['real-g-pen', 'oil-flat-alla-prima']);++ // Rename & reorder groups+ subToolGroupStoreActions.renameGroup(inking.id, 'Manga Inks');+ subToolGroupStoreActions.reorderGroup(painting.id, inking.id);+ expect(useSubToolGroupStore.getState().groups.map((g) => g.name)).toEqual([+ 'Painting',+ 'Manga Inks',+ ]);++ // Persisted reload preserves custom groups, order, and activeTab+ const reloaded = loadSubToolGroupsState();+ expect(reloaded.groups.map((g) => g.name)).toEqual(['Painting', 'Manga Inks']);+ expect(reloaded.groups[0].brushIds).toEqual(['real-g-pen', 'oil-flat-alla-prima']);++ // Sanitizer rejects invalid entries and deduplicates claimed brushes across groups+ const sanitized = sanitizeSubToolGroupsState({+ groups: [+ { id: 'all', name: 'Reserved', brushIds: ['g-pen'] },+ { id: 'g1', name: 'First', brushIds: ['g-pen', 'g-pen'] },+ { id: 'g2', name: 'Second', brushIds: ['g-pen', 'dot-pen'] },+ ],+ activeTab: 'nonexistent',+ });+ expect(sanitized.groups).toHaveLength(2);+ expect(sanitized.groups[0].brushIds).toEqual(['g-pen']);+ expect(sanitized.groups[1].brushIds).toEqual(['dot-pen']);+ expect(sanitized.activeTab).toBe('all');++ // Deleting custom group returns its brushes safely back to default built-in sections+ subToolGroupStoreActions.deleteGroup(painting.id);+ const penIds = getOrderedSubToolIdsForTab(+ 'pen',+ useSubToolGroupStore.getState().groups,+ [],+ useSubToolGroupStore.getState().brushGroupOverrides,+ useSubToolGroupStore.getState().builtinGroupOrders+ );+ expect(penIds).toContain('real-g-pen');+ expect(penIds).not.toContain('g-pen'); // still owned by Manga Inks+ });++ it('moves brushes freely between built-in groups, reorders within them, and persists across reload', () => {+ const importedBrush = createSampleCustomBrush('inkb-imported-1', 'Imported Pen');++ // Move built-in 'g-pen' from Pen -> Sketch+ expect(subToolGroupStoreActions.moveBrushToGroup('g-pen', 'sketch')).toBe(true);+ // Move imported brush from Imported -> Pen+ expect(subToolGroupStoreActions.moveBrushToGroup(importedBrush.id, 'pen')).toBe(true);++ const st = useSubToolGroupStore.getState();+ const penIds = getOrderedSubToolIdsForTab(+ 'pen',+ st.groups,+ [importedBrush],+ st.brushGroupOverrides,+ st.builtinGroupOrders+ );+ const sketchIds = getOrderedSubToolIdsForTab(+ 'sketch',+ st.groups,+ [importedBrush],+ st.brushGroupOverrides,+ st.builtinGroupOrders+ );+ expect(penIds).not.toContain('g-pen');+ expect(penIds).toContain(importedBrush.id);+ expect(sketchIds).toContain('g-pen');++ // Reorder 'g-pen' right before 'mechanical-pencil' inside Sketch+ subToolGroupStoreActions.reorderBrushInGroup(+ 'sketch',+ 'g-pen',+ 'mechanical-pencil',+ 'before',+ sketchIds+ );+ const reloaded = loadSubToolGroupsState();+ const sketchAfter = getOrderedSubToolIdsForTab(+ 'sketch',+ reloaded.groups,+ [importedBrush],+ reloaded.brushGroupOverrides,+ reloaded.builtinGroupOrders+ );+ expect(sketchAfter[0]).toBe('g-pen');+ expect(sketchAfter[1]).toBe('mechanical-pencil');++ // Resetting 'g-pen' returns it to its factory Pen group+ subToolGroupStoreActions.removeBrushFromAllGroups('g-pen');+ const stReset = useSubToolGroupStore.getState();+ expect(+ getOrderedSubToolIdsForTab(+ 'pen',+ stReset.groups,+ [importedBrush],+ stReset.brushGroupOverrides,+ stReset.builtinGroupOrders+ )+ ).toContain('g-pen');+ });++ it('cycles previous & next sub tools inside active custom group, main instruments, and sub tool groups', () => {+ const customInk = createSampleCustomBrush('inkb-hero-ink', 'Hero Ink');+ const customGroup = subToolGroupStoreActions.createGroup({+ name: 'My Ink Kit',+ initialBrushIds: ['g-pen', customInk.id, 'calligraphy'],+ selectTab: true,+ });++ activateSubToolPreset('g-pen', [customInk]);+ expect(useToolStore.getState().activePresetId).toBe('g-pen');++ // Next subtool -> customInk -> calligraphy -> wraps to g-pen+ expect(stepSubTool(1, [customInk])?.presetId).toBe(customInk.id);+ expect(useToolStore.getState().activePresetId).toBe(customInk.id);++ expect(stepSubTool(1, [customInk])?.presetId).toBe('calligraphy');+ expect(stepSubTool(1, [customInk])?.presetId).toBe('g-pen');++ // Previous subtool wraps backward to calligraphy+ expect(stepSubTool(-1, [customInk])?.presetId).toBe('calligraphy');++ // Main instrument cycling (Next & Previous Tool)+ toolStoreActions.selectTool('brush');+ expect(stepMainTool(1, false).tool).toBe('decoration');+ expect(stepMainTool(1, false).tool).toBe('eraser');+ expect(stepMainTool(1, false).tool).toBe('pipette');+ expect(stepMainTool(-1, false).tool).toBe('eraser');+ expect(stepMainTool(-1, false).tool).toBe('decoration');+ expect(stepMainTool(-1, false).tool).toBe('brush');+ // Wrap backward from brush without open doc skips '3d' and lands on 'vector-edit'+ expect(stepMainTool(-1, false).tool).toBe('vector-edit');+ // With open doc, '3d' is included+ expect(stepMainTool(1, true).tool).toBe('3d');++ // SubTool Group cycling & direct activation restores custom group's last active brush+ subToolGroupStoreActions.setActiveTab(customGroup.id);+ activateSubToolPreset(customInk.id, [customInk]);+ const nextGrp = stepSubToolGroup(1, [customInk]);+ expect(nextGrp?.groupId).toBe('pen');+ const backGrp = stepSubToolGroup(-1, [customInk]);+ expect(backGrp?.groupId).toBe(customGroup.id);+ expect(useToolStore.getState().activePresetId).toBe(customInk.id);++ const directOpen = activateSubToolGroup(customGroup.id, [customInk]);+ expect(directOpen?.groupName).toBe('My Ink Kit');+ expect(directOpen?.activatedBrushName).toBe('Hero Ink');+ });++ it('builds dynamic subtool & group commands, detects conflicts, and supports spring-loaded subtool holds', () => {+ const customBrush = createSampleCustomBrush('inkb-manga-pen', 'Manga Fineliner');+ const group = subToolGroupStoreActions.createGroup({+ name: 'Inking',+ initialBrushIds: [customBrush.id],+ });++ const dynamic = buildSubToolShortcutCommands([customBrush], [group]);+ const brushCmdId = getSubToolCommandId(customBrush.id);+ const groupCmdId = getSubToolGroupCommandId(group.id);++ expect(dynamic.find((c) => c.id === brushCmdId)?.label).toBe('Manga Fineliner');+ expect(dynamic.find((c) => c.id === groupCmdId)?.label).toBe('Group: Inking');++ const mgr = new ShortcutManager(DEFAULT_COMMANDS);+ mgr.setDynamicCommands(dynamic);+ mgr.setOverrides({+ [brushCmdId]: 'OS+1',+ [groupCmdId]: 'OS+Shift+1',+ });++ expect(+ mgr.matchEvent({ key: '1', code: 'Digit1', metaKey: true }, undefined, 'windows')?.id+ ).toBe(brushCmdId);+ expect(+ mgr.matchEvent(+ { key: '1', code: 'Digit1', metaKey: true, shiftKey: true },+ undefined,+ 'windows'+ )?.id+ ).toBe(groupCmdId);++ // Conflict detection works across static + dynamic commands+ const conflictsWithBrush = findShortcutConflicts(+ 'tool.eraser',+ 'OS+1',+ { [brushCmdId]: 'OS+1' },+ mgr.getCommands()+ );+ expect(conflictsWithBrush.map((c) => c.id)).toEqual([brushCmdId]);++ // Spring-loaded subtool hold: tap keeps subtool, hold > 250ms reverts to previous tool+preset+ let clock = 1000;+ const subSpring = new SpringLoadedSubToolController(SPRING_LOADED_HOLD_MS, () => clock);+ expect(subSpring.handleSubToolKeyDown('Digit1', customBrush.id, 'brush', 'g-pen')).toBe(true);+ clock += 100;+ expect(subSpring.handleKeyUp('Digit1', 'brush', customBrush.id)).toBeNull(); // tap stays++ expect(subSpring.handleSubToolKeyDown('Digit1', customBrush.id, 'eraser', 'g-pen')).toBe(true);+ clock += 300;+ expect(subSpring.handleKeyUp('Digit1', 'brush', customBrush.id)).toEqual({+ tool: 'eraser',+ presetId: 'g-pen',+ });+ });+});++describe('UI & GlobalShortcutListener Integration for Custom Groups, SubTool Shortcuts & OS Key', () => {+ let dom: ReturnType<typeof installMiniDom>;+ let root: Root | null = null;+ const customBrush = createSampleCustomBrush('inkb-custom-ink', 'Custom Studio Ink');++ beforeEach(async () => {+ installLocalStorage();+ dom = installMiniDom();+ resetBrushStorageCache();+ subToolGroupStoreActions.resetAllGroups();+ uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, shortcuts: {} });+ await saveCustomBrush(customBrush);+ toolStoreActions.selectTool('brush');+ activateSubToolPreset('g-pen', [customBrush]);+ });++ afterEach(async () => {+ await act(async () => {+ await Promise.resolve();+ });+ if (root) {+ act(() => {+ root?.unmount();+ });+ root = null;+ }+ dom.cleanup();+ });++ it('creates custom groups, assigns brushes, and binds OS-key subtool shortcuts inline in SubToolList', () => {+ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(<SubToolList customBrushes={[customBrush]} setCustomBrushes={() => {}} />);+ });++ // 1. Click "+ Create SubTool Group" button and create "My Inks"+ const createBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-btn');+ act(() => {+ invokeReactProp(createBtn, 'onClick');+ });+ const nameInput = dom.container.findByAttr('data-testid', 'subtool-create-group-input');+ expect(nameInput).not.toBeNull();+ act(() => {+ invokeReactProp(nameInput, 'onChange', { target: { value: 'My Inks' } });+ });+ const confirmBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-confirm');+ act(() => {+ invokeReactProp(confirmBtn, 'onClick');+ });++ const groups = useSubToolGroupStore.getState().groups;+ expect(groups).toHaveLength(1);+ expect(groups[0].name).toBe('My Inks');+ const groupId = groups[0].id;++ // 2. Open inline brush picker for "My Inks" and assign customBrush+ const addBrushesBtn = dom.container.findByAttr(+ 'data-testid',+ `subtool-group-add-brushes-btn-${groupId}`+ );+ act(() => {+ invokeReactProp(addBrushesBtn, 'onClick');+ });+ const pickCustomBtn = dom.container.findByAttr(+ 'data-testid',+ `subtool-group-pick-${groupId}-${customBrush.id}`+ );+ act(() => {+ invokeReactProp(pickCustomBtn, 'onClick');+ });+ expect(useSubToolGroupStore.getState().groups[0].brushIds).toEqual([customBrush.id]);++ // 3. Open context menu on customBrush row -> Set Shortcut... -> bind Win+1 (OS+1)+ const menuBtn = dom.container.findByAttr('data-testid', `subtool-menu-btn-${customBrush.id}`);+ act(() => {+ invokeReactProp(menuBtn, 'onClick');+ });+ const setShortcutBtn = dom.body.findByAttr('data-testid', 'subtool-ctx-set-shortcut');+ expect(setShortcutBtn).not.toBeNull();+ act(() => {+ invokeReactProp(setShortcutBtn, 'onClick');+ });++ // Toggle "+ Win Key" inside SubToolShortcutModal and press Digit1+ const osToggle = dom.body.findByAttr('data-testid', 'subtool-shortcut-os-toggle');+ expect(osToggle).not.toBeNull();+ act(() => {+ invokeReactProp(osToggle, 'onClick');+ });+ act(() => {+ dom.dispatchKeyDown({ key: '1', code: 'Digit1' });+ });++ expect(useUiStore.getState().appSettings.shortcuts[getSubToolCommandId(customBrush.id)]).toBe(+ 'OS+1'+ );+ // Shortcut badge now renders on the subtool row+ const badge = dom.container.findByAttr(+ 'data-testid',+ `subtool-shortcut-badge-${customBrush.id}`+ );+ expect(badge?.textContent).toBe('Win + 1');+ });++ it('supports Tauri-compatible pointer drag-and-drop across groups and drag-to-create custom groups', () => {+ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(<SubToolList customBrushes={[customBrush]} setCustomBrushes={() => {}} />);+ });++ // Both toolbar "+ Group" icon and wrapping tab bar "+ Group" button are rendered+ const createGroupBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-btn')!;+ const toolbarNewGroupBtn = dom.container.findByAttr(+ 'data-testid',+ 'subtool-toolbar-new-group-btn'+ );+ const sketchTab = dom.container.findByAttr('data-testid', 'subtool-group-tab-sketch')!;+ const gPenRow = dom.container.findByAttr('data-testid', 'subtool-row-g-pen')!;+ const realGPenRow = dom.container.findByAttr('data-testid', 'subtool-row-real-g-pen')!;++ expect(createGroupBtn).not.toBeNull();+ expect(toolbarNewGroupBtn).not.toBeNull();++ // Give non-overlapping deterministic bounding boxes to drop targets+ const makeRect = (left: number, top: number, width: number, height: number) => ({+ left,+ top,+ right: left + width,+ bottom: top + height,+ width,+ height,+ x: left,+ y: top,+ toJSON: () => ({}),+ });+ // Reset default rects on all elements so only our positioned targets match test coordinates+ const allDropEls = [+ ...dom.container.querySelectorAll('[data-subtool-drop="create-group"]'),+ ...dom.container.querySelectorAll('[data-subtool-drop-tab]'),+ ...dom.container.querySelectorAll('[data-subtool-drop-row]'),+ ...dom.container.querySelectorAll('[data-subtool-drop-section]'),+ ];+ for (const el of allDropEls) {+ el.getBoundingClientRect = () => makeRect(0, 0, 0, 0);+ }+ const tabBar = dom.container.findByAttr('data-testid', 'subtool-group-tab-bar')!;+ tabBar.getBoundingClientRect = () => makeRect(0, 0, 200, 44);+ sketchTab.getBoundingClientRect = () => makeRect(60, 4, 48, 20);+ createGroupBtn.getBoundingClientRect = () => makeRect(120, 24, 60, 20);++ // 1. Pointer-drag 'g-pen' onto the 'Sketch' tab -> moves 'g-pen' into 'sketch'!+ act(() => {+ invokeReactProp(gPenRow, 'onPointerDown', { button: 0, clientX: 40, clientY: 120 });+ });+ act(() => {+ dom.window.dispatchEvent({ type: 'pointermove', clientX: 80, clientY: 14 } as unknown as {+ type: string;+ });+ });+ // Floating drag ghost appears with "Move to Sketch" hint+ const ghost = dom.body.findByAttr('data-testid', 'subtool-drag-ghost');+ expect(ghost?.textContent).toContain('G-Pen');+ expect(ghost?.textContent).toContain('Move to Sketch');++ act(() => {+ dom.window.dispatchEvent({ type: 'pointerup', clientX: 80, clientY: 14 } as unknown as {+ type: string;+ });+ });+ expect(useSubToolGroupStore.getState().brushGroupOverrides['g-pen']).toBe('sketch');++ // 2. Pointer-drag 'real-g-pen' onto "+ Group" button -> creates a new Custom SubTool Group!+ act(() => {+ invokeReactProp(realGPenRow, 'onPointerDown', { button: 0, clientX: 40, clientY: 150 });+ });+ act(() => {+ dom.window.dispatchEvent({ type: 'pointermove', clientX: 140, clientY: 32 } as unknown as {+ type: string;+ });+ });+ expect(dom.body.findByAttr('data-testid', 'subtool-drag-ghost')?.textContent).toContain(+ '+ Create New Group'+ );+ act(() => {+ dom.window.dispatchEvent({ type: 'pointerup', clientX: 140, clientY: 32 } as unknown as {+ type: string;+ });+ });++ const createdGroups = useSubToolGroupStore.getState().groups;+ expect(createdGroups).toHaveLength(1);+ expect(createdGroups[0].brushIds).toEqual(['real-g-pen']);+ expect(useSubToolGroupStore.getState().activeTab).toBe(createdGroups[0].id);+ });++ it('dispatches prev/next instrument, direct custom subtool, group, and native OS-key hotkeys in GlobalShortcutListener', () => {+ const group = subToolGroupStoreActions.createGroup({+ name: 'Fast Brushes',+ initialBrushIds: ['g-pen', customBrush.id],+ selectTab: true,+ });++ const brushCmdId = getSubToolCommandId(customBrush.id);+ const groupCmdId = getSubToolGroupCommandId(group.id);+ const toasts: string[] = [];+ const onUndo = vi.fn();++ uiStoreActions.updateAppSettings({+ ...DEFAULT_APP_SETTINGS,+ shortcuts: {+ [brushCmdId]: 'OS+1',+ [groupCmdId]: 'OS+2',+ 'edit.undo': 'OS+Q',+ },+ });++ const isFalseRef = { current: false };+ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(+ <GlobalShortcutListener+ hasOpenDocument={true}+ dimensions={{ width: 800, height: 600, dpi: 300 }}+ layers={[]}+ activeLayer={undefined}+ activeLayerId=""+ selection={null}+ transformSession={null}+ textSession={null}+ activeAnimationTimeline={null}+ isSpaceDown={false}+ isHostModalOpen={false}+ isDrawingRef={isFalseRef}+ isSelectionPenDrawingRef={isFalseRef}+ isPipetteSamplingRef={isFalseRef}+ handleUndo={onUndo}+ redo={() => {}}+ handleAddLayer={() => {}}+ handleTriggerOpenFile={() => {}}+ handleSave={() => {}}+ handleSaveAs={() => {}}+ duplicateLayer={() => {}}+ handleCutSelection={() => {}}+ handleCopySelection={() => {}}+ handleCopySelectedLayer={() => {}}+ handlePasteSelectedLayer={() => {}}+ handleMoveSelectionToNewLayer={() => {}}+ handleCopySelectionToNewLayer={() => {}}+ handleGroupSelectedLayers={() => {}}+ handleStartTransform={() => {}}+ handleSelectAll={() => {}}+ handleDeselect={() => {}}+ handleInvertSelection={() => {}}+ handleApplyReverseGradient={() => {}}+ handleOpenTonalModal={() => {}}+ handleUpdateAnimationTimeline={() => {}}+ handleAddAnimationCel={() => {}}+ toggleFlipHorizontal={() => {}}+ toggleFlipVertical={() => {}}+ handleClearSelection={() => {}}+ handleDeleteSelectedLayer={() => {}}+ handleCancelTransform={() => {}}+ handleCancelText={() => {}}+ handleApplyTransform={() => {}}+ handleProcessFile={() => {}}+ showToast={(m) => toasts.push(m)}+ />+ );+ });++ // 1. Default '.' switches to Next Sub Tool inside active custom group+ expect(useToolStore.getState().activePresetId).toBe('g-pen');+ act(() => {+ dom.dispatchKeyDown({ key: '.', code: 'Period' });+ });+ expect(useToolStore.getState().activePresetId).toBe(customBrush.id);++ // 2. Default ',' switches back to Previous Sub Tool+ act(() => {+ dom.dispatchKeyDown({ key: ',', code: 'Comma' });+ });+ expect(useToolStore.getState().activePresetId).toBe('g-pen');++ // 3. Default 'Shift+.' switches to Next Main Tool (brush -> decoration)+ act(() => {+ dom.dispatchKeyDown({ key: '>', code: 'Period', shiftKey: true });+ });+ expect(useToolStore.getState().tool).toBe('decoration');++ // 4. Direct custom subtool hotkey via Win+1 (metaKey: true) jumps directly to brush + customBrush!+ act(() => {+ dom.dispatchKeyDown({ key: '1', code: 'Digit1', metaKey: true });+ });+ expect(useToolStore.getState().tool).toBe('brush');+ expect(useToolStore.getState().activePresetId).toBe(customBrush.id);++ // 5. General command (edit.undo) bound to OS+Q triggers via native Windows OS-hotkey event!+ act(() => {+ dispatchNativeOsHotkeyForTest({+ phase: 'keydown',+ code: 'KeyQ',+ key: 'q',+ ctrlKey: false,+ metaKey: true,+ shiftKey: false,+ altKey: false,+ repeat: false,+ isRecording: false,+ });+ });+ expect(onUndo).toHaveBeenCalledTimes(1);++ // 6. Native event with isRecording: true is ignored by GlobalShortcutListener+ act(() => {+ dispatchNativeOsHotkeyForTest({+ phase: 'keydown',+ code: 'KeyQ',+ key: 'q',+ ctrlKey: false,+ metaKey: true,+ shiftKey: false,+ altKey: false,+ repeat: false,+ isRecording: true,+ });+ });+ expect(onUndo).toHaveBeenCalledTimes(1);++ // 7. Direct custom group shortcut (OS+2) switches tab back to group even from 'pen' tab+ subToolGroupStoreActions.setActiveTab('pen');+ act(() => {+ dom.dispatchKeyDown({ key: '2', code: 'Digit2', metaKey: true });+ });+ expect(useSubToolGroupStore.getState().activeTab).toBe(group.id);+ });++ it('lists Sub Tools & Custom Groups in SettingsModal Shortcuts tab and records OS-key hotkeys', async () => {+ const group = subToolGroupStoreActions.createGroup({+ name: 'Manga Pens',+ initialBrushIds: [customBrush.id],+ });+ const onUpdateSettings = vi.fn();++ await act(async () => {+ root = createRoot(dom.container as unknown as Element);+ root.render(+ <SettingsModal+ isOpen={true}+ onClose={() => {}}+ settings={{ ...DEFAULT_APP_SETTINGS, shortcuts: {} }}+ onUpdateSettings={onUpdateSettings}+ onShowToast={() => {}}+ />+ );+ await Promise.resolve();+ });++ // Click Shortcuts tab in left nav+ const findButtonByText = (node: MiniEl, label: string): MiniEl | null => {+ if (node.tagName === 'BUTTON' && node.textContent.trim() === label) return node;+ for (const c of node.childNodes) {+ if (c instanceof MiniEl) {+ const hit = findButtonByText(c, label);+ if (hit) return hit;+ }+ }+ return null;+ };+ const shortcutsTabBtn = findButtonByText(dom.container, 'Shortcuts');+ expect(shortcutsTabBtn).not.toBeNull();+ act(() => {+ invokeReactProp(shortcutsTabBtn, 'onClick');+ });++ // Filter to 'Sub Tools' category+ const subToolsCatBtn = dom.container.findByAttr(+ 'data-testid',+ 'settings-shortcut-cat-Sub Tools'+ );+ expect(subToolsCatBtn).not.toBeNull();+ act(() => {+ invokeReactProp(subToolsCatBtn, 'onClick');+ });++ // Both the custom group and custom brush appear with click-to-record buttons+ const groupRecordBtn = dom.container.findByAttr(+ 'data-testid',+ `settings-shortcut-record-${getSubToolGroupCommandId(group.id)}`+ );+ const brushRecordBtn = dom.container.findByAttr(+ 'data-testid',+ `settings-shortcut-record-${getSubToolCommandId(customBrush.id)}`+ );+ expect(groupRecordBtn).not.toBeNull();+ expect(brushRecordBtn).not.toBeNull();++ // Record Win+Shift+3 (via metaKey: true) on customBrush+ act(() => {+ invokeReactProp(brushRecordBtn, 'onClick');+ });+ expect(+ dom.container.findByAttr('data-testid', 'settings-shortcut-recording-bar')+ ).not.toBeNull();++ act(() => {+ dom.dispatchKeyDown({ key: '3', code: 'Digit3', metaKey: true, shiftKey: true });+ });++ expect(onUpdateSettings).toHaveBeenCalled();+ const lastSettings = onUpdateSettings.mock.calls[onUpdateSettings.mock.calls.length - 1][0];+ expect(lastSettings.shortcuts[getSubToolCommandId(customBrush.id)]).toBe('OS+Shift+3');+ });+});diff --git a/src/utils/__tests__/timelapsePersistence.test.tsx b/src/utils/__tests__/timelapsePersistence.test.tsxnew file mode 100644index 0000000..124487c--- /dev/null+++ b/src/utils/__tests__/timelapsePersistence.test.tsx@@ -0,0 +1,689 @@+import React, { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { unzipSync, zipSync } from 'fflate';+import { LayerItem } from '../../types/editor';+import { SparseTileGrid } from '../tileEngine';+import { ViewportCompositor } from '../compositor';+import {+ globalTimelapseManager,+ packTimelapseFrameBatch,+ TimelapseRecorderManager,+} from '../timelapseEngine';+import {+ parseInkProject,+ serializeDocument,+ serializeInkProject,+} from '../saveManager';+import { openFile } from '../imageLoader';+import {+ useDocumentLifecycle,+ UseDocumentLifecycleParams,+} from '../../components/DocumentLifecycleManager';+import {+ uiStoreActions,+ useDocumentStore,+} from '../../stores';++// Mock @tauri-apps/api/core so we can test Tauri scratch-disk batch offload/restore/save+const mockTauriInvoke = vi.fn();+vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+}));++vi.mock('../recentDocumentsManager', () => ({+ saveRecentDocument: vi.fn().mockResolvedValue(undefined),+}));++function makeBaseLayer(): LayerItem {+ return {+ id: 'layer-1',+ name: 'Artwork',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ };+}++function makeFakeWebpBytes(tag: number, len = 32): Uint8Array {+ const bytes = new Uint8Array(len);+ // RIFF....WEBP header bytes followed by deterministic payload+ bytes[0] = 0x52;+ bytes[1] = 0x49;+ bytes[2] = 0x46;+ bytes[3] = 0x46;+ bytes[8] = 0x57;+ bytes[9] = 0x45;+ bytes[10] = 0x42;+ bytes[11] = 0x50;+ for (let i = 12; i < len; i++) {+ bytes[i] = (tag * 31 + i) & 0xff;+ }+ return bytes;+}++function stubCanvasForCapture(payloadQueue: Uint8Array[]) {+ let callIndex = 0;+ vi.spyOn(ViewportCompositor, 'renderLowResPreview').mockImplementation(() => {});+ vi.stubGlobal('document', {+ createElement: (tag: string) => {+ if (tag !== 'canvas') return {};+ return {+ width: 0,+ height: 0,+ getContext: () => ({+ fillStyle: '',+ fillRect: () => {},+ drawImage: () => {},+ }),+ toBlob: (cb: (b: Blob | null) => void, mime?: string) => {+ if (mime === 'image/png') {+ cb(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }));+ return;+ }+ const next = payloadQueue[callIndex++] ?? makeFakeWebpBytes(callIndex);+ cb(new Blob([next as BlobPart], { type: mime || 'image/webp' }));+ },+ };+ },+ });+}++// Minimal DOM shim for mounting useDocumentLifecycle hook+class MiniNode {+ public parentNode: MiniEl | null = null;+ constructor(+ public nodeType: number,+ public nodeName: string,+ public ownerDocument: MiniDoc+ ) {}+}++class MiniEl extends EventTarget {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public parentNode: MiniEl | null = null;+ public childNodes: Array<MiniEl | MiniNode> = [];+ public style: Record<string, string> = {};+ constructor(tag: string, public ownerDocument: MiniDoc) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ }+ appendChild<T extends MiniEl | MiniNode>(child: T): T {+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }+ removeChild<T extends MiniEl | MiniNode>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) this.childNodes.splice(idx, 1);+ child.parentNode = null;+ return child;+ }+}++class MiniDoc extends EventTarget {+ public nodeType = 9;+ public defaultView: unknown = globalThis;+ public documentElement: MiniEl;+ public body: MiniEl;+ constructor() {+ super();+ this.documentElement = new MiniEl('html', this);+ this.body = new MiniEl('body', this);+ this.documentElement.appendChild(this.body);+ }+ createElement(tag: string): MiniEl {+ return new MiniEl(tag, this);+ }+ createTextNode(): MiniNode {+ return new MiniNode(3, '#text', this);+ }+ createComment(): MiniNode {+ return new MiniNode(8, '#comment', this);+ }+}++describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {+ afterEach(async () => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ mockTauriInvoke.mockReset();+ if (typeof window !== 'undefined') {+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;+ }+ });++ it('saves recorded timelapse frames into .ink, resumes automatically after exit/reopen, and continues appending across multiple sessions', async () => {+ const f0 = makeFakeWebpBytes(1, 40);+ const f1 = makeFakeWebpBytes(2, 48);+ const f2 = makeFakeWebpBytes(3, 52);+ const f3 = makeFakeWebpBytes(4, 60);+ const f4 = makeFakeWebpBytes(5, 64);+ stubCanvasForCapture([f0, f1, f2, f3, f4]);++ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 512, 512, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 512, height: 512, dpi: 300 };++ // --- Session 1: draw for 2 hours with time-lapse enabled, then save .ink and exit ---+ const session1Manager = new TimelapseRecorderManager({ minIntervalMs: 0 });+ session1Manager.setRecording('doc-session-1', true);+ expect(await session1Manager.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);+ expect(await session1Manager.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);+ expect(await session1Manager.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);+ expect(session1Manager.getStats('doc-session-1').frameCount).toBe(3);++ const saved1 = await serializeInkProject(+ {+ name: 'Illustration',+ dimensions: dims,+ colorMode: 'color',+ layers,+ tileGrid: grid,+ getEffectiveOpacity: (l) => l.opacity,+ isLayerEffectivelyVisible: (l) => l.visible,+ timelapseFrameProvider: session1Manager.createPersistenceProvider('doc-session-1'),+ },+ grid+ );++ // Verify ZIP entries contain the stored keyframes+ const entries1 = unzipSync(saved1.bytes);+ expect(entries1['timelapse/frame_000000.webp']).toBeDefined();+ expect(entries1['timelapse/frame_000001.webp']).toBeDefined();+ expect(entries1['timelapse/frame_000002.webp']).toBeDefined();+ expect(saved1.manifest.timelapse?.enabled).toBe(true);+ expect(saved1.manifest.timelapse?.frameCount).toBe(3);+ expect(saved1.manifest.timelapse?.frames).toHaveLength(3);++ // --- Simulate app exit & relaunch: brand new manager with empty state ---+ const session2Manager = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const reopenedFile1 = new File([saved1.bytes as BlobPart], 'Illustration.ink', {+ type: 'application/octet-stream',+ });+ const loaded1 = await openFile(reopenedFile1);+ expect(loaded1.timelapse?.enabled).toBe(true);+ expect(loaded1.timelapse?.frameCount).toBe(3);+ expect(loaded1.timelapseFrames).toHaveLength(3);++ const restored1 = await session2Manager.restoreSession(+ 'doc-session-2',+ loaded1.timelapse,+ loaded1.timelapseFrames+ );+ expect(restored1).toEqual({ enabled: true, frameCount: 3 });+ expect(session2Manager.isRecording('doc-session-2')).toBe(true);+ expect(session2Manager.getStats('doc-session-2').frameCount).toBe(3);++ // Verify byte-for-byte fidelity of all 3 restored frames+ const frames2 = session2Manager.getFrames('doc-session-2');+ expect(Array.from((await session2Manager.loadFrameBytes('doc-session-2', frames2[0]))!)).toEqual(+ Array.from(f0)+ );+ expect(Array.from((await session2Manager.loadFrameBytes('doc-session-2', frames2[1]))!)).toEqual(+ Array.from(f1)+ );+ expect(Array.from((await session2Manager.loadFrameBytes('doc-session-2', frames2[2]))!)).toEqual(+ Array.from(f2)+ );++ // --- Session 2: draw 2 more strokes (automatically appends frames 3 & 4) ---+ expect(await session2Manager.captureKeyframe('doc-session-2', layers, dims, grid, true)).toBe(true);+ expect(await session2Manager.captureKeyframe('doc-session-2', layers, dims, grid, true)).toBe(true);+ expect(session2Manager.getStats('doc-session-2').frameCount).toBe(5);+ expect(session2Manager.getFrames('doc-session-2').map((f) => f.index)).toEqual([0, 1, 2, 3, 4]);++ // Save again via serializeDocument('.ink')+ const saved2Res = await serializeDocument(+ {+ name: 'Illustration',+ dimensions: dims,+ colorMode: 'color',+ layers,+ tileGrid: grid,+ getEffectiveOpacity: (l) => l.opacity,+ isLayerEffectivelyVisible: (l) => l.visible,+ timelapseFrameProvider: session2Manager.createPersistenceProvider('doc-session-2'),+ },+ '.ink'+ );+ const saved2Buf = await (saved2Res.data as Blob).arrayBuffer();++ // --- Session 3: relaunch again and verify all 5 frames survive intact ---+ const session3Manager = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const loaded2 = await openFile(+ new File([saved2Buf], 'Illustration.ink', { type: 'application/octet-stream' })+ );+ const restored2 = await session3Manager.restoreSession(+ 'doc-session-3',+ loaded2.timelapse,+ loaded2.timelapseFrames+ );+ expect(restored2).toEqual({ enabled: true, frameCount: 5 });+ expect(session3Manager.isRecording('doc-session-3')).toBe(true);++ const frames3 = session3Manager.getFrames('doc-session-3');+ const allExpected = [f0, f1, f2, f3, f4];+ for (let i = 0; i < allExpected.length; i++) {+ const restoredBytes = await session3Manager.loadFrameBytes('doc-session-3', frames3[i]);+ expect(Array.from(restoredBytes!)).toEqual(Array.from(allExpected[i]));+ }+ });++ it('preserves recorded frames when paused before saving and keeps recording paused on reopen', async () => {+ const f0 = makeFakeWebpBytes(10, 36);+ const f1 = makeFakeWebpBytes(11, 36);+ stubCanvasForCapture([f0, f1]);++ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 256, 256, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 256, height: 256, dpi: 300 };++ const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ mgr1.setRecording('doc-paused', true);+ await mgr1.captureKeyframe('doc-paused', layers, dims, grid, true);+ await mgr1.captureKeyframe('doc-paused', layers, dims, grid, true);+ mgr1.setRecording('doc-paused', false); // Pause before saving++ const saved = await serializeInkProject(+ {+ name: 'PausedArt',+ dimensions: dims,+ colorMode: 'color',+ layers,+ tileGrid: grid,+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ timelapseFrameProvider: mgr1.createPersistenceProvider('doc-paused'),+ },+ grid+ );++ const parsed = await parseInkProject(saved.bytes);+ expect(parsed.timelapse?.enabled).toBe(false);+ expect(parsed.timelapse?.frameCount).toBe(2);+ expect(parsed.timelapseFrames).toHaveLength(2);++ const mgr2 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const restored = await mgr2.restoreSession('doc-reopen', parsed.timelapse, parsed.timelapseFrames);+ expect(restored).toEqual({ enabled: false, frameCount: 2 });+ expect(mgr2.isRecording('doc-reopen')).toBe(false);+ expect(mgr2.getStats('doc-reopen').frameCount).toBe(2);+ });++ it('offloads frames to Tauri scratch disk on restore, reads them back on save, and recovers after crash', async () => {+ const f0 = makeFakeWebpBytes(21, 44);+ const f1 = makeFakeWebpBytes(22, 46);+ const f2 = makeFakeWebpBytes(23, 50);+ stubCanvasForCapture([f0, f1, f2]);++ // Simulate Tauri runtime + scratch disk store+ (globalThis as unknown as Record<string, unknown>).window = {+ __TAURI_INTERNALS__: {},+ };+ const diskStore = new Map<string, Map<string, Uint8Array>>();++ const unpackBatchJs = (raw: Uint8Array) => {+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);+ const count = view.getUint32(0, true);+ let offset = 4;+ const out: Array<{ index: number; ext: string; bytes: Uint8Array }> = [];+ for (let i = 0; i < count; i++) {+ const index = view.getUint32(offset, true);+ const extCode = raw[offset + 4];+ const ext = extCode === 1 ? 'jpg' : 'webp';+ const len = view.getUint32(offset + 5, true);+ offset += 9;+ out.push({ index, ext, bytes: raw.slice(offset, offset + len) });+ offset += len;+ }+ return out;+ };++ mockTauriInvoke.mockImplementation(+ async (cmd: string, bodyOrArgs: unknown, opts?: { headers?: Record<string, string> }) => {+ if (cmd === 'timelapse_write_frame') {+ const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');+ const idx = Number(opts?.headers?.['x-frame-index'] || '0');+ const ext = opts?.headers?.['x-ext'] || 'webp';+ if (!diskStore.has(sid)) diskStore.set(sid, new Map());+ const bytes =+ bodyOrArgs instanceof ArrayBuffer+ ? new Uint8Array(bodyOrArgs.slice(0))+ : new Uint8Array(bodyOrArgs as Uint8Array);+ diskStore.get(sid)!.set(`${idx}.${ext}`, bytes);+ return undefined;+ }+ if (cmd === 'timelapse_write_frames_batch') {+ const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');+ if (!diskStore.has(sid)) diskStore.set(sid, new Map());+ const entries = unpackBatchJs(bodyOrArgs as Uint8Array);+ for (const e of entries) {+ diskStore.get(sid)!.set(`${e.index}.${e.ext}`, e.bytes);+ }+ return entries.length;+ }+ if (cmd === 'timelapse_read_frame') {+ const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');+ const idx = Number(opts?.headers?.['x-frame-index'] || '0');+ const ext = opts?.headers?.['x-ext'] || 'webp';+ const bytes = diskStore.get(sid)?.get(`${idx}.${ext}`);+ if (!bytes) throw new Error('Frame not found');+ return bytes.slice().buffer;+ }+ if (cmd === 'timelapse_clear') {+ const sid = (bodyOrArgs as { sessionId: string }).sessionId;+ diskStore.delete(sid);+ return undefined;+ }+ if (cmd === 'timelapse_list_frames') {+ const sid = (bodyOrArgs as { sessionId: string }).sessionId;+ const sessionMap = diskStore.get(sid);+ if (!sessionMap) return [];+ return Array.from(sessionMap.keys())+ .map((k): [number, string] => {+ const [idxStr, ext] = k.split('.');+ return [Number(idxStr), ext];+ })+ .sort((a, b) => a[0] - b[0]);+ }+ return undefined;+ }+ );++ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 512, 512, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 512, height: 512, dpi: 300 };++ // Session 1: capture 2 frames -> offloaded to scratch disk (0 RAM)+ const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ mgr1.setRecording('tauri-doc-1', true);+ await mgr1.captureKeyframe('tauri-doc-1', layers, dims, grid, true);+ await mgr1.captureKeyframe('tauri-doc-1', layers, dims, grid, true);+ expect(mgr1.getStats('tauri-doc-1')).toMatchObject({+ enabled: true,+ frameCount: 2,+ diskFrames: 2,+ memoryBytes: 0,+ });++ // Save .ink -> streams frames back from scratch disk into ZIP+ const saved = await serializeInkProject(+ {+ name: 'DesktopArt',+ dimensions: dims,+ colorMode: 'color',+ layers,+ tileGrid: grid,+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ timelapseFrameProvider: mgr1.createPersistenceProvider('tauri-doc-1'),+ },+ grid+ );++ // Clean exit deletes scratch disk dir+ await mgr1.removeSession('tauri-doc-1');+ expect(diskStore.has('tauri-doc-1')).toBe(false);++ // Session 2: open .ink -> batch-offloads to scratch disk with 0 RAM usage+ const parsed = await parseInkProject(saved.bytes);+ const mgr2 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const restored = await mgr2.restoreSession('tauri-doc-2', parsed.timelapse, parsed.timelapseFrames);+ expect(restored).toEqual({ enabled: true, frameCount: 2 });+ expect(mgr2.getStats('tauri-doc-2')).toMatchObject({+ enabled: true,+ frameCount: 2,+ diskFrames: 2,+ memoryBytes: 0,+ });+ expect(mockTauriInvoke).toHaveBeenCalledWith(+ 'timelapse_write_frames_batch',+ expect.any(Uint8Array),+ expect.objectContaining({ headers: { 'x-session-id': 'tauri-doc-2' } })+ );++ // Capture 3rd frame on resumed session+ await mgr2.captureKeyframe('tauri-doc-2', layers, dims, grid, true);+ expect(mgr2.getStats('tauri-doc-2').frameCount).toBe(3);++ // Simulate crash (scratch disk files remain intact, in-memory state lost)+ const recoveryMeta = mgr2.getRecoveryMetadata('tauri-doc-2');+ expect(recoveryMeta?.enabled).toBe(true);+ expect(recoveryMeta?.frameCount).toBe(3);++ const crashRecoveredMgr = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const recovered = await crashRecoveredMgr.restoreFromScratchDisk(+ 'tauri-doc-2',+ recoveryMeta,+ dims+ );+ expect(recovered).toEqual({ enabled: true, frameCount: 3 });+ expect(crashRecoveredMgr.isRecording('tauri-doc-2')).toBe(true);+ const recoveredFrames = crashRecoveredMgr.getFrames('tauri-doc-2');+ expect(+ Array.from((await crashRecoveredMgr.loadFrameBytes('tauri-doc-2', recoveredFrames[2]))!)+ ).toEqual(Array.from(f2));+ });++ it('handles legacy metadata-only .ink files, rejects unsafe timelapse paths, and packs binary batches accurately', async () => {+ // 1. Legacy .ink file with timelapse metadata only (no embedded frames)+ const legacyManifest = {+ format: 'ink-v2',+ app: 'Ink Studio',+ version: '2.0',+ tileSize: 256,+ name: 'LegacyTL',+ dimensions: { width: 512, height: 512, dpi: 300 },+ colorMode: 'color',+ layers: [makeBaseLayer()],+ layerFormats: {},+ layerTileKeys: {},+ masksMeta: {},+ timelapse: { enabled: true, frameCount: 42 },+ preview: null,+ savedAt: Date.now(),+ };+ const legacyZip = zipSync({+ 'manifest.json': new TextEncoder().encode(JSON.stringify(legacyManifest)),+ });+ const parsedLegacy = await parseInkProject(legacyZip);+ expect(parsedLegacy.timelapse).toEqual({ enabled: true, frameCount: 42 });+ expect(parsedLegacy.timelapseFrames).toBeUndefined();++ const mgr = new TimelapseRecorderManager();+ const res = await mgr.restoreSession('legacy-doc', parsedLegacy.timelapse, parsedLegacy.timelapseFrames);+ expect(res).toEqual({ enabled: true, frameCount: 0 });+ expect(mgr.isRecording('legacy-doc')).toBe(true);++ // 2. Rejects unsafe timelapse frame path in manifest+ const evilZip = zipSync({+ 'manifest.json': new TextEncoder().encode(+ JSON.stringify({+ ...legacyManifest,+ timelapse: {+ enabled: true,+ frameCount: 1,+ frames: [+ {+ index: 0,+ path: '../escape.webp',+ timestamp: 1,+ width: 100,+ height: 100,+ mimeType: 'image/webp',+ bytes: 4,+ },+ ],+ },+ })+ ),+ });+ await expect(parseInkProject(evilZip)).rejects.toThrow(/Unsafe time-lapse frame path/);++ // 3. Binary batch packer format check+ const packed = packTimelapseFrameBatch([+ { index: 7, ext: 'webp', bytes: new Uint8Array([1, 2, 3]) },+ { index: 8, ext: 'jpg', bytes: new Uint8Array([9, 8]) },+ ]);+ const dv = new DataView(packed.buffer);+ expect(dv.getUint32(0, true)).toBe(2);+ expect(dv.getUint32(4, true)).toBe(7);+ expect(packed[8]).toBe(0); // webp+ expect(dv.getUint32(9, true)).toBe(3);+ expect(Array.from(packed.subarray(13, 16))).toEqual([1, 2, 3]);+ expect(dv.getUint32(16, true)).toBe(8);+ expect(packed[20]).toBe(1); // jpg+ expect(dv.getUint32(21, true)).toBe(2);+ expect(Array.from(packed.subarray(25, 27))).toEqual([9, 8]);+ });+});++describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {+ let root: Root | null = null;+ let container: MiniEl | null = null;+ let hookApi: ReturnType<typeof useDocumentLifecycle> | null = null;+ let prevDoc: unknown;+ let prevWin: unknown;+ let prevAct: unknown;++ beforeEach(() => {+ prevDoc = (globalThis as Record<string, unknown>).document;+ prevWin = (globalThis as Record<string, unknown>).window;+ prevAct = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ const miniDoc = new MiniDoc();+ (globalThis as Record<string, unknown>).document = miniDoc;+ (globalThis as Record<string, unknown>).window = globalThis;+ (globalThis as Record<string, unknown>).HTMLElement = MiniEl;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = class HTMLIFrameElement {};+ (globalThis as Record<string, unknown>).Element = MiniEl;+ (globalThis as Record<string, unknown>).Node = MiniNode;++ container = miniDoc.createElement('div');+ miniDoc.body.appendChild(container);+ root = createRoot(container as unknown as HTMLElement);++ useDocumentStore.reset();+ uiStoreActions.setAppView('home');+ hookApi = null;+ });++ afterEach(async () => {+ const activeId = useDocumentStore.getState().activeDocumentId;+ if (activeId) {+ await globalTimelapseManager.removeSession(activeId);+ }+ if (root) {+ act(() => {+ root?.unmount();+ });+ }+ root = null;+ container = null;+ (globalThis as Record<string, unknown>).document = prevDoc;+ (globalThis as Record<string, unknown>).window = prevWin;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevAct;+ });++ it('automatically resumes embedded timelapse on handleProcessFile(.ink) and cleans up on handleCloseDocument', async () => {+ const baseLayer = makeBaseLayer();+ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 256, 256, 'color-32bit');++ const f0 = makeFakeWebpBytes(51, 32);+ const f1 = makeFakeWebpBytes(52, 32);++ const saved = await serializeInkProject(+ {+ name: 'AttachedTL',+ dimensions: { width: 256, height: 256, dpi: 300 },+ colorMode: 'color',+ layers: [baseLayer],+ tileGrid: grid,+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ timelapse: { enabled: true, frameCount: 2 },+ timelapseFrames: [+ { index: 0, timestamp: 1000, width: 256, height: 256, mimeType: 'image/webp', bytes: f0 },+ { index: 1, timestamp: 2000, width: 256, height: 256, mimeType: 'image/webp', bytes: f1 },+ ],+ },+ grid+ );++ const showToast = vi.fn();+ const params: UseDocumentLifecycleParams = {+ layers: [baseLayer],+ activeLayer: baseLayer,+ activeLayerId: 'layer-1',+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ setActiveLayerId: vi.fn(),+ resetToNewCanvas: vi.fn(() => ({ layers: [baseLayer], activeLayerId: 'layer-1' })),+ setDefaultToneFrequency: vi.fn(),+ clearDocument: vi.fn(),+ loadDocument: vi.fn(),+ switchDocumentSession: vi.fn(),+ resizeCanvas: vi.fn(),+ copyLayer: vi.fn(() => null),+ pasteLayer: vi.fn(async () => ({ success: false })),+ deleteLayer: vi.fn(),+ pasteLayerFromFile: vi.fn(async () => 'Pasted'),+ resetZoomAndCenter: vi.fn(),+ resetHistory: vi.fn(),+ pushHistoryStep: vi.fn(),+ showToast,+ };++ function Harness() {+ hookApi = useDocumentLifecycle(params);+ return null;+ }+ act(() => {+ root!.render(React.createElement(Harness));+ });++ const inkFile = new File([saved.bytes as BlobPart], 'AttachedTL.ink', {+ type: 'application/octet-stream',+ });++ await act(async () => {+ await hookApi!.handleProcessFile(inkFile);+ });++ const openedId = useDocumentStore.getState().activeDocumentId;+ expect(openedId).toBeTruthy();+ expect(globalTimelapseManager.isRecording(openedId)).toBe(true);+ expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(2);+ expect(showToast).toHaveBeenCalledWith(+ 'Opened AttachedTL.ink — time-lapse resumed (2 frames)'+ );++ const restoredFrames = globalTimelapseManager.getFrames(openedId!);+ expect(+ Array.from((await globalTimelapseManager.loadFrameBytes(openedId!, restoredFrames[0]))!)+ ).toEqual(Array.from(f0));+ expect(+ Array.from((await globalTimelapseManager.loadFrameBytes(openedId!, restoredFrames[1]))!)+ ).toEqual(Array.from(f1));++ // Closing the document removes its time-lapse session cleanly+ await act(async () => {+ hookApi!.handleCloseDocument(openedId!);+ });+ expect(globalTimelapseManager.isRecording(openedId)).toBe(false);+ expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(0);+ });+});diff --git a/src/utils/__tests__/transformModeTransition.test.ts b/src/utils/__tests__/transformModeTransition.test.tsnew file mode 100644index 0000000..7b2b0fb--- /dev/null+++ b/src/utils/__tests__/transformModeTransition.test.ts@@ -0,0 +1,579 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import type { Point2D, TransformSession } from '../../types/editor';+import {+ createDefaultMeshPoints,+ createDefaultPerspectiveQuad,+ evaluateHomography,+ evaluateMeshSurface,+ processAffineTransformChunks,+ solveUnitSquareToQuad,+} from '../transformEngine';+import {+ createMeshPointsFromPerspectiveQuad,+ decomposeMeshToAffine,+ decomposeMeshToPerspectiveQuad,+ decomposeQuadToAffine,+ flipTransformSession,+ isPerspectiveQuadSafeForMesh,+ releaseTransformSessionCanvases,+ resetTransformSession,+ switchTransformSessionMode,+} from '../transformModeTransition';++class MockImageData {+ data: Uint8ClampedArray;+ width: number;+ height: number;+ constructor(dataOrW: Uint8ClampedArray | number, widthOrH: number, height?: number) {+ if (typeof dataOrW === 'number') {+ this.width = dataOrW;+ this.height = widthOrH;+ this.data = new Uint8ClampedArray(this.width * this.height * 4);+ } else {+ this.data = dataOrW;+ this.width = widthOrH;+ this.height = height ?? Math.floor(dataOrW.length / (4 * widthOrH));+ }+ }+}++class MockCanvas {+ private _w = 0;+ private _h = 0;+ pixels = new Uint8ClampedArray(0);+ released = false;++ get width() {+ return this._w;+ }+ set width(v: number) {+ this._w = Math.max(0, Math.floor(v));+ if (this._w === 0) this.released = true;+ this.pixels = new Uint8ClampedArray(this._w * this._h * 4);+ }+ get height() {+ return this._h;+ }+ set height(v: number) {+ this._h = Math.max(0, Math.floor(v));+ if (this._h === 0) this.released = true;+ this.pixels = new Uint8ClampedArray(this._w * this._h * 4);+ }++ getContext(type: string) {+ if (type !== '2d') return null;+ const self = this;+ return {+ createImageData(w: number, h: number) {+ return new MockImageData(w, h);+ },+ putImageData(img: MockImageData, dx = 0, dy = 0) {+ for (let y = 0; y < img.height; y++) {+ const ty = dy + y;+ if (ty < 0 || ty >= self._h) continue;+ for (let x = 0; x < img.width; x++) {+ const tx = dx + x;+ if (tx < 0 || tx >= self._w) continue;+ const sOff = (y * img.width + x) * 4;+ const dOff = (ty * self._w + tx) * 4;+ self.pixels[dOff] = img.data[sOff];+ self.pixels[dOff + 1] = img.data[sOff + 1];+ self.pixels[dOff + 2] = img.data[sOff + 2];+ self.pixels[dOff + 3] = img.data[sOff + 3];+ }+ }+ },+ getImageData(sx: number, sy: number, sw: number, sh: number) {+ const out = new Uint8ClampedArray(sw * sh * 4);+ for (let y = 0; y < sh; y++) {+ const py = sy + y;+ if (py < 0 || py >= self._h) continue;+ for (let x = 0; x < sw; x++) {+ const px = sx + x;+ if (px < 0 || px >= self._w) continue;+ const sOff = (py * self._w + px) * 4;+ const dOff = (y * sw + x) * 4;+ out[dOff] = self.pixels[sOff];+ out[dOff + 1] = self.pixels[sOff + 1];+ out[dOff + 2] = self.pixels[sOff + 2];+ out[dOff + 3] = self.pixels[sOff + 3];+ }+ }+ return new MockImageData(out, sw, sh);+ },+ };+ }+}++function makePaintedCanvas(+ w: number,+ h: number,+ painter: (x: number, y: number) => [number, number, number, number]+): { canvas: HTMLCanvasElement; pixels: { data: Uint8ClampedArray; width: number; height: number } } {+ const canvas = new MockCanvas();+ canvas.width = w;+ canvas.height = h;+ const data = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const [r, g, b, a] = painter(x, y);+ const off = (y * w + x) * 4;+ data[off] = r;+ data[off + 1] = g;+ data[off + 2] = b;+ data[off + 3] = a;+ }+ }+ canvas.pixels.set(data);+ return {+ canvas: canvas as unknown as HTMLCanvasElement,+ pixels: { data, width: w, height: h },+ };+}++function makeSession(+ x: number,+ y: number,+ w: number,+ h: number,+ painter: (px: number, py: number) => [number, number, number, number] = () => [220, 60, 80, 255]+): TransformSession {+ const { canvas, pixels } = makePaintedCanvas(w, h, painter);+ const quad = createDefaultPerspectiveQuad(x, y, w, h, 0);+ return {+ active: true,+ layerId: 'layer-1',+ sourceCanvas: canvas,+ sourcePixels: pixels,+ bounds: { x, y, width: w, height: h },+ x,+ y,+ width: w,+ height: h,+ rotation: 0,+ flipH: false,+ flipV: false,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ };+}++function getPixel(+ buf: { data: Uint8ClampedArray; width: number; height: number },+ x: number,+ y: number+): [number, number, number, number] {+ const off = (y * buf.width + x) * 4;+ return [buf.data[off], buf.data[off + 1], buf.data[off + 2], buf.data[off + 3]];+}++describe('Transform Mode Transitions (preserving edits across Free / Perspective / Mesh)', () => {+ let prevDocument: unknown;++ beforeEach(() => {+ prevDocument = (globalThis as { document?: unknown }).document;+ (globalThis as { document?: unknown }).document = {+ createElement: () => new MockCanvas(),+ };+ });++ afterEach(() => {+ (globalThis as { document?: unknown }).document = prevDocument;+ });++ it('preserves move, scale, rotation, and flip when switching from Free (affine) to Mesh or Perspective without resampling', () => {+ const initial = makeSession(20, 30, 40, 20);+ const movedAndEdited: TransformSession = {+ ...initial,+ x: 120,+ y: 90,+ width: 80,+ height: 40,+ rotation: 30,+ flipH: true,+ flipV: false,+ };++ // Switch affine -> mesh+ const inMesh = switchTransformSessionMode(movedAndEdited, 'mesh');+ expect(inMesh.mode).toBe('mesh');+ // Zero resampling: sourceCanvas stays identical+ expect(inMesh.sourceCanvas).toBe(initial.sourceCanvas);+ expect(inMesh.originalSourceCanvas).toBeUndefined();++ // Verify mesh corners match exact rotated + flipped + scaled + moved corners+ const expectedQuad = createDefaultPerspectiveQuad(120, 90, 80, 40, 30, true, false);+ const mesh = inMesh.meshPoints!;+ expect(mesh[0][0].x).toBeCloseTo(expectedQuad[0].x, 5);+ expect(mesh[0][0].y).toBeCloseTo(expectedQuad[0].y, 5);+ expect(mesh[0][3].x).toBeCloseTo(expectedQuad[1].x, 5);+ expect(mesh[0][3].y).toBeCloseTo(expectedQuad[1].y, 5);+ expect(mesh[3][3].x).toBeCloseTo(expectedQuad[2].x, 5);+ expect(mesh[3][3].y).toBeCloseTo(expectedQuad[2].y, 5);+ expect(mesh[3][0].x).toBeCloseTo(expectedQuad[3].x, 5);+ expect(mesh[3][0].y).toBeCloseTo(expectedQuad[3].y, 5);++ // Center of mesh must stay at exact affine center (120 + 40, 90 + 20) = (160, 110)+ const center = evaluateMeshSurface(mesh, 0.5, 0.5);+ expect(center.x).toBeCloseTo(160, 5);+ expect(center.y).toBeCloseTo(110, 5);++ // Switch affine -> perspective directly+ const inPersp = switchTransformSessionMode(movedAndEdited, 'perspective');+ expect(inPersp.mode).toBe('perspective');+ expect(inPersp.sourceCanvas).toBe(initial.sourceCanvas);+ for (let i = 0; i < 4; i++) {+ expect(inPersp.perspectiveQuad![i].x).toBeCloseTo(expectedQuad[i].x, 5);+ expect(inPersp.perspectiveQuad![i].y).toBeCloseTo(expectedQuad[i].y, 5);+ }++ // Switching back from unmodified mesh or perspective to affine recovers exact params with zero baking+ const backFromMesh = switchTransformSessionMode(inMesh, 'affine');+ expect(backFromMesh.sourceCanvas).toBe(initial.sourceCanvas);+ expect(backFromMesh.x).toBe(120);+ expect(backFromMesh.y).toBe(90);+ expect(backFromMesh.width).toBe(80);+ expect(backFromMesh.height).toBe(40);+ expect(backFromMesh.rotation).toBe(30);+ expect(backFromMesh.flipH).toBe(true);+ expect(backFromMesh.flipV).toBe(false);++ const backFromPersp = switchTransformSessionMode(inPersp, 'affine');+ expect(backFromPersp.sourceCanvas).toBe(initial.sourceCanvas);+ expect(backFromPersp.x).toBe(120);+ expect(backFromPersp.y).toBe(90);+ expect(backFromPersp.width).toBe(80);+ expect(backFromPersp.height).toBe(40);+ expect(backFromPersp.rotation).toBe(30);+ expect(backFromPersp.flipH).toBe(true);+ expect(backFromPersp.flipV).toBe(false);+ });++ it('preserves perspective keystone corners when switching from Perspective to Mesh via exact homography grid', () => {+ const base = makeSession(50, 50, 100, 100);+ const inPersp = switchTransformSessionMode(base, 'perspective');++ // Drag top corners inward to form a trapezoid (keystone)+ const trapezoid: [Point2D, Point2D, Point2D, Point2D] = [+ { x: 70, y: 50 },+ { x: 130, y: 50 },+ { x: 150, y: 150 },+ { x: 50, y: 150 },+ ];+ expect(isPerspectiveQuadSafeForMesh(trapezoid)).toBe(true);++ const editedPersp: TransformSession = {+ ...inPersp,+ perspectiveQuad: trapezoid,+ };++ const inMesh = switchTransformSessionMode(editedPersp, 'mesh');+ expect(inMesh.mode).toBe('mesh');+ expect(inMesh.sourceCanvas).toBe(base.sourceCanvas);++ // Every mesh control point must lie on the exact projective homography of the trapezoid+ const H = solveUnitSquareToQuad(trapezoid[0], trapezoid[1], trapezoid[2], trapezoid[3]);+ const mesh = inMesh.meshPoints!;+ for (let r = 0; r < 4; r++) {+ for (let c = 0; c < 4; c++) {+ const expected = evaluateHomography(H, c / 3, r / 3);+ expect(mesh[r][c].x).toBeCloseTo(expected.x, 5);+ expect(mesh[r][c].y).toBeCloseTo(expected.y, 5);+ }+ }++ // Switching straight back from unmodified perspective-derived mesh -> perspective recovers exact quad with zero baking+ const backToPersp = switchTransformSessionMode(inMesh, 'perspective');+ expect(backToPersp.sourceCanvas).toBe(base.sourceCanvas);+ for (let i = 0; i < 4; i++) {+ expect(backToPersp.perspectiveQuad![i].x).toBeCloseTo(trapezoid[i].x, 5);+ expect(backToPersp.perspectiveQuad![i].y).toBeCloseTo(trapezoid[i].y, 5);+ }+ });++ it('bakes perspective warp when switching from distorted Perspective to Free (affine) and allows continuing with move/scale', () => {+ // Paint left half red, right half blue+ const base = makeSession(20, 20, 40, 40, (x) => (x < 20 ? [255, 0, 0, 255] : [0, 0, 255, 255]));+ const inPersp = switchTransformSessionMode(base, 'perspective');++ // Drag top-right corner right by +30px and down by +10px (non-rectangular)+ const warpedQuad: [Point2D, Point2D, Point2D, Point2D] = [+ { x: 20, y: 20 },+ { x: 90, y: 30 },+ { x: 60, y: 60 },+ { x: 20, y: 60 },+ ];+ const editedPersp: TransformSession = {+ ...inPersp,+ perspectiveQuad: warpedQuad,+ };++ const inAffine = switchTransformSessionMode(editedPersp, 'affine');+ expect(inAffine.mode).toBe('affine');+ // Must bake into a new sourceCanvas while preserving originalSourceCanvas for Reset+ expect(inAffine.sourceCanvas).not.toBe(base.sourceCanvas);+ expect(inAffine.originalSourceCanvas).toBe(base.sourceCanvas);+ expect(inAffine.rotation).toBe(0);+ expect(inAffine.flipH).toBe(false);+ expect(inAffine.flipV).toBe(false);++ // Baked bounds should expand horizontally to cover the extended top-right corner (~x=20..90)+ expect(inAffine.x).toBeGreaterThanOrEqual(19);+ expect(inAffine.x).toBeLessThanOrEqual(21);+ expect(inAffine.x + inAffine.width).toBeGreaterThanOrEqual(85);+ expect(inAffine.sourcePixels!.width).toBe(inAffine.width);+ expect(inAffine.sourcePixels!.height).toBe(inAffine.height);++ // Verify blue pixels actually exist in the extended right wing of the baked image+ let blueRightWingPixels = 0;+ const buf = inAffine.sourcePixels!;+ for (let y = 0; y < buf.height; y++) {+ for (let x = Math.floor(buf.width * 0.75); x < buf.width; x++) {+ const [, , b, a] = getPixel(buf, x, y);+ if (a > 128 && b > 200) blueRightWingPixels++;+ }+ }+ expect(blueRightWingPixels).toBeGreaterThan(20);++ // Continue transforming in affine (move by +50, +40) and verify pixels move cleanly+ const movedAfterBake: TransformSession = {+ ...inAffine,+ x: inAffine.x + 50,+ y: inAffine.y + 40,+ };+ const out = new Uint8ClampedArray(200 * 200 * 4);+ processAffineTransformChunks(+ movedAfterBake.sourcePixels!,+ {+ x: movedAfterBake.x,+ y: movedAfterBake.y,+ width: movedAfterBake.width,+ height: movedAfterBake.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ },+ { x: 0, y: 0, width: 200, height: 200 },+ 128,+ (chunk, cx, cy, cw, ch) => {+ for (let row = 0; row < ch; row++) {+ out.set(chunk.subarray(row * cw * 4, (row + 1) * cw * 4), ((cy + row) * 200 + cx) * 4);+ }+ }+ );+ // Original position (25, 35) is now empty; moved position (75, 75) has red pixels+ expect(out[(35 * 200 + 25) * 4 + 3]).toBe(0);+ expect(out[(75 * 200 + 75) * 4]).toBeGreaterThan(200);+ expect(out[(75 * 200 + 75) * 4 + 3]).toBe(255);+ });++ it('bakes warped Mesh when switching to Free (affine) or Perspective, and supports chained multi-mode transforms + Reset', () => {+ const base = makeSession(10, 10, 40, 40, () => [30, 200, 110, 255]);++ // Step 1: Move in Free mode (+30, +20) -> box is now at (40, 30, 40, 40)+ const moved: TransformSession = { ...base, x: 40, y: 30 };++ // Step 2: Switch to Mesh mode -> mesh is placed at (40..80, 30..70)+ const inMesh = switchTransformSessionMode(moved, 'mesh');+ expect(inMesh.meshPoints![0][0]).toEqual({ x: 40, y: 30 });+ expect(inMesh.meshPoints![3][3]).toEqual({ x: 80, y: 70 });++ // Step 3: Warp an interior control point + bottom-right corner outward+ const warpedMesh = inMesh.meshPoints!.map((row) => row.map((p) => ({ ...p })));+ warpedMesh[1][2] = { x: warpedMesh[1][2].x + 25, y: warpedMesh[1][2].y - 10 };+ warpedMesh[3][3] = { x: 110, y: 90 };+ const editedMesh: TransformSession = { ...inMesh, meshPoints: warpedMesh };++ // Step 4: Switch Mesh -> Free (affine) -> bakes warped mesh into sourceCanvas+ const backAffine = switchTransformSessionMode(editedMesh, 'affine');+ expect(backAffine.mode).toBe('affine');+ expect(backAffine.sourceCanvas).not.toBe(base.sourceCanvas);+ expect(backAffine.originalSourceCanvas).toBe(base.sourceCanvas);+ // Baked bounding box must encompass the pulled-out corner near (110, 90)+ expect(backAffine.x + backAffine.width).toBeGreaterThanOrEqual(105);+ expect(backAffine.y + backAffine.height).toBeGreaterThanOrEqual(85);++ // Step 5: Move again in Free mode (+15, +10), then switch to Perspective -> preserves baked warp + new move!+ const movedAgain: TransformSession = {+ ...backAffine,+ x: backAffine.x + 15,+ y: backAffine.y + 10,+ };+ const inPersp = switchTransformSessionMode(movedAgain, 'perspective');+ expect(inPersp.mode).toBe('perspective');+ expect(inPersp.sourceCanvas).toBe(backAffine.sourceCanvas); // No second bake needed for affine -> perspective+ expect(inPersp.perspectiveQuad![0].x).toBe(movedAgain.x);+ expect(inPersp.perspectiveQuad![0].y).toBe(movedAgain.y);++ // Step 6: Reset restores completely unbaked original sourceCanvas & original bounds!+ const reset = resetTransformSession(inPersp);+ expect(reset.sourceCanvas).toBe(base.sourceCanvas);+ expect(reset.sourcePixels).toBe(base.sourcePixels);+ expect(reset.originalSourceCanvas).toBeUndefined();+ expect(reset.x).toBe(10);+ expect(reset.y).toBe(10);+ expect(reset.width).toBe(40);+ expect(reset.height).toBe(40);+ expect(reset.retiredCanvases).toContain(backAffine.sourceCanvas);++ // Releasing canvases releases original and retired canvases without throwing+ releaseTransformSessionCanvases(reset);+ expect((base.sourceCanvas as unknown as MockCanvas).released).toBe(true);+ expect((backAffine.sourceCanvas as unknown as MockCanvas).released).toBe(true);+ });++ it('preserves each individual layer independently when baking a multi-layer / folder transform', () => {+ const layerA = makePaintedCanvas(40, 40, (x, y) =>+ x < 20 && y < 20 ? [255, 0, 0, 255] : [0, 0, 0, 0]+ );+ const layerB = makePaintedCanvas(40, 40, (x, y) =>+ x >= 20 && y >= 20 ? [0, 0, 255, 255] : [0, 0, 0, 0]+ );+ const preview = makePaintedCanvas(40, 40, (x, y) => {+ if (x < 20 && y < 20) return [255, 0, 0, 255];+ if (x >= 20 && y >= 20) return [0, 0, 255, 255];+ return [0, 0, 0, 0];+ });++ const quad = createDefaultPerspectiveQuad(20, 20, 40, 40, 0);+ const session: TransformSession = {+ active: true,+ layerId: 'layer-a',+ layerIds: ['layer-a', 'layer-b'],+ layerSourceCanvases: new Map([+ ['layer-a', layerA.canvas],+ ['layer-b', layerB.canvas],+ ]),+ layerSourcePixels: new Map([+ ['layer-a', layerA.pixels],+ ['layer-b', layerB.pixels],+ ]),+ sourceCanvas: preview.canvas,+ sourcePixels: preview.pixels,+ bounds: { x: 20, y: 20, width: 40, height: 40 },+ x: 20,+ y: 20,+ width: 40,+ height: 40,+ rotation: 0,+ flipH: false,+ flipV: false,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ };++ // Move folder by (+20, +10), switch to mesh, pull bottom-right corner outward, then switch back to affine+ const inMesh = switchTransformSessionMode({ ...session, x: 40, y: 30 }, 'mesh');+ const warped = inMesh.meshPoints!.map((row) => row.map((p) => ({ ...p })));+ warped[3][3] = { x: 100, y: 90 };+ const bakedAffine = switchTransformSessionMode({ ...inMesh, meshPoints: warped }, 'affine');++ expect(bakedAffine.mode).toBe('affine');+ expect(bakedAffine.layerSourceCanvases?.size).toBe(2);+ expect(bakedAffine.originalLayerSourceCanvases?.get('layer-a')).toBe(layerA.canvas);+ expect(bakedAffine.originalLayerSourceCanvases?.get('layer-b')).toBe(layerB.canvas);++ const bakedA = bakedAffine.layerSourcePixels!.get('layer-a')!;+ const bakedB = bakedAffine.layerSourcePixels!.get('layer-b')!;+ // Both baked layer buffers share identical aligned dimensions+ expect(bakedA.width).toBe(bakedAffine.width);+ expect(bakedA.height).toBe(bakedAffine.height);+ expect(bakedB.width).toBe(bakedAffine.width);+ expect(bakedB.height).toBe(bakedAffine.height);++ // Layer A must still contain ONLY red (zero blue); Layer B must contain ONLY blue (zero red)+ let aRed = 0, aBlue = 0, bRed = 0, bBlue = 0;+ for (let i = 0; i < bakedA.data.length; i += 4) {+ if (bakedA.data[i + 3] > 128) {+ if (bakedA.data[i] > 150) aRed++;+ if (bakedA.data[i + 2] > 150) aBlue++;+ }+ if (bakedB.data[i + 3] > 128) {+ if (bakedB.data[i] > 150) bRed++;+ if (bakedB.data[i + 2] > 150) bBlue++;+ }+ }+ expect(aRed).toBeGreaterThan(50);+ expect(aBlue).toBe(0);+ expect(bBlue).toBeGreaterThan(50);+ expect(bRed).toBe(0);+ });++ it('supports Flip Horizontal and Flip Vertical in affine, perspective, and mesh modes', () => {+ const base = makeSession(10, 20, 100, 60);++ // Perspective flip mirrors quad symmetrically around center+ const inPersp = switchTransformSessionMode(base, 'perspective');+ const flippedPerspH = flipTransformSession(inPersp, 'horizontal');+ expect(flippedPerspH.flipH).toBe(true);+ expect(flippedPerspH.perspectiveQuad![0]).toEqual({ x: 110, y: 20 });+ expect(flippedPerspH.perspectiveQuad![1]).toEqual({ x: 10, y: 20 });+ expect(flippedPerspH.perspectiveQuad![2]).toEqual({ x: 10, y: 80 });+ expect(flippedPerspH.perspectiveQuad![3]).toEqual({ x: 110, y: 80 });++ // Switching flipped perspective back to affine recovers flipH = true with zero baking!+ const affineFromFlippedPersp = switchTransformSessionMode(flippedPerspH, 'affine');+ expect(affineFromFlippedPersp.sourceCanvas).toBe(base.sourceCanvas);+ expect(affineFromFlippedPersp.flipH).toBe(true);+ expect(affineFromFlippedPersp.flipV).toBe(false);+ expect(affineFromFlippedPersp.rotation).toBe(0);++ // Mesh flip mirrors all control points around mesh center and is an exact involution+ const inMesh = switchTransformSessionMode(base, 'mesh');+ const flippedMeshV = flipTransformSession(inMesh, 'vertical');+ expect(flippedMeshV.flipV).toBe(true);+ expect(flippedMeshV.meshPoints![0][0].y).toBeCloseTo(80, 5);+ expect(flippedMeshV.meshPoints![3][0].y).toBeCloseTo(20, 5);++ const unflippedMeshV = flipTransformSession(flippedMeshV, 'vertical');+ expect(unflippedMeshV.flipV).toBe(false);+ expect(unflippedMeshV.meshPoints![0][0].y).toBeCloseTo(20, 5);+ expect(unflippedMeshV.meshPoints![3][0].y).toBeCloseTo(80, 5);+ });++ it('decomposes unwarped quads/meshes accurately and rejects distorted or skewed geometry', () => {+ const rotated = createDefaultPerspectiveQuad(40, 50, 120, 60, 45, false, true);+ const dec = decomposeQuadToAffine(rotated, false, true);+ expect(dec).not.toBeNull();+ expect(dec!.x).toBe(40);+ expect(dec!.y).toBe(50);+ expect(dec!.width).toBe(120);+ expect(dec!.height).toBe(60);+ expect(dec!.rotation).toBe(45);+ expect(dec!.flipH).toBe(false);+ expect(dec!.flipV).toBe(true);++ // 1px corner nudge must reject affine decomposition so perspective change is baked+ const nudged: [Point2D, Point2D, Point2D, Point2D] = [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 101, y: 100 },+ { x: 0, y: 100 },+ ];+ expect(decomposeQuadToAffine(nudged)).toBeNull();++ // Skewed parallelogram must reject affine decomposition+ const skewed: [Point2D, Point2D, Point2D, Point2D] = [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 110, y: 100 },+ { x: 10, y: 100 },+ ];+ expect(decomposeQuadToAffine(skewed)).toBeNull();++ // Unmodified mesh decomposes cleanly; nudging a single interior point rejects both affine and perspective decomposition+ const mesh = createMeshPointsFromPerspectiveQuad(rotated, 4, 4);+ expect(decomposeMeshToAffine(mesh, false, true)).not.toBeNull();+ expect(decomposeMeshToPerspectiveQuad(mesh)).not.toBeNull();++ mesh[1][1].x += 1;+ expect(decomposeMeshToAffine(mesh, false, true)).toBeNull();+ expect(decomposeMeshToPerspectiveQuad(mesh)).toBeNull();+ });+});diff --git a/src/utils/__tests__/valueCheckAndNavigatorSplit.test.tsx b/src/utils/__tests__/valueCheckAndNavigatorSplit.test.tsxnew file mode 100644index 0000000..dcd8d4e--- /dev/null+++ b/src/utils/__tests__/valueCheckAndNavigatorSplit.test.tsx@@ -0,0 +1,1220 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ applyPerceptualGrayscaleToImageData,+ clampNavigatorSplitRatio,+ computePerceptualLuminanceByte,+ DEFAULT_NAVIGATOR_SPLIT_RATIO,+ nextNavigatorPreviewMode,+} from '../valueCheck';+import { useDocumentStore, documentStoreActions } from '../../stores/useDocumentStore';+import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';+import { useToolStore } from '../../stores/useToolStore';+import { COMMAND_CATALOG } from '../../types/workspace';+import { DEFAULT_COMMANDS } from '../shortcutManager';+import {+ executeWorkspaceCommand,+ isCommandActive,+ isCommandDisabled,+ WorkspaceCommandHandlers,+} from '../../components/CommandBar';+import {+ NavigatorPanel,+ computeNavigatorSplitRatioFromClientX,+ computePreviewBoxMetrics,+} from '../../components/NavigatorPanel';+import { Header } from '../../components/Header';+import { StatusBar } from '../../components/StatusBar';+import { SparseTileGrid, TILE_SIZE } from '../tileEngine';+import {+ COMPOSITOR_INSTANCED_VERTEX_SHADER,+ COMPOSITOR_VERTEX_SHADER,+ VIEWPORT_DRAFT_VERTEX_SHADER,+ ViewportCompositor,+} from '../compositor';+import { CameraSubscriber, CameraTransformState, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';+import { CanvasDimensions, LayerItem } from '../../types/editor';++function createMemoryStorage(): Storage {+ const store = new Map<string, string>();+ return {+ get length() {+ return store.size;+ },+ clear() {+ store.clear();+ },+ getItem(key: string) {+ return store.has(key) ? store.get(key)! : null;+ },+ key(index: number) {+ return Array.from(store.keys())[index] ?? null;+ },+ removeItem(key: string) {+ store.delete(key);+ },+ setItem(key: string, value: string) {+ store.set(key, String(value));+ },+ };+}++class MiniText {+ nodeType = 3;+ nodeName = '#text';+ parentNode: MiniEl | null = null;+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}+}++class MiniComment {+ nodeType = 8;+ nodeName = '#comment';+ parentNode: MiniEl | null = null;+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}+}++function createMock2DContext(fillColor: [number, number, number, number] = [255, 0, 0, 255]) {+ let storedData: Uint8ClampedArray | null = null;+ let storedW = 0;+ let storedH = 0;+ const drawImageCalls: unknown[][] = [];++ return {+ drawImageCalls,+ getStoredData: () => storedData,+ save: vi.fn(),+ restore: vi.fn(),+ setTransform: vi.fn(),+ clearRect: vi.fn(),+ fillRect: vi.fn(),+ strokeRect: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ closePath: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ scale: vi.fn(),+ drawImage: vi.fn((...args: unknown[]) => {+ drawImageCalls.push(args);+ }),+ createImageData: (w: number, h: number) => ({+ data: new Uint8ClampedArray(w * h * 4),+ width: w,+ height: h,+ }),+ putImageData: vi.fn((img: { data: Uint8ClampedArray; width: number; height: number }) => {+ storedData = new Uint8ClampedArray(img.data);+ storedW = img.width;+ storedH = img.height;+ }),+ getImageData: vi.fn((_x: number, _y: number, w: number, h: number) => {+ if (storedData && storedW === w && storedH === h) {+ return { data: new Uint8ClampedArray(storedData), width: w, height: h };+ }+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = fillColor[0];+ data[i + 1] = fillColor[1];+ data[i + 2] = fillColor[2];+ data[i + 3] = fillColor[3];+ }+ return { data, width: w, height: h };+ }),+ imageSmoothingEnabled: true,+ fillStyle: '',+ strokeStyle: '',+ lineWidth: 1,+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ };+}++class MiniEl extends EventTarget {+ nodeType = 1;+ nodeName: string;+ tagName: string;+ namespaceURI = 'http://www.w3.org/1999/xhtml';+ parentNode: MiniEl | null = null;+ childNodes: Array<MiniEl | MiniText | MiniComment> = [];+ style: Record<string, string> = {};+ className = '';+ disabled = false;+ value = '';+ width = 200;+ height = 120;+ clientWidth = 200;+ clientHeight = 120;+ attrs = new Map<string, string>();+ mockCtx: ReturnType<typeof createMock2DContext> | null = null;++ constructor(tag: string, public ownerDocument: MiniDoc) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ }++ get firstChild() {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((c) => (c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];+ }++ getBoundingClientRect() {+ return {+ left: 0,+ top: 0,+ width: this.clientWidth,+ height: this.clientHeight,+ right: this.clientWidth,+ bottom: this.clientHeight,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ };+ }++ setPointerCapture() {}+ releasePointerCapture() {}++ override dispatchEvent(event: Event): boolean {+ if (!event.target) {+ Object.defineProperty(event, 'target', { value: this, configurable: true });+ }+ let cur: MiniEl | null = this;+ while (cur) {+ EventTarget.prototype.dispatchEvent.call(cur, event);+ if (!event.bubbles || event.cancelBubble) break;+ cur = cur.parentNode;+ }+ return !event.defaultPrevented;+ }++ getContext(type: string) {+ if (type === '2d') {+ if (!this.mockCtx) this.mockCtx = createMock2DContext(this.ownerDocument.mockPixelColor);+ return this.mockCtx;+ }+ return null;+ }++ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ insertBefore<T extends MiniEl | MiniText | MiniComment>(+ node: T,+ ref: MiniEl | MiniText | MiniComment | null+ ): T {+ if (node.parentNode) node.parentNode.removeChild(node);+ node.parentNode = this;+ const idx = ref ? this.childNodes.indexOf(ref) : -1;+ if (idx >= 0) this.childNodes.splice(idx, 0, node);+ else this.childNodes.push(node);+ return node;+ }++ setAttribute(k: string, v: string) {+ this.attrs.set(k, String(v));+ }++ getAttribute(k: string): string | null {+ return this.attrs.get(k) ?? null;+ }++ removeAttribute(k: string) {+ this.attrs.delete(k);+ }++ contains(target: unknown): boolean {+ if (target === this) return true;+ for (const c of this.childNodes) {+ if (c === target) return true;+ if (c instanceof MiniEl && c.contains(target)) return true;+ }+ return false;+ }++ findByAttr(attr: string, value: string): MiniEl | null {+ if (this.getAttribute(attr) === value) return this;+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) {+ const found = c.findByAttr(attr, value);+ if (found) return found;+ }+ }+ return null;+ }+}++interface MiniDoc {+ nodeType: number;+ nodeName: string;+ documentElement: MiniEl;+ body: MiniEl;+ activeElement: MiniEl;+ defaultView: Record<string, unknown>;+ mockPixelColor: [number, number, number, number];+ createElement: (tag: string) => MiniEl;+ createElementNS: (_ns: string, tag: string) => MiniEl;+ createTextNode: (text: string) => MiniText;+ createComment: (text: string) => MiniComment;+ addEventListener: EventTarget['addEventListener'];+ removeEventListener: EventTarget['removeEventListener'];+ dispatchEvent: EventTarget['dispatchEvent'];+}++function installMiniDom(pixelColor: [number, number, number, number] = [255, 0, 0, 255]) {+ const g = globalThis as unknown as Record<string, unknown>;+ const saved: Record<string, unknown> = {+ window: g.window,+ document: g.document,+ HTMLElement: g.HTMLElement,+ Node: g.Node,+ Element: g.Element,+ requestAnimationFrame: g.requestAnimationFrame,+ cancelAnimationFrame: g.cancelAnimationFrame,+ IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,+ };+ g.IS_REACT_ACT_ENVIRONMENT = true;++ const winTarget = new EventTarget();+ const docTarget = new EventTarget();++ const mockDoc: MiniDoc = {+ nodeType: 9,+ nodeName: '#document',+ documentElement: null as unknown as MiniEl,+ body: null as unknown as MiniEl,+ activeElement: null as unknown as MiniEl,+ defaultView: null as unknown as Record<string, unknown>,+ mockPixelColor: pixelColor,+ createElement: (tag: string) => new MiniEl(tag, mockDoc),+ createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),+ createTextNode: (text: string) => new MiniText(text, mockDoc),+ createComment: (text: string) => new MiniComment(text, mockDoc),+ addEventListener: docTarget.addEventListener.bind(docTarget),+ removeEventListener: docTarget.removeEventListener.bind(docTarget),+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),+ };++ mockDoc.documentElement = new MiniEl('html', mockDoc);+ mockDoc.body = new MiniEl('body', mockDoc);+ mockDoc.documentElement.appendChild(mockDoc.body);+ mockDoc.activeElement = mockDoc.body;++ class MockIFrame extends MiniEl {}+ const rafMock = (cb: FrameRequestCallback) => {+ cb(16);+ return 1;+ };+ const cancelRafMock = () => {};++ const mockWin: Record<string, unknown> = {+ innerWidth: 1440,+ innerHeight: 900,+ devicePixelRatio: 1,+ document: mockDoc,+ Node: MiniEl,+ Element: MiniEl,+ HTMLElement: MiniEl,+ SVGElement: MiniEl,+ HTMLIFrameElement: MockIFrame,+ Event,+ CustomEvent,+ addEventListener: winTarget.addEventListener.bind(winTarget),+ removeEventListener: winTarget.removeEventListener.bind(winTarget),+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),+ requestAnimationFrame: rafMock,+ cancelAnimationFrame: cancelRafMock,+ };+ mockDoc.defaultView = mockWin;++ g.window = mockWin;+ g.document = mockDoc;+ g.HTMLElement = MiniEl;+ g.Node = MiniEl;+ g.Element = MiniEl;+ g.requestAnimationFrame = rafMock;+ g.cancelAnimationFrame = cancelRafMock;++ const container = new MiniEl('div', mockDoc);+ mockDoc.body.appendChild(container);++ return {+ container,+ mockDoc,+ cleanup: () => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete g[k];+ else g[k] = v;+ }+ },+ };+}++function createMockNavigation(initial?: Partial<CameraTransformState>) {+ const subs = new Set<CameraSubscriber>();+ const panRef = { current: initial?.pan ? { ...initial.pan } : { x: 400, y: 300 } };+ const zoomRef = { current: initial?.zoom ?? 1 };+ const rotationRef = { current: initial?.rotation ?? 0 };+ const flipXRef = { current: initial?.flipX ?? false };+ const flipYRef = { current: initial?.flipY ?? false };++ const emit = () => {+ const cam: CameraTransformState = {+ pan: { ...panRef.current },+ zoom: zoomRef.current,+ rotation: rotationRef.current,+ flipX: flipXRef.current,+ flipY: flipYRef.current,+ };+ subs.forEach((fn) => fn(cam));+ };++ const setPanLive = vi.fn((next: { x: number; y: number }) => {+ panRef.current = { ...next };+ emit();+ });+ const setZoomLive = vi.fn((z: number) => {+ zoomRef.current = z;+ emit();+ });+ const rotateBy = vi.fn((delta: number) => {+ rotationRef.current += delta;+ emit();+ });+ const commitCameraState = vi.fn();++ const handle: CanvasNavigationHandle = {+ panRef,+ zoomRef,+ rotationRef,+ flipXRef,+ flipYRef,+ getCameraState: () => ({+ pan: { ...panRef.current },+ zoom: zoomRef.current,+ rotation: rotationRef.current,+ flipX: flipXRef.current,+ flipY: flipYRef.current,+ }),+ subscribeCamera: (fn) => {+ subs.add(fn);+ return () => subs.delete(fn);+ },+ setPanLive,+ setZoomLive,+ rotateBy,+ commitCameraState,+ };++ return { handle, setPanLive, setZoomLive, commitCameraState };+}++function createMockWebGL2Harness() {+ let programId = 1;+ const shaderSourceByObj = new Map<object, string>();+ const programTag = new Map<object, string>();+ const uniformMeta = new Map<object, { prog: object; name: string }>();+ const programUniforms = new Map<object, Map<string, unknown>>();+ const drawProgramHistory: string[] = [];+ let activeProgram: any = null;++ const gl: Record<string, any> = {+ VERTEX_SHADER: 0x8b31,+ FRAGMENT_SHADER: 0x8b30,+ COMPILE_STATUS: 0x8b81,+ LINK_STATUS: 0x8b82,+ ARRAY_BUFFER: 0x8892,+ STATIC_DRAW: 0x88e4,+ DYNAMIC_DRAW: 0x88e8,+ FLOAT: 0x1406,+ TRIANGLES: 0x0004,+ TEXTURE0: 0x84c0,+ TEXTURE1: 0x84c1,+ TEXTURE2: 0x84c2,+ TEXTURE3: 0x84c3,+ TEXTURE_2D: 0x0de1,+ TEXTURE_2D_ARRAY: 0x8c1a,+ TEXTURE_WRAP_S: 0x2802,+ TEXTURE_WRAP_T: 0x2803,+ TEXTURE_MIN_FILTER: 0x2801,+ TEXTURE_MAG_FILTER: 0x2800,+ CLAMP_TO_EDGE: 0x812f,+ LINEAR: 0x2601,+ NEAREST: 0x2600,+ RGBA: 0x1908,+ RGBA8: 0x8058,+ UNSIGNED_BYTE: 0x1401,+ BLEND: 0x0be2,+ ONE: 1,+ ZERO: 0,+ ONE_MINUS_SRC_ALPHA: 0x0303,+ COLOR_BUFFER_BIT: 0x4000,+ STENCIL_BUFFER_BIT: 0x0400,+ STENCIL_TEST: 0x0b90,+ FRAMEBUFFER: 0x8d40,+ COLOR_ATTACHMENT0: 0x8ce0,+ STENCIL_ATTACHMENT: 0x8d20,+ RENDERBUFFER: 0x8d41,+ STENCIL_INDEX8: 0x8d48,+ FRAMEBUFFER_COMPLETE: 0x8cd5,+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,+ MAX_ARRAY_TEXTURE_LAYERS: 0x88ff,++ createShader: (type: number) => ({ __shader: type }),+ shaderSource: (shader: object, src: string) => shaderSourceByObj.set(shader, src),+ compileShader: () => {},+ getShaderParameter: () => true,+ getShaderInfoLog: () => '',+ createProgram: () => {+ const p = { id: programId++ };+ programUniforms.set(p, new Map());+ return p;+ },+ attachShader: (prog: object, shader: object) => {+ const src = shaderSourceByObj.get(shader) || '';+ if (src === COMPOSITOR_INSTANCED_VERTEX_SHADER) programTag.set(prog, 'instanced');+ else if (src === VIEWPORT_DRAFT_VERTEX_SHADER) programTag.set(prog, 'viewportDraft');+ else if (src === COMPOSITOR_VERTEX_SHADER && !programTag.has(prog)) programTag.set(prog, 'standard');+ else if (src.includes('u_blitTexture')) programTag.set(prog, 'blit');+ else if (src.includes('u_sceneTexture')) programTag.set(prog, 'softProof');+ else if (src.includes('u_lutTexture')) programTag.set(prog, 'adjustment');+ else if (src.includes('POISSON_KERNEL')) programTag.set(prog, 'styles');+ },+ linkProgram: () => {},+ getProgramParameter: () => true,+ getProgramInfoLog: () => '',+ getUniformLocation: (prog: object, name: string) => {+ const loc = { prog, name };+ uniformMeta.set(loc, { prog, name });+ return loc;+ },+ getAttribLocation: (_prog: object, name: string) => (name === 'a_instanceData' ? 1 : 0),+ useProgram: (prog: any) => {+ activeProgram = prog;+ },+ createBuffer: () => ({ __buf: true }),+ bindBuffer: () => {},+ bufferData: () => {},+ bufferSubData: () => {},+ createVertexArray: () => ({ __vao: true }),+ bindVertexArray: () => {},+ deleteVertexArray: () => {},+ enableVertexAttribArray: () => {},+ disableVertexAttribArray: () => {},+ vertexAttribPointer: () => {},+ vertexAttribDivisor: () => {},+ createTexture: () => ({ __tex: Math.random() }),+ deleteTexture: () => {},+ activeTexture: () => {},+ bindTexture: () => {},+ texParameteri: () => {},+ generateMipmap: () => {},+ texImage2D: () => {},+ texSubImage2D: () => {},+ texStorage3D: () => {},+ texSubImage3D: () => {},+ createFramebuffer: () => ({ __fbo: Math.random() }),+ deleteFramebuffer: () => {},+ bindFramebuffer: () => {},+ framebufferTexture2D: () => {},+ checkFramebufferStatus: () => 0x8cd5,+ createRenderbuffer: () => ({ __rb: Math.random() }),+ deleteRenderbuffer: () => {},+ bindRenderbuffer: () => {},+ renderbufferStorage: () => {},+ framebufferRenderbuffer: () => {},+ pixelStorei: () => {},+ getParameter: (pname: number) => (pname === 0x88ff ? 64 : 0),+ getExtension: () => null,+ viewport: () => {},+ clearColor: () => {},+ clear: () => {},+ enable: () => {},+ disable: () => {},+ isEnabled: () => false,+ blendFunc: () => {},+ colorMask: () => {},+ stencilFunc: () => {},+ stencilOp: () => {},+ stencilMask: () => {},+ uniform1i: (loc: object | null, v: number) => {+ if (!loc) return;+ const meta = uniformMeta.get(loc);+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, v);+ },+ uniform1f: (loc: object | null, v: number) => {+ if (!loc) return;+ const meta = uniformMeta.get(loc);+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, v);+ },+ uniform2f: (loc: object | null, x: number, y: number) => {+ if (!loc) return;+ const meta = uniformMeta.get(loc);+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, [x, y]);+ },+ uniform3f: (loc: object | null, x: number, y: number, z: number) => {+ if (!loc) return;+ const meta = uniformMeta.get(loc);+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, [x, y, z]);+ },+ uniform4f: (loc: object | null, x: number, y: number, z: number, w: number) => {+ if (!loc) return;+ const meta = uniformMeta.get(loc);+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, [x, y, z, w]);+ },+ drawArrays: () => {+ if (activeProgram) {+ drawProgramHistory.push(programTag.get(activeProgram) || 'unknown');+ }+ },+ drawArraysInstanced: () => {+ if (activeProgram) {+ drawProgramHistory.push(programTag.get(activeProgram) || 'unknown');+ }+ },+ deleteProgram: () => {},+ deleteBuffer: () => {},+ };++ const canvas = {+ width: 320,+ height: 240,+ getContext: (type: string) => (type === 'webgl2' ? gl : null),+ } as unknown as HTMLCanvasElement;++ const getSoftProofUniforms = () => {+ for (const [prog, tag] of programTag.entries()) {+ if (tag === 'softProof') {+ return programUniforms.get(prog) ?? new Map();+ }+ }+ return new Map();+ };++ return { canvas, gl, drawProgramHistory, getSoftProofUniforms };+}++describe('Perceptual Value Check Luminance Math', () => {+ it('preserves neutral grays identically and ranks saturated primaries by true perceptual luminance', () => {+ for (const gray of [0, 32, 64, 128, 192, 255]) {+ expect(computePerceptualLuminanceByte(gray, gray, gray)).toBe(gray);+ }++ const blueVal = computePerceptualLuminanceByte(0, 0, 255);+ const redVal = computePerceptualLuminanceByte(255, 0, 0);+ const greenVal = computePerceptualLuminanceByte(0, 255, 0);+ const yellowVal = computePerceptualLuminanceByte(255, 255, 0);++ // True linear-light Rec.709 / CIE Y perceptual values:+ // Blue (~76) < Red (~127) < Green (~220) < Yellow (~247)+ expect(blueVal).toBeGreaterThanOrEqual(72);+ expect(blueVal).toBeLessThanOrEqual(80);+ expect(redVal).toBeGreaterThanOrEqual(124);+ expect(redVal).toBeLessThanOrEqual(131);+ expect(greenVal).toBeGreaterThanOrEqual(216);+ expect(greenVal).toBeLessThanOrEqual(224);+ expect(yellowVal).toBeGreaterThanOrEqual(243);+ expect(yellowVal).toBeLessThanOrEqual(250);+ expect(blueVal).toBeLessThan(redVal);+ expect(redVal).toBeLessThan(greenVal);+ expect(greenVal).toBeLessThan(yellowVal);+ });++ it('converts full and split-slice ImageData regions in-place while preserving transparency', () => {+ // 4x1 row of pure red pixels, except pixel 3 is transparent+ const img = {+ width: 4,+ height: 1,+ data: new Uint8ClampedArray([+ 255, 0, 0, 255, // x=0 (left / Color)+ 255, 0, 0, 255, // x=1 (left / Color)+ 255, 0, 0, 255, // x=2 (right / B/W)+ 255, 0, 0, 0, // x=3 (transparent)+ ]),+ };++ applyPerceptualGrayscaleToImageData(img, 2, 4);++ // Left half [0..2) remains pure red+ expect(Array.from(img.data.slice(0, 8))).toEqual([255, 0, 0, 255, 255, 0, 0, 255]);++ // Right pixel x=2 converted to perceptual gray (~127), alpha preserved+ const expectedRedGray = computePerceptualLuminanceByte(255, 0, 0);+ expect(Array.from(img.data.slice(8, 12))).toEqual([+ expectedRedGray,+ expectedRedGray,+ expectedRedGray,+ 255,+ ]);++ // Transparent pixel x=3 untouched+ expect(Array.from(img.data.slice(12, 16))).toEqual([255, 0, 0, 0]);+ });++ it('clamps Navigator split ratios and cycles preview modes deterministically', () => {+ expect(clampNavigatorSplitRatio(0.01)).toBe(0.05);+ expect(clampNavigatorSplitRatio(0.99)).toBe(0.95);+ expect(clampNavigatorSplitRatio(0.42)).toBe(0.42);+ expect(clampNavigatorSplitRatio(Number.NaN)).toBe(DEFAULT_NAVIGATOR_SPLIT_RATIO);++ expect(nextNavigatorPreviewMode('color')).toBe('bw');+ expect(nextNavigatorPreviewMode('bw')).toBe('split');+ expect(nextNavigatorPreviewMode('split')).toBe('color');+ });+});++describe('Value Check & Navigator Split View Store, Command Bar & Shortcuts', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;++ beforeEach(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useDocumentStore.reset();+ useWorkspaceStore.reset();+ });++ afterEach(() => {+ if (prevStorage === undefined) {+ delete (globalThis as unknown as Record<string, unknown>).localStorage;+ } else {+ Object.defineProperty(globalThis, 'localStorage', {+ value: prevStorage,+ configurable: true,+ writable: true,+ });+ }+ });++ it('toggles main-canvas Value Check independently of CMYK soft proof and persists Navigator mode & split ratio', () => {+ expect(useDocumentStore.getState().valueCheckEnabled).toBe(false);+ expect(documentStoreActions.toggleValueCheck()).toBe(true);+ expect(useDocumentStore.getState().valueCheckEnabled).toBe(true);+ expect(useDocumentStore.getState().softProofSettings.enabled).toBe(false);++ workspaceStoreActions.setNavigatorPreviewMode('bw');+ workspaceStoreActions.setNavigatorSplitRatio(0.35, true);+ expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');+ expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.35);++ // Survives reload via persisted workspace state+ useWorkspaceStore.reset();+ expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');+ expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.35);++ expect(workspaceStoreActions.cycleNavigatorPreviewMode()).toBe('split');+ expect(workspaceStoreActions.cycleNavigatorPreviewMode()).toBe('color');+ });++ it('exposes value-check in COMMAND_CATALOG and registers conflict-free default shortcuts', () => {+ const entry = COMMAND_CATALOG.find((c) => c.id === 'value-check');+ expect(entry).toBeDefined();+ expect(entry?.shortcut).toBe('Shift+Y');++ const onToggleValueCheck = vi.fn();+ const handlers: WorkspaceCommandHandlers = {+ canUndo: false,+ canRedo: false,+ onUndo: vi.fn(),+ onRedo: vi.fn(),+ onToggleValueCheck,+ valueCheckEnabled: true,+ hasOpenDocument: true,+ };++ expect(isCommandDisabled('value-check', handlers)).toBe(false);+ expect(isCommandDisabled('value-check', { ...handlers, hasOpenDocument: false })).toBe(true);+ expect(isCommandActive('value-check', handlers, false)).toBe(true);+ executeWorkspaceCommand('value-check', handlers);+ expect(onToggleValueCheck).toHaveBeenCalledTimes(1);++ const valueCmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.valueCheck');+ const navModeCmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.navigatorValueMode');+ expect(valueCmd?.defaultShortcut).toBe('Shift+Y');+ expect(navModeCmd?.defaultShortcut).toBe('Alt+Shift+Y');++ // Verify zero duplicate default shortcuts across all registered commands+ const seen = new Map<string, string>();+ for (const cmd of DEFAULT_COMMANDS) {+ if (!cmd.defaultShortcut) continue;+ const key = cmd.defaultShortcut.toLowerCase();+ expect(seen.has(key), `Duplicate shortcut ${cmd.defaultShortcut} (${seen.get(key)} vs ${cmd.id})`).toBe(false);+ seen.set(key, cmd.id);+ }+ });+});++describe('GPU WebGL2 & Canvas 2D Compositor Value Check + Live Draft Preview', () => {+ it('activates WebGL2 softProof post-processing pass with u_valueCheck=1 and coexists with CMYK soft proof', () => {+ const harness = createMockWebGL2Harness();+ const compositor = new ViewportCompositor(harness.canvas);+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 512, height: 512, dpi: 300 };+ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Color',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ alphaLocked: false,+ clipped: false,+ parentId: null,+ },+ ];++ // 1. Value Check OFF -> uses plain blit, not softProof shader+ compositor.render(+ layers,+ { pan: { x: 160, y: 120 }, zoom: 1, rotation: 0 },+ dims,+ grid,+ { dimensions: dims, valueCheck: false }+ );+ expect(harness.drawProgramHistory[harness.drawProgramHistory.length - 1]).toBe('blit');++ // 2. 1-Click Value Check ON -> invokes post-processing shader with u_valueCheck=1, u_proofEnabled=0+ harness.drawProgramHistory.length = 0;+ compositor.render(+ layers,+ { pan: { x: 160, y: 120 }, zoom: 1, rotation: 0 },+ dims,+ grid,+ { dimensions: dims, valueCheck: true }+ );+ expect(harness.drawProgramHistory[harness.drawProgramHistory.length - 1]).toBe('softProof');+ const uniforms = harness.getSoftProofUniforms();+ expect(uniforms.get('u_valueCheck')).toBe(1);+ expect(uniforms.get('u_proofEnabled')).toBe(0);+ expect(uniforms.get('u_gamutWarning')).toBe(0);++ // 3. Value Check ON + CMYK Soft Proof ON -> passes both uniforms cleanly+ compositor.render(+ layers,+ { pan: { x: 160, y: 120 }, zoom: 1, rotation: 0 },+ dims,+ grid,+ {+ dimensions: dims,+ valueCheck: true,+ softProof: {+ enabled: true,+ standard: 'japan-color-2001',+ gamutWarning: false,+ gamutWarningColor: '#7f7f7f',+ },+ }+ );+ expect(uniforms.get('u_valueCheck')).toBe(1);+ expect(uniforms.get('u_proofEnabled')).toBe(1);+ expect(uniforms.get('u_standard')).toBe(0);++ compositor.dispose();+ });++ it('applies non-destructive perceptual grayscale in Canvas 2D fallback without modifying SparseTileGrid pixels', () => {+ const dom = installMiniDom([255, 0, 0, 255]);+ try {+ const grid = new SparseTileGrid();+ const tile = grid.getOrCreateTile('layer-1', 0, 0, 'color-32bit', 0);+ const rgba = tile.data as Uint8Array;+ rgba[0] = 255;+ rgba[1] = 0;+ rgba[2] = 0;+ rgba[3] = 255;++ const canvas = dom.mockDoc.createElement('canvas');+ canvas.width = 16;+ canvas.height = 16;++ const compositor = new ViewportCompositor(canvas as unknown as HTMLCanvasElement, {+ renderBackend: 'canvas2d',+ });+ const dims: CanvasDimensions = { width: TILE_SIZE, height: TILE_SIZE, dpi: 300 };+ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Paint',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ alphaLocked: false,+ clipped: false,+ parentId: null,+ },+ ];++ compositor.render(+ layers,+ { pan: { x: 8, y: 8 }, zoom: 1, rotation: 0 },+ dims,+ grid,+ { dimensions: dims, valueCheck: true }+ );++ // Output canvas buffer converted to perceptual luminance of pure red+ const expectedGray = computePerceptualLuminanceByte(255, 0, 0);+ const outData = canvas.mockCtx!.getStoredData();+ expect(outData).not.toBeNull();+ expect(outData![0]).toBe(expectedGray);+ expect(outData![1]).toBe(expectedGray);+ expect(outData![2]).toBe(expectedGray);++ // Underlying tile pixels remain 100% untouched color+ expect(rgba[0]).toBe(255);+ expect(rgba[1]).toBe(0);+ expect(rgba[2]).toBe(0);+ compositor.dispose();+ } finally {+ dom.cleanup();+ }+ });++ it('composites in-progress document-space activeDraftCanvas strokes inside renderLowResPreview', () => {+ const dom = installMiniDom();+ try {+ const grid = new SparseTileGrid();+ const target = dom.mockDoc.createElement('canvas');+ target.width = 128;+ target.height = 128;++ const draft = dom.mockDoc.createElement('canvas') as MiniEl & {+ __draftHasContent?: boolean;+ __draftSpace?: 'document' | 'viewport';+ __draftDocRect?: { x: number; y: number; width: number; height: number };+ };+ draft.width = 256;+ draft.height = 256;+ draft.__draftHasContent = true;+ draft.__draftSpace = 'document';+ draft.__draftDocRect = { x: 100, y: 50, width: 200, height: 200 };++ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Paint',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ alphaLocked: false,+ clipped: false,+ parentId: null,+ },+ ];++ ViewportCompositor.renderLowResPreview(+ target as unknown as HTMLCanvasElement,+ layers,+ { width: 512, height: 512, dpi: 300 },+ grid,+ {+ showCheckerboard: false,+ activeDraftCanvas: draft as unknown as HTMLCanvasElement,+ activeDraftLayerId: 'layer-1',+ activeDraftOpacity: 0.75,+ }+ );++ // Draft stroke was drawn scaled to target (128/512 = 0.25x -> x=25, y=12.5, w=50, h=50)+ const draftDrawCall = target.mockCtx!.drawImageCalls.find((args) => args[0] === draft);+ expect(draftDrawCall).toBeDefined();+ expect(draftDrawCall![1]).toBeCloseTo(25, 3);+ expect(draftDrawCall![2]).toBeCloseTo(12.5, 3);+ expect(draftDrawCall![3]).toBeCloseTo(50, 3);+ expect(draftDrawCall![4]).toBeCloseTo(50, 3);+ } finally {+ dom.cleanup();+ }+ });+});++describe('Navigator Live B/W Mode, Interactive Split View & Header/StatusBar 1-Click Value Check UI', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;++ beforeEach(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useDocumentStore.reset();+ useWorkspaceStore.reset();+ useToolStore.reset();+ });++ afterEach(() => {+ if (prevStorage === undefined) {+ delete (globalThis as unknown as Record<string, unknown>).localStorage;+ } else {+ Object.defineProperty(globalThis, 'localStorage', {+ value: prevStorage,+ configurable: true,+ writable: true,+ });+ }+ });++ it('switches Navigator between Color, Live B/W, and draggable Split View without re-compositing tiles or panning canvas', () => {+ vi.useFakeTimers();+ const dom = installMiniDom([255, 0, 0, 255]);+ let root: Root | null = null;+ const renderPreviewSpy = vi+ .spyOn(ViewportCompositor, 'renderLowResPreview')+ .mockImplementation(() => {});++ try {+ const grid = new SparseTileGrid();+ const nav = createMockNavigation();+ const viewportRef = { current: { clientWidth: 800, clientHeight: 600 } as HTMLDivElement };+ const draftEl = dom.mockDoc.createElement('canvas') as MiniEl & {+ __draftHasContent?: boolean;+ __draftVersion?: number;+ };+ draftEl.__draftHasContent = false;+ draftEl.__draftVersion = 0;+ const draftCanvasRef = { current: draftEl as unknown as HTMLCanvasElement };++ const dims: CanvasDimensions = { width: 1000, height: 800, dpi: 300 };+ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Color',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ alphaLocked: false,+ clipped: false,+ parentId: null,+ },+ ];++ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(+ <NavigatorPanel+ viewportRef={viewportRef}+ navigation={nav.handle}+ dimensions={dims}+ layers={layers}+ tileGrid={grid}+ showCheckerboard={false}+ zoom={1}+ rotation={0}+ flipX={false}+ flipY={false}+ draftCanvasRef={draftCanvasRef}+ activeLayerId="layer-1"+ onZoomIn={vi.fn()}+ onZoomOut={vi.fn()}+ onFitToScreen={vi.fn()}+ onZoomActualSize={vi.fn()}+ onRotateLeft={vi.fn()}+ onRotateRight={vi.fn()}+ onResetRotation={vi.fn()}+ onToggleFlipHorizontal={vi.fn()}+ onToggleFlipVertical={vi.fn()}+ throttleMs={120}+ />+ );+ });++ expect(renderPreviewSpy).toHaveBeenCalledTimes(1);+ expect(dom.container.findByAttr('data-testid', 'nav-bw-badge')).toBeNull();+ expect(dom.container.findByAttr('data-testid', 'nav-split-handle')).toBeNull();++ // 1. Switch Navigator to Live B/W mode -> main canvas stays in Color, Navigator shows B/W badge, 0 extra tile composites+ act(() => {+ dom.container+ .findByAttr('data-testid', 'nav-mode-bw')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');+ expect(useDocumentStore.getState().valueCheckEnabled).toBe(false);+ expect(dom.container.findByAttr('data-testid', 'nav-bw-badge')).not.toBeNull();+ expect(renderPreviewSpy).toHaveBeenCalledTimes(1);++ // 2. Live painting draft stroke updates trigger throttled real-time Navigator refresh!+ act(() => {+ draftEl.__draftHasContent = true;+ draftEl.__draftVersion = 1;+ grid.notifyChange(true);+ vi.advanceTimersByTime(150);+ });+ expect(renderPreviewSpy).toHaveBeenCalledTimes(2);+ const lastPreviewOpts = renderPreviewSpy.mock.calls[1]?.[4];+ expect(lastPreviewOpts?.activeDraftCanvas).toBe(draftEl);+ expect(lastPreviewOpts?.activeDraftLayerId).toBe('layer-1');++ // 3. Switch Navigator to Split View -> shows draggable handle & CLR / B/W labels+ act(() => {+ dom.container+ .findByAttr('data-testid', 'nav-mode-split')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('split');+ const handle = dom.container.findByAttr('data-testid', 'nav-split-handle');+ expect(handle).not.toBeNull();+ expect(dom.container.findByAttr('data-testid', 'nav-split-color-label')).not.toBeNull();+ expect(dom.container.findByAttr('data-testid', 'nav-split-bw-label')).not.toBeNull();++ // Drag split handle to ~25% across preview box -> updates splitRatio WITHOUT panning main canvas+ const m = computePreviewBoxMetrics(200, 120, dims);+ const dragClientX = m.offsetX + m.drawW * 0.25;+ expect(computeNavigatorSplitRatioFromClientX(dragClientX, 0, m)).toBeCloseTo(0.25, 2);++ act(() => {+ handle!.dispatchEvent(+ Object.assign(new Event('pointerdown', { bubbles: true }), {+ button: 0,+ pointerId: 7,+ clientX: dragClientX,+ clientY: 60,+ })+ );+ handle!.dispatchEvent(+ Object.assign(new Event('pointermove', { bubbles: true }), {+ button: 0,+ pointerId: 7,+ clientX: m.offsetX + m.drawW * 0.72,+ clientY: 60,+ })+ );+ handle!.dispatchEvent(+ Object.assign(new Event('pointerup', { bubbles: true }), {+ button: 0,+ pointerId: 7,+ clientX: m.offsetX + m.drawW * 0.72,+ clientY: 60,+ })+ );+ });+ expect(useWorkspaceStore.getState().navigatorSplitRatio).toBeCloseTo(0.72, 2);+ expect(nav.setPanLive).not.toHaveBeenCalled();++ // Double-click split handle resets cleanly to 0.5+ act(() => {+ handle!.dispatchEvent(new Event('dblclick', { bubbles: true }));+ });+ expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.5);++ // 4. 1-Click Value Check button inside Navigator toggles main canvas Value Check & displays Canvas B/W badge+ act(() => {+ dom.container+ .findByAttr('data-testid', 'nav-value-check')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useDocumentStore.getState().valueCheckEnabled).toBe(true);+ expect(dom.container.findByAttr('data-testid', 'nav-canvas-value-badge')).not.toBeNull();+ } finally {+ renderPreviewSpy.mockRestore();+ if (root) {+ act(() => {+ root?.unmount();+ });+ }+ dom.cleanup();+ vi.useRealTimers();+ }+ });++ it('renders 1-Click Value Check controls and active badges in Header and StatusBar', () => {+ const dom = installMiniDom();+ let root: Root | null = null;+ const onToggleValueCheck = vi.fn();++ try {+ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(+ <div>+ <Header+ canUndo={false}+ canRedo={false}+ onUndo={vi.fn()}+ onRedo={vi.fn()}+ zoom={1}+ onZoomIn={vi.fn()}+ onZoomOut={vi.fn()}+ onResetZoom={vi.fn()}+ rotation={0}+ onResetRotation={vi.fn()}+ hasOpenDocument={true}+ valueCheckEnabled={true}+ onToggleValueCheck={onToggleValueCheck}+ />+ <StatusBar+ tool="brush"+ brushSettings={useToolStore.getState().brushSettings}+ zoom={1}+ rotation={0}+ onResetRotation={vi.fn()}+ hasOpenDocument={true}+ valueCheckEnabled={true}+ onToggleValueCheck={onToggleValueCheck}+ />+ </div>+ );+ });++ const headerBtn = dom.container.findByAttr('data-testid', 'header-value-check-btn');+ const headerBadge = dom.container.findByAttr('data-testid', 'header-value-check-badge');+ const statusBadge = dom.container.findByAttr('data-testid', 'status-value-check-badge');++ expect(headerBtn).not.toBeNull();+ expect(headerBtn!.getAttribute('aria-pressed')).toBe('true');+ expect(headerBadge).not.toBeNull();+ expect(statusBadge).not.toBeNull();+ expect(statusBadge!.textContent).toContain('Value Check: B/W');++ act(() => {+ headerBtn!.dispatchEvent(new Event('click', { bubbles: true }));+ headerBadge!.dispatchEvent(new Event('click', { bubbles: true }));+ statusBadge!.dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(onToggleValueCheck).toHaveBeenCalledTimes(3);+ } finally {+ if (root) {+ act(() => {+ root?.unmount();+ });+ }+ dom.cleanup();+ }+ });+});diff --git a/src/utils/appCloseFlow.ts b/src/utils/appCloseFlow.tsindex da67918..6d0f22d 100644--- a/src/utils/appCloseFlow.ts+++ b/src/utils/appCloseFlow.ts@@ -1,6 +1,7 @@import { DocumentTab } from '../types/editor';import { isTauriEnvironment } from '../hooks/useMultiplayer';import { recoveryService } from '../services/recoveryService';+import { globalTimelapseManager } from './timelapseEngine';import {AppClosePromptState,uiStoreActions,@@ -103,6 +104,7 @@ export interface FinalizeAppCloseDeps {destroyTauriWindow?: () => Promise<void>;closeBrowserWindow?: () => void;closeRecoverySession?: (docId: string) => Promise<void>;+ closeTimelapseSession?: (docId: string) => Promise<void>;flushBrushSettings?: () => void;}@@ -125,6 +127,8 @@ export async function finalizeAppClose(deps: FinalizeAppCloseDeps = {}): Promiseconst flushBrush = deps.flushBrushSettings ?? flushPendingBrushSettingsSave;const closeRecovery =deps.closeRecoverySession ?? ((id: string) => recoveryService.closeSession(id));+ const closeTimelapse =+ deps.closeTimelapseSession ?? ((id: string) => globalTimelapseManager.removeSession(id));const checkTauri = deps.isTauri ?? isTauriEnvironment;try {@@ -133,7 +137,9 @@ export async function finalizeAppClose(deps: FinalizeAppCloseDeps = {}): Promiseconst openDocIds = useDocumentStore.getState().documents.map((d) => d.id);if (openDocIds.length > 0) {let timerId: ReturnType<typeof setTimeout> | null = null;- const cleanupAll = Promise.allSettled(openDocIds.map((id) => closeRecovery(id)));+ const cleanupAll = Promise.allSettled(+ openDocIds.flatMap((id) => [closeRecovery(id), closeTimelapse(id)])+ );const timeout = new Promise<void>((resolve) => {timerId = setTimeout(resolve, RECOVERY_CLEANUP_TIMEOUT_MS);});diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.tsindex 0a2a407..b5aac34 100644--- a/src/utils/brushPresetManager.ts+++ b/src/utils/brushPresetManager.ts@@ -21,7 +21,11 @@ import {NaturalPaintSettings,SurfaceTextureId,} from '../types/editor';-import { getBuiltinBrushConfig } from './presetBrushes';+import {+ DEFAULT_DECORATION_PRESET_ID,+ getBuiltinBrushConfig,+ isDecorationPresetId,+} from './presetBrushes';import { getPreloadedTipImage, getCachedCustomBrushes } from './brushStorage';import { safeLocalStorageSetItem } from './safeStorage';@@ -59,6 +63,7 @@ export function stepBrushSizePreset(currentSize: number, direction: -1 | 1): numexport const STORAGE_KEY_SETTINGS = 'ink_studio_brush_settings_by_id';export const STORAGE_KEY_ACTIVE_PRESET = 'ink_studio_active_brush_preset';+export const STORAGE_KEY_ACTIVE_DECORATION_PRESET = 'ink_studio_active_decoration_preset';export const STORAGE_KEY_BOTTOM_TAB = 'ink_studio_left_bottom_tab';const STORAGE_KEY_PRESET_SCHEMA = 'ink_studio_brush_preset_schema_v';export const BUILTIN_PRESET_SCHEMA_VERSION = 4;@@ -165,6 +170,7 @@ export interface BrushPersistentSettings {customTipAngle?: number;customTipAngleDynamics?: CspAngleDynamicsMode;customTipRotationRandomScale?: number;+ rotateCursor?: boolean;colorMixing?: boolean;perceptualMixing?: boolean;amountOfPaint?: number;@@ -273,6 +279,7 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {customTipAngle: 0,customTipAngleDynamics: 'none',customTipRotationRandomScale: 0,+ rotateCursor: undefined,isColorTip: false,isDualToneTip: false,subTips: undefined,@@ -468,6 +475,7 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = ['customTipAngle','customTipAngleDynamics','customTipRotationRandomScale',+ 'rotateCursor','colorMixing','perceptualMixing','amountOfPaint',@@ -568,6 +576,8 @@ function mergeIntoMemoryCache(presetId: string, settings: Partial<BrushSettings>} else {(persistent as Record<string, unknown>)[key] = val;}+ } else if (key === 'rotateCursor' && 'rotateCursor' in settings) {+ delete persistent.rotateCursor;}}@@ -637,7 +647,7 @@ export function getActivePresetId(): string {try {if (typeof localStorage === 'undefined') return DEFAULT_BRUSH_PRESET_ID;const saved = localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET);- if (!saved) return DEFAULT_BRUSH_PRESET_ID;+ if (!saved || isDecorationPresetId(saved)) return DEFAULT_BRUSH_PRESET_ID;const migrated = migrateLegacyPresetId(saved);if (migrated !== saved && getBuiltinBrushConfig(migrated)) {safeLocalStorageSetItem(STORAGE_KEY_ACTIVE_PRESET, migrated, 'active brush preset');@@ -652,9 +662,36 @@ export function getActivePresetId(): string {export function saveActivePresetId(presetId: string): void {if (!presetId || presetId === ERASER_PRESET_ID || presetId === 'eraser') return;+ if (isDecorationPresetId(presetId)) {+ saveActiveDecorationPresetId(presetId);+ return;+ }safeLocalStorageSetItem(STORAGE_KEY_ACTIVE_PRESET, presetId, 'active brush preset');}+export function getActiveDecorationPresetId(): string {+ try {+ if (typeof localStorage === 'undefined') return DEFAULT_DECORATION_PRESET_ID;+ const saved = localStorage.getItem(STORAGE_KEY_ACTIVE_DECORATION_PRESET);+ if (!saved) return DEFAULT_DECORATION_PRESET_ID;+ if (saved.startsWith('csp-') || saved.startsWith('inkb-') || getBuiltinBrushConfig(saved)) {+ return saved;+ }+ return DEFAULT_DECORATION_PRESET_ID;+ } catch {+ return DEFAULT_DECORATION_PRESET_ID;+ }+}++export function saveActiveDecorationPresetId(presetId: string): void {+ if (!presetId || presetId === ERASER_PRESET_ID || presetId === 'eraser') return;+ safeLocalStorageSetItem(+ STORAGE_KEY_ACTIVE_DECORATION_PRESET,+ presetId,+ 'active decoration preset'+ );+}+export function getEffectiveBrushSettings(presetId: string,customBrushes?: CspBrush[]@@ -758,6 +795,7 @@ export function getEffectiveBrushSettings(customTipAngle: cspMatch.angle,customTipAngleDynamics: cspMatch.angleDynamics,customTipRotationRandomScale: cspMatch.rotationRandomScale,+ rotateCursor: cspMatch.rotateCursor,subTips: cspMatch.subTips,subTipOrder: cspMatch.subTipOrder,subTipImages,diff --git a/src/utils/brushStorage.ts b/src/utils/brushStorage.tsindex f93a897..0ca5c8c 100644--- a/src/utils/brushStorage.ts+++ b/src/utils/brushStorage.ts@@ -471,6 +471,7 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<ParticustomTipAngle: brush.angle,customTipAngleDynamics: brush.angleDynamics,customTipRotationRandomScale: brush.rotationRandomScale,+ rotateCursor: brush.rotateCursor,subTips: brush.subTips,subTipOrder: brush.subTipOrder,subTipImages,diff --git a/src/utils/cageWarpEngine.ts b/src/utils/cageWarpEngine.tsnew file mode 100644index 0000000..07b9ea9--- /dev/null+++ b/src/utils/cageWarpEngine.ts@@ -0,0 +1,477 @@+import { CagePoint, CageTransformState, Point2D } from '../types/editor';+import type { PixelBuffer } from './transformResampler';++export interface CageMeshEvaluation {+ cols: number;+ rows: number;+ deformedX: Float32Array;+ deformedY: Float32Array;+ uvX: Float32Array;+ uvY: Float32Array;+ triangles: Uint32Array;+ edges: Uint32Array;+}++function evalBilinearQuad(+ quad: [Point2D, Point2D, Point2D, Point2D],+ u: number,+ v: number+): Point2D {+ const [q0, q1, q2, q3] = quad;+ const w00 = (1 - u) * (1 - v);+ const w10 = u * (1 - v);+ const w11 = u * v;+ const w01 = (1 - u) * v;+ return {+ x: w00 * q0.x + w10 * q1.x + w11 * q2.x + w01 * q3.x,+ y: w00 * q0.y + w10 * q1.y + w11 * q2.y + w01 * q3.y,+ };+}++/**+ * Ray-casting point-in-polygon test with inclusive boundary tolerance.+ */+export function isPointInPolygon(+ px: number,+ py: number,+ poly: ReadonlyArray<{ x: number; y: number }>,+ edgeTol = 1e-4+): boolean {+ const n = poly.length;+ if (n < 3) return false;+ const tolSq = edgeTol * edgeTol;++ // Check if point lies on/near any boundary edge first+ for (let i = 0, j = n - 1; i < n; j = i++) {+ const ax = poly[j].x;+ const ay = poly[j].y;+ const bx = poly[i].x;+ const by = poly[i].y;+ const dx = bx - ax;+ const dy = by - ay;+ const lenSq = dx * dx + dy * dy;+ const t = lenSq > 1e-12 ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq)) : 0;+ const qx = ax + t * dx;+ const qy = ay + t * dy;+ if ((px - qx) * (px - qx) + (py - qy) * (py - qy) <= tolSq) {+ return true;+ }+ }++ let inside = false;+ for (let i = 0, j = n - 1; i < n; j = i++) {+ const xi = poly[i].x;+ const yi = poly[i].y;+ const xj = poly[j].x;+ const yj = poly[j].y;+ const intersect =+ yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi;+ if (intersect) inside = !inside;+ }+ return inside;+}++/**+ * Computes 2D Mean Value Coordinates (Hormann & Floater 2006) for a point (px, py)+ * relative to a simple closed polygon `restPoly` (convex OR concave).+ * Writes normalized weights into `outWeights` (length >= restPoly.length).+ */+export function computeMeanValueWeights(+ px: number,+ py: number,+ restPoly: ReadonlyArray<{ x: number; y: number }>,+ outWeights: Float64Array+): boolean {+ const n = restPoly.length;+ if (n < 3) return false;++ const eps = 1e-7;+ const sx = new Float64Array(n);+ const sy = new Float64Array(n);+ const r = new Float64Array(n);++ for (let i = 0; i < n; i++) {+ const dx = restPoly[i].x - px;+ const dy = restPoly[i].y - py;+ sx[i] = dx;+ sy[i] = dy;+ const dist = Math.hypot(dx, dy);+ r[i] = dist;+ if (dist < eps) {+ for (let k = 0; k < n; k++) outWeights[k] = 0;+ outWeights[i] = 1;+ return true;+ }+ }++ const tanHalf = new Float64Array(n);+ for (let i = 0; i < n; i++) {+ const j = (i + 1) % n;+ const ri = r[i];+ const rj = r[j];+ const A = sx[i] * sy[j] - sy[i] * sx[j]; // r_i * r_j * sin(alpha)+ const D = sx[i] * sx[j] + sy[i] * sy[j]; // r_i * r_j * cos(alpha)++ // Point lies directly on segment (i, j)+ if (Math.abs(A) < eps * ri * rj && D < 0) {+ for (let k = 0; k < n; k++) outWeights[k] = 0;+ const denom = ri + rj;+ outWeights[i] = rj / denom;+ outWeights[j] = ri / denom;+ return true;+ }++ // Numerically stable half-angle tangent across (-pi, pi) with zero cancellation+ if (D >= 0) {+ const denom = ri * rj + D;+ tanHalf[i] = denom > 1e-14 ? A / denom : 0;+ } else {+ tanHalf[i] = Math.abs(A) > 1e-14 ? (ri * rj - D) / A : 0;+ }+ }++ let wSum = 0;+ for (let i = 0; i < n; i++) {+ const prev = (i - 1 + n) % n;+ const w = (tanHalf[prev] + tanHalf[i]) / r[i];+ outWeights[i] = w;+ wSum += w;+ }++ if (Math.abs(wSum) < 1e-12 || !Number.isFinite(wSum)) {+ return false;+ }++ const invSum = 1 / wSum;+ for (let i = 0; i < n; i++) {+ outWeights[i] *= invSum;+ }+ return true;+}++/**+ * Andrew's Monotone Chain 2D Convex Hull.+ */+function computeConvexHull(pts: Point2D[]): Point2D[] {+ if (pts.length <= 3) return pts.map((p) => ({ ...p }));+ const sorted = [...pts].sort((a, b) => (a.x !== b.x ? a.x - b.x : a.y - b.y));+ const cross = (o: Point2D, a: Point2D, b: Point2D) =>+ (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);++ const lower: Point2D[] = [];+ for (const p of sorted) {+ while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {+ lower.pop();+ }+ lower.push(p);+ }+ const upper: Point2D[] = [];+ for (let i = sorted.length - 1; i >= 0; i--) {+ const p = sorted[i];+ while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {+ upper.pop();+ }+ upper.push(p);+ }+ lower.pop();+ upper.pop();+ return lower.concat(upper);+}++/**+ * Simplifies a closed convex polygon to at most `maxVerts` vertices by greedily removing+ * the vertex whose removal adds the smallest exterior bulge (or least area change) while+ * keeping all original hull vertices inside (expanding adjacent edges outward slightly).+ */+function simplifyHullToVertexCount(hull: Point2D[], maxVerts = 10): Point2D[] {+ const pts = hull.map((p) => ({ ...p }));+ while (pts.length > maxVerts && pts.length > 4) {+ let bestIdx = 0;+ let minArea = Infinity;+ const n = pts.length;+ for (let i = 0; i < n; i++) {+ const prev = pts[(i - 1 + n) % n];+ const curr = pts[i];+ const next = pts[(i + 1) % n];+ const area = Math.abs(+ (curr.x - prev.x) * (next.y - prev.y) - (curr.y - prev.y) * (next.x - prev.x)+ );+ if (area < minArea) {+ minArea = area;+ bestIdx = i;+ }+ }+ pts.splice(bestIdx, 1);+ }+ return pts;+}++/**+ * Generates an automatic tight padded silhouette cage (8–10 vertices) in document space+ * around the artwork's opaque silhouette, ready for immediate Cage Transform deformation.+ */+export function buildAutoCagePoints(+ sourcePixels: PixelBuffer | undefined,+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D]+): CagePoint[] {+ const sw = Math.max(1, sourceWidth);+ const sh = Math.max(1, sourceHeight);++ // Sample extreme left/right opaque pixels per scanline for O(W*H) exact hull input+ const samplePts: Point2D[] = [];+ if (sourcePixels && sourcePixels.data.length >= sw * sh * 4) {+ const data = sourcePixels.data;+ const yStep = Math.max(1, Math.floor(sh / 256));+ for (let y = 0; y < sh; y += yStep) {+ const rowOff = y * sw * 4;+ let left = -1;+ let right = -1;+ for (let x = 0; x < sw; x++) {+ if (data[rowOff + (x << 2) + 3] > 2) {+ left = x;+ break;+ }+ }+ if (left >= 0) {+ for (let x = sw - 1; x >= left; x--) {+ if (data[rowOff + (x << 2) + 3] > 2) {+ right = x;+ break;+ }+ }+ samplePts.push({ x: left, y });+ if (right > left) samplePts.push({ x: right + 1, y: y + 1 });+ }+ }+ }++ let localCage: Point2D[];+ const hull = samplePts.length >= 3 ? computeConvexHull(samplePts) : [];++ // Check if hull covers almost the entire box (>= 88% area); if so use clean 8-point box cage+ const polyArea = (poly: Point2D[]) => {+ let a = 0;+ for (let i = 0; i < poly.length; i++) {+ const j = (i + 1) % poly.length;+ a += poly[i].x * poly[j].y - poly[j].x * poly[i].y;+ }+ return Math.abs(a) * 0.5;+ };++ if (hull.length < 4 || polyArea(hull) > sw * sh * 0.88) {+ // 8-point padded bounding cage (4 corners + 4 edge midpoints)+ const padX = Math.max(4, sw * 0.04);+ const padY = Math.max(4, sh * 0.04);+ localCage = [+ { x: -padX, y: -padY },+ { x: sw * 0.5, y: -padY },+ { x: sw + padX, y: -padY },+ { x: sw + padX, y: sh * 0.5 },+ { x: sw + padX, y: sh + padY },+ { x: sw * 0.5, y: sh + padY },+ { x: -padX, y: sh + padY },+ { x: -padX, y: sh * 0.5 },+ ];+ } else {+ const simplified = simplifyHullToVertexCount(hull, 10);+ // Compute centroid and expand outward so every opaque pixel lies strictly inside the cage+ let cx = 0;+ let cy = 0;+ for (const p of simplified) {+ cx += p.x;+ cy += p.y;+ }+ cx /= simplified.length;+ cy /= simplified.length;++ const pad = Math.max(8, Math.max(sw, sh) * 0.06);+ localCage = simplified.map((p) => {+ const dx = p.x - cx;+ const dy = p.y - cy;+ const len = Math.hypot(dx, dy) || 1;+ return {+ x: p.x + (dx / len) * pad,+ y: p.y + (dy / len) * pad,+ };+ });++ // Guarantee at least 6 vertices by subdividing longest edges if hull was a simple quad/triangle+ while (localCage.length < 6) {+ let bestEdge = 0;+ let maxLenSq = -1;+ for (let i = 0; i < localCage.length; i++) {+ const j = (i + 1) % localCage.length;+ const dx = localCage[j].x - localCage[i].x;+ const dy = localCage[j].y - localCage[i].y;+ const lSq = dx * dx + dy * dy;+ if (lSq > maxLenSq) {+ maxLenSq = lSq;+ bestEdge = i;+ }+ }+ const a = localCage[bestEdge];+ const b = localCage[(bestEdge + 1) % localCage.length];+ localCage.splice(bestEdge + 1, 0, { x: (a.x + b.x) * 0.5, y: (a.y + b.y) * 0.5 });+ }+ }++ return localCage.map((pt, idx) => {+ const world = evalBilinearQuad(quad, pt.x / sw, pt.y / sh);+ return {+ id: `cage-${idx + 1}`,+ restX: world.x,+ restY: world.y,+ x: world.x,+ y: world.y,+ };+ });+}++/**+ * Creates default CageTransformState with an auto-fitted closed silhouette cage.+ */+export function createInitialCageState(+ sourcePixels: PixelBuffer | undefined,+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D]+): CageTransformState {+ return {+ points: buildAutoCagePoints(sourcePixels, sourceWidth, sourceHeight, quad),+ closed: true,+ phase: 'deform',+ selectedPointId: null,+ showMesh: false,+ };+}++/**+ * Checks whether a CageTransformState produces any non-identity warp.+ */+export function isCageDeformed(cage: CageTransformState | undefined): boolean {+ if (!cage || !cage.closed || cage.points.length < 3) return false;+ for (const pt of cage.points) {+ if (Math.abs(pt.x - pt.restX) > 1e-4 || Math.abs(pt.y - pt.restY) > 1e-4) {+ return true;+ }+ }+ return false;+}++/**+ * Evaluates Cage Transform onto an adaptive subdivided triangle mesh over `quad`+ * using Hormann-Floater Mean Value Coordinates. Vertices outside a custom sub-cage+ * remain anchored at their rest positions.+ */+export function evaluateCageMesh(+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D],+ cage: CageTransformState,+ highQuality = false+): CageMeshEvaluation {+ const sw = Math.max(1, sourceWidth);+ const sh = Math.max(1, sourceHeight);+ const maxSub = highQuality ? 52 : 34;+ const minSub = highQuality ? 20 : 14;+ const aspect = sw / sh;+ let cols: number;+ let rows: number;+ if (aspect >= 1) {+ cols = Math.max(minSub, Math.min(maxSub, Math.ceil(sw / (highQuality ? 20 : 32))));+ rows = Math.max(minSub, Math.min(maxSub, Math.round(cols / aspect)));+ } else {+ rows = Math.max(minSub, Math.min(maxSub, Math.ceil(sh / (highQuality ? 20 : 32))));+ cols = Math.max(minSub, Math.min(maxSub, Math.round(rows * aspect)));+ }++ const vCols = cols + 1;+ const vRows = rows + 1;+ const vertCount = vCols * vRows;++ const deformedX = new Float32Array(vertCount);+ const deformedY = new Float32Array(vertCount);+ const uvX = new Float32Array(vertCount);+ const uvY = new Float32Array(vertCount);++ const canDeform = cage.closed && cage.points.length >= 3 && isCageDeformed(cage);+ const restPoly = canDeform ? cage.points.map((p) => ({ x: p.restX, y: p.restY })) : [];+ const weights = canDeform ? new Float64Array(cage.points.length) : new Float64Array(0);++ let vi = 0;+ for (let r = 0; r <= rows; r++) {+ const v = r / rows;+ for (let c = 0; c <= cols; c++) {+ const u = c / cols;+ uvX[vi] = u;+ uvY[vi] = v;+ const rest = evalBilinearQuad(quad, u, v);+ if (+ canDeform &&+ isPointInPolygon(rest.x, rest.y, restPoly, 1e-2) &&+ computeMeanValueWeights(rest.x, rest.y, restPoly, weights)+ ) {+ let nx = 0;+ let ny = 0;+ for (let k = 0; k < cage.points.length; k++) {+ const wk = weights[k];+ nx += wk * cage.points[k].x;+ ny += wk * cage.points[k].y;+ }+ deformedX[vi] = nx;+ deformedY[vi] = ny;+ } else {+ deformedX[vi] = rest.x;+ deformedY[vi] = rest.y;+ }+ vi++;+ }+ }++ const triCount = rows * cols * 2;+ const triangles = new Uint32Array(triCount * 3);+ let ti = 0;+ for (let r = 0; r < rows; r++) {+ for (let c = 0; c < cols; c++) {+ const i00 = r * vCols + c;+ const i10 = i00 + 1;+ const i01 = i00 + vCols;+ const i11 = i01 + 1;+ // Alternating diagonals keep deformation isotropic+ if (((r + c) & 1) === 0) {+ triangles[ti++] = i00; triangles[ti++] = i10; triangles[ti++] = i11;+ triangles[ti++] = i00; triangles[ti++] = i11; triangles[ti++] = i01;+ } else {+ triangles[ti++] = i00; triangles[ti++] = i10; triangles[ti++] = i01;+ triangles[ti++] = i10; triangles[ti++] = i11; triangles[ti++] = i01;+ }+ }+ }++ // Coarse grid wireframe edges (every 2nd line) for clean optional mesh preview+ const edgeArr: number[] = [];+ const stride = Math.max(1, Math.floor(Math.max(rows, cols) / 14));+ for (let r = 0; r <= rows; r += stride) {+ for (let c = 0; c < cols; c++) {+ edgeArr.push(r * vCols + c, r * vCols + c + 1);+ }+ }+ for (let c = 0; c <= cols; c += stride) {+ for (let r = 0; r < rows; r++) {+ edgeArr.push(r * vCols + c, (r + 1) * vCols + c);+ }+ }++ return {+ cols,+ rows,+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ edges: new Uint32Array(edgeArr),+ };+}diff --git a/src/utils/compositor.ts b/src/utils/compositor.tsindex 99a5447..4798010 100644--- a/src/utils/compositor.ts+++ b/src/utils/compositor.ts@@ -25,7 +25,7 @@ import { invalidatePigmentLutTexture } from './pigmentEngine';import { calculateVisibleDocumentBounds } from './compositor/bounds';import { disposeFboSurface, disposePingPongTarget } from './compositor/fboManager';import { initGL, resetGLStateOnContextLost } from './compositor/glInit';-import { renderLowResPreview } from './compositor/previewRenderer';+import { LowResPreviewOptions, renderLowResPreview } from './compositor/previewRenderer';import { renderFrame } from './compositor/renderFrame';import { LayerStackCacheTracker } from './compositor/stackCache';import {@@ -270,6 +270,7 @@ function createInitialCompositorState(uProofEnabledLoc: null,uProofGamutWarningLoc: null,uProofGamutWarningColorLoc: null,+ uProofValueCheckLoc: null,textureAccessCounter: 0,texturePool: [],activePoolByKey: new Map(),@@ -467,7 +468,7 @@ export class ViewportCompositor {layers: LayerItem[],dimensions: CanvasDimensions,grid: SparseTileGrid = globalTileGrid,- options: { showCheckerboard?: boolean } = {}+ options: LowResPreviewOptions = {}): void {renderLowResPreview(targetCanvas, layers, dimensions, grid, options);}diff --git a/src/utils/compositor/effectsPass.ts b/src/utils/compositor/effectsPass.tsindex 5018226..0971cc9 100644--- a/src/utils/compositor/effectsPass.ts+++ b/src/utils/compositor/effectsPass.ts@@ -253,7 +253,7 @@ export function blitFolderTexture(}/**- * Post-processing pass: CMYK Soft Proofing and Gamut Warning.+ * Post-processing pass: CMYK Soft Proofing, Gamut Warning, and Live Value Check (B/W luminance).* Samples directly from the Ping-Pong scene FBO texture into the default framebuffer (zero copyTexSubImage2D).*/export function applySoftProofPass(@@ -261,24 +261,26 @@ export function applySoftProofPass(gl: WebGL2RenderingContext,viewportW: number,viewportH: number,- settings: SoftProofSettings,- sceneTexture: WebGLTexture+ settings: SoftProofSettings | undefined,+ sceneTexture: WebGLTexture,+ valueCheck = false): void {if (!state.softProofProgram) return;gl.useProgram(state.softProofProgram);const standardIndex =- settings.standard === 'japan-color-2001'+ settings?.standard === 'japan-color-2001'? 0- : settings.standard === 'us-web-coated-swop'+ : settings?.standard === 'us-web-coated-swop'? 1: 2;gl.uniform1i(state.uProofStandardLoc, standardIndex);- gl.uniform1i(state.uProofEnabledLoc, settings.enabled ? 1 : 0);- gl.uniform1i(state.uProofGamutWarningLoc, settings.gamutWarning ? 1 : 0);+ gl.uniform1i(state.uProofEnabledLoc, settings?.enabled ? 1 : 0);+ gl.uniform1i(state.uProofGamutWarningLoc, settings?.gamutWarning ? 1 : 0);+ gl.uniform1i(state.uProofValueCheckLoc, valueCheck ? 1 : 0);- const warnRgb = parseHexColor(settings.gamutWarningColor || '#7f7f7f');+ const warnRgb = parseHexColor(settings?.gamutWarningColor || '#7f7f7f');gl.uniform3f(state.uProofGamutWarningColorLoc, warnRgb[0], warnRgb[1], warnRgb[2]);gl.activeTexture(gl.TEXTURE0);@@ -312,14 +314,18 @@ export function presentTextureToScreen(texture: WebGLTexture,viewportW: number,viewportH: number,- softProof?: SoftProofSettings+ softProof?: SoftProofSettings,+ valueCheck = false): void {gl.bindFramebuffer(gl.FRAMEBUFFER, null);gl.viewport(0, 0, viewportW, viewportH);gl.disable(gl.STENCIL_TEST);- if (softProof && (softProof.enabled || softProof.gamutWarning) && state.softProofProgram) {- applySoftProofPass(state, gl, viewportW, viewportH, softProof, texture);+ const needsPostProcess = Boolean(+ valueCheck || (softProof && (softProof.enabled || softProof.gamutWarning))+ );+ if (needsPostProcess && state.softProofProgram) {+ applySoftProofPass(state, gl, viewportW, viewportH, softProof, texture, valueCheck);return;}diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.tsindex 8fd1546..a5dde11 100644--- a/src/utils/compositor/fallback2d.ts+++ b/src/utils/compositor/fallback2d.ts@@ -8,6 +8,7 @@ import {import { applyScreentoneCPU } from '../screentoneEngine';import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';import { applyAdjustment } from '../tonalEngine';+import { applyPerceptualGrayscaleToImageData } from '../valueCheck';import { calculateVisibleDocumentBounds } from './bounds';import { buildLayerTree, groupTreeNodesForCompositing } from './layerTree';import { hasActiveLayerStyles } from './shaders/effectShaders';@@ -675,4 +676,15 @@ export function render2DFallback(render2DNodeList(state, ctx, tree, dimensions, grid, tileCtx, 1.0, frustum);ctx.restore();++ // Live 1-Click Value Check post-pass in Canvas 2D software fallback mode+ if (_options.valueCheck && viewportW > 0 && viewportH > 0) {+ try {+ const imgData = ctx.getImageData(0, 0, viewportW, viewportH);+ applyPerceptualGrayscaleToImageData(imgData);+ ctx.putImageData(imgData, 0, 0);+ } catch {+ // Ignore in headless/mock contexts without getImageData+ }+ }}diff --git a/src/utils/compositor/glInit.ts b/src/utils/compositor/glInit.tsindex c0fe68a..37fe2d1 100644--- a/src/utils/compositor/glInit.ts+++ b/src/utils/compositor/glInit.ts@@ -479,6 +479,7 @@ export function initGL(state: CompositorState): boolean {state.uProofEnabledLoc = gl.getUniformLocation(pProg, 'u_proofEnabled');state.uProofGamutWarningLoc = gl.getUniformLocation(pProg, 'u_gamutWarning');state.uProofGamutWarningColorLoc = gl.getUniformLocation(pProg, 'u_gamutWarningColor');+ state.uProofValueCheckLoc = gl.getUniformLocation(pProg, 'u_valueCheck');} else {console.error('Soft proof link error:', gl.getProgramInfoLog(pProg));}diff --git a/src/utils/compositor/previewRenderer.ts b/src/utils/compositor/previewRenderer.tsindex 503131c..b6c2e83 100644--- a/src/utils/compositor/previewRenderer.ts+++ b/src/utils/compositor/previewRenderer.ts@@ -9,6 +9,22 @@ import { LayerTreeNode } from './types';let previewTileCanvas: HTMLCanvasElement | null = null;let previewTileImgData: ImageData | null = null;let previewScratchCanvas: HTMLCanvasElement | null = null;+let previewDraftScratchCanvas: HTMLCanvasElement | null = null;++export interface LowResPreviewOptions {+ showCheckerboard?: boolean;+ /** Optional in-progress brush stroke canvas so Navigator reflects live painting strokes in real time */+ activeDraftCanvas?: HTMLCanvasElement | null;+ activeDraftLayerId?: string | null;+ activeDraftOpacity?: number;+}++interface PreviewDraftCanvasLike extends HTMLCanvasElement {+ __draftHasContent?: boolean;+ __draftCompositeOp?: GlobalCompositeOperation;+ __draftSpace?: 'document' | 'viewport';+ __draftDocRect?: { x: number; y: number; width: number; height: number };+}/*** Lightweight low-LOD composite preview renderer for Navigator & thumbnails.@@ -19,7 +35,7 @@ export function renderLowResPreview(layers: LayerItem[],dimensions: CanvasDimensions,grid: SparseTileGrid = globalTileGrid,- options: { showCheckerboard?: boolean } = {}+ options: LowResPreviewOptions = {}): void {if (typeof document === 'undefined') return;const ctx = targetCanvas.getContext('2d');@@ -84,28 +100,103 @@ export function renderLowResPreview(if (alpha <= 0.001) return;const tiles = grid.getOrBuildLodTiles(layer.id, targetLod);- if (tiles.length === 0) return;+ const draftEl = options.activeDraftCanvas as PreviewDraftCanvasLike | null | undefined;+ const hasDraft = Boolean(+ options.activeDraftLayerId === layer.id &&+ draftEl &&+ draftEl.width > 0 &&+ draftEl.height > 0 &&+ draftEl.__draftHasContent !== false &&+ draftEl.__draftSpace === 'document' &&+ draftEl.__draftDocRect+ );+ if (tiles.length === 0 && !hasDraft) return;++ const drawLayerTiles = (ctxTarget: CanvasRenderingContext2D) => {+ if (tiles.length === 0) return;+ if (!previewTileImgData) {+ previewTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);+ }+ const reusedImgData = previewTileImgData;++ for (const tile of tiles) {+ const rgba = grid.getTileAsRGBA(tile);+ reusedImgData.data.set(rgba);+ tileCtx.putImageData(reusedImgData, 0, 0);++ const dx = tile.tileX * lodDocSize * scaleX;+ const dy = tile.tileY * lodDocSize * scaleY;+ const dw = lodDocSize * scaleX;+ const dh = lodDocSize * scaleY;+ ctxTarget.drawImage(tileCanvas, dx, dy, dw, dh);+ }+ };++ const draftOp = hasDraft && draftEl ? (draftEl.__draftCompositeOp ?? 'source-over') : 'source-over';+ const draftAlpha = Math.max(0, Math.min(1, options.activeDraftOpacity ?? 1.0));+ const needsIsolatedDraft =+ hasDraft &&+ (draftOp === 'destination-out' ||+ draftOp === 'source-atop' ||+ draftOp === 'destination-over');++ if (needsIsolatedDraft && draftEl && draftEl.__draftDocRect) {+ if (!previewDraftScratchCanvas) {+ previewDraftScratchCanvas = document.createElement('canvas');+ }+ const iso = previewDraftScratchCanvas;+ if (iso.width !== outW) iso.width = outW;+ if (iso.height !== outH) iso.height = outH;+ const isoCtx = iso.getContext('2d');+ if (isoCtx) {+ isoCtx.save();+ isoCtx.setTransform(1, 0, 0, 1, 0, 0);+ isoCtx.clearRect(0, 0, outW, outH);+ isoCtx.globalAlpha = 1;+ isoCtx.globalCompositeOperation = 'source-over';+ isoCtx.imageSmoothingEnabled = true;+ drawLayerTiles(isoCtx);++ const dr = draftEl.__draftDocRect;+ isoCtx.globalAlpha = draftAlpha;+ isoCtx.globalCompositeOperation = draftOp;+ isoCtx.drawImage(+ draftEl,+ dr.x * scaleX,+ dr.y * scaleY,+ dr.width * scaleX,+ dr.height * scaleY+ );+ isoCtx.restore();++ dstCtx.save();+ dstCtx.globalAlpha = alpha;+ dstCtx.globalCompositeOperation =+ compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);+ dstCtx.imageSmoothingEnabled = true;+ dstCtx.drawImage(iso, 0, 0);+ dstCtx.restore();+ return;+ }+ }dstCtx.save();dstCtx.globalAlpha = alpha;dstCtx.globalCompositeOperation = compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);dstCtx.imageSmoothingEnabled = true;- if (!previewTileImgData) {- previewTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);- }- const reusedImgData = previewTileImgData;-- for (const tile of tiles) {- const rgba = grid.getTileAsRGBA(tile);- reusedImgData.data.set(rgba);- tileCtx.putImageData(reusedImgData, 0, 0);-- const dx = tile.tileX * lodDocSize * scaleX;- const dy = tile.tileY * lodDocSize * scaleY;- const dw = lodDocSize * scaleX;- const dh = lodDocSize * scaleY;- dstCtx.drawImage(tileCanvas, dx, dy, dw, dh);+ drawLayerTiles(dstCtx);++ if (hasDraft && draftEl && draftEl.__draftDocRect) {+ const dr = draftEl.__draftDocRect;+ dstCtx.globalAlpha = alpha * draftAlpha;+ dstCtx.drawImage(+ draftEl,+ dr.x * scaleX,+ dr.y * scaleY,+ dr.width * scaleX,+ dr.height * scaleY+ );}dstCtx.restore();diff --git a/src/utils/compositor/renderFrame.ts b/src/utils/compositor/renderFrame.tsindex 2afc8d3..e150fbb 100644--- a/src/utils/compositor/renderFrame.ts+++ b/src/utils/compositor/renderFrame.ts@@ -172,7 +172,8 @@ export function renderFrame(scenePP.surfaces[scenePP.activeIndex].texture,viewportW,viewportH,- _options.softProof+ _options.softProof,+ Boolean(_options.valueCheck));} else if (scenePP &&@@ -376,7 +377,8 @@ export function renderFrame(scenePP.surfaces[scenePP.activeIndex].texture,viewportW,viewportH,- _options.softProof+ _options.softProof,+ Boolean(_options.valueCheck));} else {// Safe fallback when offscreen FBOs are unsupported in a minimal WebGL contextdiff --git a/src/utils/compositor/shaders/softProofShaders.ts b/src/utils/compositor/shaders/softProofShaders.tsindex 7e15f2e..eeebee8 100644--- a/src/utils/compositor/shaders/softProofShaders.ts+++ b/src/utils/compositor/shaders/softProofShaders.ts@@ -18,6 +18,7 @@ uniform int u_standard; // 0: japan-color-2001, 1: us-web-coated-swop, 2: iso-couniform int u_proofEnabled; // 1 or 0uniform int u_gamutWarning; // 1 or 0uniform vec3 u_gamutWarningColor;+uniform int u_valueCheck; // 1 or 0 (Live perceptual B/W tone check)out vec4 fragColor;@@ -175,27 +176,37 @@ void main() {// Unpremultiply alpha for true color evaluationvec3 rgb = sceneColor.rgb / sceneColor.a;+ vec3 outRgb = rgb;- // Soft proof simulation- vec3 proofRgb = simulateCmyk(rgb, u_standard);+ if (u_proofEnabled == 1 || u_gamutWarning == 1) {+ // Soft proof simulation+ vec3 proofRgb = simulateCmyk(rgb, u_standard);- // Gamut evaluation in CIE Lab space- vec3 labOrig = srgbToLab(rgb);- vec3 labProof = srgbToLab(proofRgb);+ if (u_proofEnabled == 1) {+ outRgb = proofRgb;+ }- // Delta-E (CIE76): normalized scale where 100 Lab units = 1.0 (deltaE = norm / 100.0)- vec3 dLab = labOrig - labProof;- float deltaE = length(dLab) / 100.0;+ if (u_gamutWarning == 1) {+ // Gamut evaluation in CIE Lab space+ vec3 labOrig = srgbToLab(rgb);+ vec3 labProof = srgbToLab(proofRgb);- bool isOutOfGamut = (deltaE > 0.05);+ // Delta-E (CIE76): normalized scale where 100 Lab units = 1.0 (deltaE = norm / 100.0)+ vec3 dLab = labOrig - labProof;+ float deltaE = length(dLab) / 100.0;- vec3 outRgb = rgb;- if (u_proofEnabled == 1) {- outRgb = proofRgb;+ bool isOutOfGamut = (deltaE > 0.05);+ if (isOutOfGamut) {+ outRgb = u_gamutWarningColor;+ }+ }}- if (u_gamutWarning == 1 && isOutOfGamut) {- outRgb = u_gamutWarningColor;+ // Live 1-Click Value Check: linear-light Rec.709 / CIE Y perceptual luminance+ if (u_valueCheck == 1) {+ vec3 linOut = srgbToLinear(clamp(outRgb, 0.0, 1.0));+ float lumLin = dot(linOut, vec3(0.2126729, 0.7151522, 0.0721750));+ outRgb = linearToSrgb(vec3(lumLin));}fragColor = vec4(outRgb * sceneColor.a, sceneColor.a);diff --git a/src/utils/compositor/types.ts b/src/utils/compositor/types.tsindex 8f018b3..94c078b 100644--- a/src/utils/compositor/types.ts+++ b/src/utils/compositor/types.ts@@ -85,6 +85,8 @@ export interface CompositorOptions {devicePixelRatio?: number;onionSkinFrames?: OnionSkinCompositorFrame[];softProof?: SoftProofSettings;+ /** Non-destructive 1-Click Value Check (Live perceptual B/W luminance display pass) */+ valueCheck?: boolean;// Active layer identifier for Baked Layer Stack Cache partitioning (below / active / above)activeLayerId?: string | null;// WYSIWYG In-Stack Live Stroke Compositing@@ -425,6 +427,7 @@ export interface CompositorState {uProofEnabledLoc: WebGLUniformLocation | null;uProofGamutWarningLoc: WebGLUniformLocation | null;uProofGamutWarningColorLoc: WebGLUniformLocation | null;+ uProofValueCheckLoc: WebGLUniformLocation | null;// Pre-allocated WebGL2 Texture2D Pool (overflow fallback for TEXTURE_2D_ARRAY)textureAccessCounter: number;diff --git a/src/utils/decorationBrushes.ts b/src/utils/decorationBrushes.tsnew file mode 100644index 0000000..3f2584f--- /dev/null+++ b/src/utils/decorationBrushes.ts@@ -0,0 +1,2177 @@+import type { BrushPresetId, DecorationCategory } from '../types/editor';+import type { BuiltinBrushDefinition, BuiltinBrushSection } from './presetBrushes';++export const DECORATION_BRUSH_SECTIONS: BuiltinBrushSection[] = [+ { id: 'deco-background', label: 'Background' },+ { id: 'deco-clothing', label: 'Clothing' },+ { id: 'deco-effect', label: 'Effect' },+];++export const DECORATION_CATEGORY_SET = new Set<string>(+ DECORATION_BRUSH_SECTIONS.map((s) => s.id)+);++export const DEFAULT_DECORATION_PRESET_ID: BrushPresetId = 'deco-building';++export function isDecorationCategory(category: string | undefined): category is DecorationCategory {+ return Boolean(category && DECORATION_CATEGORY_SET.has(category));+}++export function resolveStaticBrushAssetUrl(assetPath: string): string {+ if (!assetPath) return '';+ if (assetPath.startsWith('data:') || assetPath.startsWith('http://') || assetPath.startsWith('https://') || assetPath.startsWith('blob:')) {+ return assetPath;+ }+ const base =+ typeof import.meta !== 'undefined' &&+ import.meta.env &&+ typeof import.meta.env.BASE_URL === 'string'+ ? import.meta.env.BASE_URL+ : '/';+ const cleanBase = base.endsWith('/') ? base : `${base}/`;+ const cleanPath = assetPath.replace(/^\/+/, '');+ return `${cleanBase}${cleanPath}`;+}++export const DECORATION_BRUSHES: BuiltinBrushDefinition[] = [+ {+ "id": "deco-building",+ "category": "deco-background",+ "name": "Building",+ "badge": "Background",+ "badgeBg": "bg-emerald-500/15",+ "badgeText": "text-emerald-300",+ "badgeBorder": "border-emerald-500/30",+ "desc": "Multi-tip manga cityscape buildings with primary outline and secondary fill",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/background/building_0.png",+ "width": 156,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_1.png",+ "width": 111,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_2.png",+ "width": 100,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_3.png",+ "width": 167,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_4.png",+ "width": 122,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_5.png",+ "width": 133,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_6.png",+ "width": 144,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_7.png",+ "width": 133,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_8.png",+ "width": 144,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_9.png",+ "width": 178,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_10.png",+ "width": 189,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_11.png",+ "width": 189,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/background/building_12.png",+ "width": 167,+ "height": 300,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 500,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.35,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 1,+ "stabilization": 5,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 1,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "intervalSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 1,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.8+ },+ "flipH": "random",+ "subTipOrder": "sequential",+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-cloud",+ "category": "deco-background",+ "name": "Cloud",+ "badge": "Background",+ "badgeBg": "bg-emerald-500/15",+ "badgeText": "text-emerald-300",+ "badgeBorder": "border-emerald-500/30",+ "desc": "Soft scattered cloud clusters for sky backgrounds",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/background/cloud_0.png",+ "width": 284,+ "height": 281+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": true,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.3,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 1,+ "stabilization": 6,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": true,+ "useVelocity": false,+ "useTilt": false,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.3169,+ 0.6948+ ],+ [+ 1,+ 1+ ]+ ],+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.3169,+ 0.6948+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "densitySensor": {+ "usePressure": true,+ "pressureMin": 0,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.7545,+ 0.2818+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0+ },+ "intervalSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "spray": {+ "enabled": true,+ "size": 300,+ "density": 2,+ "bias": 1,+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0.03,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.3169,+ 0.6948+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "densitySensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0+ }+ },+ "useGpu": true+ }+ },+ {+ "id": "deco-grass",+ "category": "deco-background",+ "name": "Grass",+ "badge": "Background",+ "badgeBg": "bg-emerald-500/15",+ "badgeText": "text-emerald-300",+ "badgeBorder": "border-emerald-500/30",+ "desc": "Randomized grass tuft scatter for ground and foliage",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/background/grass_0.png",+ "width": 300,+ "height": 258+ },+ {+ "assetPath": "brushes/decoration/background/grass_1.png",+ "width": 300,+ "height": 254+ }+ ],+ "settings": {+ "size": 250,+ "brushSizeUnit": 0,+ "minSizeFactor": 0.85,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.5,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 1,+ "stabilization": 2,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0.2,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.85+ },+ "intervalSensor": {+ "usePressure": true,+ "pressureMin": 0.6,+ "pressureCurve": [+ [+ 0,+ 1+ ],+ [+ 0.7455,+ 0.0091+ ],+ [+ 0.7545,+ 0+ ],+ [+ 1,+ 0+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.2+ },+ "flipH": "alternate",+ "subTipOrder": "random",+ "spray": {+ "enabled": true,+ "size": 150,+ "density": 2,+ "bias": 0.5,+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0.5,+ "pressureCurve": [+ [+ 0,+ 0.1+ ],+ [+ 0.7364,+ 1+ ],+ [+ 0.7455,+ 1+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.8+ },+ "densitySensor": {+ "usePressure": true,+ "pressureMin": 0.1,+ "pressureCurve": [+ [+ 0,+ 0.1273+ ],+ [+ 0.6,+ 1+ ],+ [+ 0.6091,+ 1+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.45+ }+ },+ "useGpu": true+ }+ },+ {+ "id": "deco-trees",+ "category": "deco-background",+ "name": "Trees",+ "badge": "Background",+ "badgeBg": "bg-emerald-500/15",+ "badgeText": "text-emerald-300",+ "badgeBorder": "border-emerald-500/30",+ "desc": "Multi-tip tree silhouettes for instant forest backgrounds",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/background/trees_0.png",+ "width": 177,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/background/trees_1.png",+ "width": 236,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/background/trees_2.png",+ "width": 115,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/background/trees_3.png",+ "width": 236,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/background/trees_4.png",+ "width": 216,+ "height": 300+ }+ ],+ "settings": {+ "size": 400,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.7,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "intervalSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.5+ },+ "flipH": "alternate",+ "subTipOrder": "random",+ "useGpu": true+ }+ },+ {+ "id": "deco-star-lace",+ "category": "deco-clothing",+ "name": "Star Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Continuous ribbon star-pattern lace trim",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/star-lace_0.png",+ "width": 300,+ "height": 199+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": false,+ "antiAlias": 1,+ "stabilization": 6,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 84.5,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-sakura-lace",+ "category": "deco-clothing",+ "name": "Sakura Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Continuous ribbon cherry-petal lace trim",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/sakura-lace_0.png",+ "width": 300,+ "height": 144+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": false,+ "antiAlias": 1,+ "stabilization": 6,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 84.5,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-cross-lace",+ "category": "deco-clothing",+ "name": "Cross Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Continuous ribbon gothic cross lace trim",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/cross-lace_0.png",+ "width": 300,+ "height": 107+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": false,+ "antiAlias": 1,+ "stabilization": 6,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 84.5,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-rope-ribbon",+ "category": "deco-clothing",+ "name": "Rope Ribbon",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone twisted rope ribbon trim",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/rope-ribbon_0.png",+ "width": 90,+ "height": 101,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 100,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-sheer-scallop",+ "category": "deco-clothing",+ "name": "Sheer Scallop",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone delicate sheer scalloped lace ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/sheer-scallop_0.png",+ "width": 176,+ "height": 138,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 475.8,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-scallop-trim-lace",+ "category": "deco-clothing",+ "name": "Scallop Trim Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone scalloped trim lace ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/scallop-trim-lace_0.png",+ "width": 93,+ "height": 111,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 285.2,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-scallop-lace",+ "category": "deco-clothing",+ "name": "Scallop Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone classic scallop lace ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/scallop-lace_0.png",+ "width": 115,+ "height": 150,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 254.1,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-ornate-scallop",+ "category": "deco-clothing",+ "name": "Ornate Scallop",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone ornate scalloped lace ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/ornate-scallop_0.png",+ "width": 215,+ "height": 252,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 250,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-simple-lace",+ "category": "deco-clothing",+ "name": "Simple Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone clean simple lace trim ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/simple-lace_0.png",+ "width": 109,+ "height": 151,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 299.7,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-decorative-rope",+ "category": "deco-clothing",+ "name": "Decorative Rope",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone braided decorative cord ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/decorative-rope_0.png",+ "width": 70,+ "height": 115,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 314.9,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.019,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": false,+ "antiAlias": 2,+ "stabilization": 50,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": true,+ "useVelocity": false,+ "useTilt": false,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.2636,+ 0.5091+ ],+ [+ 1,+ 1+ ]+ ],+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.2636,+ 0.5091+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-rose-trim",+ "category": "deco-clothing",+ "name": "Rose Trim",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Dual-tone rose floral lace trim ribbon",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/rose-trim_0.png",+ "width": 100,+ "height": 151,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 396.8,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 10,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "isRibbon": true,+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-1",+ "category": "deco-clothing",+ "name": "Standard Lace 1",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Detailed eyelet ribbon lace trim",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-1_0.png",+ "width": 300,+ "height": 246+ }+ ],+ "settings": {+ "size": 157.4,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-2",+ "category": "deco-clothing",+ "name": "Standard Lace 2",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Wide floral scallop ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-2_0.png",+ "width": 277,+ "height": 300+ }+ ],+ "settings": {+ "size": 325.5,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-3",+ "category": "deco-clothing",+ "name": "Standard Lace 3",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Fine scalloped border ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-3_0.png",+ "width": 300,+ "height": 205+ }+ ],+ "settings": {+ "size": 113.2,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-4",+ "category": "deco-clothing",+ "name": "Standard Lace 4",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Ornate embroidery ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-4_0.png",+ "width": 300,+ "height": 243+ }+ ],+ "settings": {+ "size": 219,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-5",+ "category": "deco-clothing",+ "name": "Standard Lace 5",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Delicate frill border ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-5_0.png",+ "width": 300,+ "height": 240+ }+ ],+ "settings": {+ "size": 140.3,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 270,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-standard-lace-6",+ "category": "deco-clothing",+ "name": "Standard Lace 6",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Layered crochet ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/standard-lace-6_0.png",+ "width": 300,+ "height": 243+ }+ ],+ "settings": {+ "size": 359.4,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 5,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-classic-lace",+ "category": "deco-clothing",+ "name": "Classic Lace",+ "badge": "Clothing",+ "badgeBg": "bg-pink-500/15",+ "badgeText": "text-pink-300",+ "badgeBorder": "border-pink-500/30",+ "desc": "Classic frilled ribbon lace",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/clothing/classic-lace_0.png",+ "width": 300,+ "height": 295+ }+ ],+ "settings": {+ "size": 211.9,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.1,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 1,+ "stabilization": 5,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngle": 90,+ "subTipOrder": "sequential",+ "isRibbon": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-bloodstain",+ "category": "deco-effect",+ "name": "Bloodstain",+ "badge": "Effect",+ "badgeBg": "bg-violet-500/15",+ "badgeText": "text-violet-300",+ "badgeBorder": "border-violet-500/30",+ "desc": "Multi-tip directional splatter and bloodstain spray",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/effect/bloodstain_0.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_1.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_2.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_3.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_4.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_5.png",+ "width": 300,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/bloodstain_6.png",+ "width": 300,+ "height": 300+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.8,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "thicknessSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": true,+ "velocityMin": 0.23,+ "velocityCurve": [+ [+ 0,+ 1+ ],+ [+ 1,+ 0+ ]+ ],+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.7+ },+ "antiAlias": 1,+ "stabilization": 0,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": true,+ "useVelocity": false,+ "useTilt": false,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.364,+ 0.0439+ ],+ [+ 0.5263,+ 1+ ],+ [+ 1,+ 1+ ]+ ],+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.364,+ 0.0439+ ],+ [+ 0.5263,+ 1+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 1,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.71+ },+ "intervalSensor": {+ "usePressure": true,+ "pressureMin": 0.3,+ "pressureCurve": [+ [+ 0,+ 1+ ],+ [+ 0.0091,+ 1+ ],+ [+ 1,+ 0+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": true,+ "velocityMin": 0.5,+ "velocityCurve": [+ [+ 0,+ 1+ ],+ [+ 1,+ 0+ ]+ ],+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0.86+ },+ "customTipAngle": 90,+ "customTipAngleDynamics": "direction",+ "flipH": "alternate",+ "flipV": "alternate",+ "subTipOrder": "random",+ "spray": {+ "enabled": true,+ "size": 400,+ "density": 2,+ "bias": 1,+ "sizeSensor": {+ "usePressure": true,+ "pressureMin": 0,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 0.2895,+ 0.0351+ ],+ [+ 0.5351,+ 1+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": true,+ "velocityMin": 0.2,+ "velocityCurve": [+ [+ 0,+ 1+ ],+ [+ 1,+ 0+ ]+ ],+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.5+ },+ "densitySensor": {+ "usePressure": true,+ "pressureMin": 0.18,+ "pressureCurve": [+ [+ 0,+ 0+ ],+ [+ 1,+ 1+ ]+ ],+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": true,+ "velocityMin": 0.2,+ "velocityCurve": [+ [+ 0,+ 1+ ],+ [+ 1,+ 0+ ]+ ],+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ }+ },+ "useGpu": true+ }+ },+ {+ "id": "deco-cherry",+ "category": "deco-effect",+ "name": "Cherry",+ "badge": "Effect",+ "badgeBg": "bg-violet-500/15",+ "badgeText": "text-violet-300",+ "badgeBorder": "border-violet-500/30",+ "desc": "Dual-tone fluttering cherry blossom petals",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/effect/cherry_0.png",+ "width": 298,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/cherry_1.png",+ "width": 298,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/cherry_2.png",+ "width": 297,+ "height": 300,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 300,+ "brushSizeUnit": 0,+ "minSizeFactor": 0.85,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 1.2,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": true,+ "antiAlias": 1,+ "stabilization": 2,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.85+ },+ "intervalSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.52+ },+ "customTipAngleDynamics": "direction-random",+ "customTipRotationRandomScale": 1,+ "flipH": "alternate",+ "flipV": "alternate",+ "subTipOrder": "random",+ "isDualToneTip": true,+ "useGpu": true+ }+ },+ {+ "id": "deco-feather",+ "category": "deco-effect",+ "name": "Feather",+ "badge": "Effect",+ "badgeBg": "bg-violet-500/15",+ "badgeText": "text-violet-300",+ "badgeBorder": "border-violet-500/30",+ "desc": "Multi-tip floating feathers with gentle spray scatter",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/effect/feather_0.png",+ "width": 138,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/feather_1.png",+ "width": 300,+ "height": 268+ },+ {+ "assetPath": "brushes/decoration/effect/feather_2.png",+ "width": 188,+ "height": 300+ },+ {+ "assetPath": "brushes/decoration/effect/feather_3.png",+ "width": 188,+ "height": 300+ }+ ],+ "settings": {+ "size": 200,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 0.8,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 1.5,+ "hardness": 1,+ "thickness": 1.5,+ "thicknessVertical": true,+ "antiAlias": 2,+ "stabilization": 2,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": false,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 1,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "subTipOrder": "sequential",+ "spray": {+ "enabled": true,+ "size": 120,+ "density": 2,+ "bias": 0,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 1,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0.4+ },+ "densitySensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": true,+ "randomMin": 0+ }+ },+ "useGpu": true+ }+ },+ {+ "id": "deco-roses",+ "category": "deco-effect",+ "name": "Roses",+ "badge": "Effect",+ "badgeBg": "bg-violet-500/15",+ "badgeText": "text-violet-300",+ "badgeBorder": "border-violet-500/30",+ "desc": "Multi-tip dual-tone blooming roses scatter",+ "icon": "sparkles",+ "staticTips": [+ {+ "assetPath": "brushes/decoration/effect/roses_0.png",+ "width": 300,+ "height": 294,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_1.png",+ "width": 284,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_2.png",+ "width": 300,+ "height": 297,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_3.png",+ "width": 214,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_4.png",+ "width": 272,+ "height": 300,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_5.png",+ "width": 300,+ "height": 294,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_6.png",+ "width": 300,+ "height": 228,+ "isDualToneTip": true+ },+ {+ "assetPath": "brushes/decoration/effect/roses_7.png",+ "width": 297,+ "height": 300,+ "isDualToneTip": true+ }+ ],+ "settings": {+ "size": 755,+ "brushSizeUnit": 0,+ "minSizeFactor": 0,+ "opacity": 1,+ "flow": 1,+ "adjustDensityByGap": false,+ "blendTipsMode": "darken",+ "brushCombineMode": "normal",+ "spacing": 0.64,+ "hardness": 1,+ "thickness": 1,+ "thicknessVertical": false,+ "antiAlias": 3,+ "stabilization": 0,+ "postCorrection": 0,+ "sharpCorners": false,+ "smoothing": true,+ "usePressure": false,+ "useVelocity": false,+ "useTilt": true,+ "sizeSensor": {+ "usePressure": false,+ "pressureMin": 0,+ "useTilt": false,+ "tiltMin": 0,+ "invertTilt": false,+ "useVelocity": false,+ "velocityMin": 0,+ "invertVelocity": false,+ "useRandom": false,+ "randomMin": 0+ },+ "customTipAngleDynamics": "tilt",+ "subTipOrder": "random",+ "isDualToneTip": true,+ "useGpu": true+ }+ }+];++const DECORATION_PRESET_ID_SET = new Set<string>(DECORATION_BRUSHES.map((b) => b.id));++export function isDecorationPresetId(presetId: string | undefined | null): boolean {+ return Boolean(presetId && DECORATION_PRESET_ID_SET.has(presetId));+}diff --git a/src/utils/fileDropImport.ts b/src/utils/fileDropImport.tsindex 35ee838..7443e1b 100644--- a/src/utils/fileDropImport.ts+++ b/src/utils/fileDropImport.ts@@ -1,4 +1,5 @@-export type ExternalDropZoneKind = 'layers' | 'canvas';+export type ExternalDropZoneKind = 'layers' | 'canvas' | '3d-stage';+export type ExternalFileDropPayloadKind = 'image' | '3d-model' | 'any-3d';export type LayerDropPosition = 'above' | 'below' | 'inside';export interface LayerInsertTarget {@@ -8,10 +9,12 @@ export interface LayerInsertTarget {export interface ExternalFileDropTarget extends LayerInsertTarget {zone: ExternalDropZoneKind;+ payloadKind?: ExternalFileDropPayloadKind;}export const MAX_DROPPED_IMAGE_BYTES = 100 * 1024 * 1024; // 100 MB safety ceiling per imageexport const MAX_DROPPED_IMAGE_FILES = 32;+export const MAX_DROPPED_3D_MODEL_BYTES = 250 * 1024 * 1024; // 250 MB safety ceiling per 3D modelconst EXTENSION_TO_MIME: Record<string, string> = {'.png': 'image/png',@@ -25,12 +28,23 @@ const EXTENSION_TO_MIME: Record<string, string> = {'.ico': 'image/x-icon',};+const MODEL_3D_EXTENSION_TO_MIME: Record<string, string> = {+ '.glb': 'model/gltf-binary',+ '.gltf': 'model/gltf+json',+ '.obj': 'text/plain',+};+const ALLOWED_MIME_TYPES = new Set<string>([...Object.values(EXTENSION_TO_MIME),'image/vnd.microsoft.icon','image/pjpeg',]);+const ALLOWED_3D_MODEL_MIME_TYPES = new Set<string>([+ 'model/gltf-binary',+ 'model/gltf+json',+]);+const INTERNAL_DOCK_MIME = 'application/x-inkstudio-dock-panel';export function extractFilenameFromPath(filePath: string): string {@@ -63,6 +77,66 @@ export function isSupportedImageFile(file: File): boolean {return false;}+export function isSupported3DModelExtension(filenameOrPath: string): boolean {+ const ext = getExtensionLower(filenameOrPath);+ return ext !== '' && Object.prototype.hasOwnProperty.call(MODEL_3D_EXTENSION_TO_MIME, ext);+}++export function get3DModelMimeTypeForFilename(filenameOrPath: string): string {+ const ext = getExtensionLower(filenameOrPath);+ return MODEL_3D_EXTENSION_TO_MIME[ext] || 'application/octet-stream';+}++export function isSupported3DModelFile(file: File): boolean {+ if (!file || typeof file.name !== 'string') return false;+ if (isSupported3DModelExtension(file.name)) return true;+ if (file.type && ALLOWED_3D_MODEL_MIME_TYPES.has(file.type.toLowerCase())) return true;+ return false;+}++export function inferHtml5DragPayloadKind(+ dataTransfer: DataTransfer | null | undefined,+ is3DModeActive: boolean+): ExternalFileDropPayloadKind {+ if (dataTransfer) {+ const files = dataTransfer.files;+ if (files && files.length > 0) {+ let has3D = false;+ let hasImage = false;+ for (let i = 0; i < files.length; i++) {+ const f = files[i];+ if (isSupported3DModelFile(f)) has3D = true;+ else if (isSupportedImageFile(f)) hasImage = true;+ }+ if (has3D) return '3d-model';+ if (hasImage) return 'image';+ }++ const items = dataTransfer.items;+ if (items && items.length > 0) {+ let fileItemCount = 0;+ let allKnownImages = true;+ for (let i = 0; i < items.length; i++) {+ const item = items[i];+ if (item.kind !== 'file') continue;+ fileItemCount++;+ const mime = (item.type || '').toLowerCase();+ if (mime && ALLOWED_3D_MODEL_MIME_TYPES.has(mime)) {+ return '3d-model';+ }+ if (!mime || !ALLOWED_MIME_TYPES.has(mime)) {+ allKnownImages = false;+ }+ }+ if (fileItemCount > 0 && allKnownImages) {+ return 'image';+ }+ }+ }++ return is3DModeActive ? 'any-3d' : 'image';+}+export function sanitizeImportedLayerName(filenameOrPath: string): string {const base = extractFilenameFromPath(filenameOrPath);const withoutExt = base.replace(/\.[^/.]+$/, '');@@ -147,6 +221,55 @@ export function filterDroppedImagePaths(paths: readonly string[]): FilteredPathsreturn { accepted, rejectedCount, truncatedCount };}+export function filterDropped3DModelFiles(files: Iterable<File>): FilteredFilesResult {+ const accepted: File[] = [];+ let rejectedCount = 0;+ let oversizedCount = 0;+ let truncatedCount = 0;++ for (const file of files) {+ if (!isSupported3DModelFile(file)) {+ rejectedCount++;+ continue;+ }+ if (file.size === 0) {+ rejectedCount++;+ continue;+ }+ if (file.size > MAX_DROPPED_3D_MODEL_BYTES) {+ oversizedCount++;+ continue;+ }+ if (accepted.length >= 1) {+ truncatedCount++;+ continue;+ }+ accepted.push(file);+ }++ return { accepted, rejectedCount, oversizedCount, truncatedCount };+}++export function filterDropped3DModelPaths(paths: readonly string[]): FilteredPathsResult {+ const accepted: string[] = [];+ let rejectedCount = 0;+ let truncatedCount = 0;++ for (const rawPath of paths) {+ if (!rawPath || rawPath.includes('\0') || !isSupported3DModelExtension(rawPath)) {+ rejectedCount++;+ continue;+ }+ if (accepted.length >= 1) {+ truncatedCount++;+ continue;+ }+ accepted.push(rawPath);+ }++ return { accepted, rejectedCount, truncatedCount };+}+function resolveLayerRowTarget(element: Element,clientY: number@@ -189,6 +312,9 @@ export function resolveDropZoneFromElement(if (zone === 'canvas') {return { zone: 'canvas' };}+ if (zone === '3d-stage') {+ return { zone: '3d-stage' };+ }return null;}@@ -212,29 +338,32 @@ export function isSameDropTarget(return (a.zone === b.zone &&a.targetLayerId === b.targetLayerId &&- a.position === b.position+ a.position === b.position &&+ a.payloadKind === b.payloadKind);}-export async function readTauriDroppedImageFile(path: string): Promise<File> {- if (!path || path.includes('\0') || !isSupportedImageExtension(path)) {- throw new Error('Unsupported image path');- }+async function readTauriFileBytes(path: string): Promise<Uint8Array> {const { invoke } = await import('@tauri-apps/api/core');- let bytes: Uint8Array;try {const buf = await invoke<ArrayBuffer>('read_file_binary', { path });- bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ return buf instanceof Uint8Array ? buf : new Uint8Array(buf);} catch (err) {// Fallback for older backend binaries that only expose read_file_from_diskconst msg = err instanceof Error ? err.message : String(err);if (msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('unknown')) {const arr = await invoke<number[]>('read_file_from_disk', { path });- bytes = new Uint8Array(arr);- } else {- throw err;+ return new Uint8Array(arr);}+ throw err;}+}++export async function readTauriDroppedImageFile(path: string): Promise<File> {+ if (!path || path.includes('\0') || !isSupportedImageExtension(path)) {+ throw new Error('Unsupported image path');+ }+ const bytes = await readTauriFileBytes(path);if (bytes.byteLength === 0) {throw new Error('Image file is empty');@@ -249,3 +378,23 @@ export async function readTauriDroppedImageFile(path: string): Promise<File> {copy.set(bytes);return new File([copy.buffer], filename, { type: mime });}++export async function readTauriDropped3DModelFile(path: string): Promise<File> {+ if (!path || path.includes('\0') || !isSupported3DModelExtension(path)) {+ throw new Error('Unsupported 3D model path');+ }+ const bytes = await readTauriFileBytes(path);++ if (bytes.byteLength === 0) {+ throw new Error('3D model file is empty');+ }+ if (bytes.byteLength > MAX_DROPPED_3D_MODEL_BYTES) {+ throw new Error('3D model file exceeds 250 MB safety limit');+ }++ const filename = extractFilenameFromPath(path);+ const mime = get3DModelMimeTypeForFilename(filename);+ const copy = new Uint8Array(bytes.byteLength);+ copy.set(bytes);+ return new File([copy.buffer], filename, { type: mime });+}diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.tsindex 904476d..baeafa2 100644--- a/src/utils/floodFill.ts+++ b/src/utils/floodFill.ts@@ -63,7 +63,7 @@ export interface FloodFillOptions {alphaLocked?: boolean;}-function isLayerEffectivelyVisibleInList(layer: LayerItem, layers: LayerItem[]): boolean {+export function isLayerEffectivelyVisibleInList(layer: LayerItem, layers: LayerItem[]): boolean {if (!layer.visible) return false;let parentId = layer.parentId;let guard = 0;@@ -77,6 +77,20 @@ function isLayerEffectivelyVisibleInList(layer: LayerItem, layers: LayerItem[]):return true;}+export function isLayerEffectivelyReferenceInList(layer: LayerItem, layers: LayerItem[]): boolean {+ if (layer.isReference) return true;+ let parentId = layer.parentId;+ let guard = 0;+ while (parentId && guard < 32) {+ const parent = layers.find((l) => l.id === parentId);+ if (!parent) break;+ if (parent.isReference) return true;+ parentId = parent.parentId;+ guard++;+ }+ return false;+}+function pointInPolygonFlood(px: number,py: number,@@ -149,7 +163,13 @@ export function compositeReferenceLayers(dimensions: CanvasDimensions,tileGrid?: SparseTileGrid): HTMLCanvasElement {- const refLayers = layers.filter((l) => l.visible && l.isReference && l.type !== 'folder');+ const refLayers = layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ isLayerEffectivelyReferenceInList(l, layers) &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );if (refLayers.length === 0) {return compositeVisibleLayers(layers, layerCanvasesMap, dimensions, tileGrid);}@@ -189,7 +209,7 @@ export function compositeReferenceLayers(/*** Separable 2D binary dilation (radius r) in O(W * H) time.*/-function dilateBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {+export function dilateBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {if (radius <= 0) return new Uint8Array(mask);const horiz = new Uint8Array(width * height);const out = new Uint8Array(width * height);@@ -231,7 +251,7 @@ function dilateBinaryMask(mask: Uint8Array, width: number, height: number, radiu/*** Separable 2D binary erosion (radius r) in O(W * H) time.*/-function erodeBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {+export function erodeBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {if (radius <= 0) return new Uint8Array(mask);const horiz = new Uint8Array(width * height);const out = new Uint8Array(width * height);@@ -759,7 +779,7 @@ export function executeFloodFillOnTileGrid(params: {const refs = layers.filter((l) =>isLayerEffectivelyVisibleInList(l, layers) &&- l.isReference &&+ isLayerEffectivelyReferenceInList(l, layers) &&l.type !== 'folder' &&l.type !== 'frame-folder');@@ -1195,6 +1215,7 @@ export function executeLassoFillOnTileGrid(params: {targetFormat?: TileFormat;alphaLocked?: boolean;selectionMask?: Uint8Array | null;+ opacity?: number;}): { dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] } {const {grid,@@ -1204,8 +1225,10 @@ export function executeLassoFillOnTileGrid(params: {fillColorHex,alphaLocked = false,selectionMask = null,+ opacity = 1.0,} = params;- if (polygon.length < 3) {+ const effectiveOpacity = Math.max(0, Math.min(1, Number.isFinite(opacity) ? opacity : 1.0));+ if (polygon.length < 3 || effectiveOpacity <= 0.001) {return { dirtyRect: null, modified: false, tileDeltas: [] };}@@ -1303,7 +1326,7 @@ export function executeLassoFillOnTileGrid(params: {: alphaLocked? 'source-atop': 'source-over',- opacity: 1.0,+ opacity: effectiveOpacity,snapshotOut: beforeSnapshot,suppressNotify: true,});@@ -1378,7 +1401,7 @@ export async function executeFloodFillOnTileGridAsync(params: {const r = layers.filter((l) =>isLayerEffectivelyVisibleInList(l, layers) &&- l.isReference &&+ isLayerEffectivelyReferenceInList(l, layers) &&l.type !== 'folder' &&l.type !== 'frame-folder');@@ -1459,3 +1482,17 @@ export async function executeFloodFillOnTileGridAsync(params: {grid.notifyChange(true);return { dirtyRect: res.dirtyRect, modified: tileDeltas.length > 0, tileDeltas };}++export {+ executeEncloseAndFillOnTileGrid,+ executePaintUnfilledAreaOnTileGrid,+ rasterizePolygonMask,+ rasterizeBrushStrokeMask,+ resolveSmartFillReferenceLayers,+} from './smartLineFill';+export type {+ SmartLineFillOptions,+ EncloseAndFillTileParams,+ PaintUnfilledAreaTileParams,+ SmartLineFillResult,+} from './smartLineFill';diff --git a/src/utils/gradientEngine.ts b/src/utils/gradientEngine.tsindex b88ef85..ea8e942 100644--- a/src/utils/gradientEngine.ts+++ b/src/utils/gradientEngine.ts@@ -54,6 +54,8 @@ export interface GradientMeshState {rows: number;nodes: GradientMeshNode[]; // row-major length = rows * colsselectedNodeIndex: number | null;+ selectedNodeIndices?: number[];+ rotationDeg?: number;}export interface GradientSettings {@@ -376,9 +378,264 @@ export function createDefaultGradientMesh(rows: rCount,nodes,selectedNodeIndex: 0,+ selectedNodeIndices: [0],+ rotationDeg: 0,};}+export function normalizeMeshAngleDeg(deg: number): number {+ if (!Number.isFinite(deg)) return 0;+ let a = ((((deg + 180) % 360) + 360) % 360) - 180;+ if (a <= -180) a = 180;+ return Math.abs(a) < 1e-9 ? 0 : a;+}++export function getSelectedMeshNodeIndices(mesh: GradientMeshState): number[] {+ const n = mesh.nodes.length;+ if (n === 0) return [];+ if (Array.isArray(mesh.selectedNodeIndices)) {+ const seen = new Set<number>();+ const result: number[] = [];+ for (const idx of mesh.selectedNodeIndices) {+ if (Number.isInteger(idx) && idx >= 0 && idx < n && !seen.has(idx)) {+ seen.add(idx);+ result.push(idx);+ }+ }+ result.sort((a, b) => a - b);+ return result;+ }+ if (+ mesh.selectedNodeIndex !== null &&+ Number.isInteger(mesh.selectedNodeIndex) &&+ mesh.selectedNodeIndex >= 0 &&+ mesh.selectedNodeIndex < n+ ) {+ return [mesh.selectedNodeIndex];+ }+ return [];+}++export function setGradientMeshSelection(+ mesh: GradientMeshState,+ indices: readonly number[],+ primaryIndex?: number | null+): GradientMeshState {+ const n = mesh.nodes.length;+ const seen = new Set<number>();+ const unique: number[] = [];+ for (const idx of indices) {+ if (Number.isInteger(idx) && idx >= 0 && idx < n && !seen.has(idx)) {+ seen.add(idx);+ unique.push(idx);+ }+ }+ unique.sort((a, b) => a - b);+ const resolvedPrimary =+ primaryIndex !== undefined && primaryIndex !== null && seen.has(primaryIndex)+ ? primaryIndex+ : unique.length > 0+ ? unique[unique.length - 1]+ : null;+ return {+ ...mesh,+ selectedNodeIndex: resolvedPrimary,+ selectedNodeIndices: unique,+ };+}++export function toggleGradientMeshNodeSelection(+ mesh: GradientMeshState,+ index: number+): GradientMeshState {+ if (!Number.isInteger(index) || index < 0 || index >= mesh.nodes.length) return mesh;+ const current = getSelectedMeshNodeIndices(mesh);+ const exists = current.includes(index);+ if (exists) {+ const next = current.filter((i) => i !== index);+ return setGradientMeshSelection(mesh, next);+ }+ return setGradientMeshSelection(mesh, [...current, index], index);+}++export function selectAllGradientMeshNodes(mesh: GradientMeshState): GradientMeshState {+ const all = mesh.nodes.map((_, i) => i);+ const primary =+ mesh.selectedNodeIndex !== null &&+ mesh.selectedNodeIndex >= 0 &&+ mesh.selectedNodeIndex < mesh.nodes.length+ ? mesh.selectedNodeIndex+ : all.length > 0+ ? 0+ : null;+ return setGradientMeshSelection(mesh, all, primary);+}++export function invertGradientMeshSelection(mesh: GradientMeshState): GradientMeshState {+ const current = new Set(getSelectedMeshNodeIndices(mesh));+ const next: number[] = [];+ for (let i = 0; i < mesh.nodes.length; i++) {+ if (!current.has(i)) next.push(i);+ }+ return setGradientMeshSelection(mesh, next);+}++export function selectGradientMeshNodesInRect(+ mesh: GradientMeshState,+ rect: { x: number; y: number; width: number; height: number },+ additive = false+): GradientMeshState {+ const minX = Math.min(rect.x, rect.x + rect.width);+ const maxX = Math.max(rect.x, rect.x + rect.width);+ const minY = Math.min(rect.y, rect.y + rect.height);+ const maxY = Math.max(rect.y, rect.y + rect.height);++ const hit: number[] = [];+ for (let i = 0; i < mesh.nodes.length; i++) {+ const n = mesh.nodes[i];+ if (n.x >= minX && n.x <= maxX && n.y >= minY && n.y <= maxY) {+ hit.push(i);+ }+ }+ const combined = additive ? [...getSelectedMeshNodeIndices(mesh), ...hit] : hit;+ return setGradientMeshSelection(mesh, combined);+}++export function getGradientMeshCentroid(mesh: GradientMeshState): Point2D {+ const count = mesh.nodes.length;+ if (count === 0) return { x: 0, y: 0 };+ let sx = 0;+ let sy = 0;+ for (let i = 0; i < count; i++) {+ sx += mesh.nodes[i].x;+ sy += mesh.nodes[i].y;+ }+ return { x: sx / count, y: sy / count };+}++export function getGradientMeshBounds(mesh: GradientMeshState): {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+ width: number;+ height: number;+} {+ if (mesh.nodes.length === 0) {+ return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };+ }+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (const n of mesh.nodes) {+ if (n.x < minX) minX = n.x;+ if (n.y < minY) minY = n.y;+ if (n.x > maxX) maxX = n.x;+ if (n.y > maxY) maxY = n.y;+ }+ return {+ minX,+ minY,+ maxX,+ maxY,+ width: maxX - minX,+ height: maxY - minY,+ };+}++export function rotateGradientMeshVertices(+ mesh: GradientMeshState,+ deltaDeg: number,+ pivot?: Point2D+): GradientMeshState {+ if (mesh.nodes.length === 0 || !Number.isFinite(deltaDeg)) return mesh;+ const center = pivot ?? getGradientMeshCentroid(mesh);+ const rad = (deltaDeg * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const nextNodes = mesh.nodes.map((node) => {+ const dx = node.x - center.x;+ const dy = node.y - center.y;+ return {+ ...node,+ x: center.x + dx * cos - dy * sin,+ y: center.y + dx * sin + dy * cos,+ };+ });+ return {+ ...mesh,+ nodes: nextNodes,+ rotationDeg: normalizeMeshAngleDeg((mesh.rotationDeg ?? 0) + deltaDeg),+ };+}++export function rotateGradientMeshFromBase(+ basePositions: readonly Point2D[],+ baseRotationDeg: number,+ mesh: GradientMeshState,+ deltaDeg: number,+ pivot: Point2D+): GradientMeshState {+ if (mesh.nodes.length === 0 || basePositions.length !== mesh.nodes.length || !Number.isFinite(deltaDeg)) {+ return mesh;+ }+ const rad = (deltaDeg * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const nextNodes = mesh.nodes.map((node, i) => {+ const dx = basePositions[i].x - pivot.x;+ const dy = basePositions[i].y - pivot.y;+ return {+ ...node,+ x: pivot.x + dx * cos - dy * sin,+ y: pivot.y + dx * sin + dy * cos,+ };+ });+ return {+ ...mesh,+ nodes: nextNodes,+ rotationDeg: normalizeMeshAngleDeg(baseRotationDeg + deltaDeg),+ };+}++export function setGradientMeshRotation(+ mesh: GradientMeshState,+ targetDeg: number,+ pivot?: Point2D+): GradientMeshState {+ if (!Number.isFinite(targetDeg)) return mesh;+ const current = mesh.rotationDeg ?? 0;+ const delta = targetDeg - current;+ const rotated = rotateGradientMeshVertices(mesh, delta, pivot);+ return {+ ...rotated,+ rotationDeg: normalizeMeshAngleDeg(targetDeg),+ };+}++export function updateGradientMeshNodes(+ mesh: GradientMeshState,+ indices: readonly number[],+ patch: { color?: string; opacity?: number }+): GradientMeshState {+ if (indices.length === 0 || mesh.nodes.length === 0) return mesh;+ const targetSet = new Set(indices);+ let changed = false;+ const nextNodes = mesh.nodes.map((node, i) => {+ if (!targetSet.has(i)) return node;+ const nextColor = patch.color !== undefined ? patch.color : node.color;+ const nextOpacity =+ patch.opacity !== undefined+ ? Math.max(0, Math.min(1, patch.opacity))+ : node.opacity;+ if (nextColor === node.color && nextOpacity === node.opacity) return node;+ changed = true;+ return { ...node, color: nextColor, opacity: nextOpacity };+ });+ return changed ? { ...mesh, nodes: nextNodes } : mesh;+}+function blendChannel(src: number, dst: number, mode: GradientBlendMode): number {const s = src / 255;const d = dst / 255;diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.tsindex 8ab14c5..224b666 100644--- a/src/utils/imageLoader.ts+++ b/src/utils/imageLoader.ts@@ -148,6 +148,7 @@ export async function openFile(file: File): Promise<LoadedDocument> {perspectiveRuler: project.perspectiveRuler ?? null,animationTimeline: project.animationTimeline ?? null,timelapse: project.timelapse ?? null,+ ...(project.timelapseFrames ? { timelapseFrames: project.timelapseFrames } : {}),workTimeMs: project.workTimeMs,previewDataUrl: project.previewDataUrl,};diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.tsindex ec6ba8e..6ea166b 100644--- a/src/utils/inkbBrushFormat.ts+++ b/src/utils/inkbBrushFormat.ts@@ -114,6 +114,9 @@ const VALID_CATEGORIES = new Set<BrushCategory | 'custom'>(['brush','blend','natural-paint',+ 'deco-background',+ 'deco-clothing',+ 'deco-effect','custom',]);const VALID_BRUSH_COMBINE_MODES = new Set<CspBrushCombineMode>([@@ -462,6 +465,33 @@ export function sanitizeBrushFileName(name: string): string {return `${safeBase}${INKB_EXTENSION}`;}+function imageToPngDataUrl(img?: HTMLImageElement | null): string | undefined {+ if (!img || !img.complete || typeof document === 'undefined') return undefined;+ const w = img.naturalWidth || img.width;+ const h = img.naturalHeight || img.height;+ if (!w || !h) return undefined;+ try {+ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ if (!ctx) return undefined;+ ctx.drawImage(img, 0, 0);+ return canvas.toDataURL('image/png');+ } catch {+ return undefined;+ }+}++function resolveExportDataUrl(+ url?: string,+ img?: HTMLImageElement | null+): string | undefined {+ if (!url) return undefined;+ if (SAFE_RASTER_DATA_URL_RE.test(url)) return url;+ return imageToPngDataUrl(img) ?? url;+}+/*** Converts any active or listed brush (built-in or custom) into a self-contained CspBrush* suitable for serialization to a `.inkb` file.@@ -480,6 +510,18 @@ export function buildExportableBrush(};const name = sanitizeBrushName(merged.brushName || existingCustom?.name || presetId);+ const exportTipDataUrl = resolveExportDataUrl(+ merged.customTipDataUrl ?? existingCustom?.tipDataUrl,+ merged.customTipImage+ );+ const rawSubTips = merged.subTips ?? existingCustom?.subTips;+ const exportSubTips = rawSubTips+ ? rawSubTips.map((st, idx) => ({+ ...st,+ dataUrl:+ resolveExportDataUrl(st.dataUrl, merged.subTipImages?.[idx]) ?? st.dataUrl,+ }))+ : undefined;return {id: existingCustom?.id || `inkb-${presetId}`,@@ -487,13 +529,13 @@ export function buildExportableBrush(category: existingCustom?.category,badge: 'INKB',desc: existingCustom?.desc,- tipDataUrl: merged.customTipDataUrl ?? existingCustom?.tipDataUrl,+ tipDataUrl: exportTipDataUrl,tipWidth: existingCustom?.tipWidth,tipHeight: existingCustom?.tipHeight,secondaryTipDataUrl: merged.dualTipDataUrl ?? existingCustom?.secondaryTipDataUrl,secondaryTipWidth: existingCustom?.secondaryTipWidth,secondaryTipHeight: existingCustom?.secondaryTipHeight,- subTips: merged.subTips ?? existingCustom?.subTips,+ subTips: exportSubTips,subTipOrder: merged.subTipOrder ?? existingCustom?.subTipOrder,size: clampNum(merged.size, 0.5, 2000, 12),brushSizeUnit: merged.brushSizeUnit,@@ -509,6 +551,8 @@ export function buildExportableBrush(angle: clampNum(merged.customTipAngle ?? existingCustom?.angle, -360, 360, 0),angleDynamics: merged.customTipAngleDynamics ?? existingCustom?.angleDynamics,rotationRandomScale: merged.customTipRotationRandomScale ?? existingCustom?.rotationRandomScale,+ rotateCursor:+ 'rotateCursor' in merged ? merged.rotateCursor : existingCustom?.rotateCursor,flipH: merged.flipH,flipV: merged.flipV,antiAlias: merged.antiAlias,@@ -728,6 +772,7 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink? (b.angleDynamics as CspAngleDynamicsMode): undefined,rotationRandomScale: optNum(b.rotationRandomScale, 0, 1),+ rotateCursor: optBool(b.rotateCursor),flipH:typeof b.flipH === 'string' && VALID_FLIP_MODES.has(b.flipH as CspTipFlipMode)? (b.flipH as CspTipFlipMode)diff --git a/src/utils/interfaceScale.ts b/src/utils/interfaceScale.tsnew file mode 100644index 0000000..beb2d5c--- /dev/null+++ b/src/utils/interfaceScale.ts@@ -0,0 +1,91 @@+import { isTauriEnvironment } from './tileEngine/scratchDriver';++export const MIN_INTERFACE_SCALE = 60;+export const MAX_INTERFACE_SCALE = 200;+export const DEFAULT_INTERFACE_SCALE = 100;+export const INTERFACE_SCALE_STEP = 5;+export const INTERFACE_SCALE_PRESETS = [60, 80, 100, 125, 150, 200] as const;++let activeNativeWebviewZoom = 1;+let lastAppliedNativeScale: number | null = null;++/**+ * Clamps and normalizes an interface scale percentage into the supported [60, 200] range.+ */+export function clampInterfaceScale(value: unknown): number {+ if (typeof value !== 'number' || !Number.isFinite(value)) {+ return DEFAULT_INTERFACE_SCALE;+ }+ return Math.max(MIN_INTERFACE_SCALE, Math.min(MAX_INTERFACE_SCALE, Math.round(value)));+}++/**+ * Returns the active Tauri native WebView zoom factor (1.0 when running in web mode or at 100%).+ * Used by native tablet input to convert OS window client coordinates into zoomed CSS pixels.+ */+export function getActiveNativeWebviewZoom(): number {+ return activeNativeWebviewZoom;+}++/**+ * Resets internal interface scale tracking state (primarily for unit tests).+ */+export function resetInterfaceScaleState(): void {+ activeNativeWebviewZoom = 1;+ lastAppliedNativeScale = null;+}++/**+ * Applies the user's interface scale (60%–200%) across the application.+ * - On Tauri desktop, uses the native WebView zoom API (`getCurrentWebview().setZoom`) so all+ * DOM coordinates, floating panels, modals, HiDPI canvas backing buffers, and pointer events+ * remain 100% geometrically aligned.+ * - On Web browsers, falls back to root CSS `zoom`.+ */+export async function applyInterfaceScale(percent: number): Promise<number> {+ const clamped = clampInterfaceScale(percent);+ const factor = clamped / 100;++ if (typeof document !== 'undefined' && document.documentElement) {+ const root = document.documentElement;+ if (typeof root.setAttribute === 'function') {+ root.setAttribute('data-ui-scale', String(clamped));+ }+ if (root.style) {+ if (typeof root.style.setProperty === 'function') {+ root.style.setProperty('--ui-scale', String(factor));+ }++ if (!isTauriEnvironment()) {+ activeNativeWebviewZoom = 1;+ lastAppliedNativeScale = null;+ root.style.zoom = clamped === DEFAULT_INTERFACE_SCALE ? '' : String(factor);+ return clamped;+ }++ // Clear any web CSS zoom when native WebView zoom is active+ root.style.zoom = '';+ } else if (!isTauriEnvironment()) {+ activeNativeWebviewZoom = 1;+ lastAppliedNativeScale = null;+ return clamped;+ }+ }++ if (isTauriEnvironment()) {+ activeNativeWebviewZoom = factor;+ if (lastAppliedNativeScale !== clamped) {+ lastAppliedNativeScale = clamped;+ try {+ const { getCurrentWebview } = await import('@tauri-apps/api/webview');+ await getCurrentWebview().setZoom(factor);+ } catch (err) {+ console.warn('Failed to apply native WebView interface scale:', err);+ }+ }+ } else {+ activeNativeWebviewZoom = 1;+ }++ return clamped;+}diff --git a/src/utils/legacySoraMigrator.ts b/src/utils/legacySoraMigrator.tsindex e399929..028b665 100644--- a/src/utils/legacySoraMigrator.ts+++ b/src/utils/legacySoraMigrator.ts@@ -203,6 +203,7 @@ export async function migrateLegacySoraFile(file: File): Promise<LoadedDocument>perspectiveRuler: migrated.perspectiveRuler ?? null,animationTimeline: migrated.animationTimeline ?? null,timelapse: migrated.timelapse ?? null,+ ...(migrated.timelapseFrames ? { timelapseFrames: migrated.timelapseFrames } : {}),workTimeMs: migrated.workTimeMs,previewDataUrl: migrated.previewDataUrl,};diff --git a/src/utils/nativeOsHotkeys.ts b/src/utils/nativeOsHotkeys.tsnew file mode 100644index 0000000..8479471--- /dev/null+++ b/src/utils/nativeOsHotkeys.ts@@ -0,0 +1,191 @@+/**+ * Native Windows OS-key (Windows key) hotkey bridge for Tauri desktop builds.+ *+ * When Ink Studio is the foreground window on Windows, registers a lightweight, on-demand+ * WH_KEYBOARD_LL hook ONLY for user-configured `OS+...` shortcuts (or while actively recording+ * a shortcut) so Windows Shell does not hijack bound combinations (e.g. Win+1, Win+E, Win+Q)+ * or pop up the Start Menu. Safe no-op in Web/browser and test environments.+ */++import { isTauriEnvironment } from './tileEngine/scratchDriver';+import {+ CommandDefinition,+ KeyboardEventLike,+ parseShortcut,+ resolveCommandShortcut,+} from './shortcutManager';+import { ShortcutOverrides } from '../types/settings';++export interface NativeOsHotkeyBinding {+ code: string;+ ctrl: boolean;+ shift: boolean;+ alt: boolean;+}++export interface NativeOsHotkeyEvent extends KeyboardEventLike {+ phase: 'keydown' | 'keyup';+ code: string;+ key: string;+ ctrlKey: boolean;+ metaKey: boolean;+ shiftKey: boolean;+ altKey: boolean;+ repeat: boolean;+ isRecording: boolean;+}++export type NativeOsHotkeyListener = (event: NativeOsHotkeyEvent) => void;++const listeners = new Set<NativeOsHotkeyListener>();+let activeRecordingCount = 0;+let lastBindings: NativeOsHotkeyBinding[] = [];+let lastSentSignature = '';+let activeChannel: unknown = null;++/**+ * Extracts all unique OS/Win-key (`meta: true`) bindings from the active command registry+ * + shortcut overrides, including alternate key codes (e.g. Numpad0 for Digit0).+ */+export function extractNativeOsHotkeyBindings(+ commands: readonly CommandDefinition[],+ overrides?: ShortcutOverrides+): NativeOsHotkeyBinding[] {+ const seen = new Set<string>();+ const bindings: NativeOsHotkeyBinding[] = [];++ const pushCode = (code: string, ctrl: boolean, shift: boolean, alt: boolean) => {+ const key = `${code}|${ctrl ? 1 : 0}|${shift ? 1 : 0}|${alt ? 1 : 0}`;+ if (seen.has(key)) return;+ seen.add(key);+ bindings.push({ code, ctrl, shift, alt });+ };++ const inspectRaw = (raw: string) => {+ const parsed = parseShortcut(raw);+ if (!parsed || !parsed.meta) return;+ pushCode(parsed.code, parsed.ctrl, parsed.shift, parsed.alt);+ if (parsed.altCodes) {+ for (const altCode of parsed.altCodes) {+ pushCode(altCode, parsed.ctrl, parsed.shift, parsed.alt);+ }+ }+ };++ for (const cmd of commands) {+ const bound = resolveCommandShortcut(cmd, overrides);+ if (bound) inspectRaw(bound);+ }++ // Also include any OS-key overrides whose dynamic command might not be synced yet+ if (overrides) {+ for (const val of Object.values(overrides)) {+ if (val) inspectRaw(val);+ }+ }++ return bindings;+}++function buildSignature(bindings: readonly NativeOsHotkeyBinding[], recording: boolean): string {+ const sorted = bindings+ .map((b) => `${b.code}:${b.ctrl ? 1 : 0}${b.shift ? 1 : 0}${b.alt ? 1 : 0}`)+ .sort()+ .join(',');+ return `${recording ? 'R' : 'N'}|${sorted}`;+}++async function flushNativeSync(): Promise<void> {+ const recording = activeRecordingCount > 0;+ const sig = buildSignature(lastBindings, recording);+ if (sig === lastSentSignature && activeChannel !== null) return;++ if (!isTauriEnvironment()) {+ lastSentSignature = sig;+ return;+ }++ try {+ const { invoke, Channel } = await import('@tauri-apps/api/core');+ if (lastBindings.length === 0 && !recording) {+ if (activeChannel !== null) {+ await invoke('os_hotkeys_stop');+ }+ lastSentSignature = sig;+ return;+ }++ if (!activeChannel) {+ const ch = new Channel<NativeOsHotkeyEvent>();+ ch.onmessage = (ev: NativeOsHotkeyEvent) => {+ for (const fn of Array.from(listeners)) {+ try {+ fn(ev);+ } catch (err) {+ console.error('Native OS hotkey listener error:', err);+ }+ }+ };+ activeChannel = ch;+ }++ await invoke('os_hotkeys_sync', {+ bindings: lastBindings,+ recording,+ onEvent: activeChannel,+ });+ lastSentSignature = sig;+ } catch {+ // Non-desktop or unavailable backend: keep silent fallback to DOM KeyboardEvents+ }+}++export function syncNativeOsHotkeys(+ commands: readonly CommandDefinition[],+ overrides?: ShortcutOverrides+): void {+ lastBindings = extractNativeOsHotkeyBindings(commands, overrides);+ void flushNativeSync();+}++/**+ * Marks shortcut recording active/inactive so the native Windows hook temporarily captures+ * any `Win + <key>` combination without triggering Windows Shell actions.+ * Returns a cleanup function that decrements the recording ref-count.+ */+export function acquireNativeOsHotkeyRecording(): () => void {+ activeRecordingCount += 1;+ void flushNativeSync();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ activeRecordingCount = Math.max(0, activeRecordingCount - 1);+ void flushNativeSync();+ };+}++export function subscribeNativeOsHotkeys(listener: NativeOsHotkeyListener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++export function stopNativeOsHotkeys(): void {+ lastBindings = [];+ activeRecordingCount = 0;+ lastSentSignature = '';+ activeChannel = null;+ if (!isTauriEnvironment()) return;+ void import('@tauri-apps/api/core')+ .then(({ invoke }) => invoke('os_hotkeys_stop'))+ .catch(() => {});+}++/** Test helper for dispatching synthetic native OS-key events in Vitest */+export function dispatchNativeOsHotkeyForTest(event: NativeOsHotkeyEvent): void {+ for (const fn of Array.from(listeners)) {+ fn(event);+ }+}diff --git a/src/utils/nativeTabletInput.ts b/src/utils/nativeTabletInput.tsindex a38c37b..667aca7 100644--- a/src/utils/nativeTabletInput.ts+++ b/src/utils/nativeTabletInput.ts@@ -4,6 +4,7 @@*/import { isTauriEnvironment } from './tileEngine/scratchDriver';+import { getActiveNativeWebviewZoom } from './interfaceScale';export type TabletInputMode = 'auto' | 'wintab' | 'windows-ink' | 'off';@@ -195,6 +196,24 @@ export function subscribeNativeTablet(listener: TabletSampleBatchListener): () =};}+/**+ * Converts OS logical client coordinates emitted by `tablet_input.rs` into zoomed WebView CSS+ * pixel coordinates when native WebView interface scaling is active.+ */+export function adjustTabletSamplesForWebviewZoom(+ samples: NativeTabletSample[],+ zoomFactor: number = getActiveNativeWebviewZoom()+): NativeTabletSample[] {+ if (!Number.isFinite(zoomFactor) || zoomFactor <= 0 || Math.abs(zoomFactor - 1) <= 1e-4) {+ return samples;+ }+ for (let i = 0; i < samples.length; i++) {+ samples[i].clientX /= zoomFactor;+ samples[i].clientY /= zoomFactor;+ }+ return samples;+}+export async function startNativeTablet(mode: TabletInputMode = 'auto'): Promise<NativeTabletStatus> {if (!isTauriEnvironment()) {return activeStatus;@@ -210,7 +229,7 @@ export async function startNativeTablet(mode: TabletInputMode = 'auto'): Promiseconst { invoke, Channel } = await import('@tauri-apps/api/core');const channel = new Channel<ArrayBuffer | Uint8Array | number[]>();channel.onmessage = (payload) => {- const batch = unpackTabletSampleBatch(payload);+ const batch = adjustTabletSamplesForWebviewZoom(unpackTabletSampleBatch(payload));if (batch.length === 0) return;recordNativeTabletBatchForSuppression(batch);for (const fn of listeners) {diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.tsindex 0951215..c941718 100644--- a/src/utils/presetBrushes.ts+++ b/src/utils/presetBrushes.ts@@ -37,6 +37,32 @@ import {getSurfaceTextureDataUrl,} from './proceduralBrushTips';+import {+ DECORATION_BRUSHES,+ DECORATION_BRUSH_SECTIONS,+ DEFAULT_DECORATION_PRESET_ID,+ isDecorationCategory,+ isDecorationPresetId,+ resolveStaticBrushAssetUrl,+} from './decorationBrushes';++export {+ DECORATION_BRUSHES,+ DECORATION_BRUSH_SECTIONS,+ DEFAULT_DECORATION_PRESET_ID,+ isDecorationCategory,+ isDecorationPresetId,+ resolveStaticBrushAssetUrl,+};++export interface StaticBrushTip {+ assetPath: string;+ width: number;+ height: number;+ isColor?: boolean;+ isDualToneTip?: boolean;+}+export interface BuiltinBrushDefinition {id: BrushPresetId;category: BrushCategory;@@ -46,11 +72,12 @@ export interface BuiltinBrushDefinition {badgeText: string;badgeBorder: string;desc: string;- icon: 'pen' | 'pencil' | 'paintbrush' | 'droplets' | 'palette';+ icon: 'pen' | 'pencil' | 'paintbrush' | 'droplets' | 'palette' | 'sparkles';settings: Partial<BrushSettings>;tipGenerator?: () => string; // Returns Base64 PNG data URLsubTipGenerators?: Array<() => string>; // Multi-tip procedural generators (e.g., Rough Pen ribbon, Canvas Scumble)subTipDimensions?: { width: number; height: number }; // Explicit dimensions for subTips metadata (default 256x256)+ staticTips?: StaticBrushTip[]; // Pre-extracted static PNG brush tips (e.g., CSP Decoration brushes)dualTipGenerator?: () => string; // Optional secondary tip generator for built-in Dual BrushespaperTextureGenerator?: () => string; // Returns seamless Base64 PNG data URL}@@ -68,12 +95,18 @@ export const BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [{ id: 'natural-paint', label: 'Natural Paint' },];+export const ALL_BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [+ ...BUILTIN_BRUSH_SECTIONS,+ ...DECORATION_BRUSH_SECTIONS,+];+const preloadedTipImages = new Map<string, HTMLImageElement>();export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement | undefined {if (!dataUrl || typeof Image === 'undefined') return undefined;const cached = preloadedTipImages.get(dataUrl);if (cached) return cached;const img = new Image();+ img.crossOrigin = 'anonymous';img.src = dataUrl;if (typeof img.decode === 'function') {img.decode().catch(() => {});@@ -2055,7 +2088,21 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [},];+export const ALL_BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [+ ...BUILTIN_BRUSHES,+ ...DECORATION_BRUSHES,+];++const ALL_BUILTIN_BRUSH_MAP = new Map<string, BuiltinBrushDefinition>(+ ALL_BUILTIN_BRUSHES.map((b) => [b.id, b])+);++export function findBuiltinBrush(presetId: BrushPresetId): BuiltinBrushDefinition | undefined {+ return ALL_BUILTIN_BRUSH_MAP.get(presetId);+}+let _assetsPrewarmed = false;+let _decorationAssetsPrewarmed = false;/*** Decodes all procedural builtin tip and paper PNG images into browser memory once@@ -2087,6 +2134,22 @@ export function prewarmBuiltinBrushAssets(): void {}}+/**+ * Lazily prewarms static PNG tip assets for the Decoration tool group on first use.+ */+export function prewarmDecorationBrushAssets(): void {+ if (_decorationAssetsPrewarmed || typeof Image === 'undefined') return;+ _decorationAssetsPrewarmed = true;+ for (let i = 0; i < DECORATION_BRUSHES.length; i++) {+ const tips = DECORATION_BRUSHES[i].staticTips;+ if (!tips) continue;+ for (let j = 0; j < tips.length; j++) {+ const url = resolveStaticBrushAssetUrl(tips[j].assetPath);+ if (url) getPreloadedBuiltinTipImage(url);+ }+ }+}+// Schedule non-blocking prewarm in browser environments after initial paintif (typeof window !== 'undefined' && typeof document !== 'undefined') {const scheduleWarm =@@ -2094,14 +2157,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'function'? (window as unknown as { requestIdleCallback: (cb: () => void) => number }).requestIdleCallback: (cb: () => void) => window.setTimeout(cb, 60);- scheduleWarm(() => prewarmBuiltinBrushAssets());+ scheduleWarm(() => {+ prewarmBuiltinBrushAssets();+ prewarmDecorationBrushAssets();+ });}/**- * Returns the full brush settings for a builtin preset.+ * Returns the full brush settings for a builtin preset (Brush or Decoration).*/export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSettings> | null {- const def = BUILTIN_BRUSHES.find((b) => b.id === presetId);+ const def = ALL_BUILTIN_BRUSH_MAP.get(presetId);if (!def) return null;let tipDataUrl: string | undefined = undefined;@@ -2115,7 +2181,34 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSetlet subTips: CspSubTip[] | undefined = undefined;let subTipImages: HTMLImageElement[] | undefined = undefined;- if (def.subTipGenerators && def.subTipGenerators.length > 0) {+ if (def.staticTips && def.staticTips.length > 0) {+ const builtSubTips: CspSubTip[] = [];+ const builtImages: HTMLImageElement[] = [];+ for (let i = 0; i < def.staticTips.length; i++) {+ const st = def.staticTips[i];+ const url = resolveStaticBrushAssetUrl(st.assetPath);+ if (!url) continue;+ builtSubTips.push({+ dataUrl: url,+ width: st.width,+ height: st.height,+ ...(st.isColor ? { isColor: true } : {}),+ ...(st.isDualToneTip ? { isDualToneTip: true } : {}),+ });+ const img = getPreloadedBuiltinTipImage(url);+ if (img) builtImages.push(img);+ }+ if (builtSubTips.length > 0) {+ tipDataUrl = builtSubTips[0].dataUrl;+ tipImage = builtImages[0];+ if (builtSubTips.length > 1) {+ subTips = builtSubTips;+ if (builtImages.length > 0) {+ subTipImages = builtImages;+ }+ }+ }+ } else if (def.subTipGenerators && def.subTipGenerators.length > 0) {const stW = def.subTipDimensions?.width ?? 256;const stH = def.subTipDimensions?.height ?? 256;const builtSubTips: CspSubTip[] = [];diff --git a/src/utils/primitives3D.ts b/src/utils/primitives3D.tsnew file mode 100644index 0000000..a0616d3--- /dev/null+++ b/src/utils/primitives3D.ts@@ -0,0 +1,101 @@+import * as THREE from 'three';++export type Primitive3DType = 'cube' | 'sphere' | 'capsule' | 'cylinder' | 'pyramid';++export interface Primitive3DMeta {+ type: Primitive3DType;+ label: string;+ description: string;+}++export const PRIMITIVE_3D_ITEMS: readonly Primitive3DMeta[] = [+ { type: 'cube', label: 'Cube', description: 'Create a 3D cube primitive' },+ { type: 'sphere', label: 'Sphere', description: 'Create a 3D sphere primitive' },+ { type: 'capsule', label: 'Capsule', description: 'Create a 3D capsule primitive' },+ { type: 'cylinder', label: 'Cylinder', description: 'Create a 3D cylinder primitive' },+ { type: 'pyramid', label: 'Pyramid', description: 'Create a 3D four-sided pyramid primitive' },+] as const;++export function getPrimitive3DMeta(type: Primitive3DType): Primitive3DMeta {+ return PRIMITIVE_3D_ITEMS.find((item) => item.type === type) ?? PRIMITIVE_3D_ITEMS[0];+}++/**+ * Builds clean, normalized BufferGeometry for a 3D reference primitive+ * with its base resting flush on Y = 0 and centered on X/Z.+ */+export function createPrimitive3DGeometry(type: Primitive3DType): THREE.BufferGeometry {+ let geom: THREE.BufferGeometry;++ switch (type) {+ case 'cube':+ geom = new THREE.BoxGeometry(1.4, 1.4, 1.4);+ break;+ case 'sphere':+ geom = new THREE.SphereGeometry(0.8, 36, 24);+ break;+ case 'capsule':+ geom = new THREE.CapsuleGeometry(0.48, 0.84, 16, 32);+ break;+ case 'cylinder':+ geom = new THREE.CylinderGeometry(0.65, 0.65, 1.6, 36, 1);+ break;+ case 'pyramid': {+ const raw = new THREE.ConeGeometry(0.95, 1.5, 4, 1);+ raw.rotateY(Math.PI / 4);+ // Use flat per-face normals so pyramid facets and LT lineart creases stay crisp+ geom = raw.toNonIndexed();+ raw.dispose();+ geom.computeVertexNormals();+ break;+ }+ }++ geom.computeBoundingBox();+ if (geom.boundingBox) {+ const center = new THREE.Vector3();+ geom.boundingBox.getCenter(center);+ geom.translate(-center.x, -geom.boundingBox.min.y, -center.z);+ geom.computeBoundingBox();+ geom.computeBoundingSphere();+ }++ return geom;+}++/**+ * Creates a ready-to-attach Three.js Group containing a studio-shaded 3D primitive mesh.+ */+export function createPrimitive3DObject(type: Primitive3DType): {+ group: THREE.Group;+ mesh: THREE.Mesh;+ displayName: string;+} {+ const meta = getPrimitive3DMeta(type);+ const geometry = createPrimitive3DGeometry(type);+ const material = new THREE.MeshStandardMaterial({+ color: 0xe2e8f0,+ roughness: 0.4,+ metalness: 0.08,+ side: THREE.DoubleSide,+ });++ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = `Primitive_${meta.label}`;+ mesh.castShadow = true;+ mesh.receiveShadow = true;+ mesh.userData.origGeometry = geometry;+ mesh.userData.origMaterial = material;+ mesh.userData.hasCustomMaterial = false;+ mesh.userData.primitiveType = type;++ const group = new THREE.Group();+ group.name = `PrimitiveGroup_${meta.label}`;+ group.add(mesh);++ return {+ group,+ mesh,+ displayName: meta.label,+ };+}diff --git a/src/utils/puppetWarpEngine.ts b/src/utils/puppetWarpEngine.tsnew file mode 100644index 0000000..1a0c0ff--- /dev/null+++ b/src/utils/puppetWarpEngine.ts@@ -0,0 +1,1394 @@+import {+ Point2D,+ PuppetMeshData,+ PuppetMeshDensity,+ PuppetPin,+ PuppetRigidityMode,+ PuppetWarpState,+} from '../types/editor';+import type { PixelBuffer } from './transformResampler';++export interface PuppetDeformedResult {+ x: Float32Array;+ y: Float32Array;+ triOrder?: Uint32Array;+}++export interface PuppetMeshBounds {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+ width: number;+ height: number;+}++const SQRT3_OVER_2 = Math.sqrt(3) * 0.5;+const PIN_POS_WEIGHT = 1000.0;+const PIN_ROT_WEIGHT = 450.0;+const TIKHONOV_EPS = 1e-6;++/**+ * Computes barycentric coordinates (b0, b1, b2) of point (px, py) with respect to+ * triangle (ax, ay) - (bx, by) - (cx, cy). Returns null for degenerate triangles.+ */+export function computeBarycentric(+ px: number,+ py: number,+ ax: number,+ ay: number,+ bx: number,+ by: number,+ cx: number,+ cy: number+): [number, number, number] | null {+ const v0x = bx - ax;+ const v0y = by - ay;+ const v1x = cx - ax;+ const v1y = cy - ay;+ const det = v0x * v1y - v1x * v0y;+ if (Math.abs(det) < 1e-8) return null;+ const invDet = 1 / det;+ const v2x = px - ax;+ const v2y = py - ay;+ const b1 = (v2x * v1y - v1x * v2y) * invDet;+ const b2 = (v0x * v2y - v2x * v0y) * invDet;+ const b0 = 1 - b1 - b2;+ return [b0, b1, b2];+}++/**+ * Closest point on a triangle to (px, py), returning clamped barycentric coordinates+ * and squared distance.+ */+function closestPointOnTriangleBary(+ px: number,+ py: number,+ ax: number,+ ay: number,+ bx: number,+ by: number,+ cx: number,+ cy: number+): { b0: number; b1: number; b2: number; distSq: number } {+ const bary = computeBarycentric(px, py, ax, ay, bx, by, cx, cy);+ if (bary && bary[0] >= -1e-6 && bary[1] >= -1e-6 && bary[2] >= -1e-6) {+ const b0 = Math.max(0, bary[0]);+ const b1 = Math.max(0, bary[1]);+ const b2 = Math.max(0, bary[2]);+ const s = b0 + b1 + b2 || 1;+ return { b0: b0 / s, b1: b1 / s, b2: b2 / s, distSq: 0 };+ }++ // Project onto each of the 3 edges and take the closest+ const projEdge = (x0: number, y0: number, x1: number, y1: number) => {+ const dx = x1 - x0;+ const dy = y1 - y0;+ const lenSq = dx * dx + dy * dy;+ const t = lenSq > 1e-10 ? Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / lenSq)) : 0;+ const qx = x0 + t * dx;+ const qy = y0 + t * dy;+ return { t, distSq: (px - qx) * (px - qx) + (py - qy) * (py - qy) };+ };++ const e01 = projEdge(ax, ay, bx, by);+ const e12 = projEdge(bx, by, cx, cy);+ const e20 = projEdge(cx, cy, ax, ay);++ if (e01.distSq <= e12.distSq && e01.distSq <= e20.distSq) {+ return { b0: 1 - e01.t, b1: e01.t, b2: 0, distSq: e01.distSq };+ }+ if (e12.distSq <= e20.distSq) {+ return { b0: 0, b1: 1 - e12.t, b2: e12.t, distSq: e12.distSq };+ }+ return { b0: e20.t, b1: 0, b2: 1 - e20.t, distSq: e20.distSq };+}++/**+ * Evaluates bilinear mapping of unit square (u, v) onto quad [TL, TR, BR, BL].+ */+function evalBilinearQuad(+ quad: [Point2D, Point2D, Point2D, Point2D],+ u: number,+ v: number+): Point2D {+ const [q0, q1, q2, q3] = quad;+ const w00 = (1 - u) * (1 - v);+ const w10 = u * (1 - v);+ const w11 = u * v;+ const w01 = (1 - u) * v;+ return {+ x: w00 * q0.x + w10 * q1.x + w11 * q2.x + w01 * q3.x,+ y: w00 * q0.y + w10 * q1.y + w11 * q2.y + w01 * q3.y,+ };+}++/**+ * Builds an equilateral-lattice silhouette-conforming triangle mesh over the opaque+ * regions of `sourcePixels` (with `expansion` px padding so thin lines & AA halos+ * are never clipped and narrow lineart gaps bridge cleanly).+ */+export function buildPuppetMesh(+ sourcePixels: PixelBuffer | undefined,+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D],+ density: PuppetMeshDensity = 'normal',+ expansion = 6+): PuppetMeshData {+ const sw = Math.max(1, sourceWidth);+ const sh = Math.max(1, sourceHeight);+ const safeExpansion = Math.max(0, Math.min(48, expansion));++ // Build an integral image (summed-area table) over a fast occupancy grid so we can+ // test whether any triangle's expanded bbox touches any opaque pixel in O(1).+ const occScale = Math.max(1, Math.floor(Math.max(sw, sh) / 512));+ const occW = Math.max(1, Math.ceil(sw / occScale));+ const occH = Math.max(1, Math.ceil(sh / occScale));+ const integral = new Int32Array((occW + 1) * (occH + 1));++ let opaqueCells = 0;+ const hasPixels = Boolean(sourcePixels && sourcePixels.data.length >= sw * sh * 4);+ if (hasPixels && sourcePixels) {+ const data = sourcePixels.data;+ const occ = new Uint8Array(occW * occH);+ for (let y = 0; y < sh; y++) {+ const oy = (y / occScale) | 0;+ const rowOff = y * sw * 4;+ const occRow = oy * occW;+ for (let x = 0; x < sw; x++) {+ if (data[rowOff + (x << 2) + 3] > 2) {+ occ[occRow + ((x / occScale) | 0)] = 1;+ }+ }+ }+ for (let oy = 0; oy < occH; oy++) {+ let rowSum = 0;+ const prevRow = oy * (occW + 1);+ const currRow = (oy + 1) * (occW + 1);+ const occRow = oy * occW;+ for (let ox = 0; ox < occW; ox++) {+ const v = occ[occRow + ox];+ if (v) opaqueCells++;+ rowSum += v;+ integral[currRow + ox + 1] = integral[prevRow + ox + 1] + rowSum;+ }+ }+ } else {+ opaqueCells = occW * occH;+ for (let oy = 0; oy < occH; oy++) {+ const prevRow = oy * (occW + 1);+ const currRow = (oy + 1) * (occW + 1);+ for (let ox = 0; ox < occW; ox++) {+ integral[currRow + ox + 1] = integral[prevRow + ox + 1] + (ox + 1);+ }+ }+ }++ const hasAnyOpaque = opaqueCells > 0;+ const queryHasOpaque = (minX: number, minY: number, maxX: number, maxY: number): boolean => {+ if (!hasAnyOpaque) return true;+ const gx0 = Math.max(0, Math.floor((minX - safeExpansion) / occScale));+ const gy0 = Math.max(0, Math.floor((minY - safeExpansion) / occScale));+ const gx1 = Math.min(occW, Math.ceil((maxX + safeExpansion) / occScale));+ const gy1 = Math.min(occH, Math.ceil((maxY + safeExpansion) / occScale));+ if (gx1 <= gx0 || gy1 <= gy0) return false;+ const stride = occW + 1;+ const sum =+ integral[gy1 * stride + gx1] -+ integral[gy0 * stride + gx1] -+ integral[gy1 * stride + gx0] ++ integral[gy0 * stride + gx0];+ return sum > 0;+ };++ // Estimate effective padded opaque area to adapt equilateral triangle edge step+ const cellAreaPx = occScale * occScale;+ const rawOpaqueArea = hasAnyOpaque ? opaqueCells * cellAreaPx : sw * sh;+ const perimeterEst = 4 * Math.sqrt(Math.max(1, rawOpaqueArea));+ const paddedArea = Math.min(+ (sw + safeExpansion * 2) * (sh + safeExpansion * 2),+ Math.max(1, rawOpaqueArea + perimeterEst * (safeExpansion + 4))+ );++ const targetVerts = density === 'coarse' ? 170 : density === 'fine' ? 680 : 360;+ const idealStep = Math.sqrt(paddedArea / (SQRT3_OVER_2 * targetVerts));+ const minDim = Math.min(sw, sh);+ const maxDim = Math.max(sw, sh);+ const minStep = Math.max(4, maxDim / 54);+ const maxStep = Math.max(8, Math.min(maxDim / 4, Math.max(minDim / 2, maxDim / 10)));+ const step = Math.max(minStep, Math.min(maxStep, idealStep));+ const rowStep = step * SQRT3_OVER_2;++ // Pad lattice slightly past [0, sw] x [0, sh] so border pixels & expansion fit cleanly+ const margin = Math.min(step * 0.75, safeExpansion + 2);+ const startX = -margin - step * 0.5;+ const startY = -margin;+ const endX = sw + margin + step * 0.5;+ const endY = sh + margin;++ const gridCols = Math.max(2, Math.ceil((endX - startX) / step) + 1);+ const gridRows = Math.max(2, Math.ceil((endY - startY) / rowStep) + 1);++ const latticeX = (r: number, c: number) => startX + c * step + ((r & 1) ? step * 0.5 : 0);+ const latticeY = (r: number) => startY + r * rowStep;++ // Candidate equilateral triangles from staggered hex lattice+ const rawTris: number[] = [];+ const usedLattice = new Uint8Array(gridRows * gridCols);++ const tryAddTri = (r0: number, c0: number, r1: number, c1: number, r2: number, c2: number) => {+ const x0 = latticeX(r0, c0);+ const y0 = latticeY(r0);+ const x1 = latticeX(r1, c1);+ const y1 = latticeY(r1);+ const x2 = latticeX(r2, c2);+ const y2 = latticeY(r2);++ const tMinX = Math.min(x0, x1, x2);+ const tMaxX = Math.max(x0, x1, x2);+ const tMinY = Math.min(y0, y1, y2);+ const tMaxY = Math.max(y0, y1, y2);++ if (tMaxX < 0 || tMinX > sw || tMaxY < 0 || tMinY > sh) return;+ if (!queryHasOpaque(tMinX, tMinY, tMaxX, tMaxY)) return;++ const i0 = r0 * gridCols + c0;+ const i1 = r1 * gridCols + c1;+ const i2 = r2 * gridCols + c2;+ usedLattice[i0] = 1;+ usedLattice[i1] = 1;+ usedLattice[i2] = 1;+ rawTris.push(i0, i1, i2);+ };++ for (let r = 0; r < gridRows - 1; r++) {+ const isOdd = (r & 1) === 1;+ for (let c = 0; c < gridCols - 1; c++) {+ if (!isOdd) {+ // Even row r -> odd row r+1 (shifted +0.5 step)+ // Triangle A: (r, c), (r, c+1), (r+1, c)+ tryAddTri(r, c, r, c + 1, r + 1, c);+ // Triangle B: (r, c+1), (r+1, c+1), (r+1, c)+ tryAddTri(r, c + 1, r + 1, c + 1, r + 1, c);+ } else {+ // Odd row r (shifted +0.5 step) -> even row r+1+ // Triangle A: (r, c), (r+1, c+1), (r+1, c)+ tryAddTri(r, c, r + 1, c + 1, r + 1, c);+ // Triangle B: (r, c), (r, c+1), (r+1, c+1)+ tryAddTri(r, c, r, c + 1, r + 1, c + 1);+ }+ }+ }++ // Fallback if somehow no triangles were selected (e.g., 1x1 fully transparent)+ if (rawTris.length === 0) {+ const fallbackQuad: [Point2D, Point2D, Point2D, Point2D] = [+ evalBilinearQuad(quad, 0, 0),+ evalBilinearQuad(quad, 1, 0),+ evalBilinearQuad(quad, 1, 1),+ evalBilinearQuad(quad, 0, 1),+ ];+ return {+ sourceWidth: sw,+ sourceHeight: sh,+ restLocalX: new Float32Array([0, sw, sw, 0]),+ restLocalY: new Float32Array([0, 0, sh, sh]),+ restWorldX: new Float32Array(fallbackQuad.map((p) => p.x)),+ restWorldY: new Float32Array(fallbackQuad.map((p) => p.y)),+ uvX: new Float32Array([0, 1, 1, 0]),+ uvY: new Float32Array([0, 0, 1, 1]),+ triangles: new Uint32Array([0, 1, 2, 0, 2, 3]),+ edges: new Uint32Array([0, 1, 1, 2, 2, 3, 3, 0, 0, 2]),+ componentId: new Int32Array([0, 0, 0, 0]),+ componentCount: 1,+ density,+ expansion: safeExpansion,+ };+ }++ // Assign compact vertex indices along the SHORTER axis to minimize Skyline Cholesky bandwidth+ const latticeToCompact = new Int32Array(gridRows * gridCols).fill(-1);+ const sweepColsFirst = gridCols > gridRows;+ let vertCount = 0;++ if (sweepColsFirst) {+ for (let c = 0; c < gridCols; c++) {+ for (let r = 0; r < gridRows; r++) {+ const idx = r * gridCols + c;+ if (usedLattice[idx]) {+ latticeToCompact[idx] = vertCount++;+ }+ }+ }+ } else {+ for (let r = 0; r < gridRows; r++) {+ for (let c = 0; c < gridCols; c++) {+ const idx = r * gridCols + c;+ if (usedLattice[idx]) {+ latticeToCompact[idx] = vertCount++;+ }+ }+ }+ }++ const restLocalX = new Float32Array(vertCount);+ const restLocalY = new Float32Array(vertCount);+ const restWorldX = new Float32Array(vertCount);+ const restWorldY = new Float32Array(vertCount);+ const uvX = new Float32Array(vertCount);+ const uvY = new Float32Array(vertCount);++ for (let r = 0; r < gridRows; r++) {+ const ly = latticeY(r);+ const v = ly / sh;+ for (let c = 0; c < gridCols; c++) {+ const compact = latticeToCompact[r * gridCols + c];+ if (compact < 0) continue;+ const lx = latticeX(r, c);+ const u = lx / sw;+ const world = evalBilinearQuad(quad, u, v);+ restLocalX[compact] = lx;+ restLocalY[compact] = ly;+ restWorldX[compact] = world.x;+ restWorldY[compact] = world.y;+ uvX[compact] = u;+ uvY[compact] = v;+ }+ }++ const triangles = new Uint32Array(rawTris.length);+ for (let i = 0; i < rawTris.length; i++) {+ triangles[i] = latticeToCompact[rawTris[i]];+ }++ // Collect unique edges and compute connected components via BFS+ const adj: number[][] = Array.from({ length: vertCount }, () => []);+ const edgeSet = new Set<number>();+ const edgeList: number[] = [];++ const registerEdge = (a: number, b: number) => {+ const lo = a < b ? a : b;+ const hi = a < b ? b : a;+ const key = lo * vertCount + hi;+ if (!edgeSet.has(key)) {+ edgeSet.add(key);+ edgeList.push(lo, hi);+ adj[lo].push(hi);+ adj[hi].push(lo);+ }+ };++ for (let t = 0; t < triangles.length; t += 3) {+ const i0 = triangles[t];+ const i1 = triangles[t + 1];+ const i2 = triangles[t + 2];+ registerEdge(i0, i1);+ registerEdge(i1, i2);+ registerEdge(i2, i0);+ }++ const componentId = new Int32Array(vertCount).fill(-1);+ let componentCount = 0;+ const queue = new Int32Array(vertCount);+ for (let start = 0; start < vertCount; start++) {+ if (componentId[start] >= 0) continue;+ const cid = componentCount++;+ componentId[start] = cid;+ let qHead = 0;+ let qTail = 0;+ queue[qTail++] = start;+ while (qHead < qTail) {+ const u = queue[qHead++];+ const neighbors = adj[u];+ for (let k = 0; k < neighbors.length; k++) {+ const nb = neighbors[k];+ if (componentId[nb] < 0) {+ componentId[nb] = cid;+ queue[qTail++] = nb;+ }+ }+ }+ }++ return {+ sourceWidth: sw,+ sourceHeight: sh,+ restLocalX,+ restLocalY,+ restWorldX,+ restWorldY,+ uvX,+ uvY,+ triangles,+ edges: new Uint32Array(edgeList),+ componentId,+ componentCount,+ density,+ expansion: safeExpansion,+ };+}++/**+ * Exact Skyline (Variable-Band) Cholesky Factorization for SPD matrices A = L * L^T.+ */+interface SkylineCholesky {+ n: number;+ firstCol: Int32Array;+ rowPtr: Int32Array;+ L: Float64Array;+}++function buildSkylineStructure(n: number, firstCol: Int32Array): {+ rowPtr: Int32Array;+ vals: Float64Array;+} {+ const rowPtr = new Int32Array(n + 1);+ for (let i = 0; i < n; i++) {+ const fc = Math.max(0, Math.min(i, firstCol[i]));+ firstCol[i] = fc;+ rowPtr[i + 1] = rowPtr[i] + (i - fc + 1);+ }+ return { rowPtr, vals: new Float64Array(rowPtr[n]) };+}++function factorizeSkyline(+ n: number,+ firstCol: Int32Array,+ rowPtr: Int32Array,+ vals: Float64Array+): SkylineCholesky {+ for (let i = 0; i < n; i++) {+ const ci = firstCol[i];+ const ri = rowPtr[i];+ for (let j = ci; j <= i; j++) {+ const cj = firstCol[j];+ const rj = rowPtr[j];+ let sum = vals[ri + (j - ci)];+ const kStart = ci > cj ? ci : cj;+ let idxI = ri + (kStart - ci);+ let idxJ = rj + (kStart - cj);+ for (let k = kStart; k < j; k++) {+ sum -= vals[idxI++] * vals[idxJ++];+ }+ if (i === j) {+ vals[ri + (i - ci)] = Math.sqrt(sum > 1e-12 ? sum : 1e-12);+ } else {+ const diagJ = vals[rj + (j - cj)];+ vals[ri + (j - ci)] = sum / diagJ;+ }+ }+ }+ return { n, firstCol, rowPtr, L: vals };+}++function solveSkyline(chol: SkylineCholesky, rhs: Float64Array, out: Float64Array): void {+ const { n, firstCol, rowPtr, L } = chol;+ for (let i = 0; i < n; i++) {+ const ci = firstCol[i];+ const ri = rowPtr[i];+ let sum = rhs[i];+ let idx = ri;+ for (let j = ci; j < i; j++) {+ sum -= L[idx++] * out[j];+ }+ out[i] = sum / L[ri + (i - ci)];+ }+ for (let i = n - 1; i >= 0; i--) {+ const ci = firstCol[i];+ const ri = rowPtr[i];+ const xi = out[i] / L[ri + (i - ci)];+ out[i] = xi;+ let idx = ri;+ for (let j = ci; j < i; j++) {+ out[j] -= L[idx++] * xi;+ }+ }+}++interface AttachedPin {+ pin: PuppetPin;+ /** Local component vertex indices (0..localV-1) */+ lv0: number;+ lv1: number;+ lv2: number;+ /** Global vertex indices */+ gv0: number;+ gv1: number;+ gv2: number;+ b0: number;+ b1: number;+ b2: number;+ componentId: number;+ hasRotation: boolean;+}++interface CachedComponentSolver {+ localV: number;+ globalVerts: Int32Array;+ localTris: Uint32Array;+ step1Chol: SkylineCholesky;+ step2Chol: SkylineCholesky;+ /** Precomputed local rest coordinates */+ restX: Float64Array;+ restY: Float64Array;+ /** Pin attachment info mapped into local vertex indices */+ pins: Array<{+ lv0: number;+ lv1: number;+ lv2: number;+ b0: number;+ b1: number;+ b2: number;+ hasRotation: boolean;+ }>;+}++interface MeshSolverCacheEntry {+ topoKey: string;+ compSolvers: Map<number, CachedComponentSolver>;+}++const solverCache = new WeakMap<PuppetMeshData, MeshSolverCacheEntry>();++function attachPinToMesh(+ mesh: PuppetMeshData,+ pin: PuppetPin,+ useX: Float32Array = mesh.restWorldX,+ useY: Float32Array = mesh.restWorldY+): { gv0: number; gv1: number; gv2: number; b0: number; b1: number; b2: number; componentId: number } {+ const tris = mesh.triangles;+ let bestTri = 0;+ let bestB0 = 1;+ let bestB1 = 0;+ let bestB2 = 0;+ let bestDistSq = Infinity;++ for (let t = 0; t < tris.length; t += 3) {+ const i0 = tris[t];+ const i1 = tris[t + 1];+ const i2 = tris[t + 2];+ const res = closestPointOnTriangleBary(+ pin.restX,+ pin.restY,+ useX[i0],+ useY[i0],+ useX[i1],+ useY[i1],+ useX[i2],+ useY[i2]+ );+ if (res.distSq < bestDistSq) {+ bestDistSq = res.distSq;+ bestTri = t;+ bestB0 = res.b0;+ bestB1 = res.b1;+ bestB2 = res.b2;+ if (bestDistSq === 0) break;+ }+ }++ const gv0 = tris[bestTri];+ const gv1 = tris[bestTri + 1];+ const gv2 = tris[bestTri + 2];+ return {+ gv0,+ gv1,+ gv2,+ b0: bestB0,+ b1: bestB1,+ b2: bestB2,+ componentId: mesh.componentId[gv0],+ };+}++/**+ * Projects a document-space click `(clickX, clickY)` on the CURRENT deformed mesh+ * back onto the rest mesh so adding a pin to an already-deformed character causes+ * zero sudden snapping or jumping.+ */+export function mapDeformedPointToPuppetRest(+ mesh: PuppetMeshData,+ deformedX: Float32Array,+ deformedY: Float32Array,+ clickX: number,+ clickY: number+): { restX: number; restY: number; inside: boolean; distSq: number } {+ const tris = mesh.triangles;+ let bestTri = 0;+ let bestB0 = 1;+ let bestB1 = 0;+ let bestB2 = 0;+ let bestDistSq = Infinity;++ for (let t = 0; t < tris.length; t += 3) {+ const i0 = tris[t];+ const i1 = tris[t + 1];+ const i2 = tris[t + 2];+ const res = closestPointOnTriangleBary(+ clickX,+ clickY,+ deformedX[i0],+ deformedY[i0],+ deformedX[i1],+ deformedY[i1],+ deformedX[i2],+ deformedY[i2]+ );+ if (res.distSq < bestDistSq) {+ bestDistSq = res.distSq;+ bestTri = t;+ bestB0 = res.b0;+ bestB1 = res.b1;+ bestB2 = res.b2;+ if (bestDistSq === 0) break;+ }+ }++ const i0 = tris[bestTri];+ const i1 = tris[bestTri + 1];+ const i2 = tris[bestTri + 2];+ const restX =+ bestB0 * mesh.restWorldX[i0] + bestB1 * mesh.restWorldX[i1] + bestB2 * mesh.restWorldX[i2];+ const restY =+ bestB0 * mesh.restWorldY[i0] + bestB1 * mesh.restWorldY[i1] + bestB2 * mesh.restWorldY[i2];++ return {+ restX,+ restY,+ inside: bestDistSq === 0,+ distSq: bestDistSq,+ };+}++function buildComponentSolver(+ mesh: PuppetMeshData,+ cid: number,+ compPins: AttachedPin[]+): CachedComponentSolver {+ const globalToLocal = new Int32Array(mesh.restWorldX.length).fill(-1);+ const globalVertsArr: number[] = [];+ for (let v = 0; v < mesh.restWorldX.length; v++) {+ if (mesh.componentId[v] === cid) {+ globalToLocal[v] = globalVertsArr.length;+ globalVertsArr.push(v);+ }+ }+ const localV = globalVertsArr.length;+ const globalVerts = new Int32Array(globalVertsArr);+ const restX = new Float64Array(localV);+ const restY = new Float64Array(localV);+ for (let lv = 0; lv < localV; lv++) {+ const gv = globalVerts[lv];+ restX[lv] = mesh.restWorldX[gv];+ restY[lv] = mesh.restWorldY[gv];+ }++ const localTrisArr: number[] = [];+ for (let t = 0; t < mesh.triangles.length; t += 3) {+ const g0 = mesh.triangles[t];+ if (mesh.componentId[g0] !== cid) continue;+ localTrisArr.push(+ globalToLocal[g0],+ globalToLocal[mesh.triangles[t + 1]],+ globalToLocal[mesh.triangles[t + 2]]+ );+ }+ const localTris = new Uint32Array(localTrisArr);++ const mappedPins = compPins.map((ap) => ({+ lv0: globalToLocal[ap.gv0],+ lv1: globalToLocal[ap.gv1],+ lv2: globalToLocal[ap.gv2],+ b0: ap.b0,+ b1: ap.b1,+ b2: ap.b2,+ hasRotation: ap.hasRotation,+ }));++ // --- Step 1: 2*localV x 2*localV Similarity-Transform Energy Matrix (Igarashi 2005) ---+ const n1 = localV * 2;+ const firstCol1 = new Int32Array(n1);+ for (let i = 0; i < n1; i++) firstCol1[i] = i;++ const touch1 = (r: number, c: number) => {+ const row = r >= c ? r : c;+ const col = r >= c ? c : r;+ if (col < firstCol1[row]) firstCol1[row] = col;+ };++ for (let t = 0; t < localTris.length; t += 3) {+ const v0 = localTris[t];+ const v1 = localTris[t + 1];+ const v2 = localTris[t + 2];+ const dofs = [v0 * 2, v0 * 2 + 1, v1 * 2, v1 * 2 + 1, v2 * 2, v2 * 2 + 1];+ for (let a = 0; a < 6; a++) {+ for (let b = a; b < 6; b++) {+ touch1(dofs[a], dofs[b]);+ }+ }+ }+ for (const mp of mappedPins) {+ const vs = [mp.lv0, mp.lv1, mp.lv2];+ for (let a = 0; a < 3; a++) {+ for (let b = a; b < 3; b++) {+ touch1(vs[a] * 2, vs[b] * 2);+ touch1(vs[a] * 2 + 1, vs[b] * 2 + 1);+ }+ }+ }++ const s1 = buildSkylineStructure(n1, firstCol1);+ const add1 = (r: number, c: number, val: number) => {+ const row = r >= c ? r : c;+ const col = r >= c ? c : r;+ s1.vals[s1.rowPtr[row] + (col - firstCol1[row])] += val;+ };++ // Add tiny Tikhonov regularization for guaranteed SPD even under degenerate pin configs+ for (let i = 0; i < n1; i++) {+ add1(i, i, TIKHONOV_EPS);+ }++ const addLinearResidual1 = (+ idx0: number, c0: number,+ idx1: number, c1: number,+ idx2: number, c2: number,+ idx3: number, c3: number,+ idx4: number, c4: number,+ weight: number+ ) => {+ const idxs = [idx0, idx1, idx2, idx3, idx4];+ const coeffs = [c0, c1, c2, c3, c4];+ for (let a = 0; a < 5; a++) {+ const ca = coeffs[a] * weight;+ if (ca === 0) continue;+ const ra = idxs[a];+ for (let b = a; b < 5; b++) {+ const cb = coeffs[b];+ if (cb === 0) continue;+ add1(ra, idxs[b], ca * cb);+ }+ }+ };++ const triPermWeight = 1 / 3;+ for (let t = 0; t < localTris.length; t += 3) {+ const tri = [localTris[t], localTris[t + 1], localTris[t + 2]];+ for (let p = 0; p < 3; p++) {+ const vi = tri[p];+ const vj = tri[(p + 1) % 3];+ const vk = tri[(p + 2) % 3];+ const ex = restX[vj] - restX[vi];+ const ey = restY[vj] - restY[vi];+ const lenSq = ex * ex + ey * ey;+ if (lenSq < 1e-10) continue;+ const dxk = restX[vk] - restX[vi];+ const dyk = restY[vk] - restY[vi];+ const x01 = (dxk * ex + dyk * ey) / lenSq;+ const y01 = (dxk * -ey + dyk * ex) / lenSq;++ // r_x = x_k - (1 - x01)*x_i - x01*x_j - y01*y_i + y01*y_j+ addLinearResidual1(+ vk * 2, 1,+ vi * 2, -(1 - x01),+ vj * 2, -x01,+ vi * 2 + 1, -y01,+ vj * 2 + 1, y01,+ triPermWeight+ );+ // r_y = y_k - (1 - x01)*y_i - x01*y_j + y01*x_i - y01*x_j+ addLinearResidual1(+ vk * 2 + 1, 1,+ vi * 2 + 1, -(1 - x01),+ vj * 2 + 1, -x01,+ vi * 2, y01,+ vj * 2, -y01,+ triPermWeight+ );+ }+ }++ // Pin barycentric position & optional rotation constraints in Step 1+ for (const mp of mappedPins) {+ const vs = [mp.lv0, mp.lv1, mp.lv2];+ const bs = [mp.b0, mp.b1, mp.b2];+ for (let a = 0; a < 3; a++) {+ for (let b = a; b < 3; b++) {+ const w = PIN_POS_WEIGHT * bs[a] * bs[b];+ add1(vs[a] * 2, vs[b] * 2, w);+ add1(vs[a] * 2 + 1, vs[b] * 2 + 1, w);+ }+ if (mp.hasRotation) {+ add1(vs[a] * 2, vs[a] * 2, PIN_ROT_WEIGHT);+ add1(vs[a] * 2 + 1, vs[a] * 2 + 1, PIN_ROT_WEIGHT);+ }+ }+ }++ const step1Chol = factorizeSkyline(n1, firstCol1, s1.rowPtr, s1.vals);++ // --- Step 2: localV x localV Rigid-Fitting Laplacian Matrix (shared by X and Y) ---+ const firstCol2 = new Int32Array(localV);+ for (let i = 0; i < localV; i++) firstCol2[i] = i;++ const touch2 = (r: number, c: number) => {+ const row = r >= c ? r : c;+ const col = r >= c ? c : r;+ if (col < firstCol2[row]) firstCol2[row] = col;+ };++ for (let t = 0; t < localTris.length; t += 3) {+ const v0 = localTris[t];+ const v1 = localTris[t + 1];+ const v2 = localTris[t + 2];+ touch2(v0, v1);+ touch2(v1, v2);+ touch2(v2, v0);+ }+ for (const mp of mappedPins) {+ touch2(mp.lv0, mp.lv1);+ touch2(mp.lv1, mp.lv2);+ touch2(mp.lv2, mp.lv0);+ }++ const s2 = buildSkylineStructure(localV, firstCol2);+ const add2 = (r: number, c: number, val: number) => {+ const row = r >= c ? r : c;+ const col = r >= c ? c : r;+ s2.vals[s2.rowPtr[row] + (col - firstCol2[row])] += val;+ };++ for (let i = 0; i < localV; i++) {+ add2(i, i, TIKHONOV_EPS);+ }++ // Each triangle's 3 edges contribute ||(v'_b - v'_a) - R_t (v_b - v_a)||^2+ for (let t = 0; t < localTris.length; t += 3) {+ const v0 = localTris[t];+ const v1 = localTris[t + 1];+ const v2 = localTris[t + 2];+ const pairs: [number, number][] = [+ [v0, v1],+ [v1, v2],+ [v2, v0],+ ];+ for (const [a, b] of pairs) {+ add2(a, a, 1);+ add2(b, b, 1);+ add2(a, b, -1);+ }+ }++ for (const mp of mappedPins) {+ const vs = [mp.lv0, mp.lv1, mp.lv2];+ const bs = [mp.b0, mp.b1, mp.b2];+ for (let a = 0; a < 3; a++) {+ for (let b = a; b < 3; b++) {+ add2(vs[a], vs[b], PIN_POS_WEIGHT * bs[a] * bs[b]);+ }+ if (mp.hasRotation) {+ add2(vs[a], vs[a], PIN_ROT_WEIGHT);+ }+ }+ }++ const step2Chol = factorizeSkyline(localV, firstCol2, s2.rowPtr, s2.vals);++ return {+ localV,+ globalVerts,+ localTris,+ step1Chol,+ step2Chol,+ restX,+ restY,+ pins: mappedPins,+ };+}++/**+ * Checks whether a PuppetWarpState produces any non-identity deformation.+ */+export function isPuppetDeformed(puppet: PuppetWarpState | undefined): boolean {+ if (!puppet || puppet.pins.length === 0) return false;+ for (const pin of puppet.pins) {+ if (+ Math.abs(pin.x - pin.restX) > 1e-4 ||+ Math.abs(pin.y - pin.restY) > 1e-4 ||+ Math.abs(pin.rotation) > 1e-4+ ) {+ return true;+ }+ }+ return false;+}++/**+ * Solves As-Rigid-As-Possible (Igarashi 2005 + local-global rigid refinement) Puppet Warp+ * deformation for all vertices of `mesh` given the placed joint `pins` and `rigidity` mode.+ */+export function solvePuppetDeformation(+ mesh: PuppetMeshData,+ pins: PuppetPin[],+ rigidity: PuppetRigidityMode = 'normal'+): PuppetDeformedResult {+ const vertCount = mesh.restWorldX.length;+ const outX = new Float32Array(mesh.restWorldX);+ const outY = new Float32Array(mesh.restWorldY);++ if (pins.length === 0) {+ return { x: outX, y: outY };+ }++ // Short-circuit exact identity when all pins are unmoved & unrotated+ let anyMoved = false;+ let anyDepth = false;+ for (let i = 0; i < pins.length; i++) {+ const p = pins[i];+ if (+ Math.abs(p.x - p.restX) > 1e-4 ||+ Math.abs(p.y - p.restY) > 1e-4 ||+ Math.abs(p.rotation) > 1e-4+ ) {+ anyMoved = true;+ }+ if (p.depth !== 0) anyDepth = true;+ }+ if (!anyMoved && !anyDepth) {+ return { x: outX, y: outY };+ }++ // Attach every pin to its rest triangle & group by connected component+ const compPinMap = new Map<number, AttachedPin[]>();+ const topoParts: string[] = [];+ for (let i = 0; i < pins.length; i++) {+ const p = pins[i];+ const att = attachPinToMesh(mesh, p);+ const hasRotation = Math.abs(p.rotation) > 1e-4;+ const ap: AttachedPin = {+ pin: p,+ lv0: 0,+ lv1: 0,+ lv2: 0,+ gv0: att.gv0,+ gv1: att.gv1,+ gv2: att.gv2,+ b0: att.b0,+ b1: att.b1,+ b2: att.b2,+ componentId: att.componentId,+ hasRotation,+ };+ let list = compPinMap.get(att.componentId);+ if (!list) {+ list = [];+ compPinMap.set(att.componentId, list);+ }+ list.push(ap);+ topoParts.push(+ `${att.gv0},${att.gv1},${att.gv2},${att.b0.toFixed(4)},${att.b1.toFixed(4)},${hasRotation ? 1 : 0}`+ );+ }++ const topoKey = topoParts.join('|');+ let cached = solverCache.get(mesh);+ if (!cached || cached.topoKey !== topoKey) {+ cached = { topoKey, compSolvers: new Map() };+ solverCache.set(mesh, cached);+ }++ const solvedComponents = new Set<number>();++ // Solve each component that has >= 1 pin+ for (const [cid, compPins] of compPinMap.entries()) {+ solvedComponents.add(cid);++ if (compPins.length === 1) {+ // Exact rigid translation + optional pin rotation (zero linear solve cost)+ const p = compPins[0].pin;+ const rad = (p.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ for (let v = 0; v < vertCount; v++) {+ if (mesh.componentId[v] !== cid) continue;+ const dx = mesh.restWorldX[v] - p.restX;+ const dy = mesh.restWorldY[v] - p.restY;+ outX[v] = p.x + dx * cos - dy * sin;+ outY[v] = p.y + dx * sin + dy * cos;+ }+ continue;+ }++ let solver = cached.compSolvers.get(cid);+ if (!solver) {+ solver = buildComponentSolver(mesh, cid, compPins);+ cached.compSolvers.set(cid, solver);+ }++ const { localV, globalVerts, localTris, step1Chol, step2Chol, restX, restY, pins: mappedPins } =+ solver;++ // --- Step 1 Solve: Scale-Free Similarity Transform ---+ const rhs1 = new Float64Array(localV * 2);+ for (let lv = 0; lv < localV; lv++) {+ rhs1[lv * 2] = TIKHONOV_EPS * restX[lv];+ rhs1[lv * 2 + 1] = TIKHONOV_EPS * restY[lv];+ }++ for (let pi = 0; pi < mappedPins.length; pi++) {+ const mp = mappedPins[pi];+ const pin = compPins[pi].pin;+ const vs = [mp.lv0, mp.lv1, mp.lv2];+ const bs = [mp.b0, mp.b1, mp.b2];+ for (let a = 0; a < 3; a++) {+ const w = PIN_POS_WEIGHT * bs[a];+ rhs1[vs[a] * 2] += w * pin.x;+ rhs1[vs[a] * 2 + 1] += w * pin.y;+ }+ if (mp.hasRotation) {+ const rad = (pin.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ for (let a = 0; a < 3; a++) {+ const lv = vs[a];+ const dx = restX[lv] - pin.restX;+ const dy = restY[lv] - pin.restY;+ const tx = pin.x + dx * cos - dy * sin;+ const ty = pin.y + dx * sin + dy * cos;+ rhs1[lv * 2] += PIN_ROT_WEIGHT * tx;+ rhs1[lv * 2 + 1] += PIN_ROT_WEIGHT * ty;+ }+ }+ }++ const sol1 = new Float64Array(localV * 2);+ solveSkyline(step1Chol, rhs1, sol1);++ const curX = new Float64Array(localV);+ const curY = new Float64Array(localV);+ for (let lv = 0; lv < localV; lv++) {+ curX[lv] = sol1[lv * 2];+ curY[lv] = sol1[lv * 2 + 1];+ }++ // --- Step 2 Solve: Local-Global Pure Rigid Rotation Fitting ---+ const step2Iters = rigidity === 'distort' ? 0 : rigidity === 'rigid' ? 3 : 1;+ if (step2Iters > 0) {+ const rhsX = new Float64Array(localV);+ const rhsY = new Float64Array(localV);+ const nextX = new Float64Array(localV);+ const nextY = new Float64Array(localV);++ for (let iter = 0; iter < step2Iters; iter++) {+ for (let lv = 0; lv < localV; lv++) {+ rhsX[lv] = TIKHONOV_EPS * restX[lv];+ rhsY[lv] = TIKHONOV_EPS * restY[lv];+ }++ // Fit best pure 2D rotation R_t per triangle and accumulate Laplacian RHS+ for (let t = 0; t < localTris.length; t += 3) {+ const v0 = localTris[t];+ const v1 = localTris[t + 1];+ const v2 = localTris[t + 2];++ const rcx = (restX[v0] + restX[v1] + restX[v2]) / 3;+ const rcy = (restY[v0] + restY[v1] + restY[v2]) / 3;+ const dcx = (curX[v0] + curX[v1] + curX[v2]) / 3;+ const dcy = (curY[v0] + curY[v1] + curY[v2]) / 3;++ const p0x = restX[v0] - rcx; const p0y = restY[v0] - rcy;+ const p1x = restX[v1] - rcx; const p1y = restY[v1] - rcy;+ const p2x = restX[v2] - rcx; const p2y = restY[v2] - rcy;++ const q0x = curX[v0] - dcx; const q0y = curY[v0] - dcy;+ const q1x = curX[v1] - dcx; const q1y = curY[v1] - dcy;+ const q2x = curX[v2] - dcx; const q2y = curY[v2] - dcy;++ const C =+ p0x * q0x + p0y * q0y ++ p1x * q1x + p1y * q1y ++ p2x * q2x + p2y * q2y;+ const S =+ p0x * q0y - p0y * q0x ++ p1x * q1y - p1y * q1x ++ p2x * q2y - p2y * q2x;+ const L = Math.hypot(C, S);+ const cos = L > 1e-8 ? C / L : 1;+ const sin = L > 1e-8 ? S / L : 0;++ // Edge (a -> b): rotated rest edge R_t * (v_b - v_a)+ const addEdgeRhs = (a: number, b: number) => {+ const ex = restX[b] - restX[a];+ const ey = restY[b] - restY[a];+ const rx = cos * ex - sin * ey;+ const ry = sin * ex + cos * ey;+ rhsX[a] -= rx;+ rhsX[b] += rx;+ rhsY[a] -= ry;+ rhsY[b] += ry;+ };+ addEdgeRhs(v0, v1);+ addEdgeRhs(v1, v2);+ addEdgeRhs(v2, v0);+ }++ // Pin position & rotation constraints in Step 2+ for (let pi = 0; pi < mappedPins.length; pi++) {+ const mp = mappedPins[pi];+ const pin = compPins[pi].pin;+ const vs = [mp.lv0, mp.lv1, mp.lv2];+ const bs = [mp.b0, mp.b1, mp.b2];+ for (let a = 0; a < 3; a++) {+ const w = PIN_POS_WEIGHT * bs[a];+ rhsX[vs[a]] += w * pin.x;+ rhsY[vs[a]] += w * pin.y;+ }+ if (mp.hasRotation) {+ const rad = (pin.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ for (let a = 0; a < 3; a++) {+ const lv = vs[a];+ const dx = restX[lv] - pin.restX;+ const dy = restY[lv] - pin.restY;+ rhsX[lv] += PIN_ROT_WEIGHT * (pin.x + dx * cos - dy * sin);+ rhsY[lv] += PIN_ROT_WEIGHT * (pin.y + dx * sin + dy * cos);+ }+ }+ }++ solveSkyline(step2Chol, rhsX, nextX);+ solveSkyline(step2Chol, rhsY, nextY);+ curX.set(nextX);+ curY.set(nextY);+ }+ }++ for (let lv = 0; lv < localV; lv++) {+ const gv = globalVerts[lv];+ outX[gv] = curX[lv];+ outY[gv] = curY[lv];+ }+ }++ // Handle unpinned disconnected islands (e.g. detached hair highlights / sparkles / eyebrows):+ // rigidly follow the local rigid frame of the closest triangle belonging to a pinned component.+ if (solvedComponents.size > 0 && solvedComponents.size < mesh.componentCount) {+ for (let cid = 0; cid < mesh.componentCount; cid++) {+ if (solvedComponents.has(cid)) continue;++ let cx = 0;+ let cy = 0;+ let count = 0;+ for (let v = 0; v < vertCount; v++) {+ if (mesh.componentId[v] === cid) {+ cx += mesh.restWorldX[v];+ cy += mesh.restWorldY[v];+ count++;+ }+ }+ if (count === 0) continue;+ cx /= count;+ cy /= count;++ // Find nearest solved triangle to island centroid+ let bestTri = -1;+ let bestDistSq = Infinity;+ const tris = mesh.triangles;+ for (let t = 0; t < tris.length; t += 3) {+ const i0 = tris[t];+ if (!solvedComponents.has(mesh.componentId[i0])) continue;+ const i1 = tris[t + 1];+ const i2 = tris[t + 2];+ const tcx = (mesh.restWorldX[i0] + mesh.restWorldX[i1] + mesh.restWorldX[i2]) / 3;+ const tcy = (mesh.restWorldY[i0] + mesh.restWorldY[i1] + mesh.restWorldY[i2]) / 3;+ const dSq = (cx - tcx) * (cx - tcx) + (cy - tcy) * (cy - tcy);+ if (dSq < bestDistSq) {+ bestDistSq = dSq;+ bestTri = t;+ }+ }++ if (bestTri >= 0) {+ const i0 = tris[bestTri];+ const i1 = tris[bestTri + 1];+ const i2 = tris[bestTri + 2];+ const rcx = (mesh.restWorldX[i0] + mesh.restWorldX[i1] + mesh.restWorldX[i2]) / 3;+ const rcy = (mesh.restWorldY[i0] + mesh.restWorldY[i1] + mesh.restWorldY[i2]) / 3;+ const dcx = (outX[i0] + outX[i1] + outX[i2]) / 3;+ const dcy = (outY[i0] + outY[i1] + outY[i2]) / 3;++ const p0x = mesh.restWorldX[i0] - rcx; const p0y = mesh.restWorldY[i0] - rcy;+ const p1x = mesh.restWorldX[i1] - rcx; const p1y = mesh.restWorldY[i1] - rcy;+ const p2x = mesh.restWorldX[i2] - rcx; const p2y = mesh.restWorldY[i2] - rcy;++ const q0x = outX[i0] - dcx; const q0y = outY[i0] - dcy;+ const q1x = outX[i1] - dcx; const q1y = outY[i1] - dcy;+ const q2x = outX[i2] - dcx; const q2y = outY[i2] - dcy;++ const C = p0x * q0x + p0y * q0y + p1x * q1x + p1y * q1y + p2x * q2x + p2y * q2y;+ const S = p0x * q0y - p0y * q0x + p1x * q1y - p1y * q1x + p2x * q2y - p2y * q2x;+ const L = Math.hypot(C, S);+ const cos = L > 1e-8 ? C / L : 1;+ const sin = L > 1e-8 ? S / L : 0;++ for (let v = 0; v < vertCount; v++) {+ if (mesh.componentId[v] !== cid) continue;+ const rx = mesh.restWorldX[v] - rcx;+ const ry = mesh.restWorldY[v] - rcy;+ outX[v] = dcx + rx * cos - ry * sin;+ outY[v] = dcy + rx * sin + ry * cos;+ }+ }+ }+ }++ // Optional back-to-front triangle ordering when any pin has a non-zero stacking depth+ let triOrder: Uint32Array | undefined;+ if (anyDepth) {+ const triCount = mesh.triangles.length / 3;+ const depths = new Float32Array(triCount);+ const order = new Uint32Array(triCount);+ for (let ti = 0; ti < triCount; ti++) {+ order[ti] = ti;+ const i0 = mesh.triangles[ti * 3];+ const i1 = mesh.triangles[ti * 3 + 1];+ const i2 = mesh.triangles[ti * 3 + 2];+ const tx = (mesh.restWorldX[i0] + mesh.restWorldX[i1] + mesh.restWorldX[i2]) / 3;+ const ty = (mesh.restWorldY[i0] + mesh.restWorldY[i1] + mesh.restWorldY[i2]) / 3;++ let wSum = 0;+ let dSum = 0;+ for (let pi = 0; pi < pins.length; pi++) {+ const p = pins[pi];+ const dx = tx - p.restX;+ const dy = ty - p.restY;+ const w = 1 / (dx * dx + dy * dy + 1e-3);+ wSum += w;+ dSum += w * p.depth;+ }+ depths[ti] = wSum > 0 ? dSum / wSum : 0;+ }+ order.sort((a, b) => depths[a] - depths[b]);+ triOrder = order;+ }++ return { x: outX, y: outY, triOrder };+}++/**+ * Calculates tight integer bounding box of deformed vertex coordinates.+ */+export function getDeformedMeshBounds(xs: Float32Array, ys: Float32Array): PuppetMeshBounds {+ const n = xs.length;+ if (n === 0) {+ return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };+ }+ let minX = xs[0];+ let maxX = xs[0];+ let minY = ys[0];+ let maxY = ys[0];+ for (let i = 1; i < n; i++) {+ const x = xs[i];+ const y = ys[i];+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ const minXF = Math.floor(minX);+ const minYF = Math.floor(minY);+ const maxXC = Math.ceil(maxX);+ const maxYC = Math.ceil(maxY);+ return {+ minX: minXF,+ minY: minYF,+ maxX: maxXC,+ maxY: maxYC,+ width: Math.max(1, maxXC - minXF),+ height: Math.max(1, maxYC - minYF),+ };+}++/**+ * Creates a fresh PuppetWarpState with silhouette mesh fitted to the given rest quad.+ */+export function createInitialPuppetState(+ sourcePixels: PixelBuffer | undefined,+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D],+ options?: {+ density?: PuppetMeshDensity;+ expansion?: number;+ rigidity?: PuppetRigidityMode;+ showMesh?: boolean;+ }+): PuppetWarpState {+ const density = options?.density ?? 'normal';+ const expansion = options?.expansion ?? 6;+ const rigidity = options?.rigidity ?? 'normal';+ const showMesh = options?.showMesh ?? true;+ const mesh = buildPuppetMesh(sourcePixels, sourceWidth, sourceHeight, quad, density, expansion);+ return {+ pins: [],+ selectedPinId: null,+ rigidity,+ density,+ expansion,+ showMesh,+ mesh,+ };+}++/**+ * Ensures `puppet.mesh` is populated and matches current density/expansion settings.+ */+export function ensurePuppetMesh(+ puppet: PuppetWarpState | undefined,+ sourcePixels: PixelBuffer | undefined,+ sourceWidth: number,+ sourceHeight: number,+ quad: [Point2D, Point2D, Point2D, Point2D]+): PuppetMeshData {+ if (+ puppet?.mesh &&+ puppet.mesh.sourceWidth === sourceWidth &&+ puppet.mesh.sourceHeight === sourceHeight &&+ puppet.mesh.density === puppet.density &&+ puppet.mesh.expansion === puppet.expansion+ ) {+ return puppet.mesh;+ }+ return buildPuppetMesh(+ sourcePixels,+ sourceWidth,+ sourceHeight,+ quad,+ puppet?.density ?? 'normal',+ puppet?.expansion ?? 6+ );+}++/**+ * Mirrors an active PuppetMeshData horizontally or vertically around `mid` without losing UVs.+ */+export function flipPuppetMesh(+ mesh: PuppetMeshData,+ axis: 'horizontal' | 'vertical',+ mid: number+): PuppetMeshData {+ const restWorldX = new Float32Array(mesh.restWorldX);+ const restWorldY = new Float32Array(mesh.restWorldY);+ if (axis === 'horizontal') {+ for (let i = 0; i < restWorldX.length; i++) restWorldX[i] = 2 * mid - restWorldX[i];+ } else {+ for (let i = 0; i < restWorldY.length; i++) restWorldY[i] = 2 * mid - restWorldY[i];+ }+ return {+ ...mesh,+ restWorldX,+ restWorldY,+ };+}diff --git a/src/utils/quickBrushUtils.ts b/src/utils/quickBrushUtils.tsnew file mode 100644index 0000000..5249e8a--- /dev/null+++ b/src/utils/quickBrushUtils.ts@@ -0,0 +1,272 @@+import { BrushCategory, BrushPresetId, BrushSettings, CspBrush } from '../types/editor';+import {+ ALL_BUILTIN_BRUSHES,+ getBuiltinBrushConfig,+ isDecorationCategory,+ isDecorationPresetId,+} from './presetBrushes';+import {+ DEFAULT_ERASER_SETTINGS,+ ERASER_PRESET_ID,+ NEUTRAL_BRUSH_DEFAULTS,+ getEffectiveBrushSettings,+ getSavedBrushSettings,+ migrateLegacyPresetId,+ saveActiveDecorationPresetId,+ saveActivePresetId,+} from './brushPresetManager';+import { prepareBrushSettingsForCsp } from './brushStorage';+import { toolStoreActions } from '../stores';++export const DND_BRUSH_MIME = 'application/x-inkstudio-brush';+export const DND_QUICK_BRUSH_REORDER_MIME = 'application/x-inkstudio-quick-brush-reorder';++export type QuickBrushCategory = BrushCategory | 'custom' | 'eraser';++export interface ResolvedQuickBrush {+ id: BrushPresetId;+ name: string;+ category: QuickBrushCategory;+ desc?: string;+ tipDataUrl?: string;+ isColorTip?: boolean;+ hardness: number;+ thickness: number;+ thicknessVertical: boolean;+ angle: number;+ isEraser?: boolean;+ isCustom?: boolean;+ customBrush?: CspBrush;+ previewSettings?: Partial<BrushSettings>;+}++export interface CategoryAccentStyle {+ barColor: string | null;+ cardTint: string | null;+ label: string;+}++export function getCategoryAccentStyle(category: QuickBrushCategory): CategoryAccentStyle {+ switch (category) {+ case 'pen':+ return {+ barColor: null,+ cardTint: null,+ label: 'Pen',+ };+ case 'sketch':+ return {+ barColor: '#d9a45b',+ cardTint: 'rgba(217, 164, 91, 0.08)',+ label: 'Sketch',+ };+ case 'brush':+ return {+ barColor: '#6ea8d8',+ cardTint: 'rgba(110, 168, 216, 0.08)',+ label: 'Brush',+ };+ case 'blend':+ return {+ barColor: '#9b87c4',+ cardTint: 'rgba(155, 135, 196, 0.14)',+ label: 'Blend',+ };+ case 'natural-paint':+ return {+ barColor: '#5ab4a8',+ cardTint: 'rgba(90, 180, 168, 0.15)',+ label: 'Natural Paint',+ };+ case 'deco-background':+ return {+ barColor: '#34d399',+ cardTint: 'rgba(52, 211, 153, 0.12)',+ label: 'Background',+ };+ case 'deco-clothing':+ return {+ barColor: '#f472b6',+ cardTint: 'rgba(244, 114, 182, 0.12)',+ label: 'Clothing',+ };+ case 'deco-effect':+ return {+ barColor: '#a78bfa',+ cardTint: 'rgba(167, 139, 250, 0.14)',+ label: 'Effect',+ };+ case 'eraser':+ return {+ barColor: '#e58aa3',+ cardTint: 'rgba(229, 138, 163, 0.11)',+ label: 'Eraser',+ };+ case 'custom':+ default:+ return {+ barColor: '#8d99ae',+ cardTint: 'rgba(141, 153, 174, 0.10)',+ label: 'Imported',+ };+ }+}++export function resolveQuickBrush(+ presetId: BrushPresetId,+ customBrushes: CspBrush[]+): ResolvedQuickBrush | null {+ const resolvedId = migrateLegacyPresetId(presetId);++ if (resolvedId === ERASER_PRESET_ID || resolvedId === 'eraser') {+ return {+ id: ERASER_PRESET_ID,+ name: 'Eraser',+ category: 'eraser',+ desc: 'Standard Eraser Tool',+ hardness: DEFAULT_ERASER_SETTINGS.hardness ?? 0.9,+ thickness: 1.0,+ thicknessVertical: false,+ angle: 0,+ isEraser: true,+ previewSettings: DEFAULT_ERASER_SETTINGS,+ };+ }++ const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === resolvedId);+ if (builtin) {+ let cfg: Partial<BrushSettings> | null = null;+ try {+ cfg = getBuiltinBrushConfig(builtin.id);+ } catch {+ cfg = null;+ }+ const tipDataUrl = cfg?.customTipDataUrl || cfg?.subTips?.[0]?.dataUrl;+ const angleDynamics = builtin.settings.customTipAngleDynamics;+ const staticAngle =+ !angleDynamics || angleDynamics === 'none' ? (builtin.settings.customTipAngle ?? 0) : 0;+ return {+ id: builtin.id,+ name: builtin.name,+ category: builtin.category,+ desc: builtin.desc,+ tipDataUrl,+ isColorTip: Boolean(builtin.settings.isColorTip),+ hardness: builtin.settings.hardness ?? 1.0,+ thickness: builtin.settings.thickness ?? 1.0,+ thicknessVertical: Boolean(builtin.settings.thicknessVertical),+ angle: staticAngle,+ previewSettings: cfg ?? builtin.settings,+ };+ }++ const custom = customBrushes.find((b) => b.id === presetId || b.id === resolvedId);+ if (custom) {+ const tipDataUrl = custom.tipDataUrl || custom.subTips?.[0]?.dataUrl;+ const staticAngle =+ !custom.angleDynamics || custom.angleDynamics === 'none' ? (custom.angle ?? 0) : 0;+ return {+ id: custom.id,+ name: custom.name,+ category: custom.category || 'custom',+ desc: custom.badge ? `${custom.badge} brush` : 'Custom brush',+ tipDataUrl,+ isColorTip: Boolean(custom.isColorTip),+ hardness: custom.hardness ?? 0.9,+ thickness: custom.thickness ?? 1.0,+ thicknessVertical: Boolean(custom.thicknessVertical),+ angle: staticAngle,+ isCustom: true,+ customBrush: custom,+ previewSettings: {+ ...NEUTRAL_BRUSH_DEFAULTS,+ preset: custom.id,+ brushName: custom.name,+ size: custom.size,+ minSizeFactor: custom.minSizeFactor,+ flow: custom.flow,+ opacity: custom.opacity,+ spacing: custom.spacing,+ hardness: custom.hardness,+ thickness: custom.thickness,+ thicknessVertical: custom.thicknessVertical,+ customTipDataUrl: tipDataUrl,+ customTipAngle: custom.angle,+ customTipAngleDynamics: custom.angleDynamics,+ isColorTip: custom.isColorTip,+ isRibbon: custom.isRibbon,+ subTips: custom.subTips,+ dynamics: custom.dynamics,+ colorMixing: custom.colorMixing,+ renderMode: custom.renderMode,+ bristle: custom.bristle,+ naturalPaint: custom.naturalPaint,+ },+ };+ }++ return null;+}++export async function activateQuickBrush(+ resolved: ResolvedQuickBrush,+ customBrushes: CspBrush[]+): Promise<void> {+ if (resolved.isEraser) {+ toolStoreActions.selectTool('eraser');+ return;+ }++ const targetIsDeco =+ isDecorationPresetId(resolved.id) || isDecorationCategory(resolved.category);++ if (resolved.customBrush) {+ toolStoreActions.selectTool(targetIsDeco ? 'decoration' : 'brush');+ if (targetIsDeco) {+ saveActiveDecorationPresetId(resolved.customBrush.id);+ } else {+ saveActivePresetId(resolved.customBrush.id);+ }+ const prepared = await prepareBrushSettingsForCsp(resolved.customBrush);+ const saved = getSavedBrushSettings(resolved.customBrush.id);+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...prepared,+ ...saved,+ preset: resolved.customBrush.id,+ });+ return;+ }++ toolStoreActions.selectTool(targetIsDeco ? 'decoration' : 'brush');+ if (targetIsDeco) {+ saveActiveDecorationPresetId(resolved.id);+ } else {+ saveActivePresetId(resolved.id);+ }+ const effective = getEffectiveBrushSettings(resolved.id, customBrushes);+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...effective,+ preset: resolved.id,+ });+}++export function clampQuickBrushPosition(+ x: number,+ y: number,+ panelWidth: number,+ panelHeight: number,+ viewport?: { width: number; height: number }+): { x: number; y: number } {+ const vw = viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 1280);+ const vh = viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 800);+ const minX = 8;+ const minY = 40;+ const maxX = Math.max(minX, vw - Math.max(48, panelWidth) - 8);+ const maxY = Math.max(minY, vh - Math.max(48, panelHeight) - 8);+ return {+ x: Math.max(minX, Math.min(maxX, Math.round(x))),+ y: Math.max(minY, Math.min(maxY, Math.round(y))),+ };+}diff --git a/src/utils/quickShapeEngine.ts b/src/utils/quickShapeEngine.tsnew file mode 100644index 0000000..dbe2a75--- /dev/null+++ b/src/utils/quickShapeEngine.ts@@ -0,0 +1,2481 @@+import { Point } from '../types/editor';++export type QuickShapeKind =+ | 'line'+ | 'arc'+ | 'circle'+ | 'ellipse'+ | 'triangle'+ | 'rectangle';++export interface Vec2 {+ x: number;+ y: number;+}++export interface QuickShapeLine {+ kind: 'line';+ start: Vec2;+ end: Vec2;+}++export interface QuickShapeArc {+ kind: 'arc';+ start: Vec2;+ mid: Vec2;+ end: Vec2;+}++export interface QuickShapeCircle {+ kind: 'circle';+ center: Vec2;+ radius: number;+ handleAngle: number;+}++export interface QuickShapeEllipse {+ kind: 'ellipse';+ center: Vec2;+ rx: number;+ ry: number;+ rotation: number;+ handleAngle: number;+}++export interface QuickShapeTriangle {+ kind: 'triangle';+ vertices: [Vec2, Vec2, Vec2];+}++export interface QuickShapeRectangle {+ kind: 'rectangle';+ center: Vec2;+ width: number;+ height: number;+ rotation: number;+}++export type QuickShapeGeometry =+ | QuickShapeLine+ | QuickShapeArc+ | QuickShapeCircle+ | QuickShapeEllipse+ | QuickShapeTriangle+ | QuickShapeRectangle;++export interface QuickShapeHandle {+ id: string;+ x: number;+ y: number;+ kind: 'corner' | 'endpoint' | 'mid' | 'rim' | 'axis' | 'center';+ active?: boolean;+}++export interface QuickShapeStrokeStyle {+ pressure: number;+ width: number;+ tiltX: number;+ tiltY: number;+ twist: number;+}++export interface QuickShapeRecognitionResult {+ shape: QuickShapeGeometry;+ confidence: number;+ rmsNorm: number;+}++export interface QuickShapePreviewState {+ shape: QuickShapeGeometry;+ label: string;+ readout: string;+ hint: string;+ svgPath: string;+ guideLine?: { x1: number; y1: number; x2: number; y2: number };+ centerMarker?: Vec2;+ handles: QuickShapeHandle[];+ anchorPos: Vec2;+ activeHandleId: string;+ snappedAtMs: number;+}++export interface QuickShapeSession {+ initialShape: QuickShapeGeometry;+ currentShape: QuickShapeGeometry;+ snapPenPos: Vec2;+ activeHandleId: string;+ activeCornerIndex: number;+ initialArcBulgeRatio: number;+ hasExitedDeadzone: boolean;+ style: QuickShapeStrokeStyle;+ snappedAtMs: number;+}++export const QUICK_SHAPE_HOLD_MS = 350;+export const QUICK_SHAPE_HOLD_TOLERANCE_SCREEN_PX = 6;+export const QUICK_SHAPE_DRAG_DEADZONE_SCREEN_PX = 4;+export const QUICK_SHAPE_MIN_STROKE_LENGTH_DOC = 24;++const TWO_PI = Math.PI * 2;++function clamp(v: number, min: number, max: number): number {+ return v < min ? min : v > max ? max : v;+}++function mod2Pi(a: number): number {+ const m = a % TWO_PI;+ return m < 0 ? m + TWO_PI : m;+}++function normalizeHalfPiAngle(a: number): number {+ let r = a % Math.PI;+ if (r > Math.PI * 0.5) r -= Math.PI;+ if (r <= -Math.PI * 0.5) r += Math.PI;+ return r;+}++function snapAngleRad(rad: number, stepDeg: number): number {+ const step = (stepDeg * Math.PI) / 180;+ return Math.round(rad / step) * step;+}++function distSq(a: Vec2, b: Vec2): number {+ const dx = a.x - b.x;+ const dy = a.y - b.y;+ return dx * dx + dy * dy;+}++function dist(a: Vec2, b: Vec2): number {+ return Math.hypot(a.x - b.x, a.y - b.y);+}++function pointToSegmentDistSq(p: Vec2, a: Vec2, b: Vec2): number {+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const lenSq = dx * dx + dy * dy;+ if (lenSq < 1e-9) return distSq(p, a);+ const t = clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq, 0, 1);+ const projX = a.x + t * dx;+ const projY = a.y + t * dy;+ const ex = p.x - projX;+ const ey = p.y - projY;+ return ex * ex + ey * ey;+}++function pointToSegmentDist(p: Vec2, a: Vec2, b: Vec2): number {+ return Math.sqrt(pointToSegmentDistSq(p, a, b));+}++function polylineLength(pts: ReadonlyArray<Vec2>): number {+ let len = 0;+ for (let i = 1; i < pts.length; i++) {+ len += dist(pts[i - 1], pts[i]);+ }+ return len;+}++function computeBounds(pts: ReadonlyArray<Vec2>): {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+ width: number;+ height: number;+ diag: number;+} {+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (let i = 0; i < pts.length; i++) {+ const p = pts[i];+ if (p.x < minX) minX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.x > maxX) maxX = p.x;+ if (p.y > maxY) maxY = p.y;+ }+ const width = Math.max(0, maxX - minX);+ const height = Math.max(0, maxY - minY);+ return { minX, minY, maxX, maxY, width, height, diag: Math.hypot(width, height) };+}++function resamplePolyline(pts: ReadonlyArray<Vec2>, targetCount: number): Vec2[] {+ if (pts.length === 0) return [];+ if (pts.length === 1 || targetCount <= 1) return [{ x: pts[0].x, y: pts[0].y }];++ const cumLen = new Float64Array(pts.length);+ for (let i = 1; i < pts.length; i++) {+ cumLen[i] = cumLen[i - 1] + dist(pts[i - 1], pts[i]);+ }+ const totalLen = cumLen[pts.length - 1];+ if (totalLen < 1e-6) {+ return Array.from({ length: targetCount }, () => ({ x: pts[0].x, y: pts[0].y }));+ }++ const out: Vec2[] = new Array(targetCount);+ out[0] = { x: pts[0].x, y: pts[0].y };+ let segIdx = 0;+ for (let k = 1; k < targetCount - 1; k++) {+ const targetDist = (totalLen * k) / (targetCount - 1);+ while (segIdx < pts.length - 2 && cumLen[segIdx + 1] < targetDist) {+ segIdx++;+ }+ const segStart = cumLen[segIdx];+ const segEnd = cumLen[segIdx + 1];+ const span = segEnd - segStart;+ const t = span > 1e-9 ? (targetDist - segStart) / span : 0;+ const a = pts[segIdx];+ const b = pts[segIdx + 1];+ out[k] = {+ x: a.x + (b.x - a.x) * t,+ y: a.y + (b.y - a.y) * t,+ };+ }+ out[targetCount - 1] = { x: pts[pts.length - 1].x, y: pts[pts.length - 1].y };+ return out;+}++/**+ * Trims trailing micro-jitter points accumulated while the artist holds the stylus still.+ */+function trimTrailingHoldJitter(pts: ReadonlyArray<Vec2>, toleranceDoc: number): Vec2[] {+ if (pts.length <= 4) return pts.map((p) => ({ x: p.x, y: p.y }));+ const endPt = pts[pts.length - 1];+ const tolSq = toleranceDoc * toleranceDoc;+ let lastOutside = pts.length - 1;+ while (lastOutside > 2 && distSq(pts[lastOutside - 1], endPt) <= tolSq) {+ lastOutside--;+ }+ const trimmed = pts.slice(0, lastOutside + 1).map((p) => ({ x: p.x, y: p.y }));+ if (lastOutside < pts.length - 1) {+ // Anchor final point at the actual resting stylus coordinate+ trimmed[trimmed.length - 1] = { x: endPt.x, y: endPt.y };+ }+ return trimmed;+}++function shoelaceArea(pts: ReadonlyArray<Vec2>): number {+ let sum = 0;+ const n = pts.length;+ for (let i = 0; i < n; i++) {+ const a = pts[i];+ const b = pts[(i + 1) % n];+ sum += a.x * b.y - b.x * a.y;+ }+ return Math.abs(sum) * 0.5;+}++function computeCentroidWindingAngle(pts: ReadonlyArray<Vec2>): number {+ const n = pts.length;+ if (n < 3) return 0;+ let cx = 0;+ let cy = 0;+ for (let i = 0; i < n; i++) {+ cx += pts[i].x;+ cy += pts[i].y;+ }+ cx /= n;+ cy /= n;+ let total = 0;+ let prevA = Math.atan2(pts[0].y - cy, pts[0].x - cx);+ for (let i = 1; i <= n; i++) {+ const p = pts[i % n];+ const dx = p.x - cx;+ const dy = p.y - cy;+ if (dx * dx + dy * dy < 1e-4) continue;+ const a = Math.atan2(dy, dx);+ let da = a - prevA;+ while (da > Math.PI) da -= TWO_PI;+ while (da < -Math.PI) da += TWO_PI;+ total += da;+ prevA = a;+ }+ return total;+}++/**+ * Algebraic Kasa circle fit + Gauss-Newton geometric refinement.+ */+function fitCircleLeastSquares(+ pts: ReadonlyArray<Vec2>+): { cx: number; cy: number; radius: number } | null {+ const n = pts.length;+ if (n < 3) return null;++ let meanX = 0;+ let meanY = 0;+ for (let i = 0; i < n; i++) {+ meanX += pts[i].x;+ meanY += pts[i].y;+ }+ meanX /= n;+ meanY /= n;++ let suu = 0;+ let suv = 0;+ let svv = 0;+ let suuu = 0;+ let svvv = 0;+ let suvv = 0;+ let svuu = 0;++ for (let i = 0; i < n; i++) {+ const u = pts[i].x - meanX;+ const v = pts[i].y - meanY;+ const u2 = u * u;+ const v2 = v * v;+ suu += u2;+ suv += u * v;+ svv += v2;+ suuu += u2 * u;+ svvv += v2 * v;+ suvv += u * v2;+ svuu += v * u2;+ }++ const det = suu * svv - suv * suv;+ if (Math.abs(det) < 1e-6) return null;++ const rhs1 = 0.5 * (suuu + suvv);+ const rhs2 = 0.5 * (svvv + svuu);+ const uc = (rhs1 * svv - rhs2 * suv) / det;+ const vc = (suu * rhs2 - suv * rhs1) / det;++ let cx = meanX + uc;+ let cy = meanY + vc;+ let rSum = 0;+ for (let i = 0; i < n; i++) {+ rSum += Math.hypot(pts[i].x - cx, pts[i].y - cy);+ }+ let radius = rSum / n;+ if (!Number.isFinite(cx) || !Number.isFinite(cy) || !Number.isFinite(radius) || radius < 2) {+ return null;+ }++ // 4 iterations of geometric Gauss-Newton refinement+ for (let iter = 0; iter < 4; iter++) {+ let j00 = 0;+ let j01 = 0;+ let j02 = 0;+ let j11 = 0;+ let j12 = 0;+ const j22 = n;+ let b0 = 0;+ let b1 = 0;+ let b2 = 0;++ for (let i = 0; i < n; i++) {+ const dx = cx - pts[i].x;+ const dy = cy - pts[i].y;+ const d = Math.hypot(dx, dy);+ if (d < 1e-6) continue;+ const gx = dx / d;+ const gy = dy / d;+ const err = d - radius;+ j00 += gx * gx;+ j01 += gx * gy;+ j02 -= gx;+ j11 += gy * gy;+ j12 -= gy;+ b0 -= gx * err;+ b1 -= gy * err;+ b2 += err;+ }++ // Solve 3x3 symmetric system (with light Tikhonov damping)+ const a00 = j00 + 1e-4;+ const a01 = j01;+ const a02 = j02;+ const a11 = j11 + 1e-4;+ const a12 = j12;+ const a22 = j22 + 1e-4;++ const d3 =+ a00 * (a11 * a22 - a12 * a12) -+ a01 * (a01 * a22 - a12 * a02) ++ a02 * (a01 * a12 - a11 * a02);+ if (Math.abs(d3) < 1e-9) break;++ const dcx =+ (b0 * (a11 * a22 - a12 * a12) -+ a01 * (b1 * a22 - a12 * b2) ++ a02 * (b1 * a12 - a11 * b2)) /+ d3;+ const dcy =+ (a00 * (b1 * a22 - a12 * b2) -+ b0 * (a01 * a22 - a12 * a02) ++ a02 * (a01 * b2 - b1 * a02)) /+ d3;+ const dr =+ (a00 * (a11 * b2 - b1 * a12) -+ a01 * (a01 * b2 - b1 * a02) ++ b0 * (a01 * a12 - a11 * a02)) /+ d3;++ if (!Number.isFinite(dcx) || !Number.isFinite(dcy) || !Number.isFinite(dr)) break;+ if (Math.hypot(dcx, dcy) > radius * 0.5) break;+ cx += dcx;+ cy += dcy;+ radius = Math.max(2, radius + dr);+ if (Math.hypot(dcx, dcy) + Math.abs(dr) < 1e-3) break;+ }++ return { cx, cy, radius };+}++/**+ * Computes exact-ish closest distance from a point to an ellipse centered at origin with semi-axes (rx, ry).+ */+function pointToAlignedEllipseDist(lx: number, ly: number, rx: number, ry: number): number {+ const safeRx = Math.max(1e-3, rx);+ const safeRy = Math.max(1e-3, ry);+ let t = Math.atan2(ly / safeRy, lx / safeRx);+ // 2 Newton steps to minimize f(t) = 0.5 * ((rx cos t - lx)^2 + (ry sin t - ly)^2)+ for (let k = 0; k < 2; k++) {+ const ct = Math.cos(t);+ const st = Math.sin(t);+ const ex = safeRx * ct - lx;+ const ey = safeRy * st - ly;+ const d1 = -safeRx * st * ex + safeRy * ct * ey;+ const d2 =+ -safeRx * ct * ex ++ safeRx * safeRx * st * st -+ safeRy * st * ey ++ safeRy * safeRy * ct * ct;+ if (d2 > 1e-6) {+ t -= clamp(d1 / d2, -0.5, 0.5);+ }+ }+ const px = safeRx * Math.cos(t);+ const py = safeRy * Math.sin(t);+ return Math.hypot(lx - px, ly - py);+}++function evaluateEllipseError(+ pts: ReadonlyArray<Vec2>,+ cx: number,+ cy: number,+ rx: number,+ ry: number,+ rot: number+): { rms: number; max: number } {+ const cos = Math.cos(-rot);+ const sin = Math.sin(-rot);+ let sumSq = 0;+ let maxD = 0;+ for (let i = 0; i < pts.length; i++) {+ const dx = pts[i].x - cx;+ const dy = pts[i].y - cy;+ const lx = dx * cos - dy * sin;+ const ly = dx * sin + dy * cos;+ const d = pointToAlignedEllipseDist(lx, ly, rx, ry);+ sumSq += d * d;+ if (d > maxD) maxD = d;+ }+ return { rms: Math.sqrt(sumSq / Math.max(1, pts.length)), max: maxD };+}++function fitEllipseGeometric(+ pts: ReadonlyArray<Vec2>+): { cx: number; cy: number; rx: number; ry: number; rotation: number; rms: number; max: number } | null {+ const n = pts.length;+ if (n < 6) return null;++ let cx = 0;+ let cy = 0;+ for (let i = 0; i < n; i++) {+ cx += pts[i].x;+ cy += pts[i].y;+ }+ cx /= n;+ cy /= n;++ // PCA for initial orientation+ let sxx = 0;+ let sxy = 0;+ let syy = 0;+ for (let i = 0; i < n; i++) {+ const dx = pts[i].x - cx;+ const dy = pts[i].y - cy;+ sxx += dx * dx;+ sxy += dx * dy;+ syy += dy * dy;+ }+ let rot = 0.5 * Math.atan2(2 * sxy, sxx - syy);++ // Project onto PCA frame to estimate center & semi-axes+ const cos0 = Math.cos(-rot);+ const sin0 = Math.sin(-rot);+ let minU = Infinity;+ let maxU = -Infinity;+ let minV = Infinity;+ let maxV = -Infinity;+ for (let i = 0; i < n; i++) {+ const dx = pts[i].x - cx;+ const dy = pts[i].y - cy;+ const u = dx * cos0 - dy * sin0;+ const v = dx * sin0 + dy * cos0;+ if (u < minU) minU = u;+ if (u > maxU) maxU = u;+ if (v < minV) minV = v;+ if (v > maxV) maxV = v;+ }++ const du = (minU + maxU) * 0.5;+ const dv = (minV + maxV) * 0.5;+ const cRot = Math.cos(rot);+ const sRot = Math.sin(rot);+ cx += du * cRot - dv * sRot;+ cy += du * sRot + dv * cRot;+ let rx = Math.max(3, (maxU - minU) * 0.5);+ let ry = Math.max(3, (maxV - minV) * 0.5);++ let bestErr = evaluateEllipseError(pts, cx, cy, rx, ry, rot);+ const scaleRef = Math.max(rx, ry);++ // Coordinate-search refinement (deterministic, fast, handles partial gaps & hand wobble)+ let stepPos = scaleRef * 0.08;+ let stepRad = scaleRef * 0.08;+ let stepAng = 0.14;++ for (let round = 0; round < 6; round++) {+ // Refine rotation+ for (const dir of [-1, 1]) {+ const cand = rot + dir * stepAng;+ const err = evaluateEllipseError(pts, cx, cy, rx, ry, cand);+ if (err.rms < bestErr.rms) {+ rot = cand;+ bestErr = err;+ }+ }+ // Refine center X / Y+ for (const dir of [-1, 1]) {+ const cand = cx + dir * stepPos;+ const err = evaluateEllipseError(pts, cand, cy, rx, ry, rot);+ if (err.rms < bestErr.rms) {+ cx = cand;+ bestErr = err;+ }+ }+ for (const dir of [-1, 1]) {+ const cand = cy + dir * stepPos;+ const err = evaluateEllipseError(pts, cx, cand, rx, ry, rot);+ if (err.rms < bestErr.rms) {+ cy = cand;+ bestErr = err;+ }+ }+ // Refine rx / ry+ for (const dir of [-1, 1]) {+ const cand = Math.max(3, rx + dir * stepRad);+ const err = evaluateEllipseError(pts, cx, cy, cand, ry, rot);+ if (err.rms < bestErr.rms) {+ rx = cand;+ bestErr = err;+ }+ }+ for (const dir of [-1, 1]) {+ const cand = Math.max(3, ry + dir * stepRad);+ const err = evaluateEllipseError(pts, cx, cy, rx, cand, rot);+ if (err.rms < bestErr.rms) {+ ry = cand;+ bestErr = err;+ }+ }+ stepPos *= 0.5;+ stepRad *= 0.5;+ stepAng *= 0.5;+ }++ // Canonicalize rx >= ry+ if (ry > rx) {+ const tmp = rx;+ rx = ry;+ ry = tmp;+ rot += Math.PI * 0.5;+ }+ rot = normalizeHalfPiAngle(rot);++ // Gentle axis-alignment snap within 3.5 deg for nearly horizontal/vertical ellipses+ const snapDist = Math.abs(rot - snapAngleRad(rot, 90));+ if (snapDist < (3.5 * Math.PI) / 180) {+ const snappedRot = normalizeHalfPiAngle(snapAngleRad(rot, 90));+ const snappedErr = evaluateEllipseError(pts, cx, cy, rx, ry, snappedRot);+ if (snappedErr.rms <= bestErr.rms * 1.06 + 0.5) {+ rot = snappedRot;+ bestErr = snappedErr;+ }+ }++ return { cx, cy, rx, ry, rotation: rot, rms: bestErr.rms, max: bestErr.max };+}++function computeConvexHull(pts: ReadonlyArray<Vec2>): Vec2[] {+ if (pts.length <= 3) return pts.map((p) => ({ x: p.x, y: p.y }));+ const sorted = pts+ .map((p) => ({ x: p.x, y: p.y }))+ .sort((a, b) => (a.x !== b.x ? a.x - b.x : a.y - b.y));+ const cross = (o: Vec2, a: Vec2, b: Vec2) =>+ (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);++ const lower: Vec2[] = [];+ for (let i = 0; i < sorted.length; i++) {+ const p = sorted[i];+ while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {+ lower.pop();+ }+ lower.push(p);+ }+ const upper: Vec2[] = [];+ for (let i = sorted.length - 1; i >= 0; i--) {+ const p = sorted[i];+ while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {+ upper.pop();+ }+ upper.push(p);+ }+ lower.pop();+ upper.pop();+ return lower.concat(upper);+}++/**+ * Fits an infinite line (normal nx, ny and offset c: nx*x + ny*y = c) via orthogonal regression.+ */+function fitLineTLS(pts: ReadonlyArray<Vec2>): { nx: number; ny: number; c: number } | null {+ const n = pts.length;+ if (n < 2) return null;+ let mx = 0;+ let my = 0;+ for (let i = 0; i < n; i++) {+ mx += pts[i].x;+ my += pts[i].y;+ }+ mx /= n;+ my /= n;++ let sxx = 0;+ let sxy = 0;+ let syy = 0;+ for (let i = 0; i < n; i++) {+ const dx = pts[i].x - mx;+ const dy = pts[i].y - my;+ sxx += dx * dx;+ sxy += dx * dy;+ syy += dy * dy;+ }+ // Direction of largest variance is theta; normal is theta + pi/2+ const theta = 0.5 * Math.atan2(2 * sxy, sxx - syy);+ const nx = -Math.sin(theta);+ const ny = Math.cos(theta);+ const c = nx * mx + ny * my;+ return { nx, ny, c };+}++function intersectLines(+ l1: { nx: number; ny: number; c: number },+ l2: { nx: number; ny: number; c: number }+): Vec2 | null {+ const det = l1.nx * l2.ny - l1.ny * l2.nx;+ if (Math.abs(det) < 0.08) return null; // nearly parallel+ return {+ x: (l1.c * l2.ny - l1.ny * l2.c) / det,+ y: (l1.nx * l2.c - l1.c * l2.nx) / det,+ };+}++function evaluateTriangleFit(+ pts: ReadonlyArray<Vec2>,+ verts: [Vec2, Vec2, Vec2]+): { rms: number; max: number; edgeCounts: [number, number, number] } {+ let sumSq = 0;+ let maxD = 0;+ const edgeCounts: [number, number, number] = [0, 0, 0];+ for (let i = 0; i < pts.length; i++) {+ const p = pts[i];+ const d0 = pointToSegmentDistSq(p, verts[0], verts[1]);+ const d1 = pointToSegmentDistSq(p, verts[1], verts[2]);+ const d2 = pointToSegmentDistSq(p, verts[2], verts[0]);+ let best = d0;+ let bestIdx: 0 | 1 | 2 = 0;+ if (d1 < best) {+ best = d1;+ bestIdx = 1;+ }+ if (d2 < best) {+ best = d2;+ bestIdx = 2;+ }+ edgeCounts[bestIdx]++;+ sumSq += best;+ const d = Math.sqrt(best);+ if (d > maxD) maxD = d;+ }+ return {+ rms: Math.sqrt(sumSq / Math.max(1, pts.length)),+ max: maxD,+ edgeCounts,+ };+}++function fitTriangleClosed(+ pts: ReadonlyArray<Vec2>,+ diag: number+): { vertices: [Vec2, Vec2, Vec2]; rms: number; max: number; perimeter: number } | null {+ const n = pts.length;+ if (n < 9) return null;++ const triArea2 = (a: Vec2, b: Vec2, c: Vec2) =>+ Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x));++ // Find maximum-area inscribed triangle over the closed loop (O(N^2) with advancing third pointer)+ let bestI = 0;+ let bestJ = Math.floor(n / 3);+ let bestK = Math.floor((2 * n) / 3);+ let maxArea2 = -1;++ for (let i = 0; i < n; i++) {+ let k = (i + 2) % n;+ for (let stepJ = 1; stepJ < n - 1; stepJ++) {+ const j = (i + stepJ) % n;+ if (k === j) k = (j + 1) % n;+ let curArea = triArea2(pts[i], pts[j], pts[k]);+ while (true) {+ const nextK = (k + 1) % n;+ if (nextK === i) break;+ const nextArea = triArea2(pts[i], pts[j], pts[nextK]);+ if (nextArea > curArea) {+ k = nextK;+ curArea = nextArea;+ } else {+ break;+ }+ }+ if (curArea > maxArea2) {+ maxArea2 = curArea;+ bestI = i;+ bestJ = j;+ bestK = k;+ }+ }+ }++ if (maxArea2 < 0.04 * diag * diag) return null;++ const indices = [bestI, bestJ, bestK].sort((a, b) => a - b);+ let vertices: [Vec2, Vec2, Vec2] = [+ { x: pts[indices[0]].x, y: pts[indices[0]].y },+ { x: pts[indices[1]].x, y: pts[indices[1]].y },+ { x: pts[indices[2]].x, y: pts[indices[2]].y },+ ];+ let bestEval = evaluateTriangleFit(pts, vertices);++ // Refine corners by fitting orthogonal lines to the middle 65% of each of the 3 edge chains+ const chains: Vec2[][] = [[], [], []];+ for (let edge = 0; edge < 3; edge++) {+ const startIdx = indices[edge];+ const endIdx = indices[(edge + 1) % 3];+ const span = (endIdx - startIdx + n) % n;+ const trim = Math.max(1, Math.floor(span * 0.18));+ for (let s = trim; s <= span - trim; s++) {+ chains[edge].push(pts[(startIdx + s) % n]);+ }+ }++ const l0 = fitLineTLS(chains[0]);+ const l1 = fitLineTLS(chains[1]);+ const l2 = fitLineTLS(chains[2]);+ if (l0 && l1 && l2) {+ const r0 = intersectLines(l2, l0);+ const r1 = intersectLines(l0, l1);+ const r2 = intersectLines(l1, l2);+ if (+ r0 &&+ r1 &&+ r2 &&+ dist(r0, vertices[0]) <= 0.22 * diag &&+ dist(r1, vertices[1]) <= 0.22 * diag &&+ dist(r2, vertices[2]) <= 0.22 * diag+ ) {+ const refined: [Vec2, Vec2, Vec2] = [r0, r1, r2];+ const refinedEval = evaluateTriangleFit(pts, refined);+ if (refinedEval.rms <= bestEval.rms * 1.02) {+ vertices = refined;+ bestEval = refinedEval;+ }+ }+ }++ const e0 = dist(vertices[0], vertices[1]);+ const e1 = dist(vertices[1], vertices[2]);+ const e2 = dist(vertices[2], vertices[0]);+ const minEdge = Math.min(e0, e1, e2);+ const minCount = Math.min(bestEval.edgeCounts[0], bestEval.edgeCounts[1], bestEval.edgeCounts[2]);+ if (minEdge < 0.15 * diag || minCount < Math.max(3, Math.floor(n * 0.08))) {+ return null;+ }++ return {+ vertices,+ rms: bestEval.rms,+ max: bestEval.max,+ perimeter: e0 + e1 + e2,+ };+}++export function getRectangleCorners(rect: QuickShapeRectangle): [Vec2, Vec2, Vec2, Vec2] {+ const cos = Math.cos(rect.rotation);+ const sin = Math.sin(rect.rotation);+ const hw = rect.width * 0.5;+ const hh = rect.height * 0.5;+ const ux = cos * hw;+ const uy = sin * hw;+ const vx = -sin * hh;+ const vy = cos * hh;+ return [+ { x: rect.center.x - ux - vx, y: rect.center.y - uy - vy },+ { x: rect.center.x + ux - vx, y: rect.center.y + uy - vy },+ { x: rect.center.x + ux + vx, y: rect.center.y + uy + vy },+ { x: rect.center.x - ux + vx, y: rect.center.y - uy + vy },+ ];+}++function evaluateRectAtAngle(+ pts: ReadonlyArray<Vec2>,+ angle: number,+ refineEdges: boolean+): {+ rect: QuickShapeRectangle;+ rms: number;+ max: number;+ sideCounts: [number, number, number, number];+ meanNormCornerDist: number;+} {+ const cos = Math.cos(-angle);+ const sin = Math.sin(-angle);+ const n = pts.length;+ const us = new Float64Array(n);+ const vs = new Float64Array(n);+ let minU = Infinity;+ let maxU = -Infinity;+ let minV = Infinity;+ let maxV = -Infinity;++ for (let i = 0; i < n; i++) {+ const u = pts[i].x * cos - pts[i].y * sin;+ const v = pts[i].x * sin + pts[i].y * cos;+ us[i] = u;+ vs[i] = v;+ if (u < minU) minU = u;+ if (u > maxU) maxU = u;+ if (v < minV) minV = v;+ if (v > maxV) maxV = v;+ }++ if (refineEdges && maxU - minU > 4 && maxV - minV > 4) {+ // Refine each of the 4 sides to the mean coordinate of points clearly belonging to that side+ let sumLeft = 0;+ let cntLeft = 0;+ let sumRight = 0;+ let cntRight = 0;+ let sumTop = 0;+ let cntTop = 0;+ let sumBot = 0;+ let cntBot = 0;+ const spanU = maxU - minU;+ const spanV = maxV - minV;++ for (let i = 0; i < n; i++) {+ const u = us[i];+ const v = vs[i];+ const dL = Math.abs(u - minU);+ const dR = Math.abs(maxU - u);+ const dT = Math.abs(v - minV);+ const dB = Math.abs(maxV - v);+ const m = Math.min(dL, dR, dT, dB);+ if (m === dL && v > minV + spanV * 0.1 && v < maxV - spanV * 0.1) {+ sumLeft += u;+ cntLeft++;+ } else if (m === dR && v > minV + spanV * 0.1 && v < maxV - spanV * 0.1) {+ sumRight += u;+ cntRight++;+ } else if (m === dT && u > minU + spanU * 0.1 && u < maxU - spanU * 0.1) {+ sumTop += v;+ cntTop++;+ } else if (m === dB && u > minU + spanU * 0.1 && u < maxU - spanU * 0.1) {+ sumBot += v;+ cntBot++;+ }+ }+ if (cntLeft >= 3) minU = sumLeft / cntLeft;+ if (cntRight >= 3) maxU = sumRight / cntRight;+ if (cntTop >= 3) minV = sumTop / cntTop;+ if (cntBot >= 3) maxV = sumBot / cntBot;+ }++ const width = Math.max(2, maxU - minU);+ const height = Math.max(2, maxV - minV);+ const cu = (minU + maxU) * 0.5;+ const cv = (minV + maxV) * 0.5;+ const hw = width * 0.5;+ const hh = height * 0.5;++ let sumSq = 0;+ let maxD = 0;+ const sideCounts: [number, number, number, number] = [0, 0, 0, 0];+ const minCornerNorm = [Infinity, Infinity, Infinity, Infinity];++ for (let i = 0; i < n; i++) {+ const du = us[i] - cu;+ const dv = vs[i] - cv;++ // Distance to rectangle boundary in local frame+ const dxOut = Math.abs(du) - hw;+ const dyOut = Math.abs(dv) - hh;+ let d: number;+ if (dxOut > 0 && dyOut > 0) {+ d = Math.hypot(dxOut, dyOut);+ } else if (dxOut > 0) {+ d = dxOut;+ } else if (dyOut > 0) {+ d = dyOut;+ } else {+ d = Math.min(-dxOut, -dyOut);+ }+ sumSq += d * d;+ if (d > maxD) maxD = d;++ // Side assignment+ const dL = Math.abs(us[i] - minU);+ const dR = Math.abs(maxU - us[i]);+ const dT = Math.abs(vs[i] - minV);+ const dB = Math.abs(maxV - vs[i]);+ const m = Math.min(dL, dR, dT, dB);+ if (m === dL) sideCounts[0]++;+ else if (m === dR) sideCounts[1]++;+ else if (m === dT) sideCounts[2]++;+ else sideCounts[3]++;++ // Normalized corner proximity in [-1, 1]^2 unit box coordinates+ const nu = du / Math.max(1e-3, hw);+ const nv = dv / Math.max(1e-3, hh);+ const c0 = Math.hypot(nu + 1, nv + 1);+ const c1 = Math.hypot(nu - 1, nv + 1);+ const c2 = Math.hypot(nu - 1, nv - 1);+ const c3 = Math.hypot(nu + 1, nv - 1);+ if (c0 < minCornerNorm[0]) minCornerNorm[0] = c0;+ if (c1 < minCornerNorm[1]) minCornerNorm[1] = c1;+ if (c2 < minCornerNorm[2]) minCornerNorm[2] = c2;+ if (c3 < minCornerNorm[3]) minCornerNorm[3] = c3;+ }++ const cRot = Math.cos(angle);+ const sRot = Math.sin(angle);+ const cx = cu * cRot - cv * sRot;+ const cy = cu * sRot + cv * cRot;++ return {+ rect: {+ kind: 'rectangle',+ center: { x: cx, y: cy },+ width,+ height,+ rotation: normalizeHalfPiAngle(angle),+ },+ rms: Math.sqrt(sumSq / Math.max(1, n)),+ max: maxD,+ sideCounts,+ meanNormCornerDist:+ (minCornerNorm[0] + minCornerNorm[1] + minCornerNorm[2] + minCornerNorm[3]) * 0.25,+ };+}++function fitRectangleClosed(+ pts: ReadonlyArray<Vec2>,+ diag: number+): {+ rect: QuickShapeRectangle;+ rms: number;+ max: number;+ perimeter: number;+ meanNormCornerDist: number;+} | null {+ const hull = computeConvexHull(pts);+ if (hull.length < 3) return null;++ const candidateAngles: number[] = [0];+ for (let i = 0; i < hull.length; i++) {+ const a = hull[i];+ const b = hull[(i + 1) % hull.length];+ if (distSq(a, b) > 1) {+ candidateAngles.push(normalizeHalfPiAngle(Math.atan2(b.y - a.y, b.x - a.x)));+ }+ }++ let best = evaluateRectAtAngle(pts, 0, false);+ for (let i = 1; i < candidateAngles.length; i++) {+ const res = evaluateRectAtAngle(pts, candidateAngles[i], false);+ if (res.rms < best.rms) {+ best = res;+ }+ }++ // Fine local angle search around best orientation (+/- 4 deg in 0.5 deg steps)+ const baseAngle = best.rect.rotation;+ best = evaluateRectAtAngle(pts, baseAngle, true);+ for (let deg = -4; deg <= 4; deg += 0.5) {+ if (deg === 0) continue;+ const cand = baseAngle + (deg * Math.PI) / 180;+ const res = evaluateRectAtAngle(pts, cand, true);+ if (res.rms < best.rms) {+ best = res;+ }+ }++ // Gentle auto-alignment within 4 deg to horizontal/vertical axes+ const snappedAxis = normalizeHalfPiAngle(snapAngleRad(best.rect.rotation, 90));+ if (Math.abs(best.rect.rotation - snappedAxis) < (4 * Math.PI) / 180) {+ const axisRes = evaluateRectAtAngle(pts, snappedAxis, true);+ if (axisRes.rms <= best.rms * 1.08 + 0.75) {+ best = axisRes;+ }+ }++ // Canonicalize rotation into (-pi/4, pi/4] so width is always the more-horizontal side+ let rect = best.rect;+ if (rect.rotation > Math.PI * 0.25) {+ rect = {+ kind: 'rectangle',+ center: rect.center,+ width: rect.height,+ height: rect.width,+ rotation: rect.rotation - Math.PI * 0.5,+ };+ } else if (rect.rotation <= -Math.PI * 0.25) {+ rect = {+ kind: 'rectangle',+ center: rect.center,+ width: rect.height,+ height: rect.width,+ rotation: rect.rotation + Math.PI * 0.5,+ };+ }++ const minSide = Math.min(rect.width, rect.height);+ const minCount = Math.min(+ best.sideCounts[0],+ best.sideCounts[1],+ best.sideCounts[2],+ best.sideCounts[3]+ );+ if (minSide < 0.1 * diag || minCount < Math.max(2, Math.floor(pts.length * 0.05))) {+ return null;+ }++ // Gentle square snap when sides are already within 8% of each other+ const ratio = minSide / Math.max(rect.width, rect.height);+ if (ratio >= 0.92) {+ const avgSide = (rect.width + rect.height) * 0.5;+ rect = { ...rect, width: avgSide, height: avgSide };+ }++ return {+ rect,+ rms: best.rms,+ max: best.max,+ perimeter: 2 * (rect.width + rect.height),+ meanNormCornerDist: best.meanNormCornerDist,+ };+}++/**+ * Computes the circumcircle and signed sweep of an arc passing from start -> mid -> end.+ */+export function computeArcCircle(+ start: Vec2,+ mid: Vec2,+ end: Vec2+): { cx: number; cy: number; radius: number; startAngle: number; sweep: number } | null {+ const ax = start.x;+ const ay = start.y;+ const bx = mid.x;+ const by = mid.y;+ const cx = end.x;+ const cy = end.y;++ const chordLen = Math.hypot(cx - ax, cy - ay);+ const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));+ if (Math.abs(d) < Math.max(1e-3, 1e-4 * chordLen * chordLen)) {+ return null;+ }++ const a2 = ax * ax + ay * ay;+ const b2 = bx * bx + by * by;+ const c2 = cx * cx + cy * cy;+ const ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;+ const uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;+ const radius = Math.hypot(ax - ux, ay - uy);++ if (!Number.isFinite(radius) || radius < 1 || radius > Math.max(20000, chordLen * 35)) {+ return null;+ }++ const startAngle = Math.atan2(ay - uy, ax - ux);+ const midAngle = Math.atan2(by - uy, bx - ux);+ const endAngle = Math.atan2(cy - uy, cx - ux);++ const ccwMid = mod2Pi(midAngle - startAngle);+ const ccwEnd = mod2Pi(endAngle - startAngle);++ const sweep = ccwMid < ccwEnd ? ccwEnd : ccwEnd - TWO_PI;+ return { cx: ux, cy: uy, radius, startAngle, sweep };+}++/**+ * Recognizes a freehand stroke as one of:+ * line, arc, circle, ellipse, triangle, or rectangle.+ * Returns null if the stroke is too short or does not cleanly match any of the 6 shapes.+ */+export function recognizeQuickShape(+ rawPoints: ReadonlyArray<Point>,+ holdToleranceDoc: number = 4+): QuickShapeRecognitionResult | null {+ if (!rawPoints || rawPoints.length < 2) return null;++ const trimmed = trimTrailingHoldJitter(rawPoints, Math.max(0.5, holdToleranceDoc));+ const totalLen = polylineLength(trimmed);+ if (totalLen < QUICK_SHAPE_MIN_STROKE_LENGTH_DOC) return null;++ const bounds = computeBounds(trimmed);+ if (bounds.diag < 18) return null;++ const resampled = resamplePolyline(trimmed, 64);+ const first = resampled[0];+ const last = resampled[resampled.length - 1];+ const endDist = dist(first, last);++ // Check for closure (direct or slight overshoot past start)+ let closedTrimStart = 0;+ let closedTrimEnd = resampled.length - 1;+ let minClosureDist = endDist;+ const n = resampled.length;+ const tailRange = Math.floor(n * 0.22);+ for (let i = 0; i <= tailRange; i++) {+ for (let j = n - 1 - tailRange; j < n; j++) {+ if (j - i < Math.floor(n * 0.65)) continue;+ const d = dist(resampled[i], resampled[j]);+ if (d < minClosureDist) {+ minClosureDist = d;+ closedTrimStart = i;+ closedTrimEnd = j;+ }+ }+ }++ const isClosed =+ (endDist <= Math.max(22, 0.34 * bounds.diag) && endDist <= 0.24 * totalLen) ||+ (minClosureDist <= Math.max(18, 0.22 * bounds.diag) &&+ minClosureDist <= 0.18 * totalLen &&+ Math.abs(computeCentroidWindingAngle(resampled.slice(closedTrimStart, closedTrimEnd + 1))) >=+ 1.55 * Math.PI);++ // 1. Evaluate Line candidate (open stroke)+ let lineCandidate: { shape: QuickShapeLine; rmsNorm: number; maxNorm: number } | null = null;+ if (!isClosed && endDist >= 16) {+ const straightRatio = endDist / Math.max(1e-6, totalLen);+ if (straightRatio >= 0.88) {+ const dx = last.x - first.x;+ const dy = last.y - first.y;+ const lenSq = dx * dx + dy * dy;+ let sumSq = 0;+ let maxD = 0;+ let outOfRange = false;+ for (let i = 0; i < resampled.length; i++) {+ const p = resampled[i];+ const t = ((p.x - first.x) * dx + (p.y - first.y) * dy) / lenSq;+ if (t < -0.1 || t > 1.1) {+ outOfRange = true;+ break;+ }+ const d = pointToSegmentDist(p, first, last);+ sumSq += d * d;+ if (d > maxD) maxD = d;+ }+ if (!outOfRange) {+ const rmsNorm = Math.sqrt(sumSq / resampled.length) / endDist;+ const maxNorm = maxD / endDist;+ if (rmsNorm <= 0.055 && maxNorm <= 0.13) {+ let endPt = { x: last.x, y: last.y };+ // Subtle snap within 2 deg to pure horizontal/vertical for clean lines+ const angle = Math.atan2(dy, dx);+ const snappedAxis = snapAngleRad(angle, 90);+ if (Math.abs(angle - snappedAxis) < (2.0 * Math.PI) / 180) {+ endPt = {+ x: first.x + Math.cos(snappedAxis) * endDist,+ y: first.y + Math.sin(snappedAxis) * endDist,+ };+ }+ lineCandidate = {+ shape: { kind: 'line', start: { x: first.x, y: first.y }, end: endPt },+ rmsNorm,+ maxNorm,+ };+ }+ }+ }+ }++ // 2. Evaluate Arc candidate (open curved stroke)+ let arcCandidate: {+ shape: QuickShapeArc;+ rmsNorm: number;+ maxNorm: number;+ sagittaRatio: number;+ } | null = null;+ if (!isClosed) {+ const circ = fitCircleLeastSquares(resampled);+ if (circ && circ.radius <= totalLen * 12) {+ // Unwrap angles from start to end to check monotonicity (rejects S-curves)+ let netSweep = 0;+ let absSweep = 0;+ let prevA = Math.atan2(resampled[0].y - circ.cy, resampled[0].x - circ.cx);+ for (let i = 1; i < resampled.length; i++) {+ const a = Math.atan2(resampled[i].y - circ.cy, resampled[i].x - circ.cx);+ let da = a - prevA;+ while (da > Math.PI) da -= TWO_PI;+ while (da < -Math.PI) da += TWO_PI;+ netSweep += da;+ absSweep += Math.abs(da);+ prevA = a;+ }++ const absNetSweep = Math.abs(netSweep);+ const monotonicity = absSweep > 1e-4 ? absNetSweep / absSweep : 0;+ const startAngle = Math.atan2(first.y - circ.cy, first.x - circ.cx);+ const midAngle = startAngle + netSweep * 0.5;+ const arcStart: Vec2 = {+ x: circ.cx + Math.cos(startAngle) * circ.radius,+ y: circ.cy + Math.sin(startAngle) * circ.radius,+ };+ const arcMid: Vec2 = {+ x: circ.cx + Math.cos(midAngle) * circ.radius,+ y: circ.cy + Math.sin(midAngle) * circ.radius,+ };+ const arcEndAngle = startAngle + netSweep;+ const arcEnd: Vec2 = {+ x: circ.cx + Math.cos(arcEndAngle) * circ.radius,+ y: circ.cy + Math.sin(arcEndAngle) * circ.radius,+ };++ const chordLen = Math.max(1, dist(arcStart, arcEnd));+ const sagitta = pointToSegmentDist(arcMid, arcStart, arcEnd);+ const sagittaRatio = sagitta / chordLen;++ if (+ monotonicity >= 0.8 &&+ absNetSweep >= 0.32 &&+ absNetSweep <= 5.65 &&+ sagittaRatio >= 0.065+ ) {+ let sumSq = 0;+ let maxD = 0;+ for (let i = 0; i < resampled.length; i++) {+ const d = Math.abs(Math.hypot(resampled[i].x - circ.cx, resampled[i].y - circ.cy) - circ.radius);+ sumSq += d * d;+ if (d > maxD) maxD = d;+ }+ const rmsNorm = Math.sqrt(sumSq / resampled.length) / bounds.diag;+ const maxNorm = maxD / bounds.diag;+ const expectedArcLen = circ.radius * absNetSweep;+ const lenRatio = totalLen / Math.max(1, expectedArcLen);++ if (rmsNorm <= 0.085 && maxNorm <= 0.2 && lenRatio >= 0.78 && lenRatio <= 1.28) {+ arcCandidate = {+ shape: { kind: 'arc', start: arcStart, mid: arcMid, end: arcEnd },+ rmsNorm,+ maxNorm,+ sagittaRatio,+ };+ }+ }+ }+ }++ if (!isClosed) {+ if (lineCandidate && (!arcCandidate || arcCandidate.sagittaRatio < 0.085)) {+ return {+ shape: lineCandidate.shape,+ confidence: clamp(1 - lineCandidate.rmsNorm * 8, 0.2, 1),+ rmsNorm: lineCandidate.rmsNorm,+ };+ }+ if (arcCandidate) {+ return {+ shape: arcCandidate.shape,+ confidence: clamp(1 - arcCandidate.rmsNorm * 8, 0.2, 1),+ rmsNorm: arcCandidate.rmsNorm,+ };+ }+ if (lineCandidate) {+ return {+ shape: lineCandidate.shape,+ confidence: clamp(1 - lineCandidate.rmsNorm * 8, 0.2, 1),+ rmsNorm: lineCandidate.rmsNorm,+ };+ }+ return null;+ }++ // 3. Closed Shapes: Circle, Ellipse, Triangle, Rectangle+ const loopSource =+ closedTrimEnd - closedTrimStart >= Math.floor(n * 0.65)+ ? resampled.slice(closedTrimStart, closedTrimEnd + 1)+ : resampled;+ const loopPts = resamplePolyline(loopSource, 64);+ const loopBounds = computeBounds(loopPts);+ const loopDiag = Math.max(1, loopBounds.diag);+ const loopLen = polylineLength(loopPts) + dist(loopPts[0], loopPts[loopPts.length - 1]);+ const enclosedArea = shoelaceArea(loopPts);++ // Reject folded back-and-forth lines and figure-8 self-crossing scribbles+ const totalTurn = Math.abs(computeCentroidWindingAngle(loopPts));+ if (totalTurn < 1.3 * Math.PI || enclosedArea < 0.035 * loopDiag * loopDiag) {+ return null;+ }++ // Candidate A: Circle+ let circleCand: {+ shape: QuickShapeCircle;+ rmsNorm: number;+ maxNorm: number;+ score: number;+ } | null = null;+ const circleFit = fitCircleLeastSquares(loopPts);+ if (circleFit) {+ // Verify angular coverage across 12 bins+ const bins = new Uint8Array(12);+ let sumSq = 0;+ let maxD = 0;+ for (let i = 0; i < loopPts.length; i++) {+ const dx = loopPts[i].x - circleFit.cx;+ const dy = loopPts[i].y - circleFit.cy;+ const d = Math.abs(Math.hypot(dx, dy) - circleFit.radius);+ sumSq += d * d;+ if (d > maxD) maxD = d;+ const bin = Math.floor((mod2Pi(Math.atan2(dy, dx)) / TWO_PI) * 12) % 12;+ bins[bin] = 1;+ }+ let filledBins = 0;+ for (let b = 0; b < 12; b++) filledBins += bins[b];+ const rmsNorm = Math.sqrt(sumSq / loopPts.length) / loopDiag;+ const maxNorm = maxD / loopDiag;+ const perimRatio = loopLen / Math.max(1, TWO_PI * circleFit.radius);++ if (filledBins >= 10 && rmsNorm <= 0.095 && maxNorm <= 0.23 && perimRatio >= 0.78 && perimRatio <= 1.32) {+ const handleAngle = Math.atan2(last.y - circleFit.cy, last.x - circleFit.cx);+ circleCand = {+ shape: {+ kind: 'circle',+ center: { x: circleFit.cx, y: circleFit.cy },+ radius: circleFit.radius,+ handleAngle,+ },+ rmsNorm,+ maxNorm,+ score: rmsNorm * 0.72 + maxNorm * 0.28,+ };+ }+ }++ // Candidate B: Ellipse+ let ellipseCand: {+ shape: QuickShapeEllipse;+ rmsNorm: number;+ maxNorm: number;+ score: number;+ aspect: number;+ } | null = null;+ const ellFit = fitEllipseGeometric(loopPts);+ if (ellFit && ellFit.ry >= 4 && ellFit.rx >= 6) {+ const rmsNorm = ellFit.rms / loopDiag;+ const maxNorm = ellFit.max / loopDiag;+ // Ramanujan perimeter approximation+ const h = Math.pow(ellFit.rx - ellFit.ry, 2) / Math.pow(ellFit.rx + ellFit.ry, 2);+ const ellPerim = Math.PI * (ellFit.rx + ellFit.ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));+ const perimRatio = loopLen / Math.max(1, ellPerim);+ const aspect = ellFit.ry / ellFit.rx;++ if (rmsNorm <= 0.095 && maxNorm <= 0.23 && perimRatio >= 0.78 && perimRatio <= 1.34) {+ const cosR = Math.cos(-ellFit.rotation);+ const sinR = Math.sin(-ellFit.rotation);+ const ldx = (last.x - ellFit.cx) * cosR - (last.y - ellFit.cy) * sinR;+ const ldy = (last.x - ellFit.cx) * sinR + (last.y - ellFit.cy) * cosR;+ const handleAngle = Math.atan2(ldy / ellFit.ry, ldx / ellFit.rx);+ ellipseCand = {+ shape: {+ kind: 'ellipse',+ center: { x: ellFit.cx, y: ellFit.cy },+ rx: ellFit.rx,+ ry: ellFit.ry,+ rotation: ellFit.rotation,+ handleAngle,+ },+ rmsNorm,+ maxNorm,+ score: rmsNorm * 0.72 + maxNorm * 0.28,+ aspect,+ };+ }+ }++ // Candidate C: Triangle+ let triCand: {+ shape: QuickShapeTriangle;+ rmsNorm: number;+ maxNorm: number;+ score: number;+ } | null = null;+ const triFit = fitTriangleClosed(loopPts, loopDiag);+ if (triFit) {+ const rmsNorm = triFit.rms / loopDiag;+ const maxNorm = triFit.max / loopDiag;+ const perimRatio = loopLen / Math.max(1, triFit.perimeter);+ if (rmsNorm <= 0.095 && maxNorm <= 0.24 && perimRatio >= 0.78 && perimRatio <= 1.34) {+ triCand = {+ shape: {+ kind: 'triangle',+ vertices: triFit.vertices,+ },+ rmsNorm,+ maxNorm,+ score: rmsNorm * 0.72 + maxNorm * 0.28,+ };+ }+ }++ // Candidate D: Rectangle+ let rectCand: {+ shape: QuickShapeRectangle;+ rmsNorm: number;+ maxNorm: number;+ score: number;+ meanNormCornerDist: number;+ } | null = null;+ const rectFit = fitRectangleClosed(loopPts, loopDiag);+ if (rectFit) {+ const rmsNorm = rectFit.rms / loopDiag;+ const maxNorm = rectFit.max / loopDiag;+ const perimRatio = loopLen / Math.max(1, rectFit.perimeter);+ if (rmsNorm <= 0.095 && maxNorm <= 0.24 && perimRatio >= 0.78 && perimRatio <= 1.34) {+ // Corner-proximity invariant cleanly separates rectangles (meanNormCornerDist ~0.0-0.20)+ // from ellipses/circles (meanNormCornerDist ~0.414 in unit-square space)+ let cornerAdj = 0;+ if (rectFit.meanNormCornerDist > 0.28) {+ cornerAdj += (rectFit.meanNormCornerDist - 0.28) * 0.22;+ } else if (rectFit.meanNormCornerDist < 0.19) {+ cornerAdj -= (0.19 - rectFit.meanNormCornerDist) * 0.08;+ }+ rectCand = {+ shape: rectFit.rect,+ rmsNorm,+ maxNorm,+ score: Math.max(0, rmsNorm * 0.72 + maxNorm * 0.28 + cornerAdj),+ meanNormCornerDist: rectFit.meanNormCornerDist,+ };+ }+ }++ // Pick best curved candidate (prefer Circle over Ellipse when nearly circular)+ let bestCurved: {+ shape: QuickShapeCircle | QuickShapeEllipse;+ rmsNorm: number;+ score: number;+ } | null = null;+ if (circleCand && ellipseCand) {+ if (ellipseCand.aspect >= 0.85 && circleCand.rmsNorm <= ellipseCand.rmsNorm + 0.025) {+ bestCurved = circleCand;+ } else {+ bestCurved = ellipseCand;+ }+ } else if (circleCand) {+ bestCurved = circleCand;+ } else if (ellipseCand) {+ bestCurved = ellipseCand;+ }++ // Pick overall best closed shape+ const candidates: Array<{ shape: QuickShapeGeometry; rmsNorm: number; score: number }> = [];+ if (bestCurved) candidates.push(bestCurved);+ if (triCand) candidates.push(triCand);+ if (rectCand) candidates.push(rectCand);++ if (candidates.length === 0) return null;++ candidates.sort((a, b) => a.score - b.score);+ const winner = candidates[0];++ return {+ shape: winner.shape,+ confidence: clamp(1 - winner.rmsNorm * 7.5, 0.2, 1),+ rmsNorm: winner.rmsNorm,+ };+}++/**+ * Extracts a clean median-trimmed brush style profile from the original freehand stroke+ * so the snapped geometric shape preserves the artist's actual pressure & width feel.+ */+export function extractQuickShapeStrokeStyle(+ points: ReadonlyArray<Point>,+ fallbackSize: number+): QuickShapeStrokeStyle {+ if (!points || points.length === 0) {+ return { pressure: 0.5, width: Math.max(1, fallbackSize), tiltX: 0, tiltY: 0, twist: 0 };+ }++ // Use middle 70% of points to avoid soft pen-down/pen-up taper outliers+ const n = points.length;+ const start = n >= 6 ? Math.floor(n * 0.15) : 0;+ const end = n >= 6 ? Math.max(start + 1, Math.ceil(n * 0.85)) : n;+ const slice = points.slice(start, end);++ const widths = slice.map((p) => p.width).sort((a, b) => a - b);+ const pressures = slice.map((p) => p.pressure).sort((a, b) => a - b);+ const midIdx = Math.floor(widths.length * 0.55);++ let tiltX = 0;+ let tiltY = 0;+ let twist = 0;+ for (let i = 0; i < slice.length; i++) {+ tiltX += slice[i].tiltX ?? 0;+ tiltY += slice[i].tiltY ?? 0;+ twist += slice[i].twist ?? 0;+ }+ const inv = 1 / Math.max(1, slice.length);++ return {+ pressure: clamp(pressures[midIdx] ?? 0.5, 0.05, 1.0),+ width: Math.max(0.5, widths[midIdx] ?? fallbackSize),+ tiltX: tiltX * inv,+ tiltY: tiltY * inv,+ twist: twist * inv,+ };+}++function makeStrokePoint(+ x: number,+ y: number,+ style: QuickShapeStrokeStyle,+ timestamp: number,+ isCorner: boolean = false+): Point {+ return {+ x,+ y,+ pressure: style.pressure,+ width: style.width,+ tiltX: style.tiltX,+ tiltY: style.tiltY,+ twist: style.twist,+ timestamp,+ isCorner,+ };+}++/**+ * Samples a straight segment with tight corner brackets so centripetal Catmull-Rom splines+ * stay razor-sharp at polygon corners with zero loop overshoot.+ */+function appendStraightSegment(+ out: Point[],+ a: Vec2,+ b: Vec2,+ style: QuickShapeStrokeStyle,+ stepPx: number,+ includeStart: boolean+): void {+ const segLen = dist(a, b);+ const baseTs = out.length * 4;+ if (includeStart) {+ out.push(makeStrokePoint(a.x, a.y, style, baseTs, true));+ }+ if (segLen < 1e-4) return;++ const ux = (b.x - a.x) / segLen;+ const uy = (b.y - a.y) / segLen;++ // Tight bracket just after start corner+ if (segLen > 2.5) {+ out.push(makeStrokePoint(a.x + ux * 0.6, a.y + uy * 0.6, style, out.length * 4, false));+ }++ const steps = Math.max(2, Math.ceil(segLen / Math.max(2, stepPx)));+ for (let i = 1; i < steps; i++) {+ const t = i / steps;+ const d = t * segLen;+ if (d <= 0.8 || d >= segLen - 0.8) continue;+ out.push(makeStrokePoint(a.x + ux * d, a.y + uy * d, style, out.length * 4, false));+ }++ // Tight bracket just before end corner+ if (segLen > 2.5) {+ out.push(makeStrokePoint(b.x - ux * 0.6, b.y - uy * 0.6, style, out.length * 4, false));+ }+ out.push(makeStrokePoint(b.x, b.y, style, out.length * 4, true));+}++/**+ * Generates dense, perfectly smooth brush `Point[]` along any QuickShape geometry+ * ready for `renderCompleteStroke` (raster, natural paint, ribbon, dual brush, vector, mask).+ */+export function sampleQuickShapePoints(+ shape: QuickShapeGeometry,+ style: QuickShapeStrokeStyle+): Point[] {+ const stepPx = clamp(style.width * 0.45, 2.5, 8);+ const out: Point[] = [];++ switch (shape.kind) {+ case 'line': {+ appendStraightSegment(out, shape.start, shape.end, style, stepPx, true);+ return out;+ }++ case 'arc': {+ const circle = computeArcCircle(shape.start, shape.mid, shape.end);+ if (!circle) {+ appendStraightSegment(out, shape.start, shape.end, style, stepPx, true);+ return out;+ }+ const arcLen = Math.abs(circle.sweep) * circle.radius;+ const steps = clamp(Math.ceil(arcLen / stepPx), 16, 360);+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const a = circle.startAngle + circle.sweep * t;+ out.push(+ makeStrokePoint(+ circle.cx + Math.cos(a) * circle.radius,+ circle.cy + Math.sin(a) * circle.radius,+ style,+ i * 4,+ i === 0 || i === steps+ )+ );+ }+ return out;+ }++ case 'circle': {+ const r = Math.max(1, shape.radius);+ const circum = TWO_PI * r;+ const steps = clamp(Math.ceil(circum / stepPx), 36, 480);+ const startA = shape.handleAngle;+ for (let i = 0; i <= steps; i++) {+ const a = startA + (TWO_PI * i) / steps;+ out.push(+ makeStrokePoint(+ shape.center.x + Math.cos(a) * r,+ shape.center.y + Math.sin(a) * r,+ style,+ i * 4,+ false+ )+ );+ }+ return out;+ }++ case 'ellipse': {+ const rx = Math.max(1, shape.rx);+ const ry = Math.max(1, shape.ry);+ const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2);+ const perim = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));+ const steps = clamp(Math.ceil(perim / stepPx), 40, 520);+ const cosR = Math.cos(shape.rotation);+ const sinR = Math.sin(shape.rotation);+ const startA = shape.handleAngle;+ for (let i = 0; i <= steps; i++) {+ const a = startA + (TWO_PI * i) / steps;+ const lx = Math.cos(a) * rx;+ const ly = Math.sin(a) * ry;+ out.push(+ makeStrokePoint(+ shape.center.x + lx * cosR - ly * sinR,+ shape.center.y + lx * sinR + ly * cosR,+ style,+ i * 4,+ false+ )+ );+ }+ return out;+ }++ case 'triangle': {+ const [v0, v1, v2] = shape.vertices;+ appendStraightSegment(out, v0, v1, style, stepPx, true);+ appendStraightSegment(out, v1, v2, style, stepPx, false);+ appendStraightSegment(out, v2, v0, style, stepPx, false);+ return out;+ }++ case 'rectangle': {+ const [c0, c1, c2, c3] = getRectangleCorners(shape);+ appendStraightSegment(out, c0, c1, style, stepPx, true);+ appendStraightSegment(out, c1, c2, style, stepPx, false);+ appendStraightSegment(out, c2, c3, style, stepPx, false);+ appendStraightSegment(out, c3, c0, style, stepPx, false);+ return out;+ }+ }+}++export function computeQuickShapeBounds(shape: QuickShapeGeometry): {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+} {+ switch (shape.kind) {+ case 'line':+ return {+ minX: Math.min(shape.start.x, shape.end.x),+ minY: Math.min(shape.start.y, shape.end.y),+ maxX: Math.max(shape.start.x, shape.end.x),+ maxY: Math.max(shape.start.y, shape.end.y),+ };+ case 'arc': {+ const circle = computeArcCircle(shape.start, shape.mid, shape.end);+ if (!circle) {+ return {+ minX: Math.min(shape.start.x, shape.mid.x, shape.end.x),+ minY: Math.min(shape.start.y, shape.mid.y, shape.end.y),+ maxX: Math.max(shape.start.x, shape.mid.x, shape.end.x),+ maxY: Math.max(shape.start.y, shape.mid.y, shape.end.y),+ };+ }+ let minX = Math.min(shape.start.x, shape.mid.x, shape.end.x);+ let minY = Math.min(shape.start.y, shape.mid.y, shape.end.y);+ let maxX = Math.max(shape.start.x, shape.mid.x, shape.end.x);+ let maxY = Math.max(shape.start.y, shape.mid.y, shape.end.y);+ const samples = 24;+ for (let i = 1; i < samples; i++) {+ const a = circle.startAngle + (circle.sweep * i) / samples;+ const x = circle.cx + Math.cos(a) * circle.radius;+ const y = circle.cy + Math.sin(a) * circle.radius;+ if (x < minX) minX = x;+ if (y < minY) minY = y;+ if (x > maxX) maxX = x;+ if (y > maxY) maxY = y;+ }+ return { minX, minY, maxX, maxY };+ }+ case 'circle':+ return {+ minX: shape.center.x - shape.radius,+ minY: shape.center.y - shape.radius,+ maxX: shape.center.x + shape.radius,+ maxY: shape.center.y + shape.radius,+ };+ case 'ellipse': {+ const cos = Math.cos(shape.rotation);+ const sin = Math.sin(shape.rotation);+ const ex = Math.hypot(shape.rx * cos, shape.ry * sin);+ const ey = Math.hypot(shape.rx * sin, shape.ry * cos);+ return {+ minX: shape.center.x - ex,+ minY: shape.center.y - ey,+ maxX: shape.center.x + ex,+ maxY: shape.center.y + ey,+ };+ }+ case 'triangle': {+ const [v0, v1, v2] = shape.vertices;+ return {+ minX: Math.min(v0.x, v1.x, v2.x),+ minY: Math.min(v0.y, v1.y, v2.y),+ maxX: Math.max(v0.x, v1.x, v2.x),+ maxY: Math.max(v0.y, v1.y, v2.y),+ };+ }+ case 'rectangle': {+ const [c0, c1, c2, c3] = getRectangleCorners(shape);+ return {+ minX: Math.min(c0.x, c1.x, c2.x, c3.x),+ minY: Math.min(c0.y, c1.y, c2.y, c3.y),+ maxX: Math.max(c0.x, c1.x, c2.x, c3.x),+ maxY: Math.max(c0.y, c1.y, c2.y, c3.y),+ };+ }+ }+}++export function getQuickShapeLabel(kind: QuickShapeKind): string {+ switch (kind) {+ case 'line':+ return 'Line';+ case 'arc':+ return 'Arc';+ case 'circle':+ return 'Circle';+ case 'ellipse':+ return 'Ellipse';+ case 'triangle':+ return 'Triangle';+ case 'rectangle':+ return 'Rectangle';+ }+}++export function getQuickShapeHandles(+ shape: QuickShapeGeometry,+ activeHandleId: string+): QuickShapeHandle[] {+ switch (shape.kind) {+ case 'line':+ return [+ { id: 'start', x: shape.start.x, y: shape.start.y, kind: 'endpoint', active: activeHandleId === 'start' },+ { id: 'end', x: shape.end.x, y: shape.end.y, kind: 'endpoint', active: activeHandleId === 'end' },+ ];+ case 'arc':+ return [+ { id: 'start', x: shape.start.x, y: shape.start.y, kind: 'endpoint', active: activeHandleId === 'start' },+ { id: 'mid', x: shape.mid.x, y: shape.mid.y, kind: 'mid', active: activeHandleId === 'mid' },+ { id: 'end', x: shape.end.x, y: shape.end.y, kind: 'endpoint', active: activeHandleId === 'end' },+ ];+ case 'circle': {+ const rx = shape.center.x + Math.cos(shape.handleAngle) * shape.radius;+ const ry = shape.center.y + Math.sin(shape.handleAngle) * shape.radius;+ return [+ { id: 'center', x: shape.center.x, y: shape.center.y, kind: 'center', active: activeHandleId === 'center' },+ { id: 'rim', x: rx, y: ry, kind: 'rim', active: activeHandleId === 'rim' },+ ];+ }+ case 'ellipse': {+ const cos = Math.cos(shape.rotation);+ const sin = Math.sin(shape.rotation);+ const ux = cos * shape.rx;+ const uy = sin * shape.rx;+ const vx = -sin * shape.ry;+ const vy = cos * shape.ry;+ const lx = Math.cos(shape.handleAngle) * shape.rx;+ const ly = Math.sin(shape.handleAngle) * shape.ry;+ const px = shape.center.x + lx * cos - ly * sin;+ const py = shape.center.y + lx * sin + ly * cos;+ return [+ { id: 'axis-pos-x', x: shape.center.x + ux, y: shape.center.y + uy, kind: 'axis', active: false },+ { id: 'axis-neg-x', x: shape.center.x - ux, y: shape.center.y - uy, kind: 'axis', active: false },+ { id: 'axis-pos-y', x: shape.center.x + vx, y: shape.center.y + vy, kind: 'axis', active: false },+ { id: 'axis-neg-y', x: shape.center.x - vx, y: shape.center.y - vy, kind: 'axis', active: false },+ { id: 'rim', x: px, y: py, kind: 'rim', active: activeHandleId === 'rim' },+ ];+ }+ case 'triangle':+ return shape.vertices.map((v, i) => ({+ id: `corner-${i}`,+ x: v.x,+ y: v.y,+ kind: 'corner' as const,+ active: activeHandleId === `corner-${i}`,+ }));+ case 'rectangle':+ return getRectangleCorners(shape).map((c, i) => ({+ id: `corner-${i}`,+ x: c.x,+ y: c.y,+ kind: 'corner' as const,+ active: activeHandleId === `corner-${i}`,+ }));+ }+}++export function buildQuickShapePreview(session: QuickShapeSession): QuickShapePreviewState {+ const shape = session.currentShape;+ const handles = getQuickShapeHandles(shape, session.activeHandleId);+ const activeHandle = handles.find((h) => h.active) ?? handles[handles.length - 1];++ let svgPath = '';+ let readout = '';+ let hint = '';+ let guideLine: { x1: number; y1: number; x2: number; y2: number } | undefined;+ let centerMarker: Vec2 | undefined;++ switch (shape.kind) {+ case 'line': {+ svgPath = `M ${shape.start.x} ${shape.start.y} L ${shape.end.x} ${shape.end.y}`;+ const len = Math.round(dist(shape.start, shape.end));+ const deg = Math.round((Math.atan2(shape.end.y - shape.start.y, shape.end.x - shape.start.x) * 180) / Math.PI);+ readout = `${len}px · ${deg}°`;+ hint = 'Shift: 15° · Alt: Move';+ break;+ }+ case 'arc': {+ const circle = computeArcCircle(shape.start, shape.mid, shape.end);+ if (circle) {+ const largeArc = Math.abs(circle.sweep) > Math.PI ? 1 : 0;+ const sweepFlag = circle.sweep >= 0 ? 1 : 0;+ svgPath = `M ${shape.start.x} ${shape.start.y} A ${circle.radius} ${circle.radius} 0 ${largeArc} ${sweepFlag} ${shape.end.x} ${shape.end.y}`;+ readout = `${Math.round((Math.abs(circle.sweep) * 180) / Math.PI)}° · R ${Math.round(circle.radius)}px`;+ centerMarker = { x: circle.cx, y: circle.cy };+ } else {+ svgPath = `M ${shape.start.x} ${shape.start.y} L ${shape.end.x} ${shape.end.y}`;+ readout = `${Math.round(dist(shape.start, shape.end))}px`;+ }+ guideLine = { x1: shape.start.x, y1: shape.start.y, x2: shape.end.x, y2: shape.end.y };+ hint = 'Alt: Bend · Shift: 15°';+ break;+ }+ case 'circle': {+ const r = Math.max(1, shape.radius);+ const { x: cx, y: cy } = shape.center;+ svgPath = `M ${cx - r} ${cy} A ${r} ${r} 0 1 0 ${cx + r} ${cy} A ${r} ${r} 0 1 0 ${cx - r} ${cy} Z`;+ const rim = handles.find((h) => h.id === 'rim');+ if (rim) {+ guideLine = { x1: cx, y1: cy, x2: rim.x, y2: rim.y };+ }+ centerMarker = shape.center;+ readout = `Ø ${Math.round(r * 2)}px`;+ hint = 'Alt: Move';+ break;+ }+ case 'ellipse': {+ const rx = Math.max(1, shape.rx);+ const ry = Math.max(1, shape.ry);+ const cos = Math.cos(shape.rotation);+ const sin = Math.sin(shape.rotation);+ const deg = (shape.rotation * 180) / Math.PI;+ const p1x = shape.center.x - rx * cos;+ const p1y = shape.center.y - rx * sin;+ const p2x = shape.center.x + rx * cos;+ const p2y = shape.center.y + rx * sin;+ svgPath = `M ${p1x} ${p1y} A ${rx} ${ry} ${deg} 1 0 ${p2x} ${p2y} A ${rx} ${ry} ${deg} 1 0 ${p1x} ${p1y} Z`;+ centerMarker = shape.center;+ readout = `${Math.round(rx * 2)} × ${Math.round(ry * 2)}px`;+ hint = 'Shift: Circle · Alt: Stretch';+ break;+ }+ case 'triangle': {+ const [v0, v1, v2] = shape.vertices;+ svgPath = `M ${v0.x} ${v0.y} L ${v1.x} ${v1.y} L ${v2.x} ${v2.y} Z`;+ const perim = Math.round(dist(v0, v1) + dist(v1, v2) + dist(v2, v0));+ readout = `P ${perim}px`;+ hint = 'Shift: Snap · Alt: Scale/Rotate';+ break;+ }+ case 'rectangle': {+ const [c0, c1, c2, c3] = getRectangleCorners(shape);+ svgPath = `M ${c0.x} ${c0.y} L ${c1.x} ${c1.y} L ${c2.x} ${c2.y} L ${c3.x} ${c3.y} Z`;+ centerMarker = shape.center;+ readout = `${Math.round(shape.width)} × ${Math.round(shape.height)}px`;+ hint = 'Shift: Square · Alt: Rotate';+ break;+ }+ }++ return {+ shape,+ label: getQuickShapeLabel(shape.kind),+ readout,+ hint,+ svgPath,+ guideLine,+ centerMarker,+ handles,+ anchorPos: activeHandle ? { x: activeHandle.x, y: activeHandle.y } : session.snapPenPos,+ activeHandleId: session.activeHandleId,+ snappedAtMs: session.snappedAtMs,+ };+}++/**+ * Creates a live interactive QuickShape session immediately upon hold-snap.+ */+export function createQuickShapeSession(+ shape: QuickShapeGeometry,+ snapPenPos: Vec2,+ style: QuickShapeStrokeStyle,+ nowMs: number = performance.now()+): QuickShapeSession {+ let activeHandleId = 'end';+ let activeCornerIndex = 0;+ let initialArcBulgeRatio = 0;++ switch (shape.kind) {+ case 'line':+ activeHandleId = 'end';+ break;+ case 'arc': {+ activeHandleId = 'end';+ const dx = shape.end.x - shape.start.x;+ const dy = shape.end.y - shape.start.y;+ const chordLen = Math.max(1e-4, Math.hypot(dx, dy));+ const nx = -dy / chordLen;+ const ny = dx / chordLen;+ const mx = shape.mid.x - (shape.start.x + shape.end.x) * 0.5;+ const my = shape.mid.y - (shape.start.y + shape.end.y) * 0.5;+ initialArcBulgeRatio = (mx * nx + my * ny) / chordLen;+ break;+ }+ case 'circle':+ case 'ellipse':+ activeHandleId = 'rim';+ break;+ case 'triangle': {+ let bestDist = Infinity;+ for (let i = 0; i < 3; i++) {+ const d = distSq(shape.vertices[i], snapPenPos);+ if (d < bestDist) {+ bestDist = d;+ activeCornerIndex = i;+ }+ }+ activeHandleId = `corner-${activeCornerIndex}`;+ break;+ }+ case 'rectangle': {+ const corners = getRectangleCorners(shape);+ let bestDist = Infinity;+ for (let i = 0; i < 4; i++) {+ const d = distSq(corners[i], snapPenPos);+ if (d < bestDist) {+ bestDist = d;+ activeCornerIndex = i;+ }+ }+ activeHandleId = `corner-${activeCornerIndex}`;+ break;+ }+ }++ return {+ initialShape: shape,+ currentShape: shape,+ snapPenPos: { x: snapPenPos.x, y: snapPenPos.y },+ activeHandleId,+ activeCornerIndex,+ initialArcBulgeRatio,+ hasExitedDeadzone: false,+ style,+ snappedAtMs: nowMs,+ };+}++/**+ * Updates the active QuickShape geometry while the artist drags the pen before releasing it.+ * Uses a tiny screen-space deadzone to prevent unintentional jumps on lift/jitter,+ * and supports direct handle/corner dragging + Shift/Alt modifiers.+ */+export function updateQuickShapeFromDrag(+ session: QuickShapeSession,+ penDocPos: Vec2,+ modifiers: { shiftKey: boolean; altKey: boolean },+ zoom: number = 1.0+): QuickShapeGeometry {+ const dx = penDocPos.x - session.snapPenPos.x;+ const dy = penDocPos.y - session.snapPenPos.y;+ const deadzoneDoc = QUICK_SHAPE_DRAG_DEADZONE_SCREEN_PX / Math.max(0.1, zoom);++ if (!session.hasExitedDeadzone) {+ if (Math.hypot(dx, dy) < deadzoneDoc && !modifiers.shiftKey) {+ session.currentShape = session.initialShape;+ return session.currentShape;+ }+ if (Math.hypot(dx, dy) >= deadzoneDoc) {+ session.hasExitedDeadzone = true;+ }+ }++ const init = session.initialShape;++ switch (init.kind) {+ case 'line': {+ if (modifiers.altKey) {+ session.activeHandleId = 'end';+ session.currentShape = {+ kind: 'line',+ start: { x: init.start.x + dx, y: init.start.y + dy },+ end: { x: init.end.x + dx, y: init.end.y + dy },+ };+ } else {+ session.activeHandleId = 'end';+ let endX = init.end.x + dx;+ let endY = init.end.y + dy;+ if (modifiers.shiftKey) {+ const vx = endX - init.start.x;+ const vy = endY - init.start.y;+ const len = Math.hypot(vx, vy);+ if (len > 1) {+ const ang = snapAngleRad(Math.atan2(vy, vx), 15);+ endX = init.start.x + Math.cos(ang) * len;+ endY = init.start.y + Math.sin(ang) * len;+ }+ }+ session.currentShape = {+ kind: 'line',+ start: init.start,+ end: { x: endX, y: endY },+ };+ }+ return session.currentShape;+ }++ case 'arc': {+ if (modifiers.altKey) {+ // Alt bends the arc by dragging the curvature midpoint handle directly+ session.activeHandleId = 'mid';+ const curMidX = init.mid.x + dx;+ const curMidY = init.mid.y + dy;+ let mid: Vec2 = { x: curMidX, y: curMidY };+ if (modifiers.shiftKey) {+ // Snap to clean semicircle on the side the user dragged toward+ const cdx = init.end.x - init.start.x;+ const cdy = init.end.y - init.start.y;+ const cLen = Math.max(1, Math.hypot(cdx, cdy));+ const nx = -cdy / cLen;+ const ny = cdx / cLen;+ const side =+ (curMidX - (init.start.x + init.end.x) * 0.5) * nx ++ (curMidY - (init.start.y + init.end.y) * 0.5) * ny >=+ 0+ ? 1+ : -1;+ mid = {+ x: (init.start.x + init.end.x) * 0.5 + nx * (cLen * 0.5 * side),+ y: (init.start.y + init.end.y) * 0.5 + ny * (cLen * 0.5 * side),+ };+ }+ session.currentShape = {+ kind: 'arc',+ start: init.start,+ mid,+ end: init.end,+ };+ } else {+ // Default: drag endpoint while preserving relative arc curvature bulge+ session.activeHandleId = 'end';+ let endX = init.end.x + dx;+ let endY = init.end.y + dy;+ if (modifiers.shiftKey) {+ const vx = endX - init.start.x;+ const vy = endY - init.start.y;+ const len = Math.hypot(vx, vy);+ if (len > 1) {+ const ang = snapAngleRad(Math.atan2(vy, vx), 15);+ endX = init.start.x + Math.cos(ang) * len;+ endY = init.start.y + Math.sin(ang) * len;+ }+ }+ const cdx = endX - init.start.x;+ const cdy = endY - init.start.y;+ const cLen = Math.max(1e-4, Math.hypot(cdx, cdy));+ const nx = -cdy / cLen;+ const ny = cdx / cLen;+ const mid: Vec2 = {+ x: (init.start.x + endX) * 0.5 + nx * (cLen * session.initialArcBulgeRatio),+ y: (init.start.y + endY) * 0.5 + ny * (cLen * session.initialArcBulgeRatio),+ };+ session.currentShape = {+ kind: 'arc',+ start: init.start,+ mid,+ end: { x: endX, y: endY },+ };+ }+ return session.currentShape;+ }++ case 'circle': {+ if (modifiers.altKey) {+ session.activeHandleId = 'center';+ session.currentShape = {+ kind: 'circle',+ center: { x: init.center.x + dx, y: init.center.y + dy },+ radius: init.radius,+ handleAngle: init.handleAngle,+ };+ } else {+ session.activeHandleId = 'rim';+ const initRimX = init.center.x + Math.cos(init.handleAngle) * init.radius;+ const initRimY = init.center.y + Math.sin(init.handleAngle) * init.radius;+ const targetX = initRimX + dx;+ const targetY = initRimY + dy;+ let radius = Math.max(4, Math.hypot(targetX - init.center.x, targetY - init.center.y));+ if (modifiers.shiftKey) {+ radius = Math.max(5, Math.round(radius / 5) * 5);+ }+ const handleAngle = Math.atan2(targetY - init.center.y, targetX - init.center.x);+ session.currentShape = {+ kind: 'circle',+ center: init.center,+ radius,+ handleAngle,+ };+ }+ return session.currentShape;+ }++ case 'ellipse': {+ session.activeHandleId = 'rim';+ const cosR = Math.cos(init.rotation);+ const sinR = Math.sin(init.rotation);+ const initLx = Math.cos(init.handleAngle) * init.rx;+ const initLy = Math.sin(init.handleAngle) * init.ry;+ const initRimX = init.center.x + initLx * cosR - initLy * sinR;+ const initRimY = init.center.y + initLx * sinR + initLy * cosR;+ const targetX = initRimX + dx;+ const targetY = initRimY + dy;++ if (modifiers.altKey) {+ // Alt stretches rx / ry independently in the ellipse's local frame+ const relX = targetX - init.center.x;+ const relY = targetY - init.center.y;+ const locX = relX * cosR + relY * sinR;+ const locY = -relX * sinR + relY * cosR;+ const initCosH = Math.abs(Math.cos(init.handleAngle));+ const initSinH = Math.abs(Math.sin(init.handleAngle));+ const newRx =+ initCosH > 0.25 ? Math.max(4, Math.abs(locX) / initCosH) : Math.max(4, init.rx + Math.abs(locX) - Math.abs(initLx));+ const newRy =+ initSinH > 0.25 ? Math.max(4, Math.abs(locY) / initSinH) : Math.max(4, init.ry + Math.abs(locY) - Math.abs(initLy));+ session.currentShape = {+ kind: 'ellipse',+ center: init.center,+ rx: newRx,+ ry: newRy,+ rotation: init.rotation,+ handleAngle: Math.atan2(locY / newRy, locX / newRx),+ };+ } else {+ const initVecR = Math.max(4, Math.hypot(initRimX - init.center.x, initRimY - init.center.y));+ const curVecR = Math.max(4, Math.hypot(targetX - init.center.x, targetY - init.center.y));+ const scale = curVecR / initVecR;+ const initAng = Math.atan2(initRimY - init.center.y, initRimX - init.center.x);+ const curAng = Math.atan2(targetY - init.center.y, targetX - init.center.x);+ let rotDelta = curAng - initAng;+ while (rotDelta > Math.PI) rotDelta -= TWO_PI;+ while (rotDelta < -Math.PI) rotDelta += TWO_PI;++ let rx = Math.max(4, init.rx * scale);+ let ry = Math.max(4, init.ry * scale);+ let rotation = normalizeHalfPiAngle(init.rotation + rotDelta);++ if (modifiers.shiftKey) {+ // Shift snaps ellipse to a perfect circle + 15 deg rotation+ const avgR = (rx + ry) * 0.5;+ rx = avgR;+ ry = avgR;+ rotation = normalizeHalfPiAngle(snapAngleRad(rotation, 15));+ }++ session.currentShape = {+ kind: 'ellipse',+ center: init.center,+ rx,+ ry,+ rotation,+ handleAngle: init.handleAngle,+ };+ }+ return session.currentShape;+ }++ case 'triangle': {+ const k = session.activeCornerIndex;+ session.activeHandleId = `corner-${k}`;+ if (modifiers.altKey) {+ // Alt uniformly scales & rotates the entire triangle around its centroid+ const cx = (init.vertices[0].x + init.vertices[1].x + init.vertices[2].x) / 3;+ const cy = (init.vertices[0].y + init.vertices[1].y + init.vertices[2].y) / 3;+ const initCorner = init.vertices[k];+ const targetX = initCorner.x + dx;+ const targetY = initCorner.y + dy;+ const r0 = Math.max(4, Math.hypot(initCorner.x - cx, initCorner.y - cy));+ const r1 = Math.max(4, Math.hypot(targetX - cx, targetY - cy));+ const scale = r1 / r0;+ let rotDelta = Math.atan2(targetY - cy, targetX - cx) - Math.atan2(initCorner.y - cy, initCorner.x - cx);+ if (modifiers.shiftKey) {+ rotDelta = snapAngleRad(rotDelta, 15);+ }+ const cos = Math.cos(rotDelta);+ const sin = Math.sin(rotDelta);+ const nextVerts = init.vertices.map((v) => {+ const rx = (v.x - cx) * scale;+ const ry = (v.y - cy) * scale;+ return { x: cx + rx * cos - ry * sin, y: cy + rx * sin + ry * cos };+ }) as [Vec2, Vec2, Vec2];+ session.currentShape = { kind: 'triangle', vertices: nextVerts };+ } else {+ // Default: drag the active corner handle directly!+ const nextVerts: [Vec2, Vec2, Vec2] = [+ { ...init.vertices[0] },+ { ...init.vertices[1] },+ { ...init.vertices[2] },+ ];+ const targetX = init.vertices[k].x + dx;+ const targetY = init.vertices[k].y + dy;++ if (modifiers.shiftKey) {+ // Shift snaps active corner to form a clean symmetric isosceles / equilateral apex over the opposite base+ const a = init.vertices[(k + 1) % 3];+ const b = init.vertices[(k + 2) % 3];+ const midX = (a.x + b.x) * 0.5;+ const midY = (a.y + b.y) * 0.5;+ const bdx = b.x - a.x;+ const bdy = b.y - a.y;+ const baseLen = Math.max(1, Math.hypot(bdx, bdy));+ const nx = -bdy / baseLen;+ const ny = bdx / baseLen;+ const proj = (targetX - midX) * nx + (targetY - midY) * ny;+ const sign = proj >= 0 ? 1 : -1;+ const eqHeight = baseLen * (Math.sqrt(3) * 0.5);+ const height =+ Math.abs(Math.abs(proj) - eqHeight) < baseLen * 0.25 ? eqHeight : Math.max(4, Math.abs(proj));+ nextVerts[k] = {+ x: midX + nx * height * sign,+ y: midY + ny * height * sign,+ };+ } else {+ nextVerts[k] = { x: targetX, y: targetY };+ }+ session.currentShape = { kind: 'triangle', vertices: nextVerts };+ }+ return session.currentShape;+ }++ case 'rectangle': {+ const k = session.activeCornerIndex;+ session.activeHandleId = `corner-${k}`;+ const initCorners = getRectangleCorners(init);+ const initCorner = initCorners[k];+ const oppCorner = initCorners[(k + 2) % 4];+ const targetX = initCorner.x + dx;+ const targetY = initCorner.y + dy;++ if (modifiers.altKey) {+ // Alt rotates & uniformly scales the rectangle around its center+ const cx = init.center.x;+ const cy = init.center.y;+ const r0 = Math.max(4, Math.hypot(initCorner.x - cx, initCorner.y - cy));+ const r1 = Math.max(4, Math.hypot(targetX - cx, targetY - cy));+ const scale = r1 / r0;+ let rotDelta = Math.atan2(targetY - cy, targetX - cx) - Math.atan2(initCorner.y - cy, initCorner.x - cx);+ let nextRot = normalizeHalfPiAngle(init.rotation + rotDelta);+ if (modifiers.shiftKey) {+ nextRot = normalizeHalfPiAngle(snapAngleRad(nextRot, 15));+ }+ let nextW = Math.max(4, init.width * scale);+ let nextH = Math.max(4, init.height * scale);+ if (modifiers.shiftKey) {+ const s = (nextW + nextH) * 0.5;+ nextW = s;+ nextH = s;+ }+ session.currentShape = {+ kind: 'rectangle',+ center: init.center,+ width: nextW,+ height: nextH,+ rotation: nextRot,+ };+ } else {+ // Default: drag corner handle k with opposite corner anchored (preserves crisp 90 deg angles)+ const cos = Math.cos(init.rotation);+ const sin = Math.sin(init.rotation);+ const vx = targetX - oppCorner.x;+ const vy = targetY - oppCorner.y;+ let projU = vx * cos + vy * sin;+ let projV = -vx * sin + vy * cos;++ if (modifiers.shiftKey) {+ const side = Math.max(4, Math.max(Math.abs(projU), Math.abs(projV)));+ projU = (projU >= 0 ? 1 : -1) * side;+ projV = (projV >= 0 ? 1 : -1) * side;+ }++ const nextW = Math.max(4, Math.abs(projU));+ const nextH = Math.max(4, Math.abs(projV));+ const signedU = (projU >= 0 ? 1 : -1) * nextW;+ const signedV = (projV >= 0 ? 1 : -1) * nextH;++ const nextCenter: Vec2 = {+ x: oppCorner.x + (cos * signedU - sin * signedV) * 0.5,+ y: oppCorner.y + (sin * signedU + cos * signedV) * 0.5,+ };++ session.currentShape = {+ kind: 'rectangle',+ center: nextCenter,+ width: nextW,+ height: nextH,+ rotation: init.rotation,+ };+ }+ return session.currentShape;+ }+ }+}++// ============================================================================+// Subtle Soft-Click Synthesized Tactile Audio Feedback+// ============================================================================++let sharedAudioCtx: AudioContext | null = null;++/**+ * Plays a gentle, refined tactile "soft click" (~20ms damped acoustic transient)+ * using Web Audio API when QuickShape snaps a freehand stroke into a smooth shape.+ * Fails silently in headless/test environments or if audio autoplay is restricted.+ */+export function playQuickShapeSnapClick(): void {+ try {+ if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') {+ navigator.vibrate(8);+ }+ } catch {+ // Ignore vibration errors on unsupported platforms+ }++ try {+ if (typeof window === 'undefined') return;+ const AudioCtxCtor =+ window.AudioContext ||+ (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;+ if (!AudioCtxCtor) return;++ if (!sharedAudioCtx || sharedAudioCtx.state === 'closed') {+ sharedAudioCtx = new AudioCtxCtor();+ }+ const ctx = sharedAudioCtx;+ if (ctx.state === 'suspended') {+ void ctx.resume().catch(() => {});+ }++ const now = ctx.currentTime;++ // Soft resonant wood/ceramic-like click: brief pitched sine transient + gentle lowpass+ const osc = ctx.createOscillator();+ const filter = ctx.createBiquadFilter();+ const gain = ctx.createGain();++ osc.type = 'triangle';+ osc.frequency.setValueAtTime(1150, now);+ osc.frequency.exponentialRampToValueAtTime(380, now + 0.018);++ filter.type = 'lowpass';+ filter.frequency.setValueAtTime(2200, now);+ filter.Q.setValueAtTime(1.2, now);++ gain.gain.setValueAtTime(0.0001, now);+ gain.gain.linearRampToValueAtTime(0.075, now + 0.002);+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.024);++ osc.connect(filter);+ filter.connect(gain);+ gain.connect(ctx.destination);++ osc.start(now);+ osc.stop(now + 0.028);+ } catch {+ // Silently ignore if Web Audio is unavailable or blocked+ }+}diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.tsindex c54b53a..f480372 100644--- a/src/utils/saveManager.ts+++ b/src/utils/saveManager.ts@@ -4,6 +4,9 @@ export type {SaveDocumentData,InkProjectManifest,ParsedInkProject,+ TimelapsePersistenceFrameMeta,+ TimelapsePersistenceSnapshot,+ TimelapsePersistenceProvider,ExportImageOptions,ExportImageResult,CompositeCanvasOptions,diff --git a/src/utils/saveManager/inkParse.ts b/src/utils/saveManager/inkParse.tsindex 4dd4f33..70077b9 100644--- a/src/utils/saveManager/inkParse.ts+++ b/src/utils/saveManager/inkParse.ts@@ -1,5 +1,12 @@import { unzipSync } from 'fflate';-import { CanvasColorMode, LayerItem, hasTileBackedLayer } from '../../types/editor';+import {+ CanvasColorMode,+ InkTimelapseFrameData,+ InkTimelapseFrameMetadata,+ InkTimelapseMetadata,+ LayerItem,+ hasTileBackedLayer,+} from '../../types/editor';import { SparseTileGrid, TileBuffer, TileFormat } from '../tileEngine';import { extractWorkTimeMsFromManifest } from '../artworkTimeTracker';import {@@ -7,6 +14,8 @@ import {MAX_DOCUMENT_DIM,MAX_MANIFEST_BYTES,MAX_TILE_ENTRIES,+ MAX_TIMELAPSE_FRAMES,+ MAX_TIMELAPSE_FRAME_BYTES,ParsedInkProject,SaveProgress,isInkProjectBytes,@@ -216,6 +225,205 @@ export async function parseInkZipBytes(const previewBytes = previewRaw && previewRaw.byteLength > 0 ? new Uint8Array(previewRaw) : null;const previewDataUrl = toPngDataUrl(previewBytes);+ // Extract embedded time-lapse keyframes (if present in archive)+ const rawTimelapse =+ parsedManifest.timelapse && typeof parsedManifest.timelapse === 'object'+ ? (parsedManifest.timelapse as Record<string, any>)+ : null;++ const timelapseFrames: InkTimelapseFrameData[] = [];+ const sanitizedFrameMetas: InkTimelapseFrameMetadata[] = [];+ const fallbackScale = Math.min(1, 1080 / Math.max(1, Math.max(width, height)));+ const fallbackFrameW = Math.max(2, Math.round((width * fallbackScale) / 2) * 2);+ const fallbackFrameH = Math.max(2, Math.round((height * fallbackScale) / 2) * 2);++ if (rawTimelapse && Array.isArray(rawTimelapse.frames)) {+ if (rawTimelapse.frames.length > MAX_TIMELAPSE_FRAMES) {+ throw new Error(+ `Invalid ${label} project: time-lapse frame count ${rawTimelapse.frames.length} exceeds limit`+ );+ }+ const totalFrames = rawTimelapse.frames.length;+ for (let i = 0; i < totalFrames; i++) {+ const rawFrame = rawTimelapse.frames[i];+ if (!rawFrame || typeof rawFrame !== 'object') continue;+ const framePath = rawFrame.path;+ if (+ typeof framePath !== 'string' ||+ !isSafeZipPath(framePath) ||+ !framePath.startsWith('timelapse/')+ ) {+ throw new Error(`Unsafe time-lapse frame path in ${label} archive: "${String(framePath)}"`);+ }+ const rawPayload = files[framePath];+ if (!rawPayload || rawPayload.byteLength === 0) continue;+ if (rawPayload.byteLength > MAX_TIMELAPSE_FRAME_BYTES) {+ throw new Error(+ `Invalid ${label} project: time-lapse frame "${framePath}" exceeds 8 MB size limit`+ );+ }++ const lowerPath = framePath.toLowerCase();+ const mimeType: 'image/webp' | 'image/jpeg' =+ rawFrame.mimeType === 'image/jpeg' ||+ lowerPath.endsWith('.jpg') ||+ lowerPath.endsWith('.jpeg')+ ? 'image/jpeg'+ : 'image/webp';+ const idx =+ typeof rawFrame.index === 'number' &&+ Number.isSafeInteger(rawFrame.index) &&+ rawFrame.index >= 0+ ? rawFrame.index+ : i;+ const timestamp =+ typeof rawFrame.timestamp === 'number' && Number.isFinite(rawFrame.timestamp)+ ? rawFrame.timestamp+ : 0;+ const fw = Math.max(+ 2,+ Math.min(MAX_DOCUMENT_DIM, Math.round(Number(rawFrame.width)) || fallbackFrameW)+ );+ const fh = Math.max(+ 2,+ Math.min(MAX_DOCUMENT_DIM, Math.round(Number(rawFrame.height)) || fallbackFrameH)+ );+ // Copy into a standalone Uint8Array so individual frames do not pin the whole archive buffer+ const copiedBytes = new Uint8Array(rawPayload);++ timelapseFrames.push({+ index: idx,+ timestamp,+ width: fw,+ height: fh,+ mimeType,+ bytes: copiedBytes,+ });+ sanitizedFrameMetas.push({+ index: idx,+ path: framePath,+ timestamp,+ width: fw,+ height: fh,+ mimeType,+ bytes: copiedBytes.byteLength,+ });++ const done = i + 1;+ if (done % (CHUNK_YIELD_INTERVAL * 4) === 0 && done < totalFrames) {+ onProgress?.({+ phase: 'timelapse',+ current: done,+ total: totalFrames,+ percent: 85 + Math.round((done / totalFrames) * 14),+ message: `Loading time-lapse frames (${done}/${totalFrames})...`,+ });+ await yieldToMainThread();+ }+ }+ } else {+ // Fallback recovery: detect timelapse/frame_XXXXXX.{webp|jpg} files even if manifest omitted frames[]+ const tlFrameRegex = /^timelapse\/frame_(\d+)(?:_\d+)?\.(webp|jpe?g)$/i;+ const orphanFrames: Array<{ index: number; path: string; ext: string }> = [];+ for (const path of fileNames) {+ const m = tlFrameRegex.exec(path);+ if (!m) continue;+ const idx = parseInt(m[1], 10);+ if (!Number.isSafeInteger(idx) || idx < 0) continue;+ orphanFrames.push({ index: idx, path, ext: m[2].toLowerCase() });+ }+ if (orphanFrames.length > MAX_TIMELAPSE_FRAMES) {+ throw new Error(+ `Invalid ${label} project: time-lapse frame count ${orphanFrames.length} exceeds limit`+ );+ }+ orphanFrames.sort((a, b) => a.index - b.index || a.path.localeCompare(b.path));+ for (const item of orphanFrames) {+ const rawPayload = files[item.path];+ if (!rawPayload || rawPayload.byteLength === 0) continue;+ if (rawPayload.byteLength > MAX_TIMELAPSE_FRAME_BYTES) {+ throw new Error(+ `Invalid ${label} project: time-lapse frame "${item.path}" exceeds 8 MB size limit`+ );+ }+ const mimeType: 'image/webp' | 'image/jpeg' =+ item.ext === 'webp' ? 'image/webp' : 'image/jpeg';+ const copiedBytes = new Uint8Array(rawPayload);+ timelapseFrames.push({+ index: item.index,+ timestamp: 0,+ width: fallbackFrameW,+ height: fallbackFrameH,+ mimeType,+ bytes: copiedBytes,+ });+ sanitizedFrameMetas.push({+ index: item.index,+ path: item.path,+ timestamp: 0,+ width: fallbackFrameW,+ height: fallbackFrameH,+ mimeType,+ bytes: copiedBytes.byteLength,+ });+ }+ }++ if (timelapseFrames.length > 1) {+ const paired = timelapseFrames.map((f, i) => ({ frame: f, meta: sanitizedFrameMetas[i] }));+ paired.sort((a, b) => a.frame.index - b.frame.index);+ timelapseFrames.length = 0;+ sanitizedFrameMetas.length = 0;+ for (const p of paired) {+ timelapseFrames.push(p.frame);+ sanitizedFrameMetas.push(p.meta);+ }+ }++ let parsedTimelapse: InkTimelapseMetadata | null = null;+ if (rawTimelapse) {+ const hasEmbeddedFrames = sanitizedFrameMetas.length > 0;+ const baseMeta: InkTimelapseMetadata = {+ enabled: Boolean(rawTimelapse.enabled),+ frameCount: hasEmbeddedFrames+ ? sanitizedFrameMetas.length+ : Math.max(0, Math.floor(Number(rawTimelapse.frameCount) || 0)),+ ...(typeof rawTimelapse.fps === 'number' && Number.isFinite(rawTimelapse.fps)+ ? { fps: rawTimelapse.fps }+ : {}),+ ...(rawTimelapse.resolution === '720p' || rawTimelapse.resolution === '1080p'+ ? { resolution: rawTimelapse.resolution }+ : {}),+ ...(rawTimelapse.aspectRatio === 'original' ||+ rawTimelapse.aspectRatio === '16:9' ||+ rawTimelapse.aspectRatio === '9:16' ||+ rawTimelapse.aspectRatio === '1:1'+ ? { aspectRatio: rawTimelapse.aspectRatio }+ : {}),+ ...(typeof rawTimelapse.nextIndex === 'number' &&+ Number.isSafeInteger(rawTimelapse.nextIndex) &&+ rawTimelapse.nextIndex >= 0+ ? {+ nextIndex: Math.max(+ rawTimelapse.nextIndex,+ sanitizedFrameMetas.reduce((m, f) => Math.max(m, f.index + 1), 0)+ ),+ }+ : hasEmbeddedFrames+ ? { nextIndex: sanitizedFrameMetas.reduce((m, f) => Math.max(m, f.index + 1), 0) }+ : {}),+ ...(hasEmbeddedFrames ? { frames: sanitizedFrameMetas } : {}),+ };+ parsedTimelapse = baseMeta;+ } else if (sanitizedFrameMetas.length > 0) {+ parsedTimelapse = {+ enabled: false,+ frameCount: sanitizedFrameMetas.length,+ nextIndex: sanitizedFrameMetas.reduce((m, f) => Math.max(m, f.index + 1), 0),+ frames: sanitizedFrameMetas,+ };+ }+onProgress?.({phase: 'done',current: 1,@@ -236,7 +444,8 @@ export async function parseInkZipBytes(masksBinary,perspectiveRuler: parsedManifest.perspectiveRuler ?? null,animationTimeline: parsedManifest.animationTimeline ?? null,- timelapse: parsedManifest.timelapse ?? null,+ timelapse: parsedTimelapse,+ ...(timelapseFrames.length > 0 ? { timelapseFrames } : {}),workTimeMs: extractWorkTimeMsFromManifest(parsedManifest),previewBytes,previewDataUrl,diff --git a/src/utils/saveManager/inkSerialize.ts b/src/utils/saveManager/inkSerialize.tsindex cd10bd0..6336139 100644--- a/src/utils/saveManager/inkSerialize.ts+++ b/src/utils/saveManager/inkSerialize.ts@@ -1,5 +1,10 @@import { Zip, ZipDeflate, ZipPassThrough } from 'fflate';-import { LayerItem, hasTileBackedLayer } from '../../types/editor';+import {+ InkTimelapseFrameMetadata,+ InkTimelapseMetadata,+ LayerItem,+ hasTileBackedLayer,+} from '../../types/editor';import {SparseTileGrid,TILE_SIZE,@@ -12,6 +17,8 @@ import { sanitizeWorkTimeMs } from '../artworkTimeTracker';import {CHUNK_YIELD_INTERVAL,InkProjectManifest,+ MAX_TIMELAPSE_FRAMES,+ MAX_TIMELAPSE_FRAME_BYTES,SaveDocumentData,concatUint8Arrays,toPngDataUrl,@@ -31,6 +38,7 @@ import {* - `preview.png` (downscaled preview for Recent Documents)* - `tiles/<layerKey>/<tx>_<ty>.bin` (native 1-bit/8-bit/32-bit SparseTileGrid buffers)* - `masks/<layerKey>.bin` (8-bit mask luminance buffers)+ * - `timelapse/frame_XXXXXX.{webp|jpg}` (stored time-lapse keyframes when recorded)*/export async function serializeInkProject(data: SaveDocumentData,@@ -139,32 +147,22 @@ export async function serializeInkProject(});const preview = await generatePreviewPng(data, resolvedGrid);- const manifest: InkProjectManifest = {- format: 'ink-v2',- app: 'Ink Studio',- version: '2.0',- tileSize: TILE_SIZE,- name: data.name,- dimensions: {- width: data.dimensions.width,- height: data.dimensions.height,- dpi: data.dimensions.dpi ?? 300,- },- colorMode: data.colorMode,- layers: serializableLayers,- layerFormats,- layerTileKeys,- masksMeta,- perspectiveRuler: data.perspectiveRuler ?? null,- animationTimeline: data.animationTimeline ?? null,- timelapse: data.timelapse ?? null,- workTimeMs: sanitizeWorkTimeMs(data.workTimeMs),- preview: preview ? { path: 'preview.png', width: preview.width, height: preview.height } : null,- savedAt: Date.now(),- };+ // Wait for any in-flight timelapse keyframe capture so the latest stroke is included in the save+ const tlProvider = data.timelapseFrameProvider ?? null;+ if (tlProvider?.waitForPendingCapture) {+ await tlProvider.waitForPendingCapture().catch(() => {});+ }+ const tlSnapshot = tlProvider ? tlProvider.getSessionSnapshot() : null;+ const explicitTimelapseFrames = Array.isArray(data.timelapseFrames) ? data.timelapseFrames : null;+ const timelapseFramesSourceCount = explicitTimelapseFrames+ ? explicitTimelapseFrames.length+ : tlSnapshot+ ? tlSnapshot.frames.length+ : 0;+ const hasTimelapseFramesToWrite = timelapseFramesSourceCount > 0;- const encoder = new TextEncoder();- const manifestBytes = encoder.encode(JSON.stringify(manifest));+ const tilesEndPct = hasTimelapseFramesToWrite ? 70 : 85;+ const masksEndPct = hasTimelapseFramesToWrite ? 78 : 95;const chunks: Uint8Array[] = [];let zipError: Error | null = null;@@ -179,11 +177,6 @@ export async function serializeInkProject(});try {- const manifestEntry = new ZipDeflate('manifest.json', { level: 6 });- zip.add(manifestEntry);- manifestEntry.push(manifestBytes, true);- if (zipError) throw zipError;-if (preview) {const previewEntry = new ZipPassThrough('preview.png');zip.add(previewEntry);@@ -214,12 +207,12 @@ export async function serializeInkProject(const done = i + 1;if (done % CHUNK_YIELD_INTERVAL === 0 || done === totalTiles) {- const pct = 10 + Math.round((done / Math.max(1, totalTiles)) * 75);+ const pct = 10 + Math.round((done / Math.max(1, totalTiles)) * (tilesEndPct - 10));onProgress?.({phase: 'tiles',current: done,total: totalTiles,- percent: Math.min(85, pct),+ percent: Math.min(tilesEndPct, pct),message: `Saving tiles (${done}/${totalTiles})...`,});if (done < totalTiles) {@@ -241,7 +234,8 @@ export async function serializeInkProject(phase: 'masks',current: done,total: totalMasks,- percent: 85 + Math.round((done / Math.max(1, totalMasks)) * 10),+ percent:+ tilesEndPct + Math.round((done / Math.max(1, totalMasks)) * (masksEndPct - tilesEndPct)),message: `Saving layer masks (${done}/${totalMasks})...`,});if (done % CHUNK_YIELD_INTERVAL === 0 && done < totalMasks) {@@ -249,6 +243,156 @@ export async function serializeInkProject(}}+ // Stream time-lapse keyframes directly into ZIP with ZipPassThrough (already WebP/JPEG compressed)+ const savedTimelapseFrames: InkTimelapseFrameMetadata[] = [];+ const usedTimelapsePaths = new Set<string>();+ const allocateTimelapsePath = (frameIndex: number, ext: 'webp' | 'jpg'): string => {+ const baseIndex = Number.isSafeInteger(frameIndex) && frameIndex >= 0 ? frameIndex : 0;+ let candidate = `timelapse/frame_${String(baseIndex).padStart(6, '0')}.${ext}`;+ let suffix = 1;+ while (usedTimelapsePaths.has(candidate)) {+ candidate = `timelapse/frame_${String(baseIndex).padStart(6, '0')}_${suffix++}.${ext}`;+ }+ usedTimelapsePaths.add(candidate);+ return candidate;+ };++ const framesLimit = Math.min(timelapseFramesSourceCount, MAX_TIMELAPSE_FRAMES);+ for (let i = 0; i < framesLimit; i++) {+ let frameMeta: {+ index: number;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ };+ let frameBytes: Uint8Array | null = null;++ if (explicitTimelapseFrames) {+ const src = explicitTimelapseFrames[i];+ frameMeta = src;+ frameBytes = src.bytes;+ } else if (tlSnapshot && tlProvider) {+ const src = tlSnapshot.frames[i];+ frameMeta = src;+ frameBytes = await tlProvider.readFrameBytes(src.index);+ } else {+ break;+ }++ if (+ frameBytes &&+ frameBytes.byteLength > 0 &&+ frameBytes.byteLength <= MAX_TIMELAPSE_FRAME_BYTES+ ) {+ const mimeType: 'image/webp' | 'image/jpeg' =+ frameMeta.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp';+ const ext: 'webp' | 'jpg' = mimeType === 'image/jpeg' ? 'jpg' : 'webp';+ const safeIndex =+ Number.isSafeInteger(frameMeta.index) && frameMeta.index >= 0 ? frameMeta.index : i;+ const framePath = allocateTimelapsePath(safeIndex, ext);++ const tlEntry = new ZipPassThrough(framePath);+ zip.add(tlEntry);+ tlEntry.push(frameBytes, true);+ if (zipError) throw zipError;++ savedTimelapseFrames.push({+ index: safeIndex,+ path: framePath,+ timestamp: Number.isFinite(frameMeta.timestamp) ? frameMeta.timestamp : 0,+ width: Math.max(2, Math.round(frameMeta.width) || 2),+ height: Math.max(2, Math.round(frameMeta.height) || 2),+ mimeType,+ bytes: frameBytes.byteLength,+ });+ }++ const done = i + 1;+ if (done % CHUNK_YIELD_INTERVAL === 0 || done === framesLimit) {+ const pct =+ masksEndPct + Math.round((done / Math.max(1, framesLimit)) * (95 - masksEndPct));+ onProgress?.({+ phase: 'timelapse',+ current: done,+ total: framesLimit,+ percent: Math.min(95, pct),+ message: `Saving time-lapse frames (${done}/${framesLimit})...`,+ });+ if (done < framesLimit) {+ await yieldToMainThread();+ }+ }+ }++ let manifestTimelapse: InkTimelapseMetadata | null;+ if (explicitTimelapseFrames !== null || tlProvider !== null) {+ const enabled = tlSnapshot+ ? Boolean(tlSnapshot.enabled)+ : Boolean(data.timelapse?.enabled);+ if (enabled || savedTimelapseFrames.length > 0) {+ const maxSavedNextIndex = savedTimelapseFrames.reduce(+ (max, f) => Math.max(max, f.index + 1),+ 0+ );+ const nextIndex = Math.max(+ tlSnapshot?.nextIndex ?? 0,+ data.timelapse?.nextIndex ?? 0,+ maxSavedNextIndex+ );+ manifestTimelapse = {+ ...(data.timelapse?.fps !== undefined ? { fps: data.timelapse.fps } : {}),+ ...(data.timelapse?.resolution !== undefined+ ? { resolution: data.timelapse.resolution }+ : {}),+ ...(data.timelapse?.aspectRatio !== undefined+ ? { aspectRatio: data.timelapse.aspectRatio }+ : {}),+ enabled,+ frameCount: savedTimelapseFrames.length,+ nextIndex,+ ...(savedTimelapseFrames.length > 0 ? { frames: savedTimelapseFrames } : {}),+ };+ } else {+ manifestTimelapse = null;+ }+ } else {+ manifestTimelapse = data.timelapse ?? null;+ }++ const manifest: InkProjectManifest = {+ format: 'ink-v2',+ app: 'Ink Studio',+ version: '2.0',+ tileSize: TILE_SIZE,+ name: data.name,+ dimensions: {+ width: data.dimensions.width,+ height: data.dimensions.height,+ dpi: data.dimensions.dpi ?? 300,+ },+ colorMode: data.colorMode,+ layers: serializableLayers,+ layerFormats,+ layerTileKeys,+ masksMeta,+ perspectiveRuler: data.perspectiveRuler ?? null,+ animationTimeline: data.animationTimeline ?? null,+ timelapse: manifestTimelapse,+ workTimeMs: sanitizeWorkTimeMs(data.workTimeMs),+ preview: preview+ ? { path: 'preview.png', width: preview.width, height: preview.height }+ : null,+ savedAt: Date.now(),+ };++ const encoder = new TextEncoder();+ const manifestBytes = encoder.encode(JSON.stringify(manifest));+ const manifestEntry = new ZipDeflate('manifest.json', { level: 6 });+ zip.add(manifestEntry);+ manifestEntry.push(manifestBytes, true);+ if (zipError) throw zipError;+onProgress?.({phase: 'finalizing',current: 1,diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.tsindex 8178d87..ceff779 100644--- a/src/utils/saveManager/types.ts+++ b/src/utils/saveManager/types.ts@@ -4,12 +4,34 @@ import type {CanvasColorMode,AnimationTimeline,InkTimelapseMetadata,+ InkTimelapseFrameData,} from '../../types/editor';import type { PerspectiveRuler } from '../../types/perspective';import type { SparseTileGrid, TileFormat } from '../tileEngine';export const PRIMARY_PROJECT_EXTENSION = '.ink';+export interface TimelapsePersistenceFrameMeta {+ index: number;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: number;+}++export interface TimelapsePersistenceSnapshot {+ enabled: boolean;+ nextIndex: number;+ frames: TimelapsePersistenceFrameMeta[];+}++export interface TimelapsePersistenceProvider {+ waitForPendingCapture?: () => Promise<void>;+ getSessionSnapshot: () => TimelapsePersistenceSnapshot | null;+ readFrameBytes: (frameIndex: number) => Promise<Uint8Array | null>;+}+export interface SavedFileInfo {handle?: any; // FileSystemFileHandlename: string;@@ -19,7 +41,16 @@ export interface SavedFileInfo {}export interface SaveProgress {- phase: 'preparing' | 'preview' | 'tiles' | 'masks' | 'compositing' | 'encoding' | 'finalizing' | 'done';+ phase:+ | 'preparing'+ | 'preview'+ | 'tiles'+ | 'masks'+ | 'timelapse'+ | 'compositing'+ | 'encoding'+ | 'finalizing'+ | 'done';current: number;total: number;percent: number;@@ -39,6 +70,8 @@ export interface SaveDocumentData {perspectiveRuler?: PerspectiveRuler | null;animationTimeline?: AnimationTimeline | null;timelapse?: InkTimelapseMetadata | null;+ timelapseFrames?: InkTimelapseFrameData[] | null;+ timelapseFrameProvider?: TimelapsePersistenceProvider | null;workTimeMs?: number;onProgress?: (progress: SaveProgress) => void;compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;@@ -77,6 +110,7 @@ export interface ParsedInkProject {perspectiveRuler?: PerspectiveRuler | null;animationTimeline?: AnimationTimeline | null;timelapse?: InkTimelapseMetadata | null;+ timelapseFrames?: InkTimelapseFrameData[];workTimeMs?: number;previewBytes?: Uint8Array | null;previewDataUrl?: string;@@ -138,6 +172,8 @@ export const MASK_BINARY_HEADER_BYTES = 8; // [width:u32 LE][height:u32 LE]export const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;export const MAX_DOCUMENT_DIM = 65536;export const MAX_TILE_ENTRIES = 120000;+export const MAX_TIMELAPSE_FRAMES = 100000;+export const MAX_TIMELAPSE_FRAME_BYTES = 8 * 1024 * 1024; // 8 MB ceiling per keyframeexport const CHUNK_YIELD_INTERVAL = 8;export const MAX_STYLE_MARGIN_PX = 256;export const PREVIEW_MAX_DIM = 512;diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.tsindex 8429551..ea87054 100644--- a/src/utils/selectionUtils.ts+++ b/src/utils/selectionUtils.ts@@ -240,6 +240,152 @@ export function selectionToMask(return mask;}+export interface StrokeSelectionMaskSpec {+ mask: Uint8Array | null;+ bounds: { x: number; y: number; width: number; height: number };+ maskWidth?: number;+ maskHeight?: number;+}++/**+ * Builds a selection mask specification suitable for `SparseTileGrid.compositeStrokeToTiles`.+ * - For existing full-canvas masks (`selection.mask`), passes the full mask with `maskWidth`/`maskHeight`.+ * - For rectangular selections, returns a zero-allocation bounds-only spec (`mask: null`).+ * - For regular lasso (`type === 'lasso'`) and `svgPath` selections, rasterizes only the+ * intersection of `dirtyRect` and `selection.bounds` so strokes (including Natural Paint)+ * clip accurately without allocating full-canvas buffers.+ */+export function buildStrokeSelectionMask(+ selection: CanvasSelection | null | undefined,+ dirtyRect: DirtyRect,+ dimensions: CanvasDimensions+): StrokeSelectionMaskSpec | null {+ if (!selection) return null;++ if (selection.mask && selection.maskWidth && selection.maskHeight) {+ return {+ mask: selection.mask,+ bounds: selection.bounds,+ maskWidth: selection.maskWidth,+ maskHeight: selection.maskHeight,+ };+ }++ const x0 = Math.max(0, Math.floor(dirtyRect.x), Math.floor(selection.bounds.x));+ const y0 = Math.max(0, Math.floor(dirtyRect.y), Math.floor(selection.bounds.y));+ const x1 = Math.min(+ dimensions.width,+ Math.ceil(dirtyRect.x + dirtyRect.width),+ Math.ceil(selection.bounds.x + selection.bounds.width)+ );+ const y1 = Math.min(+ dimensions.height,+ Math.ceil(dirtyRect.y + dirtyRect.height),+ Math.ceil(selection.bounds.y + selection.bounds.height)+ );+ const w = x1 - x0;+ const h = y1 - y0;+ if (w <= 0 || h <= 0) {+ return { mask: new Uint8Array(0), bounds: { x: 0, y: 0, width: 0, height: 0 } };+ }++ if (selection.type === 'rect') {+ return { mask: null, bounds: { x: x0, y: y0, width: w, height: h } };+ }++ if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {+ const localMask = new Uint8Array(w * h);+ const poly = selection.polygon;+ const offCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ const offCtx = offCanvas ? offCanvas.getContext('2d', { willReadFrequently: true }) : null;+ if (offCanvas && offCtx && typeof offCtx.getImageData === 'function') {+ const CHUNK = 1024;+ try {+ for (let cy = 0; cy < h; cy += CHUNK) {+ const ch = Math.min(CHUNK, h - cy);+ for (let cx = 0; cx < w; cx += CHUNK) {+ const cw = Math.min(CHUNK, w - cx);+ if (offCanvas.width !== cw) offCanvas.width = cw;+ if (offCanvas.height !== ch) offCanvas.height = ch;+ offCtx.clearRect(0, 0, cw, ch);+ offCtx.save();+ offCtx.translate(-(x0 + cx), -(y0 + cy));+ offCtx.fillStyle = '#ffffff';+ offCtx.beginPath();+ offCtx.moveTo(poly[0].x, poly[0].y);+ for (let i = 1; i < poly.length; i++) {+ offCtx.lineTo(poly[i].x, poly[i].y);+ }+ offCtx.closePath();+ offCtx.fill();+ offCtx.restore();+ const imgData = offCtx.getImageData(0, 0, cw, ch);+ for (let ly = 0; ly < ch; ly++) {+ const dRow = (cy + ly) * w + cx;+ const sRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ localMask[dRow + lx] = imgData.data[sRow + lx * 4 + 3];+ }+ }+ }+ }+ } finally {+ releaseTemporaryCanvas(offCanvas);+ }+ } else {+ for (let ly = 0; ly < h; ly++) {+ const py = y0 + ly + 0.5;+ const row = ly * w;+ for (let lx = 0; lx < w; lx++) {+ if (isPointInPolygon(x0 + lx + 0.5, py, poly)) {+ localMask[row + lx] = 255;+ }+ }+ }+ }+ return { mask: localMask, bounds: { x: x0, y: y0, width: w, height: h } };+ }++ if (selection.svgPath && typeof Path2D !== 'undefined') {+ const offCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ const offCtx = offCanvas ? offCanvas.getContext('2d', { willReadFrequently: true }) : null;+ if (offCanvas && offCtx && typeof offCtx.getImageData === 'function') {+ const localMask = new Uint8Array(w * h);+ const path = new Path2D(selection.svgPath);+ const CHUNK = 1024;+ try {+ for (let cy = 0; cy < h; cy += CHUNK) {+ const ch = Math.min(CHUNK, h - cy);+ for (let cx = 0; cx < w; cx += CHUNK) {+ const cw = Math.min(CHUNK, w - cx);+ if (offCanvas.width !== cw) offCanvas.width = cw;+ if (offCanvas.height !== ch) offCanvas.height = ch;+ offCtx.clearRect(0, 0, cw, ch);+ offCtx.save();+ offCtx.translate(-(x0 + cx), -(y0 + cy));+ offCtx.fillStyle = '#ffffff';+ offCtx.fill(path, 'evenodd');+ offCtx.restore();+ const imgData = offCtx.getImageData(0, 0, cw, ch);+ for (let ly = 0; ly < ch; ly++) {+ const dRow = (cy + ly) * w + cx;+ const sRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ localMask[dRow + lx] = imgData.data[sRow + lx * 4 + 3];+ }+ }+ }+ }+ } finally {+ releaseTemporaryCanvas(offCanvas);+ }+ return { mask: localMask, bounds: { x: x0, y: y0, width: w, height: h } };+ }+ }++ return { mask: null, bounds: { x: x0, y: y0, width: w, height: h } };+}+/*** Felzenszwalb-Huttenlocher 1D squared Euclidean Distance Transform.*/diff --git a/src/utils/shortcutManager.ts b/src/utils/shortcutManager.tsindex 9a534b0..6c1bab5 100644--- a/src/utils/shortcutManager.ts+++ b/src/utils/shortcutManager.ts@@ -1,4 +1,4 @@-import { ToolType } from '../types/editor';+import { BrushPresetId, CspBrush, ToolType } from '../types/editor';import {DEFAULT_MODIFIER_KEY_SETTINGS,ModifierAction,@@ -7,9 +7,40 @@ import {ShortcutCategory,ShortcutOverrides,} from '../types/settings';+import { ALL_BUILTIN_BRUSHES, ALL_BUILTIN_BRUSH_SECTIONS } from './presetBrushes';+import { CustomSubToolGroup, buildBrushToCustomGroupMap } from './subToolGroups';export const SPRING_LOADED_HOLD_MS = 250;+export const SUBTOOL_COMMAND_PREFIX = 'subtool:';+export const SUBTOOL_GROUP_COMMAND_PREFIX = 'subtool-group:';++export function getSubToolCommandId(presetId: BrushPresetId): string {+ return `${SUBTOOL_COMMAND_PREFIX}${presetId}`;+}++export function getSubToolGroupCommandId(groupId: string): string {+ return `${SUBTOOL_GROUP_COMMAND_PREFIX}${groupId}`;+}++export type ShortcutPlatform = 'windows' | 'mac' | 'linux';++export function detectShortcutPlatform(): ShortcutPlatform {+ if (typeof navigator === 'undefined') return 'windows';+ const info = `${navigator.platform || ''} ${navigator.userAgent || ''}`.toLowerCase();+ if (info.includes('mac') || info.includes('darwin')) return 'mac';+ if (info.includes('linux') && !info.includes('android')) return 'linux';+ return 'windows';+}++export function getOsModifierDisplayName(+ platform: ShortcutPlatform = detectShortcutPlatform()+): string {+ if (platform === 'mac') return 'Cmd';+ if (platform === 'windows') return 'Win';+ return 'OS';+}+export interface CommandDefinition {id: string;label: string;@@ -20,6 +51,14 @@ export interface CommandDefinition {altDefaultShortcut?: string;/** Tool selected by this command (enables spring-loaded hold-to-revert) */toolId?: ToolType;+ /** Brush / sub tool preset ID opened directly by this command */+ subToolPresetId?: BrushPresetId;+ /** Sub tool group ID (custom or built-in) opened directly by this command */+ subToolGroupId?: string;+ /** Whether this command represents a user-defined custom brush or custom sub tool group */+ isCustomSubTool?: boolean;+ /** Optional section/group badge text shown in the Shortcuts UI */+ groupBadge?: string;/** Whether holding the key (> 250ms or used while held) reverts on keyup */springLoaded?: boolean;/** Runtime handler */@@ -28,6 +67,8 @@ export interface CommandDefinition {export interface ParsedShortcut {ctrl: boolean;+ /** OS / Windows / Super / Meta modifier key */+ meta: boolean;shift: boolean;alt: boolean;/** Canonical display key token (e.g. 'Z', '[', '0', 'Delete', 'Tab', ',') */@@ -50,6 +91,7 @@ export interface KeyboardEventLike {export const SHORTCUT_CATEGORIES: readonly ShortcutCategory[] = ['Tools',+ 'Sub Tools','Menu','Canvas View','Layer',@@ -67,6 +109,15 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [toolId: 'brush',springLoaded: true,},+ {+ id: 'tool.decoration',+ label: 'Decoration Tool',+ description: 'Switch to Decoration tool group (Background, Clothing, Effect)',+ category: 'Tools',+ defaultShortcut: '',+ toolId: 'decoration',+ springLoaded: true,+ },{id: 'tool.eraser',label: 'Eraser Tool',@@ -211,6 +262,66 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [toolId: '3d',springLoaded: false,},+ {+ id: 'tool.selectPen',+ label: 'Selection Pen',+ description: 'Paint freehand selection mask strokes',+ category: 'Tools',+ defaultShortcut: '',+ toolId: 'select-pen',+ springLoaded: true,+ },+ {+ id: 'tool.object',+ label: 'Object Tool',+ description: 'Select and manipulate vector, balloon, and frame objects',+ category: 'Tools',+ defaultShortcut: '',+ toolId: 'object',+ springLoaded: true,+ },+ {+ id: 'tool.prevSubTool',+ label: 'Previous Sub Tool',+ description: 'Switch to the previous sub tool in the active group',+ category: 'Tools',+ defaultShortcut: ',',+ },+ {+ id: 'tool.nextSubTool',+ label: 'Next Sub Tool',+ description: 'Switch to the next sub tool in the active group',+ category: 'Tools',+ defaultShortcut: '.',+ },+ {+ id: 'tool.prevTool',+ label: 'Previous Instrument / Tool',+ description: 'Switch to the previous instrument on the tool bar',+ category: 'Tools',+ defaultShortcut: 'Shift+,',+ },+ {+ id: 'tool.nextTool',+ label: 'Next Instrument / Tool',+ description: 'Switch to the next instrument on the tool bar',+ category: 'Tools',+ defaultShortcut: 'Shift+.',+ },+ {+ id: 'tool.prevSubToolGroup',+ label: 'Previous Sub Tool Group',+ description: 'Switch to the previous sub tool group tab',+ category: 'Tools',+ defaultShortcut: 'Alt+,',+ },+ {+ id: 'tool.nextSubToolGroup',+ label: 'Next Sub Tool Group',+ description: 'Switch to the next sub tool group tab',+ category: 'Tools',+ defaultShortcut: 'Alt+.',+ },{id: 'tool.brushSizeDown',label: 'Decrease Brush Size',@@ -290,6 +401,13 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [category: 'Menu',defaultShortcut: 'Tab',},+ {+ id: 'view.toggleQuickBrushPanel',+ label: 'Toggle Quick Brush Panel',+ description: 'Show or hide the floating Quick-Access Brush Panel',+ category: 'Menu',+ defaultShortcut: 'Shift+B',+ },{id: 'view.toggleLeftPanel',label: 'Toggle Left Panel',@@ -348,6 +466,13 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [category: 'Canvas View',defaultShortcut: 'Ctrl+0',},+ {+ id: 'view.zoomActualSize',+ label: 'Reset Zoom to 100%',+ description: 'Reset canvas zoom level to 100% (actual pixels)',+ category: 'Canvas View',+ defaultShortcut: 'Ctrl+1',+ },{id: 'view.resetRotation',label: 'Reset Rotation',@@ -369,6 +494,20 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [category: 'Canvas View',defaultShortcut: 'Shift+V',},+ {+ id: 'view.valueCheck',+ label: 'Value Check (Live B/W)',+ description: '1-click non-destructive live B/W tonal value check on main canvas',+ category: 'Canvas View',+ defaultShortcut: 'Shift+Y',+ },+ {+ id: 'view.navigatorValueMode',+ label: 'Cycle Navigator B/W / Split View',+ description: 'Cycle Navigator preview between Color, Live B/W, and Color | B/W Split View',+ category: 'Canvas View',+ defaultShortcut: 'Alt+Shift+Y',+ },{id: 'view.straightRuler',label: 'Straight Ruler',@@ -473,6 +612,20 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [category: 'Edit',defaultShortcut: 'Ctrl+T',},+ {+ id: 'edit.puppetWarp',+ label: 'Puppet Warp',+ description: 'Place joint pins to smoothly bend limbs, tilt head, or adjust folds',+ category: 'Edit',+ defaultShortcut: 'Ctrl+Shift+T',+ },+ {+ id: 'edit.cageTransform',+ label: 'Cage Transform',+ description: 'Warp artwork smoothly inside an editable polygon cage',+ category: 'Edit',+ defaultShortcut: '',+ },{id: 'edit.selectAll',label: 'Select All',@@ -553,6 +706,9 @@ const PURE_MODIFIER_KEYS = new Set(['alt','meta','os',+ 'win',+ 'windows',+ 'super','command','cmd',]);@@ -566,6 +722,8 @@ const PURE_MODIFIER_CODES = new Set(['AltRight','MetaLeft','MetaRight',+ 'OSLeft',+ 'OSRight',]);function resolveKeyToken(rawToken: string): KeyCodeSpec | null {@@ -651,7 +809,7 @@ function resolveEventKeySpec(e: KeyboardEventLike): KeyCodeSpec | null {}/**- * Parses a shortcut string such as 'Ctrl+Shift+S', 'Ctrl + ,', '[', or 'Alt+C'.+ * Parses a shortcut string such as 'Ctrl+Shift+S', 'OS+Q', 'Win+1', 'Ctrl + ,', '[', or 'Alt+C'.* Returns null if invalid or empty.*/export function parseShortcut(raw: string): ParsedShortcut | null {@@ -661,6 +819,7 @@ export function parseShortcut(raw: string): ParsedShortcut | null {// Handle literal '+' key carefully (e.g. 'Ctrl++' or '+')let ctrl = false;+ let meta = false;let shift = false;let alt = false;let mainToken = '';@@ -691,10 +850,20 @@ export function parseShortcut(raw: string): ParsedShortcut | null {const p = parts[i];const lower = p.toLowerCase();if (i < parts.length - 1) {- if (lower === 'ctrl' || lower === 'control' || lower === 'cmd' || lower === 'meta') {+ if (lower === 'ctrl' || lower === 'control' || lower === 'cmd' || lower === 'command') {ctrl = true;continue;}+ if (+ lower === 'os' ||+ lower === 'win' ||+ lower === 'windows' ||+ lower === 'meta' ||+ lower === 'super'+ ) {+ meta = true;+ continue;+ }if (lower === 'shift') {shift = true;continue;@@ -717,6 +886,7 @@ export function parseShortcut(raw: string): ParsedShortcut | null {return {ctrl,+ meta,shift,alt,key: spec.key,@@ -726,11 +896,12 @@ export function parseShortcut(raw: string): ParsedShortcut | null {}/**- * Serializes a ParsedShortcut into canonical storage format: 'Ctrl+Shift+Alt+Key'.+ * Serializes a ParsedShortcut into canonical storage format: 'Ctrl+OS+Shift+Alt+Key'.*/export function serializeShortcut(parsed: ParsedShortcut): string {const parts: string[] = [];if (parsed.ctrl) parts.push('Ctrl');+ if (parsed.meta) parts.push('OS');if (parsed.shift) parts.push('Shift');if (parsed.alt) parts.push('Alt');parts.push(parsed.key);@@ -746,13 +917,17 @@ export function normalizeShortcut(raw: string): string {}/**- * Formats a canonical shortcut for clean UI display (e.g. 'Ctrl + Shift + S').+ * Formats a canonical shortcut for clean UI display (e.g. 'Ctrl + Shift + S', 'Win + Q').*/-export function formatShortcutLabel(raw: string): string {+export function formatShortcutLabel(+ raw: string,+ platform: ShortcutPlatform = detectShortcutPlatform()+): string {const parsed = parseShortcut(raw);if (!parsed) return 'Unassigned';const parts: string[] = [];if (parsed.ctrl) parts.push('Ctrl');+ if (parsed.meta) parts.push(getOsModifierDisplayName(platform));if (parsed.shift) parts.push('Shift');if (parsed.alt) parts.push('Alt');parts.push(parsed.key);@@ -761,13 +936,14 @@ export function formatShortcutLabel(raw: string): string {/*** Captures a canonical shortcut string from a live KeyboardEvent (for click-to-record UI).- * Returns null for pure modifier presses.+ * Supports Ctrl, OS/Win/Meta, Shift, and Alt independently. Returns null for pure modifier presses.*/export function formatShortcutFromEvent(e: KeyboardEventLike): string | null {const spec = resolveEventKeySpec(e);if (!spec) return null;return serializeShortcut({- ctrl: Boolean(e.ctrlKey || e.metaKey),+ ctrl: Boolean(e.ctrlKey),+ meta: Boolean(e.metaKey),shift: Boolean(e.shiftKey),alt: Boolean(e.altKey),key: spec.key,@@ -778,16 +954,23 @@ export function formatShortcutFromEvent(e: KeyboardEventLike): string | null {/*** Matches a live KeyboardEvent against a shortcut string (layout-independent via e.code).+ * Treats Ctrl and OS/Win/Meta as independent modifiers so users can bind distinct OS-key hotkeys.*/export function matchesKeyboardEvent(e: KeyboardEventLike, shortcutStr: string): boolean {const parsed = parseShortcut(shortcutStr);if (!parsed) return false;- const eventCtrl = Boolean(e.ctrlKey || e.metaKey);+ const eventCtrl = Boolean(e.ctrlKey);+ const eventMeta = Boolean(e.metaKey);const eventShift = Boolean(e.shiftKey);const eventAlt = Boolean(e.altKey);- if (parsed.ctrl !== eventCtrl || parsed.shift !== eventShift || parsed.alt !== eventAlt) {+ if (+ parsed.ctrl !== eventCtrl ||+ parsed.meta !== eventMeta ||+ parsed.shift !== eventShift ||+ parsed.alt !== eventAlt+ ) {return false;}@@ -933,12 +1116,178 @@ export class SpringLoadedToolController {}}+export interface ActiveSubToolHold {+ code: string;+ prevTool: ToolType;+ prevPresetId: BrushPresetId;+ targetPresetId: BrushPresetId;+ downAt: number;+ usedWhileHeld: boolean;+}++/**+ * Spring-loaded direct subtool hold controller:+ * - Quick tap (< thresholdMs, unused): stays on target subtool permanently.+ * - Hold (>= thresholdMs) OR pointer used while held: reverts to previous tool + preset on keyup.+ */+export class SpringLoadedSubToolController {+ private activeHold: ActiveSubToolHold | null = null;+ private thresholdMs: number;+ private nowFn: () => number;++ constructor(+ thresholdMs: number = SPRING_LOADED_HOLD_MS,+ nowFn: () => number = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())+ ) {+ this.thresholdMs = thresholdMs;+ this.nowFn = nowFn;+ }++ public getActiveHold(): Readonly<ActiveSubToolHold> | null {+ return this.activeHold;+ }++ public handleSubToolKeyDown(+ code: string,+ targetPresetId: BrushPresetId,+ currentTool: ToolType,+ currentPresetId: BrushPresetId+ ): boolean {+ if (+ (currentTool === 'brush' || currentTool === 'decoration') &&+ currentPresetId === targetPresetId+ ) {+ return false;+ }+ this.activeHold = {+ code,+ prevTool: currentTool,+ prevPresetId: currentPresetId,+ targetPresetId,+ downAt: this.nowFn(),+ usedWhileHeld: false,+ };+ return true;+ }++ public markUsedWhileHeld(): void {+ if (this.activeHold) {+ this.activeHold.usedWhileHeld = true;+ }+ }++ public handleKeyUp(+ code: string,+ currentTool: ToolType,+ currentPresetId: BrushPresetId+ ): { tool: ToolType; presetId: BrushPresetId } | null {+ const hold = this.activeHold;+ if (!hold || hold.code !== code) return null;+ this.activeHold = null;++ const heldMs = this.nowFn() - hold.downAt;+ if (+ (heldMs >= this.thresholdMs || hold.usedWhileHeld) &&+ (currentTool === 'brush' || currentTool === 'decoration') &&+ currentPresetId === hold.targetPresetId+ ) {+ return { tool: hold.prevTool, presetId: hold.prevPresetId };+ }+ return null;+ }++ public cancel(+ currentTool?: ToolType,+ currentPresetId?: BrushPresetId+ ): { tool: ToolType; presetId: BrushPresetId } | null {+ const hold = this.activeHold;+ this.activeHold = null;+ if (!hold || !currentTool || !currentPresetId) return null;+ const heldMs = this.nowFn() - hold.downAt;+ if (+ (heldMs >= this.thresholdMs || hold.usedWhileHeld) &&+ (currentTool === 'brush' || currentTool === 'decoration') &&+ currentPresetId === hold.targetPresetId+ ) {+ return { tool: hold.prevTool, presetId: hold.prevPresetId };+ }+ return null;+ }+}++/**+ * Builds dynamic CommandDefinitions for all Custom SubTool Groups, Custom/Imported Brushes,+ * and Built-in SubTools (Brush + Decoration) so users can bind direct keyboard shortcuts to any of them.+ */+export function buildSubToolShortcutCommands(+ customBrushes: readonly CspBrush[],+ customGroups: readonly CustomSubToolGroup[]+): CommandDefinition[] {+ const ownerMap = buildBrushToCustomGroupMap(customGroups);+ const sectionLabelMap = new Map<string, string>(+ ALL_BUILTIN_BRUSH_SECTIONS.map((s) => [s.id, s.label])+ );+ const result: CommandDefinition[] = [];++ // 1. Custom SubTool Groups+ for (const group of customGroups) {+ const count = group.brushIds.length;+ result.push({+ id: getSubToolGroupCommandId(group.id),+ label: `Group: ${group.name}`,+ description: `Open custom sub tool group "${group.name}" (${count} ${count === 1 ? 'sub tool' : 'sub tools'})`,+ category: 'Sub Tools',+ defaultShortcut: '',+ subToolGroupId: group.id,+ isCustomSubTool: true,+ groupBadge: 'Custom Group',+ });+ }++ // 2. Custom / Imported User Brushes+ for (const brush of customBrushes) {+ const owner = ownerMap.get(brush.id);+ result.push({+ id: getSubToolCommandId(brush.id),+ label: brush.name,+ description: `Directly open custom sub tool "${brush.name}" (hold > 250ms for temporary switch)`,+ category: 'Sub Tools',+ defaultShortcut: '',+ subToolPresetId: brush.id,+ isCustomSubTool: true,+ groupBadge: owner ? owner.name : brush.badge || 'Custom',+ springLoaded: true,+ });+ }++ // 3. Built-in Sub Tools (Brush + Decoration)+ for (const builtin of ALL_BUILTIN_BRUSHES) {+ const owner = ownerMap.get(builtin.id);+ const sectionLabel = owner ? owner.name : sectionLabelMap.get(builtin.category) || builtin.badge;+ result.push({+ id: getSubToolCommandId(builtin.id),+ label: builtin.name,+ description: `Directly open ${builtin.name} sub tool (hold > 250ms for temporary switch)`,+ category: 'Sub Tools',+ defaultShortcut: '',+ subToolPresetId: builtin.id,+ isCustomSubTool: false,+ groupBadge: sectionLabel,+ springLoaded: true,+ });+ }++ return result;+}+/*** Centralized Command & Shortcut Manager.*/export class ShortcutManager {private commands: CommandDefinition[];private commandMap: Map<string, CommandDefinition>;+ private dynamicCommands: CommandDefinition[] = [];+ private dynamicCommandMap: Map<string, CommandDefinition> = new Map();private overrides: ShortcutOverrides = {};private handlers: Map<string, () => void> = new Map();@@ -947,12 +1296,23 @@ export class ShortcutManager {this.commandMap = new Map(this.commands.map((c) => [c.id, c]));}+ public setDynamicCommands(dynamicCommands: readonly CommandDefinition[]): void {+ this.dynamicCommands = dynamicCommands.map((c) => ({ ...c }));+ this.dynamicCommandMap = new Map(this.dynamicCommands.map((c) => [c.id, c]));+ }++ public getDynamicCommands(): readonly CommandDefinition[] {+ return this.dynamicCommands;+ }+public getCommands(): readonly CommandDefinition[] {- return this.commands;+ return this.dynamicCommands.length > 0+ ? [...this.commands, ...this.dynamicCommands]+ : this.commands;}public getCommand(id: string): CommandDefinition | undefined {- return this.commandMap.get(id);+ return this.commandMap.get(id) ?? this.dynamicCommandMap.get(id);}public setOverrides(overrides: ShortcutOverrides | undefined): void {@@ -964,7 +1324,7 @@ export class ShortcutManager {}public getShortcut(commandId: string): string {- const cmd = this.commandMap.get(commandId);+ const cmd = this.getCommand(commandId);if (!cmd) return '';return resolveCommandShortcut(cmd, this.overrides);}@@ -989,34 +1349,53 @@ export class ShortcutManager {}public findConflicts(commandId: string, candidateShortcut: string): CommandDefinition[] {- return findShortcutConflicts(commandId, candidateShortcut, this.overrides, this.commands);+ return findShortcutConflicts(commandId, candidateShortcut, this.overrides, this.getCommands());}/**- * Finds the first matching command for a KeyboardEvent.+ * Finds the first matching command (static or dynamic subtool/group) for a KeyboardEvent.* Respects overrides immediately; falls back to altDefaultShortcut only if not overridden.+ * On macOS, falls back to matching Cmd (metaKey) against Ctrl shortcuts when no explicit OS/Meta shortcut matches.*/public matchEvent(e: KeyboardEventLike,- overridesOverride?: ShortcutOverrides+ overridesOverride?: ShortcutOverrides,+ platform: ShortcutPlatform = detectShortcutPlatform()): CommandDefinition | null {const activeOverrides = overridesOverride ?? this.overrides;+ const allCommands = this.getCommands();- for (const cmd of this.commands) {- const bound = resolveCommandShortcut(cmd, activeOverrides);- if (bound && matchesKeyboardEvent(e, bound)) {- return cmd;- }- const isOverridden = Object.prototype.hasOwnProperty.call(activeOverrides, cmd.id);- if (!isOverridden && cmd.altDefaultShortcut && matchesKeyboardEvent(e, cmd.altDefaultShortcut)) {- return cmd;+ const tryMatch = (ev: KeyboardEventLike): CommandDefinition | null => {+ for (const cmd of allCommands) {+ const bound = resolveCommandShortcut(cmd, activeOverrides);+ if (bound && matchesKeyboardEvent(ev, bound)) {+ return cmd;+ }+ const isOverridden = Object.prototype.hasOwnProperty.call(activeOverrides, cmd.id);+ if (+ !isOverridden &&+ cmd.altDefaultShortcut &&+ matchesKeyboardEvent(ev, cmd.altDefaultShortcut)+ ) {+ return cmd;+ }}+ return null;+ };++ const direct = tryMatch(e);+ if (direct) return direct;++ // On macOS, allow Cmd (metaKey) to trigger Ctrl-based shortcuts when no explicit OS/Meta shortcut claimed it+ if (platform === 'mac' && e.metaKey && !e.ctrlKey) {+ return tryMatch({ ...e, ctrlKey: true, metaKey: false });}+return null;}public executeCommand(commandId: string): boolean {- const fn = this.handlers.get(commandId) ?? this.commandMap.get(commandId)?.handler;+ const fn = this.handlers.get(commandId) ?? this.getCommand(commandId)?.handler;if (!fn) return false;fn();return true;@@ -1052,7 +1431,8 @@ export function resolvePointerModifierAction(settings: ModifierKeySettings = DEFAULT_MODIFIER_KEY_SETTINGS): ResolvedPointerModifier | null {const isPen = ctx.pointerType === 'pen';- const ctrl = ctx.ctrlKey || ctx.metaKey;+ const ctrl =+ detectShortcutPlatform() === 'mac' ? ctx.ctrlKey || ctx.metaKey : ctx.ctrlKey;// 1. Non-primary buttons (Stylus barrel buttons, Right click, Middle click)if (isPen) {diff --git a/src/utils/smartLineFill.ts b/src/utils/smartLineFill.tsnew file mode 100644index 0000000..f009e08--- /dev/null+++ b/src/utils/smartLineFill.ts@@ -0,0 +1,1270 @@+import {+ CanvasDimensions,+ DirtyRect,+ LayerItem,+ Point2D,+ SmartFillReferMode,+ SmartFillTargetMode,+ TileDelta,+} from '../types/editor';+import {+ BYTES_32BIT,+ SparseTileGrid,+ TILE_SIZE,+ TileFormat,+ TileSnapshotEntry,+ pixelToTileCoord,+} from './tileEngine';+import {+ buildCompositedReferenceTile,+ dilateBinaryMask,+ erodeBinaryMask,+ isLayerEffectivelyReferenceInList,+ isLayerEffectivelyVisibleInList,+ parseColorToRgba,+} from './floodFill';++export interface SmartLineFillOptions {+ /** Bridges gaps in line art up to N pixels wide (0–40) via isotropic morphological closing */+ closeGap?: number;+ /** Expands (+1..+20) or shrinks (-20..-1) the filled region in pixels */+ areaScale?: number;+ /** Smooths boundary pixels against anti-aliased line art */+ antiAlias?: boolean;+ /** Optional active selection mask (1/255 = inside selection, 0 = outside) */+ selectionMask?: Uint8Array | null;+ /** When true, only modifies pixels with existing non-zero alpha on the target layer */+ alphaLocked?: boolean;+ /** Fill opacity (0.01 - 1.0) */+ opacity?: number;+}++export interface EncloseAndFillTileParams {+ grid: SparseTileGrid;+ targetLayerId: string;+ layers: LayerItem[];+ dimensions: CanvasDimensions;+ polygon: Point2D[];+ fillColorHex: string;+ tolerance: number;+ referMode?: SmartFillReferMode;+ targetMode?: SmartFillTargetMode;+ targetFormat?: TileFormat;+ options?: SmartLineFillOptions;+}++export interface PaintUnfilledAreaTileParams {+ grid: SparseTileGrid;+ targetLayerId: string;+ layers: LayerItem[];+ dimensions: CanvasDimensions;+ strokePoints: Point2D[];+ brushSize: number;+ fillColorHex: string;+ tolerance: number;+ referMode?: SmartFillReferMode;+ targetFormat?: TileFormat;+ options?: SmartLineFillOptions;+}++export interface SmartLineFillResult {+ dirtyRect: DirtyRect | null;+ modified: boolean;+ tileDeltas: TileDelta[];+}++function isBackgroundLayerId(id: string): boolean {+ return id === 'layer-bg' || id.startsWith('layer-bg');+}++/**+ * O(W*H) L1 (diamond / 45°-oriented) morphological dilation.+ */+function dilateDiamondMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {+ if (radius <= 0) return new Uint8Array(mask);+ const total = width * height;+ const dist = new Int32Array(total);+ const INF = 1000000;+ for (let i = 0; i < total; i++) {+ dist[i] = mask[i] ? 0 : INF;+ }++ for (let y = 0; y < height; y++) {+ const row = y * width;+ for (let x = 0; x < width; x++) {+ const idx = row + x;+ let v = dist[idx];+ if (v === 0) continue;+ if (x > 0) {+ const c = dist[idx - 1] + 1;+ if (c < v) v = c;+ }+ if (y > 0) {+ const c = dist[idx - width] + 1;+ if (c < v) v = c;+ }+ dist[idx] = v;+ }+ }++ for (let y = height - 1; y >= 0; y--) {+ const row = y * width;+ for (let x = width - 1; x >= 0; x--) {+ const idx = row + x;+ let v = dist[idx];+ if (v === 0) continue;+ if (x < width - 1) {+ const c = dist[idx + 1] + 1;+ if (c < v) v = c;+ }+ if (y < height - 1) {+ const c = dist[idx + width] + 1;+ if (c < v) v = c;+ }+ dist[idx] = v;+ }+ }++ const out = new Uint8Array(total);+ for (let i = 0; i < total; i++) {+ if (dist[i] <= radius) out[i] = 1;+ }+ return out;+}++/**+ * O(W*H) L1 (diamond / 45°-oriented) morphological erosion.+ * Pixels outside the buffer are treated as 1 so border lines are not eroded away.+ */+function erodeDiamondMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {+ if (radius <= 0) return new Uint8Array(mask);+ const total = width * height;+ const inv = new Uint8Array(total);+ for (let i = 0; i < total; i++) {+ inv[i] = mask[i] ? 0 : 1;+ }+ const dilInv = dilateDiamondMask(inv, width, height, radius);+ const out = new Uint8Array(total);+ for (let i = 0; i < total; i++) {+ out[i] = dilInv[i] ? 0 : 1;+ }+ return out;+}++/**+ * Isotropic gap closing: union of H/V box closing and 45° diamond closing.+ * Bridges horizontal, vertical, AND diagonal line-art gaps up to `closeGap` pixels+ * without thickening 1px strokes.+ */+function closeLineArtGaps(rawBarrier: Uint8Array, width: number, height: number, closeGap: number): Uint8Array {+ const rBox = Math.max(1, Math.ceil(closeGap / 2));+ const boxClosed = erodeBinaryMask(dilateBinaryMask(rawBarrier, width, height, rBox), width, height, rBox);++ const rDia = Math.max(1, Math.ceil(closeGap * 0.71));+ const diaClosed = erodeDiamondMask(dilateDiamondMask(rawBarrier, width, height, rDia), width, height, rDia);++ const total = width * height;+ const out = new Uint8Array(total);+ for (let i = 0; i < total; i++) {+ if (rawBarrier[i] || boxClosed[i] || diaClosed[i]) {+ out[i] = 1;+ }+ }+ return out;+}++/**+ * Pure JS non-zero winding scanline polygon rasterizer into a tight local mask [bx0..bx0+bw-1] x [by0..by0+bh-1].+ * Deterministic across browser and headless environments, zero DOM canvas allocation, and handles self-intersections cleanly.+ */+export function rasterizePolygonMask(+ polygon: Point2D[],+ bx0: number,+ by0: number,+ bw: number,+ bh: number+): Uint8Array {+ const mask = new Uint8Array(bw * bh);+ const n = polygon.length;+ if (n < 3 || bw <= 0 || bh <= 0) return mask;++ // Pre-extract non-horizontal edges+ const edgeX0: number[] = [];+ const edgeY0: number[] = [];+ const edgeSlope: number[] = [];+ const edgeYMin: number[] = [];+ const edgeYMax: number[] = [];+ const edgeDir: number[] = [];++ for (let i = 0, j = n - 1; i < n; j = i++) {+ const x0 = polygon[j].x;+ const y0 = polygon[j].y;+ const x1 = polygon[i].x;+ const y1 = polygon[i].y;+ if (y0 === y1) continue;+ edgeX0.push(x0);+ edgeY0.push(y0);+ edgeSlope.push((x1 - x0) / (y1 - y0));+ if (y1 > y0) {+ edgeYMin.push(y0);+ edgeYMax.push(y1);+ edgeDir.push(1);+ } else {+ edgeYMin.push(y1);+ edgeYMax.push(y0);+ edgeDir.push(-1);+ }+ }++ const edgeCount = edgeX0.length;+ if (edgeCount === 0) return mask;++ const crossX = new Float64Array(edgeCount);+ const crossDir = new Int8Array(edgeCount);+ const order = new Int32Array(edgeCount);+ const bx1 = bx0 + bw - 1;++ for (let ly = 0; ly < bh; ly++) {+ const py = by0 + ly + 0.5;+ let count = 0;+ for (let e = 0; e < edgeCount; e++) {+ if (py >= edgeYMin[e] && py < edgeYMax[e]) {+ crossX[count] = edgeX0[e] + (py - edgeY0[e]) * edgeSlope[e];+ crossDir[count] = edgeDir[e];+ order[count] = count;+ count++;+ }+ }+ if (count < 2) continue;++ // Insertion sort on crossing indices by X (small count per scanline -> blazing fast)+ for (let i = 1; i < count; i++) {+ const key = order[i];+ const kx = crossX[key];+ let j = i - 1;+ while (j >= 0 && crossX[order[j]] > kx) {+ order[j + 1] = order[j];+ j--;+ }+ order[j + 1] = key;+ }++ const rowOffset = ly * bw;+ let winding = 0;+ for (let k = 0; k < count - 1; k++) {+ const curIdx = order[k];+ winding += crossDir[curIdx];+ if (winding === 0) continue;++ const xStartF = crossX[curIdx];+ const xEndF = crossX[order[k + 1]];+ if (xEndF <= xStartF) continue;++ const startX = Math.max(bx0, Math.ceil(xStartF - 0.5));+ const endX = Math.min(bx1, Math.floor(xEndF - 0.5));+ for (let gx = startX; gx <= endX; gx++) {+ mask[rowOffset + (gx - bx0)] = 1;+ }+ }+ }++ return mask;+}++/**+ * Pure JS capsule-swept polyline rasterizer for Paint Unfilled Area brush strokes.+ * Supports single-click dabs (`points.length === 1`) and continuous multi-segment strokes.+ */+export function rasterizeBrushStrokeMask(+ points: Point2D[],+ radius: number,+ bx0: number,+ by0: number,+ bw: number,+ bh: number+): Uint8Array {+ const mask = new Uint8Array(bw * bh);+ if (points.length === 0 || bw <= 0 || bh <= 0) return mask;++ const r = Math.max(1, radius);+ const rSq = r * r;+ const rPad = Math.ceil(r) + 1;+ const bx1 = bx0 + bw - 1;+ const by1 = by0 + bh - 1;++ if (points.length === 1) {+ const cx = points[0].x;+ const cy = points[0].y;+ const minX = Math.max(bx0, Math.floor(cx - rPad));+ const maxX = Math.min(bx1, Math.ceil(cx + rPad));+ const minY = Math.max(by0, Math.floor(cy - rPad));+ const maxY = Math.min(by1, Math.ceil(cy + rPad));+ for (let gy = minY; gy <= maxY; gy++) {+ const dy = gy + 0.5 - cy;+ const dySq = dy * dy;+ const row = (gy - by0) * bw;+ for (let gx = minX; gx <= maxX; gx++) {+ const dx = gx + 0.5 - cx;+ if (dx * dx + dySq <= rSq) {+ mask[row + (gx - bx0)] = 1;+ }+ }+ }+ return mask;+ }++ for (let i = 0; i < points.length - 1; i++) {+ const ax = points[i].x;+ const ay = points[i].y;+ const bx = points[i + 1].x;+ const by = points[i + 1].y;+ const abx = bx - ax;+ const aby = by - ay;+ const abLenSq = abx * abx + aby * aby;++ const minX = Math.max(bx0, Math.floor(Math.min(ax, bx) - rPad));+ const maxX = Math.min(bx1, Math.ceil(Math.max(ax, bx) + rPad));+ const minY = Math.max(by0, Math.floor(Math.min(ay, by) - rPad));+ const maxY = Math.min(by1, Math.ceil(Math.max(ay, by) + rPad));++ for (let gy = minY; gy <= maxY; gy++) {+ const py = gy + 0.5 - ay;+ const row = (gy - by0) * bw;+ for (let gx = minX; gx <= maxX; gx++) {+ const lIdx = row + (gx - bx0);+ if (mask[lIdx]) continue;+ const px = gx + 0.5 - ax;+ let t = 0;+ if (abLenSq > 1e-6) {+ t = (px * abx + py * aby) / abLenSq;+ if (t < 0) t = 0;+ else if (t > 1) t = 1;+ }+ const dx = px - t * abx;+ const dy = py - t * aby;+ if (dx * dx + dy * dy <= rSq) {+ mask[lIdx] = 1;+ }+ }+ }+ }++ return mask;+}++/**+ * Resolves the layers that contribute line-art outlines for Smart Line Fill.+ * - `'refer-reference'`: Uses visible Reference layers (and layers inside Reference folders).+ * Falls back to visible non-paper layers if no Reference layer is designated.+ * - `'refer-all'`: Composites all visible non-paper layers (CSP "Exclude Paper Layer"),+ * including the background paper layer only when painting directly on it or when no other layer has content.+ * - `'active'`: Returns `null` to indicate sampling directly from `targetLayerId`.+ */+export function resolveSmartFillReferenceLayers(+ layers: LayerItem[],+ targetLayerId: string,+ referMode: SmartFillReferMode,+ grid: SparseTileGrid+): LayerItem[] | null {+ if (referMode === 'active') return null;++ const isPaintableVisible = (l: LayerItem): boolean =>+ isLayerEffectivelyVisibleInList(l, layers) && l.type !== 'folder' && l.type !== 'frame-folder';++ if (referMode === 'refer-reference') {+ const explicitRefs = layers.filter(+ (l) => isPaintableVisible(l) && isLayerEffectivelyReferenceInList(l, layers)+ );+ if (explicitRefs.length > 0) {+ return explicitRefs;+ }+ }++ const allVisible = layers.filter(isPaintableVisible);+ if (isBackgroundLayerId(targetLayerId)) {+ return allVisible;+ }++ const nonBgVisible = allVisible.filter((l) => !isBackgroundLayerId(l.id));+ if (nonBgVisible.some((l) => grid.hasLayerTiles(l.id))) {+ return nonBgVisible;+ }+ return allVisible;+}++/**+ * Reads an RGBA buffer for the local rectangle [bx0..bx0+bw-1] x [by0..by0+bh-1]+ * from either a list of composited reference layers or a single layer in SparseTileGrid.+ */+function readLocalRegionRgba(+ grid: SparseTileGrid,+ refLayers: LayerItem[] | null,+ singleLayerId: string,+ bx0: number,+ by0: number,+ bw: number,+ bh: number+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(bw * bh * 4);+ const bx1 = bx0 + bw - 1;+ const by1 = by0 + bh - 1;+ const minTx = pixelToTileCoord(bx0, 0);+ const minTy = pixelToTileCoord(by0, 0);+ const maxTx = pixelToTileCoord(bx1, 0);+ const maxTy = pixelToTileCoord(by1, 0);++ for (let ty = minTy; ty <= maxTy; ty++) {+ const tileDocY = ty * TILE_SIZE;+ const startLY = Math.max(0, by0 - tileDocY);+ const endLY = Math.min(TILE_SIZE, by1 - tileDocY + 1);++ for (let tx = minTx; tx <= maxTx; tx++) {+ let tileData: Uint8ClampedArray | null = null;+ if (refLayers) {+ tileData = buildCompositedReferenceTile(grid, refLayers, tx, ty);+ } else {+ const tile = grid.getTile(singleLayerId, tx, ty, 0);+ tileData = tile && tile.data ? grid.getTileAsRGBA(tile) : null;+ }+ if (!tileData) continue;++ const tileDocX = tx * TILE_SIZE;+ const startLX = Math.max(0, bx0 - tileDocX);+ const endLX = Math.min(TILE_SIZE, bx1 - tileDocX + 1);+ const copyPx = endLX - startLX;+ if (copyPx <= 0) continue;+ const rowBytes = copyPx * 4;++ for (let ly = startLY; ly < endLY; ly++) {+ const srcOff = (ly * TILE_SIZE + startLX) * 4;+ const dstOff = ((tileDocY + ly - by0) * bw + (tileDocX + startLX - bx0)) * 4;+ out.set(tileData.subarray(srcOff, srcOff + rowBytes), dstOff);+ }+ }+ }++ return out;+}++/**+ * Estimates the dominant background/paper RGB color on an opaque reference composite+ * by quantizing exterior pixels into 4-bit-per-channel buckets.+ */+function detectOpaqueBackgroundRgb(+ refData: Uint8ClampedArray,+ regionMask: Uint8Array,+ alphaThreshold: number+): [number, number, number] {+ const bucketCounts = new Int32Array(4096);+ const bucketSumR = new Float64Array(4096);+ const bucketSumG = new Float64Array(4096);+ const bucketSumB = new Float64Array(4096);++ const total = regionMask.length;+ let sampleCount = 0;++ // Prefer exterior (!regionMask) pixels first+ for (let i = 0; i < total; i++) {+ if (regionMask[i] !== 0) continue;+ const off = i * 4;+ if (refData[off + 3] <= alphaThreshold) continue;+ const r = refData[off];+ const g = refData[off + 1];+ const b = refData[off + 2];+ const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4);+ bucketCounts[key]++;+ bucketSumR[key] += r;+ bucketSumG[key] += g;+ bucketSumB[key] += b;+ sampleCount++;+ }++ // Fallback to entire local box if lasso/stroke filled the entire box+ if (sampleCount === 0) {+ for (let i = 0; i < total; i++) {+ const off = i * 4;+ if (refData[off + 3] <= alphaThreshold) continue;+ const r = refData[off];+ const g = refData[off + 1];+ const b = refData[off + 2];+ const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4);+ bucketCounts[key]++;+ bucketSumR[key] += r;+ bucketSumG[key] += g;+ bucketSumB[key] += b;+ sampleCount++;+ }+ }++ if (sampleCount === 0) {+ return [255, 255, 255];+ }++ let bestKey = 0;+ let bestCount = -1;+ for (let k = 0; k < 4096; k++) {+ if (bucketCounts[k] > bestCount) {+ bestCount = bucketCounts[k];+ bestKey = k;+ }+ }++ return [+ Math.round(bucketSumR[bestKey] / bestCount),+ Math.round(bucketSumG[bestKey] / bestCount),+ Math.round(bucketSumB[bestKey] / bestCount),+ ];+}++interface CoreSmartFillParams {+ grid: SparseTileGrid;+ targetLayerId: string;+ layers: LayerItem[];+ dimensions: CanvasDimensions;+ bx0: number;+ by0: number;+ bw: number;+ bh: number;+ regionMask: Uint8Array;+ fillColorHex: string;+ tolerance: number;+ referMode: SmartFillReferMode;+ preserveExistingTarget: boolean;+ /** When true on opaque reference canvases, treats near-white paper as the unfilled color */+ opaqueUnfilledIsWhite: boolean;+ targetFormat?: TileFormat;+ options?: SmartLineFillOptions;+}++function runCoreSmartLineFill(params: CoreSmartFillParams): SmartLineFillResult {+ const {+ grid,+ targetLayerId,+ layers,+ dimensions,+ bx0,+ by0,+ bw,+ bh,+ regionMask,+ fillColorHex,+ tolerance,+ referMode,+ preserveExistingTarget,+ opaqueUnfilledIsWhite,+ options,+ } = params;++ const width = dimensions.width;+ const height = dimensions.height;+ const localPixels = bw * bh;+ if (width <= 0 || height <= 0 || bw <= 0 || bh <= 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ const effectiveOpacity = Math.max(+ 0,+ Math.min(1, Number.isFinite(options?.opacity) ? (options?.opacity as number) : 1.0)+ );+ if (effectiveOpacity <= 0.001) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ const clampedTol = Math.max(0, Math.min(100, Number.isFinite(tolerance) ? tolerance : 32));+ const closeGap = Math.max(0, Math.min(40, Math.round(options?.closeGap ?? 0)));+ const areaScale = Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0)));+ const antiAlias = options?.antiAlias ?? true;+ const alphaLocked = Boolean(options?.alphaLocked);+ const selectionMask =+ options?.selectionMask && options.selectionMask.length === width * height+ ? options.selectionMask+ : null;++ const [fillR, fillG, fillB, fillA] = parseColorToRgba(fillColorHex);+ const isEraseFill = fillA === 0;++ // Gentle alpha threshold for transparent line art (tol=0 -> 0, tol=32 -> 25, tol=100 -> 140)+ // so thin 1-2px tapered anime pen/pencil strokes remain solid barriers instead of leaking.+ const alphaBarrierThreshold =+ clampedTol <= 0 ? 0 : Math.min(140, Math.round(Math.pow(clampedTol / 100, 1.5) * 140));+ const colorTolerance = (clampedTol / 100) * 255;++ // 1. Read local Reference composite & (if needed) Target layer pixels+ const refLayers = resolveSmartFillReferenceLayers(layers, targetLayerId, referMode, grid);+ const refData = readLocalRegionRgba(grid, refLayers, targetLayerId, bx0, by0, bw, bh);++ let targetData: Uint8ClampedArray | null = null;+ if (preserveExistingTarget) {+ targetData =+ refLayers === null+ ? refData+ : readLocalRegionRgba(grid, null, targetLayerId, bx0, by0, bw, bh);+ }++ // 2. Detect transparent-background vs opaque-paper reference composite+ let transparentTotal = 0;+ let opaqueWhiteTotal = 0;+ for (let i = 0; i < localPixels; i++) {+ const off = i * 4;+ const a = refData[off + 3];+ if (a <= alphaBarrierThreshold) {+ transparentTotal++;+ } else if (refData[off] >= 245 && refData[off + 1] >= 245 && refData[off + 2] >= 245) {+ opaqueWhiteTotal++;+ }+ }+ const refIsTransparentBg =+ transparentTotal > 0 &&+ (opaqueWhiteTotal === 0 || transparentTotal >= Math.floor(opaqueWhiteTotal * 0.1));++ // 3. Build rawRefBarrier from reference outlines+ const rawRefBarrier = new Uint8Array(localPixels);+ let bgR = 255;+ let bgG = 255;+ let bgB = 255;++ if (refIsTransparentBg) {+ for (let i = 0; i < localPixels; i++) {+ if (refData[i * 4 + 3] > alphaBarrierThreshold) {+ rawRefBarrier[i] = 1;+ }+ }+ } else {+ if (!opaqueUnfilledIsWhite) {+ [bgR, bgG, bgB] = detectOpaqueBackgroundRgb(refData, regionMask, alphaBarrierThreshold);+ }+ for (let i = 0; i < localPixels; i++) {+ const off = i * 4;+ if (refData[off + 3] <= alphaBarrierThreshold) continue;+ const maxDiff = Math.max(+ Math.abs(refData[off] - bgR),+ Math.abs(refData[off + 1] - bgG),+ Math.abs(refData[off + 2] - bgB)+ );+ if (maxDiff > colorTolerance) {+ rawRefBarrier[i] = 1;+ }+ }+ }++ // 4. Build targetFilledBarrier (protects already-painted regions in Paint Unfilled Area / Unfilled-Only mode)+ let targetFilledBarrier: Uint8Array | null = null;+ if (preserveExistingTarget && targetData) {+ targetFilledBarrier = new Uint8Array(localPixels);+ let targetTransparentCount = 0;+ let targetWhiteCount = 0;+ for (let i = 0; i < localPixels; i++) {+ const off = i * 4;+ const a = targetData[off + 3];+ if (a <= alphaBarrierThreshold) {+ targetTransparentCount++;+ } else if (targetData[off] >= 245 && targetData[off + 1] >= 245 && targetData[off + 2] >= 245) {+ targetWhiteCount++;+ }+ }+ const targetIsOpaqueWhiteBg =+ isBackgroundLayerId(targetLayerId) ||+ (targetTransparentCount === 0 && targetWhiteCount > 0);++ if (targetIsOpaqueWhiteBg) {+ for (let i = 0; i < localPixels; i++) {+ const off = i * 4;+ if (targetData[off + 3] <= alphaBarrierThreshold) continue;+ const maxDiff = Math.max(+ 255 - targetData[off],+ 255 - targetData[off + 1],+ 255 - targetData[off + 2]+ );+ if (maxDiff > colorTolerance) {+ targetFilledBarrier[i] = 1;+ }+ }+ } else {+ for (let i = 0; i < localPixels; i++) {+ if (targetData[i * 4 + 3] > alphaBarrierThreshold) {+ targetFilledBarrier[i] = 1;+ }+ }+ }+ }++ // 5. Apply Close Gap morphological closing strictly to reference outlines (never bridging between outline & existing fill)+ const closedRefBarrier: Uint8Array =+ closeGap > 0 ? closeLineArtGaps(rawRefBarrier, bw, bh, closeGap) : rawRefBarrier;++ // Combine flood-stopping barriers+ const barrier = new Uint8Array(localPixels);+ if (targetFilledBarrier) {+ for (let i = 0; i < localPixels; i++) {+ if (closedRefBarrier[i] || targetFilledBarrier[i]) barrier[i] = 1;+ }+ } else {+ barrier.set(closedRefBarrier);+ }++ // 6. Exterior Flood Fill from all open pixels outside regionMask+ const exterior = new Uint8Array(localPixels);+ const queue = new Int32Array(localPixels);+ let qHead = 0;+ let qTail = 0;++ let hasAnyOutsideSeed = false;+ for (let i = 0; i < localPixels; i++) {+ if (regionMask[i] === 0 && barrier[i] === 0) {+ exterior[i] = 1;+ queue[qTail++] = i;+ hasAnyOutsideSeed = true;+ }+ }++ // Edge case: if lasso/stroke covers 100% of the entire canvas with zero exterior pixels,+ // seed the canvas borders so the open background is still recognized as exterior.+ if (!hasAnyOutsideSeed && bx0 === 0 && by0 === 0 && bw === width && bh === height) {+ for (let lx = 0; lx < bw; lx++) {+ const top = lx;+ if (!barrier[top] && !exterior[top]) {+ exterior[top] = 1;+ queue[qTail++] = top;+ }+ const bot = (bh - 1) * bw + lx;+ if (!barrier[bot] && !exterior[bot]) {+ exterior[bot] = 1;+ queue[qTail++] = bot;+ }+ }+ for (let ly = 1; ly < bh - 1; ly++) {+ const left = ly * bw;+ if (!barrier[left] && !exterior[left]) {+ exterior[left] = 1;+ queue[qTail++] = left;+ }+ const right = left + bw - 1;+ if (!barrier[right] && !exterior[right]) {+ exterior[right] = 1;+ queue[qTail++] = right;+ }+ }+ }++ while (qHead < qTail) {+ const idx = queue[qHead++];+ const lx = idx % bw;+ const ly = (idx - lx) / bw;++ if (lx > 0) {+ const n = idx - 1;+ if (!exterior[n] && !barrier[n]) {+ exterior[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (lx < bw - 1) {+ const n = idx + 1;+ if (!exterior[n] && !barrier[n]) {+ exterior[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (ly > 0) {+ const n = idx - bw;+ if (!exterior[n] && !barrier[n]) {+ exterior[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (ly < bh - 1) {+ const n = idx + bw;+ if (!exterior[n] && !barrier[n]) {+ exterior[n] = 1;+ queue[qTail++] = n;+ }+ }+ }++ // 7. Extract enclosed pixels inside regionMask+ const enclosed = new Uint8Array(localPixels);+ let enclosedCount = 0;+ for (let i = 0; i < localPixels; i++) {+ if (regionMask[i] && !barrier[i] && !exterior[i]) {+ enclosed[i] = 1;+ enclosedCount++;+ }+ }++ // Sharp V-tip corner recovery when closeGap > 0:+ // Pixels blocked ONLY by morphological closing (not actual line art or existing target fill)+ // that do NOT connect to `exterior` are narrow enclosed corners (e.g. acute hair tips), not outer line gaps.+ let gapBridge: Uint8Array | null = null;+ if (closeGap > 0) {+ gapBridge = new Uint8Array(localPixels);+ qHead = 0;+ qTail = 0;++ const isClosingOnly = (idx: number): boolean =>+ closedRefBarrier[idx] !== 0 &&+ rawRefBarrier[idx] === 0 &&+ !(targetFilledBarrier && targetFilledBarrier[idx] !== 0);++ for (let ly = 0; ly < bh; ly++) {+ const row = ly * bw;+ for (let lx = 0; lx < bw; lx++) {+ const idx = row + lx;+ if (!isClosingOnly(idx)) continue;+ const touchesExterior =+ (lx > 0 && exterior[idx - 1] !== 0) ||+ (lx < bw - 1 && exterior[idx + 1] !== 0) ||+ (ly > 0 && exterior[idx - bw] !== 0) ||+ (ly < bh - 1 && exterior[idx + bw] !== 0);+ if (touchesExterior) {+ gapBridge[idx] = 1;+ queue[qTail++] = idx;+ }+ }+ }++ while (qHead < qTail) {+ const idx = queue[qHead++];+ const lx = idx % bw;+ const ly = (idx - lx) / bw;+ if (lx > 0) {+ const n = idx - 1;+ if (!gapBridge[n] && isClosingOnly(n)) {+ gapBridge[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (lx < bw - 1) {+ const n = idx + 1;+ if (!gapBridge[n] && isClosingOnly(n)) {+ gapBridge[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (ly > 0) {+ const n = idx - bw;+ if (!gapBridge[n] && isClosingOnly(n)) {+ gapBridge[n] = 1;+ queue[qTail++] = n;+ }+ }+ if (ly < bh - 1) {+ const n = idx + bw;+ if (!gapBridge[n] && isClosingOnly(n)) {+ gapBridge[n] = 1;+ queue[qTail++] = n;+ }+ }+ }++ for (let i = 0; i < localPixels; i++) {+ if (regionMask[i] && isClosingOnly(i) && !gapBridge[i] && !exterior[i]) {+ enclosed[i] = 1;+ enclosedCount++;+ }+ }+ }++ if (enclosedCount === 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ // 8. Area Scaling (Expand under line art with centerline + exterior + existing-target guards, or Shrink)+ let finalMask: Uint8Array = enclosed;+ if (areaScale > 0) {+ const getLineStrength = (idx: number): number => {+ const off = idx * 4;+ if (refIsTransparentBg) {+ return refData[off + 3] / 255;+ }+ return (+ Math.max(+ Math.abs(refData[off] - bgR),+ Math.abs(refData[off + 1] - bgG),+ Math.abs(refData[off + 2] - bgB)+ ) / 255+ );+ };++ let frontier: number[] = [];+ for (let ly = 0; ly < bh; ly++) {+ const row = ly * bw;+ for (let lx = 0; lx < bw; lx++) {+ const idx = row + lx;+ if (!finalMask[idx]) continue;+ if (+ (lx > 0 && !finalMask[idx - 1]) ||+ (lx < bw - 1 && !finalMask[idx + 1]) ||+ (ly > 0 && !finalMask[idx - bw]) ||+ (ly < bh - 1 && !finalMask[idx + bw])+ ) {+ frontier.push(idx);+ }+ }+ }++ const dirs = [-1, 1, -bw, bw];+ for (let step = 0; step < areaScale && frontier.length > 0; step++) {+ const nextFrontier: number[] = [];+ for (let i = 0; i < frontier.length; i++) {+ const idx = frontier[i];+ const lx = idx % bw;+ const ly = (idx - lx) / bw;+ const curStrength = getLineStrength(idx);++ for (let d = 0; d < 4; d++) {+ const offset = dirs[d];+ if (offset === -1 && lx === 0) continue;+ if (offset === 1 && lx === bw - 1) continue;+ if (offset === -bw && ly === 0) continue;+ if (offset === bw && ly === bh - 1) continue;++ const nIdx = idx + offset;+ if (finalMask[nIdx]) continue;+ // Never spill into exterior background or across a bridged gap+ if (exterior[nIdx]) continue;+ if (gapBridge && gapBridge[nIdx]) continue;+ // In Paint Unfilled Area / Unfilled-Only mode, never overwrite already-painted target pixels+ if (preserveExistingTarget && targetFilledBarrier && targetFilledBarrier[nIdx]) continue;++ const nStrength = getLineStrength(nIdx);+ // Line-art centerline stop guard: stop once line density peaks and starts dropping+ if (curStrength > 0.55 && nStrength < curStrength - 0.05) {+ continue;+ }++ finalMask[nIdx] = 1;+ nextFrontier.push(nIdx);+ }+ }+ frontier = nextFrontier;+ }+ } else if (areaScale < 0) {+ finalMask = erodeBinaryMask(enclosed, bw, bh, Math.abs(areaScale));+ }++ // Compute tight modified local bounds+ let minLX = bw;+ let maxLX = -1;+ let minLY = bh;+ let maxLY = -1;+ for (let ly = 0; ly < bh; ly++) {+ const row = ly * bw;+ for (let lx = 0; lx < bw; lx++) {+ if (finalMask[row + lx]) {+ if (lx < minLX) minLX = lx;+ if (lx > maxLX) maxLX = lx;+ if (ly < minLY) minLY = ly;+ if (ly > maxLY) maxLY = ly;+ }+ }+ }++ if (maxLX < minLX || maxLY < minLY) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ if (antiAlias) {+ minLX = Math.max(0, minLX - 1);+ minLY = Math.max(0, minLY - 1);+ maxLX = Math.min(bw - 1, maxLX + 1);+ maxLY = Math.min(bh - 1, maxLY + 1);+ }++ const dirtyMinX = bx0 + minLX;+ const dirtyMinY = by0 + minLY;+ const dirtyMaxX = bx0 + maxLX;+ const dirtyMaxY = by0 + maxLY;++ // 9. Write pixels directly to touched tiles in SparseTileGrid+ const targetFormat = params.targetFormat ?? grid.getLayerFormat(targetLayerId);+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();+ const minTx = pixelToTileCoord(dirtyMinX, 0);+ const minTy = pixelToTileCoord(dirtyMinY, 0);+ const maxTx = pixelToTileCoord(dirtyMaxX, 0);+ const maxTy = pixelToTileCoord(dirtyMaxY, 0);+ const workBuf = new Uint8ClampedArray(BYTES_32BIT);++ const fillColorAlphaNorm = isEraseFill ? 1.0 : fillA / 255;++ for (let ty = minTy; ty <= maxTy; ty++) {+ const tileDocY = ty * TILE_SIZE;+ const startLY = Math.max(0, dirtyMinY - tileDocY);+ const endLY = Math.min(TILE_SIZE, dirtyMaxY - tileDocY + 1);++ for (let tx = minTx; tx <= maxTx; tx++) {+ const tileDocX = tx * TILE_SIZE;+ const startLX = Math.max(0, dirtyMinX - tileDocX);+ const endLX = Math.min(TILE_SIZE, dirtyMaxX - tileDocX + 1);++ const existingTile = grid.getTile(targetLayerId, tx, ty, 0);+ if ((alphaLocked || isEraseFill) && (!existingTile || !existingTile.data)) {+ continue;+ }+ if (existingTile && existingTile.data) {+ workBuf.set(grid.getTileAsRGBA(existingTile));+ } else {+ workBuf.fill(0);+ }++ let tileChanged = false;+ for (let tly = startLY; tly < endLY; tly++) {+ const gy = tileDocY + tly;+ const ly = gy - by0;+ const lRow = ly * bw;+ const tRow = tly * TILE_SIZE;+ const selRow = gy * width;++ for (let tlx = startLX; tlx < endLX; tlx++) {+ const gx = tileDocX + tlx;+ if (selectionMask && selectionMask[selRow + gx] === 0) {+ continue;+ }++ const lx = gx - bx0;+ const lIdx = lRow + lx;+ let cov = 0;++ if (finalMask[lIdx]) {+ cov = 1.0;+ } else if (+ antiAlias &&+ !exterior[lIdx] &&+ !(gapBridge && gapBridge[lIdx]) &&+ !(preserveExistingTarget && targetFilledBarrier && targetFilledBarrier[lIdx])+ ) {+ let filledNeighbors = 0;+ if (lx > 0 && finalMask[lIdx - 1]) filledNeighbors++;+ if (lx < bw - 1 && finalMask[lIdx + 1]) filledNeighbors++;+ if (ly > 0 && finalMask[lIdx - bw]) filledNeighbors++;+ if (ly < bh - 1 && finalMask[lIdx + bw]) filledNeighbors++;+ if (filledNeighbors >= 2) {+ cov = (filledNeighbors / 4) * 0.5;+ }+ }++ if (cov <= 0) continue;++ const off = (tRow + tlx) << 2;+ const srcA = cov * effectiveOpacity * fillColorAlphaNorm;+ if (srcA <= 0.0005) continue;++ if (isEraseFill) {+ const curA = workBuf[off + 3];+ if (curA === 0) continue;+ const nextA = Math.round(curA * (1 - srcA));+ if (nextA === curA) continue;+ workBuf[off + 3] = nextA;+ if (nextA === 0) {+ workBuf[off] = 0;+ workBuf[off + 1] = 0;+ workBuf[off + 2] = 0;+ }+ tileChanged = true;+ } else if (alphaLocked) {+ const dstAlpha = workBuf[off + 3];+ if (dstAlpha === 0) continue;+ const inv = 1 - srcA;+ workBuf[off] = Math.round(fillR * srcA + workBuf[off] * inv);+ workBuf[off + 1] = Math.round(fillG * srcA + workBuf[off + 1] * inv);+ workBuf[off + 2] = Math.round(fillB * srcA + workBuf[off + 2] * inv);+ tileChanged = true;+ } else if (srcA >= 0.999) {+ workBuf[off] = fillR;+ workBuf[off + 1] = fillG;+ workBuf[off + 2] = fillB;+ workBuf[off + 3] = fillA;+ tileChanged = true;+ } else {+ const dstA = workBuf[off + 3] / 255;+ const outA = srcA + dstA * (1 - srcA);+ if (outA > 0) {+ const invOut = 1 / outA;+ const invS = 1 - srcA;+ workBuf[off] = Math.round((fillR * srcA + workBuf[off] * dstA * invS) * invOut);+ workBuf[off + 1] = Math.round((fillG * srcA + workBuf[off + 1] * dstA * invS) * invOut);+ workBuf[off + 2] = Math.round((fillB * srcA + workBuf[off + 2] * dstA * invS) * invOut);+ workBuf[off + 3] = Math.round(outA * 255);+ tileChanged = true;+ }+ }+ }+ }++ if (tileChanged) {+ grid.snapshotSingleTileInto(targetLayerId, tx, ty, beforeSnapshot);+ grid.writeImageData(+ targetLayerId,+ { data: workBuf, width: TILE_SIZE, height: TILE_SIZE },+ tileDocX,+ tileDocY,+ targetFormat,+ true+ );+ }+ }+ }++ const dirtyRect: DirtyRect = {+ x: dirtyMinX,+ y: dirtyMinY,+ width: Math.max(1, dirtyMaxX - dirtyMinX + 1),+ height: Math.max(1, dirtyMaxY - dirtyMinY + 1),+ };+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, dirtyRect);+ if (tileDeltas.length > 0) {+ grid.notifyChange(true);+ }+ return { dirtyRect, modified: tileDeltas.length > 0, tileDeltas };+}++/**+ * CSP-grade "Enclose and Fill" (Close & Fill):+ * Draw a lasso around a complex outline region (e.g. hair with many small strands),+ * and every closed area inside the Reference layer's outline is filled automatically+ * without affecting the open background or partially enclosed regions.+ */+export function executeEncloseAndFillOnTileGrid(+ params: EncloseAndFillTileParams+): SmartLineFillResult {+ const {+ grid,+ targetLayerId,+ layers,+ dimensions,+ polygon,+ fillColorHex,+ tolerance,+ referMode = 'refer-reference',+ targetMode = 'all-enclosed',+ targetFormat,+ options,+ } = params;++ if (polygon.length < 3 || dimensions.width <= 0 || dimensions.height <= 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ let minX = polygon[0].x;+ let maxX = polygon[0].x;+ let minY = polygon[0].y;+ let maxY = polygon[0].y;+ for (let i = 1; i < polygon.length; i++) {+ const pt = polygon[i];+ if (pt.x < minX) minX = pt.x;+ if (pt.x > maxX) maxX = pt.x;+ if (pt.y < minY) minY = pt.y;+ if (pt.y > maxY) maxY = pt.y;+ }++ const closeGap = Math.max(0, Math.min(40, Math.round(options?.closeGap ?? 0)));+ const areaScale = Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0)));+ const pad = Math.max(closeGap, Math.abs(areaScale)) + 4;++ const bx0 = Math.max(0, Math.floor(minX) - pad);+ const by0 = Math.max(0, Math.floor(minY) - pad);+ const bx1 = Math.min(dimensions.width - 1, Math.ceil(maxX) + pad);+ const by1 = Math.min(dimensions.height - 1, Math.ceil(maxY) + pad);+ const bw = bx1 - bx0 + 1;+ const bh = by1 - by0 + 1;+ if (bw <= 0 || bh <= 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ const regionMask = rasterizePolygonMask(polygon, bx0, by0, bw, bh);++ return runCoreSmartLineFill({+ grid,+ targetLayerId,+ layers,+ dimensions,+ bx0,+ by0,+ bw,+ bh,+ regionMask,+ fillColorHex,+ tolerance,+ referMode,+ preserveExistingTarget: targetMode === 'unfilled-only',+ opaqueUnfilledIsWhite: false,+ targetFormat,+ options,+ });+}++/**+ * CSP-grade "Paint Unfilled Area":+ * Paint a brush stroke over outlines, tight V-corners, and narrow unfilled crevices.+ * Fills ONLY enclosed unfilled pockets/pixels inside the stroke bounded by line art+ * and existing flat fills — never spilling onto the open background or overwriting already-painted areas.+ */+export function executePaintUnfilledAreaOnTileGrid(+ params: PaintUnfilledAreaTileParams+): SmartLineFillResult {+ const {+ grid,+ targetLayerId,+ layers,+ dimensions,+ strokePoints,+ brushSize,+ fillColorHex,+ tolerance,+ referMode = 'refer-reference',+ targetFormat,+ options,+ } = params;++ if (strokePoints.length === 0 || dimensions.width <= 0 || dimensions.height <= 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ const radius = Math.max(1, Math.min(150, (Number.isFinite(brushSize) ? brushSize : 24) / 2));++ let minX = strokePoints[0].x;+ let maxX = strokePoints[0].x;+ let minY = strokePoints[0].y;+ let maxY = strokePoints[0].y;+ for (let i = 1; i < strokePoints.length; i++) {+ const pt = strokePoints[i];+ if (pt.x < minX) minX = pt.x;+ if (pt.x > maxX) maxX = pt.x;+ if (pt.y < minY) minY = pt.y;+ if (pt.y > maxY) maxY = pt.y;+ }++ const closeGap = Math.max(0, Math.min(40, Math.round(options?.closeGap ?? 0)));+ const areaScale = Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0)));+ const pad = Math.ceil(radius) + Math.max(closeGap, Math.abs(areaScale)) + 4;++ const bx0 = Math.max(0, Math.floor(minX) - pad);+ const by0 = Math.max(0, Math.floor(minY) - pad);+ const bx1 = Math.min(dimensions.width - 1, Math.ceil(maxX) + pad);+ const by1 = Math.min(dimensions.height - 1, Math.ceil(maxY) + pad);+ const bw = bx1 - bx0 + 1;+ const bh = by1 - by0 + 1;+ if (bw <= 0 || bh <= 0) {+ return { dirtyRect: null, modified: false, tileDeltas: [] };+ }++ const regionMask = rasterizeBrushStrokeMask(strokePoints, radius, bx0, by0, bw, bh);++ return runCoreSmartLineFill({+ grid,+ targetLayerId,+ layers,+ dimensions,+ bx0,+ by0,+ bw,+ bh,+ regionMask,+ fillColorHex,+ tolerance,+ referMode,+ preserveExistingTarget: true,+ opaqueUnfilledIsWhite: true,+ targetFormat,+ options,+ });+}diff --git a/src/utils/subToolGroups.ts b/src/utils/subToolGroups.tsnew file mode 100644index 0000000..9beea49--- /dev/null+++ b/src/utils/subToolGroups.ts@@ -0,0 +1,655 @@+import { BrushCategory, BrushPresetId, CspBrush, DecorationCategory } from '../types/editor';+import {+ ALL_BUILTIN_BRUSHES,+ ALL_BUILTIN_BRUSH_SECTIONS,+ BUILTIN_BRUSH_SECTIONS,+ DECORATION_BRUSH_SECTIONS,+ isDecorationCategory,+} from './presetBrushes';+import { ERASER_PRESET_ID, migrateLegacyPresetId } from './brushPresetManager';+import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';++export const SUBTOOL_GROUPS_STORAGE_KEY = 'ink_studio_subtool_groups_v1';++export type SubToolGroupIconId =+ | 'folder'+ | 'pen'+ | 'pencil'+ | 'paintbrush'+ | 'droplets'+ | 'palette'+ | 'sparkles'+ | 'star'+ | 'layers';++export const SUBTOOL_GROUP_ICON_IDS: readonly SubToolGroupIconId[] = [+ 'folder',+ 'pen',+ 'pencil',+ 'paintbrush',+ 'droplets',+ 'palette',+ 'sparkles',+ 'star',+ 'layers',+];++export const SUBTOOL_GROUP_COLOR_SWATCHES: readonly {+ id: string;+ label: string;+ hex: string | null;+}[] = [+ { id: 'none', label: 'Default', hex: null },+ { id: 'indigo', label: 'Indigo', hex: '#818cf8' },+ { id: 'sky', label: 'Sky', hex: '#38bdf8' },+ { id: 'emerald', label: 'Emerald', hex: '#34d399' },+ { id: 'amber', label: 'Amber', hex: '#fbbf24' },+ { id: 'rose', label: 'Rose', hex: '#fb7185' },+ { id: 'violet', label: 'Violet', hex: '#a78bfa' },+];++export type BuiltinTargetGroupId = BrushCategory | 'custom';+export type SubToolGroupScope = 'brush' | 'decoration';++export interface CustomSubToolGroup {+ id: string;+ name: string;+ color?: string | null;+ icon?: SubToolGroupIconId;+ /** Tool group scope: 'brush' (default) or 'decoration' */+ toolScope?: SubToolGroupScope;+ /** Ordered list of BrushPresetIds (built-in or custom CspBrush IDs) assigned to this group */+ brushIds: BrushPresetId[];+ /** Last selected brush inside this group so opening the group restores it (CSP-style) */+ lastActiveBrushId?: BrushPresetId;+ createdAt: number;+}++export function isDecorationCustomGroup(group: CustomSubToolGroup): boolean {+ return group.toolScope === 'decoration';+}++/**+ * Active tab filter in the Sub Tool palette:+ * - 'all': show every group (default, full list view)+ * - BrushCategory: built-in section ('pen' | 'sketch' | 'brush' | 'blend' | 'natural-paint')+ * - 'custom': Imported/Custom brushes section+ * - string: a CustomSubToolGroup.id+ */+export type ActiveSubToolGroupTab = 'all' | BuiltinTargetGroupId | string;+export type ActiveDecorationSubToolTab = 'all' | DecorationCategory | string;++export type BrushGroupOverridesMap = Record<string, BuiltinTargetGroupId>;+export type BuiltinGroupOrdersMap = Partial<Record<BuiltinTargetGroupId, BrushPresetId[]>>;++export interface PersistedSubToolGroupsState {+ version: 1;+ groups: CustomSubToolGroup[];+ activeTab: ActiveSubToolGroupTab;+ activeDecorationTab?: ActiveDecorationSubToolTab;+ /** Maps any BrushPresetId moved into a built-in/Imported group to that target group ID */+ brushGroupOverrides?: BrushGroupOverridesMap;+ /** Optional user-reordered brush sequence inside built-in/Imported groups */+ builtinGroupOrders?: BuiltinGroupOrdersMap;+}++export const BUILTIN_CATEGORY_SET = new Set<string>(+ ALL_BUILTIN_BRUSH_SECTIONS.map((s) => s.id)+);+export const BUILTIN_TARGET_GROUP_SET = new Set<string>([+ ...ALL_BUILTIN_BRUSH_SECTIONS.map((s) => s.id),+ 'custom',+]);+const VALID_ICON_SET = new Set<string>(SUBTOOL_GROUP_ICON_IDS);++let groupUidSeq = 1;+export function createSubToolGroupId(): string {+ groupUidSeq += 1;+ return `stg-${Date.now().toString(36)}-${groupUidSeq}-${Math.random().toString(36).slice(2, 5)}`;+}++export function normalizeBrushIdForGroup(presetId: string): BrushPresetId | null {+ if (!presetId || typeof presetId !== 'string') return null;+ const trimmed = presetId.trim();+ if (!trimmed || trimmed === ERASER_PRESET_ID || trimmed === 'eraser') return null;+ return migrateLegacyPresetId(trimmed);+}++export function isBuiltinGroupTab(tab: string): tab is BrushCategory {+ return BUILTIN_CATEGORY_SET.has(tab);+}++export function isBuiltinTargetGroupId(id: string): id is BuiltinTargetGroupId {+ return BUILTIN_TARGET_GROUP_SET.has(id);+}++export function getFactoryGroupIdForBrush(+ presetId: BrushPresetId,+ customBrushes?: readonly CspBrush[]+): BuiltinTargetGroupId {+ const norm = migrateLegacyPresetId(presetId);+ const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === norm);+ if (builtin) return builtin.category;+ if (customBrushes?.some((b) => b.id === presetId || b.id === norm)) {+ return 'custom';+ }+ return 'custom';+}++export function getGroupDisplayLabel(+ groupId: string,+ customGroups: readonly CustomSubToolGroup[]+): string {+ const custom = customGroups.find((g) => g.id === groupId);+ if (custom) return custom.name;+ const sec = ALL_BUILTIN_BRUSH_SECTIONS.find((s) => s.id === groupId);+ if (sec) return sec.label;+ if (groupId === 'custom') return 'Imported';+ return groupId;+}++export function sanitizeSubToolGroupsState(raw: unknown): PersistedSubToolGroupsState {+ const fallback: PersistedSubToolGroupsState = {+ version: 1,+ groups: [],+ activeTab: 'all',+ brushGroupOverrides: {},+ builtinGroupOrders: {},+ };+ if (!raw || typeof raw !== 'object') return fallback;+ const rec = raw as Record<string, unknown>;+ const rawGroups = Array.isArray(rec.groups) ? rec.groups : [];++ const seenGroupIds = new Set<string>();+ const claimedBrushIds = new Set<string>();+ const groups: CustomSubToolGroup[] = [];++ for (const entry of rawGroups) {+ if (!entry || typeof entry !== 'object') continue;+ const g = entry as Record<string, unknown>;+ const rawId = typeof g.id === 'string' && g.id.trim() ? g.id.trim() : createSubToolGroupId();+ if (+ seenGroupIds.has(rawId) ||+ rawId === 'all' ||+ rawId === 'custom' ||+ BUILTIN_CATEGORY_SET.has(rawId)+ ) {+ continue;+ }+ seenGroupIds.add(rawId);++ const name =+ typeof g.name === 'string' && g.name.trim().length > 0+ ? g.name.trim().slice(0, 32)+ : `Custom Group ${groups.length + 1}`;++ const color =+ typeof g.color === 'string' && /^#[0-9a-fA-F]{3,6}$/.test(g.color.trim())+ ? g.color.trim()+ : null;++ const icon: SubToolGroupIconId =+ typeof g.icon === 'string' && VALID_ICON_SET.has(g.icon)+ ? (g.icon as SubToolGroupIconId)+ : 'folder';++ const brushIds: BrushPresetId[] = [];+ if (Array.isArray(g.brushIds)) {+ for (const bid of g.brushIds) {+ if (typeof bid !== 'string') continue;+ const normalized = normalizeBrushIdForGroup(bid);+ if (!normalized || claimedBrushIds.has(normalized)) continue;+ claimedBrushIds.add(normalized);+ brushIds.push(normalized);+ }+ }++ const rawLast =+ typeof g.lastActiveBrushId === 'string'+ ? normalizeBrushIdForGroup(g.lastActiveBrushId)+ : null;+ const lastActiveBrushId = rawLast && brushIds.includes(rawLast) ? rawLast : undefined;++ const createdAt =+ typeof g.createdAt === 'number' && Number.isFinite(g.createdAt) ? g.createdAt : Date.now();+ const toolScope: SubToolGroupScope | undefined =+ g.toolScope === 'decoration' ? 'decoration' : undefined;++ groups.push({+ id: rawId,+ name,+ color,+ icon,+ ...(toolScope ? { toolScope } : {}),+ brushIds,+ lastActiveBrushId,+ createdAt,+ });+ }++ const brushGroupOverrides: BrushGroupOverridesMap = {};+ if (rec.brushGroupOverrides && typeof rec.brushGroupOverrides === 'object') {+ for (const [rawBrushId, rawTarget] of Object.entries(+ rec.brushGroupOverrides as Record<string, unknown>+ )) {+ const norm = normalizeBrushIdForGroup(rawBrushId);+ if (+ norm &&+ !claimedBrushIds.has(norm) &&+ typeof rawTarget === 'string' &&+ isBuiltinTargetGroupId(rawTarget)+ ) {+ brushGroupOverrides[norm] = rawTarget;+ }+ }+ }++ const builtinGroupOrders: BuiltinGroupOrdersMap = {};+ if (rec.builtinGroupOrders && typeof rec.builtinGroupOrders === 'object') {+ for (const [rawGroupId, rawOrder] of Object.entries(+ rec.builtinGroupOrders as Record<string, unknown>+ )) {+ if (!isBuiltinTargetGroupId(rawGroupId) || !Array.isArray(rawOrder)) continue;+ const seenInOrder = new Set<string>();+ const cleanedOrder: BrushPresetId[] = [];+ for (const bid of rawOrder) {+ if (typeof bid !== 'string') continue;+ const norm = normalizeBrushIdForGroup(bid);+ if (!norm || claimedBrushIds.has(norm) || seenInOrder.has(norm)) continue;+ seenInOrder.add(norm);+ cleanedOrder.push(norm);+ }+ if (cleanedOrder.length > 0) {+ builtinGroupOrders[rawGroupId] = cleanedOrder;+ }+ }+ }++ let activeTab: ActiveSubToolGroupTab = 'all';+ if (typeof rec.activeTab === 'string') {+ const t = rec.activeTab;+ if (+ t === 'all' ||+ t === 'custom' ||+ BUILTIN_CATEGORY_SET.has(t) ||+ groups.some((g) => g.id === t)+ ) {+ activeTab = t;+ }+ }++ let activeDecorationTab: ActiveDecorationSubToolTab = 'all';+ if (typeof rec.activeDecorationTab === 'string') {+ const dt = rec.activeDecorationTab;+ if (+ dt === 'all' ||+ isDecorationCategory(dt) ||+ groups.some((g) => g.id === dt && isDecorationCustomGroup(g))+ ) {+ activeDecorationTab = dt;+ }+ }++ return {+ version: 1,+ groups,+ activeTab,+ activeDecorationTab,+ brushGroupOverrides,+ builtinGroupOrders,+ };+}++export function loadSubToolGroupsState(): PersistedSubToolGroupsState {+ try {+ const raw = safeLocalStorageGetItem(SUBTOOL_GROUPS_STORAGE_KEY);+ if (!raw) {+ return {+ version: 1,+ groups: [],+ activeTab: 'all',+ activeDecorationTab: 'all',+ brushGroupOverrides: {},+ builtinGroupOrders: {},+ };+ }+ return sanitizeSubToolGroupsState(JSON.parse(raw));+ } catch {+ return {+ version: 1,+ groups: [],+ activeTab: 'all',+ activeDecorationTab: 'all',+ brushGroupOverrides: {},+ builtinGroupOrders: {},+ };+ }+}++export function saveSubToolGroupsState(state: PersistedSubToolGroupsState): void {+ safeLocalStorageSetItem(+ SUBTOOL_GROUPS_STORAGE_KEY,+ JSON.stringify(state),+ 'custom sub tool groups'+ );+}++/**+ * Returns a lookup map from normalized BrushPresetId -> owning CustomSubToolGroup.+ */+export function buildBrushToCustomGroupMap(+ groups: readonly CustomSubToolGroup[]+): Map<BrushPresetId, CustomSubToolGroup> {+ const map = new Map<BrushPresetId, CustomSubToolGroup>();+ for (const g of groups) {+ for (const bid of g.brushIds) {+ map.set(migrateLegacyPresetId(bid), g);+ }+ }+ return map;+}++/**+ * Resolves valid BrushPresetIds belonging to a given custom group (filtering out deleted custom brushes).+ */+export function getValidBrushIdsInCustomGroup(+ group: CustomSubToolGroup,+ customBrushes: readonly CspBrush[]+): BrushPresetId[] {+ const builtinSet = new Set<string>(ALL_BUILTIN_BRUSHES.map((b) => b.id));+ const customSet = new Set<string>(customBrushes.map((b) => b.id));+ return group.brushIds.filter((id) => {+ const norm = migrateLegacyPresetId(id);+ return builtinSet.has(norm) || customSet.has(id) || customSet.has(norm);+ });+}++/**+ * Resolves the effective owning group ID (custom group ID, built-in category, or 'custom')+ * for any brush preset, accounting for both custom groups and built-in group moves.+ */+export function getEffectiveBrushGroupId(+ presetId: BrushPresetId,+ customGroups: readonly CustomSubToolGroup[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ customBrushes?: readonly CspBrush[]+): string {+ const norm = migrateLegacyPresetId(presetId);+ for (const g of customGroups) {+ if (g.brushIds.includes(norm) || g.brushIds.includes(presetId)) {+ return g.id;+ }+ }+ const override = brushGroupOverrides[norm] ?? brushGroupOverrides[presetId];+ if (override) return override;+ return getFactoryGroupIdForBrush(presetId, customBrushes);+}++/**+ * Returns the ordered list of BrushPresetIds currently inside a built-in or 'custom' (Imported) group,+ * respecting cross-group moves (`brushGroupOverrides`) and per-group reordering (`builtinGroupOrders`).+ */+export function getOrderedBrushIdsInBuiltinGroup(+ groupId: BuiltinTargetGroupId,+ customGroups: readonly CustomSubToolGroup[],+ customBrushes: readonly CspBrush[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ builtinGroupOrders: BuiltinGroupOrdersMap = {}+): BrushPresetId[] {+ const assignedToCustom = buildBrushToCustomGroupMap(customGroups);+ const memberIds: BrushPresetId[] = [];+ const memberSet = new Set<string>();++ const pushIfMember = (id: BrushPresetId, defaultGroup: BuiltinTargetGroupId) => {+ const norm = migrateLegacyPresetId(id);+ if (assignedToCustom.has(norm)) return;+ const effective = brushGroupOverrides[norm] ?? brushGroupOverrides[id] ?? defaultGroup;+ if (effective !== groupId) return;+ if (memberSet.has(norm)) return;+ memberSet.add(norm);+ memberIds.push(id);+ };++ // Built-in presets (Brush + Decoration)+ for (const b of ALL_BUILTIN_BRUSHES) {+ pushIfMember(b.id, b.category);+ }+ // Custom / imported brushes+ for (const cb of customBrushes) {+ pushIfMember(cb.id, 'custom');+ }++ const customOrder = builtinGroupOrders[groupId];+ if (!customOrder || customOrder.length === 0) {+ return memberIds;+ }++ // Apply explicit ordering while keeping any new/unlisted members appended in default order+ const byNorm = new Map<string, BrushPresetId>(+ memberIds.map((id) => [migrateLegacyPresetId(id), id])+ );+ const ordered: BrushPresetId[] = [];+ const emitted = new Set<string>();+ for (const rawId of customOrder) {+ const norm = migrateLegacyPresetId(rawId);+ const actual = byNorm.get(norm);+ if (actual && !emitted.has(norm)) {+ emitted.add(norm);+ ordered.push(actual);+ }+ }+ for (const id of memberIds) {+ const norm = migrateLegacyPresetId(id);+ if (!emitted.has(norm)) {+ emitted.add(norm);+ ordered.push(id);+ }+ }+ return ordered;+}++/**+ * Returns the ordered list of subtool BrushPresetIds for a specific tab view+ * (matching the exact display order in SubToolList).+ */+export function getOrderedSubToolIdsForTab(+ activeTab: ActiveSubToolGroupTab,+ customGroups: readonly CustomSubToolGroup[],+ customBrushes: readonly CspBrush[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ builtinGroupOrders: BuiltinGroupOrdersMap = {}+): BrushPresetId[] {+ const customGroup = customGroups.find((g) => g.id === activeTab);+ if (customGroup) {+ return getValidBrushIdsInCustomGroup(customGroup, customBrushes);+ }++ if (isBuiltinTargetGroupId(activeTab)) {+ return getOrderedBrushIdsInBuiltinGroup(+ activeTab,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ }++ // 'all' view: Brush custom groups first, then built-in sections, then Imported+ const ordered: BrushPresetId[] = [];+ for (const g of customGroups) {+ if (isDecorationCustomGroup(g)) continue;+ ordered.push(...getValidBrushIdsInCustomGroup(g, customBrushes));+ }+ for (const sec of BUILTIN_BRUSH_SECTIONS) {+ ordered.push(+ ...getOrderedBrushIdsInBuiltinGroup(+ sec.id,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ );+ }+ ordered.push(+ ...getOrderedBrushIdsInBuiltinGroup(+ 'custom',+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ );+ return ordered;+}++export interface NavigableSubToolGroupEntry {+ id: ActiveSubToolGroupTab;+ label: string;+ isCustom: boolean;+ brushIds: BrushPresetId[];+}++/**+ * Returns the ordered list of Sub Tool Groups for Next/Previous SubTool Group navigation+ * (custom groups first, then non-empty built-in sections, then Imported if non-empty).+ */+export function getNavigableSubToolGroups(+ customGroups: readonly CustomSubToolGroup[],+ customBrushes: readonly CspBrush[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ builtinGroupOrders: BuiltinGroupOrdersMap = {}+): NavigableSubToolGroupEntry[] {+ const entries: NavigableSubToolGroupEntry[] = [];++ for (const g of customGroups) {+ if (isDecorationCustomGroup(g)) continue;+ entries.push({+ id: g.id,+ label: g.name,+ isCustom: true,+ brushIds: getValidBrushIdsInCustomGroup(g, customBrushes),+ });+ }++ for (const sec of BUILTIN_BRUSH_SECTIONS) {+ const ids = getOrderedBrushIdsInBuiltinGroup(+ sec.id,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ if (ids.length > 0) {+ entries.push({+ id: sec.id,+ label: sec.label,+ isCustom: false,+ brushIds: ids,+ });+ }+ }++ const importedIds = getOrderedBrushIdsInBuiltinGroup(+ 'custom',+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ if (importedIds.length > 0) {+ entries.push({+ id: 'custom',+ label: 'Imported',+ isCustom: false,+ brushIds: importedIds,+ });+ }++ return entries;+}++/**+ * Returns the ordered list of Decoration subtool BrushPresetIds for a specific Decoration tab+ * ('all' | 'deco-background' | 'deco-clothing' | 'deco-effect').+ */+export function getOrderedDecorationSubToolIdsForTab(+ activeDecorationTab: ActiveDecorationSubToolTab,+ customGroups: readonly CustomSubToolGroup[],+ customBrushes: readonly CspBrush[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ builtinGroupOrders: BuiltinGroupOrdersMap = {}+): BrushPresetId[] {+ const decoCustomGroup = customGroups.find(+ (g) => g.id === activeDecorationTab && isDecorationCustomGroup(g)+ );+ if (decoCustomGroup) {+ return getValidBrushIdsInCustomGroup(decoCustomGroup, customBrushes);+ }+ if (isDecorationCategory(activeDecorationTab)) {+ return getOrderedBrushIdsInBuiltinGroup(+ activeDecorationTab,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ }+ const ordered: BrushPresetId[] = [];+ for (const g of customGroups) {+ if (!isDecorationCustomGroup(g)) continue;+ ordered.push(...getValidBrushIdsInCustomGroup(g, customBrushes));+ }+ for (const sec of DECORATION_BRUSH_SECTIONS) {+ ordered.push(+ ...getOrderedBrushIdsInBuiltinGroup(+ sec.id,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ );+ }+ return ordered;+}++/**+ * Returns the ordered list of Decoration Sub Tool Groups (custom Decoration groups first,+ * then Background, Clothing, Effect) for Next/Previous SubTool Group navigation.+ */+export function getNavigableDecorationSubToolGroups(+ customGroups: readonly CustomSubToolGroup[],+ customBrushes: readonly CspBrush[],+ brushGroupOverrides: BrushGroupOverridesMap = {},+ builtinGroupOrders: BuiltinGroupOrdersMap = {}+): NavigableSubToolGroupEntry[] {+ const entries: NavigableSubToolGroupEntry[] = [];+ for (const g of customGroups) {+ if (!isDecorationCustomGroup(g)) continue;+ entries.push({+ id: g.id,+ label: g.name,+ isCustom: true,+ brushIds: getValidBrushIdsInCustomGroup(g, customBrushes),+ });+ }+ for (const sec of DECORATION_BRUSH_SECTIONS) {+ const ids = getOrderedBrushIdsInBuiltinGroup(+ sec.id,+ customGroups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ if (ids.length > 0) {+ entries.push({+ id: sec.id,+ label: sec.label,+ isCustom: false,+ brushIds: ids,+ });+ }+ }+ return entries;+}diff --git a/src/utils/subToolNavigation.ts b/src/utils/subToolNavigation.tsnew file mode 100644index 0000000..69d45a4--- /dev/null+++ b/src/utils/subToolNavigation.ts@@ -0,0 +1,410 @@+import { BrushPresetId, CspBrush, ToolType } from '../types/editor';+import {+ ALL_BUILTIN_BRUSHES,+ BUILTIN_BRUSH_SECTIONS,+ DECORATION_BRUSH_SECTIONS,+ isDecorationCategory,+ isDecorationPresetId,+} from './presetBrushes';+import {+ ERASER_PRESET_ID,+ NEUTRAL_BRUSH_DEFAULTS,+ getEffectiveBrushSettings,+ getSavedBrushSettings,+ migrateLegacyPresetId,+ saveActiveDecorationPresetId,+ saveActivePresetId,+} from './brushPresetManager';+import { getCachedCustomBrushes, prepareBrushSettingsForCsp } from './brushStorage';+import {+ ActiveSubToolGroupTab,+ getEffectiveBrushGroupId,+ getNavigableDecorationSubToolGroups,+ getNavigableSubToolGroups,+ getOrderedDecorationSubToolIdsForTab,+ getOrderedSubToolIdsForTab,+ getValidBrushIdsInCustomGroup,+ isDecorationCustomGroup,+} from './subToolGroups';+import { toolStoreActions, useToolStore } from '../stores/useToolStore';+import {+ subToolGroupStoreActions,+ useSubToolGroupStore,+} from '../stores/useSubToolGroupStore';++/**+ * Ordered list of drawing/editing instruments matching ToolStrip order+ * (excludes 'transform' which is a modal edit session triggered via Ctrl+T).+ */+export const TOOL_CYCLE_ORDER: readonly ToolType[] = [+ 'brush',+ 'decoration',+ 'eraser',+ 'pipette',+ 'liquify',+ 'retouch',+ 'select-rect',+ 'select-lasso',+ 'select-wand',+ 'select-pen',+ 'fill',+ 'gradient',+ 'shape',+ 'pen',+ 'object',+ 'text',+ 'frame',+ 'balloon',+ 'vector-edit',+ '3d',+];++export const TOOL_DISPLAY_LABELS: Record<ToolType, string> = {+ brush: 'Brush',+ decoration: 'Decoration',+ eraser: 'Eraser',+ pipette: 'Eyedropper',+ transform: 'Transform',+ 'select-rect': 'Rectangle Selection',+ 'select-lasso': 'Lasso Selection',+ 'select-wand': 'Magic Wand',+ 'select-pen': 'Selection Pen',+ 'select-eraser': 'Selection Eraser',+ fill: 'Fill Bucket',+ gradient: 'Gradient',+ retouch: 'Retouch',+ shape: 'Shapes',+ pen: 'Bézier Pen',+ text: 'Text',+ frame: 'Frame Border',+ balloon: 'Speech Balloon',+ object: 'Object',+ 'vector-edit': 'Correct Line',+ liquify: 'Liquify',+ '3d': '3D Object & Camera',+};++export interface SubToolActivationResult {+ presetId: BrushPresetId;+ name: string;+}++export interface MainToolStepResult {+ tool: ToolType;+ label: string;+}++export interface SubToolGroupActivationResult {+ groupId: ActiveSubToolGroupTab;+ groupName: string;+ activatedBrushName?: string;+}++export function resolveSubToolDisplayName(+ presetId: BrushPresetId,+ customBrushes: readonly CspBrush[] = getCachedCustomBrushes()+): string {+ const norm = migrateLegacyPresetId(presetId);+ if (norm === ERASER_PRESET_ID || norm === 'eraser') return 'Eraser';+ const custom = customBrushes.find((b) => b.id === presetId || b.id === norm);+ if (custom) return custom.name;+ const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === norm);+ if (builtin) return builtin.name;+ return presetId;+}++/**+ * Activates any subtool preset (built-in Brush, built-in Decoration, or custom CspBrush)+ * synchronously for immediate canvas response, while also hydrating custom brush images asynchronously.+ */+export function activateSubToolPreset(+ presetId: BrushPresetId,+ customBrushesInput?: readonly CspBrush[]+): SubToolActivationResult | null {+ const norm = migrateLegacyPresetId(presetId);+ if (!norm) return null;++ if (norm === ERASER_PRESET_ID || norm === 'eraser') {+ toolStoreActions.selectTool('eraser');+ return { presetId: ERASER_PRESET_ID, name: 'Eraser' };+ }++ const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();+ const customMatch = customBrushes.find((b) => b.id === presetId || b.id === norm);+ const builtinMatch = !customMatch ? ALL_BUILTIN_BRUSHES.find((b) => b.id === norm) : undefined;+ if (!customMatch && !builtinMatch) return null;++ const targetId = customMatch ? customMatch.id : builtinMatch!.id;+ const displayName = customMatch ? customMatch.name : builtinMatch!.name;++ const groupState = useSubToolGroupStore.getState();+ const ownerGroupId = getEffectiveBrushGroupId(+ targetId,+ groupState.groups,+ groupState.brushGroupOverrides,+ customBrushes+ );+ const ownerCustomGroup = groupState.groups.find((g) => g.id === ownerGroupId);+ const targetIsDecoration =+ Boolean(ownerCustomGroup && isDecorationCustomGroup(ownerCustomGroup)) ||+ isDecorationCategory(ownerGroupId) ||+ (!ownerCustomGroup &&+ (isDecorationPresetId(targetId) || isDecorationCategory(customMatch?.category)));++ toolStoreActions.selectTool(targetIsDecoration ? 'decoration' : 'brush');+ if (targetIsDecoration) {+ saveActiveDecorationPresetId(targetId);+ } else {+ saveActivePresetId(targetId);+ }++ // Immediate synchronous activation so zero frames are dropped on hotkey press+ const effective = getEffectiveBrushSettings(targetId, customBrushes);+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...effective,+ preset: targetId,+ });+ subToolGroupStoreActions.recordActiveBrush(targetId);++ // Async image decode hydration for custom brushes whose tip images aren't yet decoded+ if (customMatch) {+ void prepareBrushSettingsForCsp(customMatch).then((prepared) => {+ // Only apply if user hasn't already switched away to another preset+ if (useToolStore.getState().activePresetId !== targetId) return;+ const saved = getSavedBrushSettings(targetId);+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...prepared,+ ...saved,+ preset: targetId,+ });+ });+ }++ return { presetId: targetId, name: displayName };+}++/**+ * Switches to the previous (-1) or next (+1) sub tool within the currently active SubTool group+ * (wrapping cleanly around the edges, matching Clip Studio Paint's ',' and '.' workflow).+ */+export function stepSubTool(+ direction: -1 | 1,+ customBrushesInput?: readonly CspBrush[]+): SubToolActivationResult | null {+ const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();+ const currentState = useToolStore.getState();+ const { activeTab, activeDecorationTab, groups, brushGroupOverrides, builtinGroupOrders } =+ useSubToolGroupStore.getState();++ const isDecoMode = currentState.tool === 'decoration';+ let ordered = isDecoMode+ ? getOrderedDecorationSubToolIdsForTab(+ activeDecorationTab,+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ : getOrderedSubToolIdsForTab(+ activeTab,+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ if (ordered.length === 0) {+ // Active custom group is empty — fall back to full list so shortcut always feels responsive+ ordered = isDecoMode+ ? getOrderedDecorationSubToolIdsForTab(+ 'all',+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ : getOrderedSubToolIdsForTab(+ 'all',+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ }+ if (ordered.length === 0) return null;++ const currentPreset = migrateLegacyPresetId(currentState.activePresetId);+ const currentIdx = ordered.findIndex(+ (id) => id === currentState.activePresetId || migrateLegacyPresetId(id) === currentPreset+ );++ let nextIdx: number;+ if (currentIdx < 0) {+ nextIdx = direction > 0 ? 0 : ordered.length - 1;+ } else {+ nextIdx = (currentIdx + direction + ordered.length) % ordered.length;+ }++ return activateSubToolPreset(ordered[nextIdx], customBrushes);+}++/**+ * Switches to the previous (-1) or next (+1) main instrument along the ToolStrip.+ */+export function stepMainTool(+ direction: -1 | 1,+ hasOpenDocument: boolean+): MainToolStepResult {+ const available = hasOpenDocument+ ? TOOL_CYCLE_ORDER+ : TOOL_CYCLE_ORDER.filter((t) => t !== '3d');++ const currentTool = useToolStore.getState().tool;+ const idx = available.indexOf(currentTool);+ const nextIdx =+ idx < 0+ ? direction > 0+ ? 0+ : available.length - 1+ : (idx + direction + available.length) % available.length;++ const nextTool = available[nextIdx];+ toolStoreActions.selectTool(nextTool);+ return {+ tool: nextTool,+ label: TOOL_DISPLAY_LABELS[nextTool] || nextTool,+ };+}++/**+ * Opens/focuses a SubTool group by ID (custom group ID, built-in category, or 'custom')+ * and activates its last-used or first subtool (like CSP).+ */+export function activateSubToolGroup(+ groupId: ActiveSubToolGroupTab,+ customBrushesInput?: readonly CspBrush[]+): SubToolGroupActivationResult | null {+ const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();+ const { groups, brushGroupOverrides, builtinGroupOrders } = useSubToolGroupStore.getState();++ const customGroup = groups.find((g) => g.id === groupId);+ if (customGroup) {+ const isDecoGroup = isDecorationCustomGroup(customGroup);+ if (isDecoGroup) {+ subToolGroupStoreActions.setActiveDecorationTab(customGroup.id);+ } else {+ subToolGroupStoreActions.setActiveTab(customGroup.id);+ }+ const validIds = getValidBrushIdsInCustomGroup(customGroup, customBrushes);+ const preferred =+ customGroup.lastActiveBrushId && validIds.includes(customGroup.lastActiveBrushId)+ ? customGroup.lastActiveBrushId+ : validIds[0];+ const activated = preferred ? activateSubToolPreset(preferred, customBrushes) : null;+ if (!activated) {+ toolStoreActions.selectTool(isDecoGroup ? 'decoration' : 'brush');+ }+ return {+ groupId: customGroup.id,+ groupName: customGroup.name,+ activatedBrushName: activated?.name,+ };+ }++ const builtinSection = BUILTIN_BRUSH_SECTIONS.find((s) => s.id === groupId);+ if (builtinSection) {+ subToolGroupStoreActions.setActiveTab(builtinSection.id);+ const ids = getOrderedSubToolIdsForTab(+ builtinSection.id,+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;+ return {+ groupId: builtinSection.id,+ groupName: builtinSection.label,+ activatedBrushName: activated?.name,+ };+ }++ const decoSection = DECORATION_BRUSH_SECTIONS.find((s) => s.id === groupId);+ if (decoSection && isDecorationCategory(decoSection.id)) {+ subToolGroupStoreActions.setActiveDecorationTab(decoSection.id);+ const ids = getOrderedDecorationSubToolIdsForTab(+ decoSection.id,+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;+ if (!activated) {+ toolStoreActions.selectTool('decoration');+ }+ return {+ groupId: decoSection.id,+ groupName: decoSection.label,+ activatedBrushName: activated?.name,+ };+ }++ if (groupId === 'custom') {+ subToolGroupStoreActions.setActiveTab('custom');+ const ids = getOrderedSubToolIdsForTab(+ 'custom',+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ const activated = ids[0] ? activateSubToolPreset(ids[0], customBrushes) : null;+ return {+ groupId: 'custom',+ groupName: 'Imported',+ activatedBrushName: activated?.name,+ };+ }++ return null;+}++/**+ * Cycles to the previous (-1) or next (+1) SubTool group tab and selects its brush.+ */+export function stepSubToolGroup(+ direction: -1 | 1,+ customBrushesInput?: readonly CspBrush[]+): SubToolGroupActivationResult | null {+ const customBrushes = customBrushesInput ? [...customBrushesInput] : getCachedCustomBrushes();+ const isDecoMode = useToolStore.getState().tool === 'decoration';+ const { activeTab, activeDecorationTab, groups, brushGroupOverrides, builtinGroupOrders } =+ useSubToolGroupStore.getState();+ const navigable = isDecoMode+ ? getNavigableDecorationSubToolGroups(+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ )+ : getNavigableSubToolGroups(+ groups,+ customBrushes,+ brushGroupOverrides,+ builtinGroupOrders+ );+ if (navigable.length === 0) return null;++ const currentTab = isDecoMode ? activeDecorationTab : activeTab;+ const idx = navigable.findIndex((entry) => entry.id === currentTab);+ const nextIdx =+ idx < 0+ ? direction > 0+ ? 0+ : navigable.length - 1+ : (idx + direction + navigable.length) % navigable.length;++ return activateSubToolGroup(navigable[nextIdx].id, customBrushes);+}diff --git a/src/utils/tileEngine/strokeComposite.ts b/src/utils/tileEngine/strokeComposite.tsindex 880319c..5f9a192 100644--- a/src/utils/tileEngine/strokeComposite.ts+++ b/src/utils/tileEngine/strokeComposite.ts@@ -39,8 +39,11 @@ export interface CompositeStrokeOptions {expressWhite: boolean;};selectionMask?: {- mask: Uint8Array;+ mask: Uint8Array | null;bounds: { x: number; y: number; width: number; height: number };+ /** When provided, `mask` is a full-document buffer indexed by `docY * maskWidth + docX`. */+ maskWidth?: number;+ maskHeight?: number;} | null;snapshotOut?: Map<string, { format: TileFormat; data: Uint8Array | null }>;suppressNotify?: boolean;@@ -541,12 +544,15 @@ export function compositeStrokeToTiles(const monoThresh = Math.max(1, Math.min(255, monochrome?.threshold ?? 128));const monoExpressBlack = monochrome?.expressBlack !== false;- const hasSelMask = Boolean(selectionMask?.mask);+ const hasSel = Boolean(selectionMask);const selMask = selectionMask?.mask ?? null;const selBx = selectionMask ? Math.floor(selectionMask.bounds.x) : 0;const selBy = selectionMask ? Math.floor(selectionMask.bounds.y) : 0;const selBw = selectionMask ? Math.ceil(selectionMask.bounds.width) : 0;const selBh = selectionMask ? Math.ceil(selectionMask.bounds.height) : 0;+ const selMaskW = selectionMask?.maskWidth ?? 0;+ const selMaskH = selectionMask?.maskHeight ?? 0;+ const selUsesFullDocMask = Boolean(selMask && selMaskW > 0 && selMaskH > 0);const fullOpacity = opacity >= 0.999;const memoryManager = host.getMemoryManager();const pxOut: [number, number, number, number] = [0, 0, 0, 0];@@ -644,21 +650,34 @@ export function compositeStrokeToTiles(const docY = destY + sy;const rowByteBase = tileLocalY << 5;let srcOff = (sy * w + srcStartX) << 2;- const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;- const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;+ const selRowValid =+ hasSel &&+ docY >= selBy &&+ docY < selBy + selBh &&+ (!selUsesFullDocMask || (docY >= 0 && docY < selMaskH));+ const selRowOff =+ selRowValid && selMask+ ? selUsesFullDocMask+ ? docY * selMaskW+ : (docY - selBy) * selBw+ : 0;for (let dx = 0; dx < copyWidth; dx++, srcOff += 4) {const sa = srcData[srcOff + 3];if (sa === 0) continue;let effA = fullOpacity ? sa : Math.round(sa * opacity);- if (hasSelMask) {+ if (hasSel) {const docX = destX + srcStartX + dx;if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;- const ma = selMask![selRowOff + (docX - selBx)];- if (ma === 0) continue;- if (ma < 255) {- effA = Math.round((effA * ma) / 255);+ if (selMask) {+ if (selUsesFullDocMask && (docX < 0 || docX >= selMaskW)) continue;+ const ma =+ selMask[selUsesFullDocMask ? selRowOff + docX : selRowOff + (docX - selBx)];+ if (ma === 0) continue;+ if (ma < 255) {+ effA = Math.round((effA * ma) / 255);+ }}}@@ -719,8 +738,17 @@ export function compositeStrokeToTiles(const docY = destY + sy;let srcOff = (sy * w + srcStartX) << 2;let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;- const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;- const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;+ const selRowValid =+ hasSel &&+ docY >= selBy &&+ docY < selBy + selBh &&+ (!selUsesFullDocMask || (docY >= 0 && docY < selMaskH));+ const selRowOff =+ selRowValid && selMask+ ? selUsesFullDocMask+ ? docY * selMaskW+ : (docY - selBy) * selBw+ : 0;for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {const sa = srcData[srcOff + 3];@@ -730,12 +758,16 @@ export function compositeStrokeToTiles(if (effA === 0) continue;let maskFrac = 1.0;- if (hasSelMask) {+ if (hasSel) {const docX = destX + srcStartX + dx;if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;- const ma = selMask![selRowOff + (docX - selBx)];- if (ma === 0) continue;- if (ma < 255) maskFrac = ma / 255;+ if (selMask) {+ if (selUsesFullDocMask && (docX < 0 || docX >= selMaskW)) continue;+ const ma =+ selMask[selUsesFullDocMask ? selRowOff + docX : selRowOff + (docX - selBx)];+ if (ma === 0) continue;+ if (ma < 255) maskFrac = ma / 255;+ }}const sr = srcData[srcOff];@@ -866,13 +898,39 @@ export function compositeStrokeToTiles(unpack8BitToRGBA(tile.data, tileScratch);for (let sy = srcStartY; sy < srcEndY; sy++) {const tileLocalY = destY + sy - tileDocY;+ const docY = destY + sy;let srcOff = (sy * w + srcStartX) << 2;let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;+ const selRowValid =+ hasSel &&+ docY >= selBy &&+ docY < selBy + selBh &&+ (!selUsesFullDocMask || (docY >= 0 && docY < selMaskH));+ const selRowOff =+ selRowValid && selMask+ ? selUsesFullDocMask+ ? docY * selMaskW+ : (docY - selBy) * selBw+ : 0;for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {const sa = srcData[srcOff + 3];if (sa === 0) continue;- const effA = fullOpacity ? sa : Math.round(sa * opacity);+ let effA = fullOpacity ? sa : Math.round(sa * opacity);if (effA <= 0) continue;+ if (hasSel) {+ const docX = destX + srcStartX + dx;+ if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;+ if (selMask) {+ if (selUsesFullDocMask && (docX < 0 || docX >= selMaskW)) continue;+ const ma =+ selMask[selUsesFullDocMask ? selRowOff + docX : selRowOff + (docX - selBx)];+ if (ma === 0) continue;+ if (ma < 255) {+ effA = Math.round((effA * ma) / 255);+ if (effA <= 0) continue;+ }+ }+ }compositeBrushPixelInto(tileScratch[dstOff],tileScratch[dstOff + 1],diff --git a/src/utils/timelapseEngine.ts b/src/utils/timelapseEngine.tsindex 6ee2ed7..f3e4e5f 100644--- a/src/utils/timelapseEngine.ts+++ b/src/utils/timelapseEngine.ts@@ -7,10 +7,16 @@* videos via MediaRecorder or native FFmpeg (when installed in Tauri).*/-import { CanvasDimensions, LayerItem } from '../types/editor';+import {+ CanvasDimensions,+ InkTimelapseFrameData,+ InkTimelapseFrameMetadata,+ InkTimelapseMetadata,+ LayerItem,+} from '../types/editor';import { ViewportCompositor } from './compositor';import { SparseTileGrid } from './tileEngine';-import { canvasToBlob } from './saveManager';+import { canvasToBlob, TimelapsePersistenceProvider } from './saveManager';export type TimelapseDurationPreset = '15s' | '30s' | '60s' | 'full';export type TimelapseAspectRatio = 'original' | '16:9' | '9:16' | '1:1';@@ -56,6 +62,8 @@ export interface TimelapseExportResult {const DEFAULT_MIN_INTERVAL_MS = 350;const DEFAULT_MAX_CAPTURE_DIM = 1080;const DEFAULT_MAX_RAM_BYTES = 48 * 1024 * 1024; // 48 MB RAM cap per document+const TAURI_BATCH_MAX_FRAMES = 128;+const TAURI_BATCH_MAX_BYTES = 16 * 1024 * 1024; // 16 MB per IPC batchfunction isTauriRuntime(): boolean {return typeof window !== 'undefined' && Boolean((window as unknown as Record<string, unknown>).__TAURI_INTERNALS__);@@ -84,6 +92,32 @@ function packFrameIndices(indices: number[]): Uint8Array {return out;}+/**+ * Packs a batch of timelapse frames into the binary format expected by Rust `timelapse_write_frames_batch`:+ * `[count: u32 LE] ([frameIndex: u32 LE][extCode: u8 (0=webp, 1=jpg)][dataLen: u32 LE][data])*`+ */+export function packTimelapseFrameBatch(+ entries: Array<{ index: number; ext: 'webp' | 'jpg'; bytes: Uint8Array }>+): Uint8Array {+ let total = 4;+ for (const e of entries) {+ total += 9 + e.bytes.byteLength;+ }+ const out = new Uint8Array(total);+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);+ view.setUint32(0, entries.length >>> 0, true);+ let offset = 4;+ for (const e of entries) {+ view.setUint32(offset, e.index >>> 0, true);+ out[offset + 4] = e.ext === 'jpg' ? 1 : 0;+ view.setUint32(offset + 5, e.bytes.byteLength >>> 0, true);+ offset += 9;+ out.set(e.bytes, offset);+ offset += e.bytes.byteLength;+ }+ return out;+}+function toArrayBuffer(raw: ArrayBuffer | Uint8Array | number[]): ArrayBuffer {if (raw instanceof ArrayBuffer) return raw;if (raw instanceof Uint8Array) {@@ -95,6 +129,11 @@ function toArrayBuffer(raw: ArrayBuffer | Uint8Array | number[]): ArrayBuffer {return new Uint8Array(raw).buffer;}+async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {+ const buf = await blob.arrayBuffer();+ return new Uint8Array(buf);+}+/*** Computes even-dimension output video size for the chosen aspect ratio & resolution preset.*/@@ -176,7 +215,9 @@ interface InternalSession {nextIndex: number;lastCaptureAt: number;pendingCapture: boolean;+ pendingCapturePromise: Promise<boolean> | null;memoryBytes: number;+ generation: number;}export class TimelapseRecorderManager {@@ -207,7 +248,9 @@ export class TimelapseRecorderManager {nextIndex: 0,lastCaptureAt: 0,pendingCapture: false,+ pendingCapturePromise: null,memoryBytes: 0,+ generation: 0,};this.sessions.set(documentId, sess);}@@ -276,9 +319,21 @@ export class TimelapseRecorderManager {return this.sessions.get(documentId)?.frames ?? [];}+ public async waitForPendingCapture(documentId: string): Promise<void> {+ const sess = this.sessions.get(documentId);+ if (sess?.pendingCapturePromise) {+ await sess.pendingCapturePromise.catch(() => {});+ }+ }+public async clearSession(documentId: string): Promise<void> {const sess = this.sessions.get(documentId);if (sess) {+ sess.generation++;+ const inFlight = sess.pendingCapturePromise;+ if (inFlight) {+ await inFlight.catch(() => {});+ }sess.frames = [];sess.nextIndex = 0;sess.memoryBytes = 0;@@ -290,6 +345,352 @@ export class TimelapseRecorderManager {this.notify();}+ /**+ * Completely removes a document's time-lapse session from memory and scratch disk+ * (called when closing a document tab or exiting the application).+ */+ public async removeSession(documentId: string): Promise<void> {+ const sess = this.sessions.get(documentId);+ if (sess) {+ sess.generation++;+ const inFlight = sess.pendingCapturePromise;+ this.sessions.delete(documentId);+ if (inFlight) {+ await inFlight.catch(() => {});+ }+ }+ if (isTauriRuntime()) {+ await invokeTauri('timelapse_clear', { sessionId: documentId }).catch(() => {});+ }+ this.notify();+ }++ /**+ * Restores a time-lapse session from a `.ink` archive's metadata and embedded keyframes.+ * Offloads frames to Tauri scratch disk in binary batches when available, or holds Blobs in RAM+ * in browser mode, and automatically resumes recording if `metadata.enabled` was true.+ */+ public async restoreSession(+ documentId: string,+ metadata: InkTimelapseMetadata | null | undefined,+ frames?: InkTimelapseFrameData[] | null,+ onProgress?: (done: number, total: number) => void+ ): Promise<{ enabled: boolean; frameCount: number }> {+ const existing = this.sessions.get(documentId);+ const nextGen = (existing?.generation ?? 0) + 1;+ if (existing) {+ existing.generation = nextGen;+ if (existing.pendingCapturePromise) {+ await existing.pendingCapturePromise.catch(() => {});+ }+ }++ if (isTauriRuntime()) {+ await invokeTauri('timelapse_clear', { sessionId: documentId }).catch(() => {});+ }++ const validFrames = Array.isArray(frames)+ ? frames+ .filter((f) => f && f.bytes && f.bytes.byteLength > 0)+ .slice()+ .sort((a, b) => a.index - b.index)+ : [];++ const enabled = Boolean(metadata?.enabled);+ if (!enabled && validFrames.length === 0) {+ this.sessions.delete(documentId);+ this.notify();+ return { enabled: false, frameCount: 0 };+ }++ const sess: InternalSession = {+ documentId,+ enabled,+ frames: [],+ nextIndex: 0,+ lastCaptureAt: 0,+ pendingCapture: false,+ pendingCapturePromise: null,+ memoryBytes: 0,+ generation: nextGen,+ };+ this.sessions.set(documentId, sess);++ const total = validFrames.length;+ if (total > 0) {+ const normalized = validFrames.map((f, seqIdx) => {+ const mimeType: 'image/webp' | 'image/jpeg' =+ f.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp';+ const ext: 'webp' | 'jpg' = mimeType === 'image/jpeg' ? 'jpg' : 'webp';+ return {+ index: seqIdx,+ timestamp: Number.isFinite(f.timestamp) ? f.timestamp : 0,+ width: Math.max(2, Math.round(f.width) || 2),+ height: Math.max(2, Math.round(f.height) || 2),+ mimeType,+ ext,+ bytes: f.bytes,+ };+ });++ if (isTauriRuntime()) {+ let cursor = 0;+ while (cursor < total) {+ if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {+ return { enabled: false, frameCount: 0 };+ }+ const batch: typeof normalized = [];+ let batchBytes = 0;+ while (+ cursor < total &&+ batch.length < TAURI_BATCH_MAX_FRAMES &&+ (batch.length === 0 || batchBytes + normalized[cursor].bytes.byteLength <= TAURI_BATCH_MAX_BYTES)+ ) {+ batch.push(normalized[cursor]);+ batchBytes += normalized[cursor].bytes.byteLength;+ cursor++;+ }++ let batchOffloaded = false;+ try {+ const packed = packTimelapseFrameBatch(+ batch.map((b) => ({ index: b.index, ext: b.ext, bytes: b.bytes }))+ );+ await invokeTauriRaw<number>('timelapse_write_frames_batch', packed, {+ 'x-session-id': encodeURIComponent(documentId),+ });+ batchOffloaded = true;+ } catch {+ // Fallback to individual frame writes (e.g. partial mocks or older backend)+ batchOffloaded = false;+ }++ if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {+ return { enabled: false, frameCount: 0 };+ }++ for (const item of batch) {+ let offloaded = batchOffloaded;+ if (!offloaded) {+ try {+ await invokeTauriRaw('timelapse_write_frame', item.bytes, {+ 'x-session-id': encodeURIComponent(documentId),+ 'x-frame-index': String(item.index),+ 'x-ext': item.ext,+ });+ offloaded = true;+ } catch {+ offloaded = false;+ }+ }+ const blob = offloaded+ ? undefined+ : new Blob([item.bytes as BlobPart], { type: item.mimeType });+ if (blob) {+ sess.memoryBytes += blob.size;+ }+ sess.frames.push({+ id: `tl-${documentId}-${item.index}`,+ index: item.index,+ timestamp: item.timestamp,+ width: item.width,+ height: item.height,+ mimeType: item.mimeType,+ bytes: item.bytes.byteLength,+ offloadedToDisk: offloaded,+ blob,+ });+ }++ onProgress?.(cursor, total);+ }+ } else {+ for (let i = 0; i < total; i++) {+ const item = normalized[i];+ const blob = new Blob([item.bytes as BlobPart], { type: item.mimeType });+ sess.memoryBytes += blob.size;+ sess.frames.push({+ id: `tl-${documentId}-${item.index}`,+ index: item.index,+ timestamp: item.timestamp,+ width: item.width,+ height: item.height,+ mimeType: item.mimeType,+ bytes: blob.size,+ offloadedToDisk: false,+ blob,+ });+ }+ onProgress?.(total, total);+ }++ sess.nextIndex = sess.frames.length;+ }++ this.notify();+ return { enabled: sess.enabled, frameCount: sess.frames.length };+ }++ /**+ * Restores a time-lapse session after an unexpected crash using the WAL recovery manifest+ * and any keyframes still present on the Tauri scratch disk for that session ID.+ */+ public async restoreFromScratchDisk(+ documentId: string,+ metadata: InkTimelapseMetadata | null | undefined,+ fallbackDims?: CanvasDimensions+ ): Promise<{ enabled: boolean; frameCount: number }> {+ if (!metadata) {+ return { enabled: false, frameCount: 0 };+ }+ const existing = this.sessions.get(documentId);+ const nextGen = (existing?.generation ?? 0) + 1;+ if (existing) {+ existing.generation = nextGen;+ if (existing.pendingCapturePromise) {+ await existing.pendingCapturePromise.catch(() => {});+ }+ }++ const enabled = Boolean(metadata.enabled);+ const sess: InternalSession = {+ documentId,+ enabled,+ frames: [],+ nextIndex: 0,+ lastCaptureAt: 0,+ pendingCapture: false,+ pendingCapturePromise: null,+ memoryBytes: 0,+ generation: nextGen,+ };+ this.sessions.set(documentId, sess);++ const metaByIndex = new Map<number, InkTimelapseFrameMetadata>();+ if (Array.isArray(metadata.frames)) {+ for (const fm of metadata.frames) {+ if (fm && Number.isSafeInteger(fm.index) && fm.index >= 0) {+ metaByIndex.set(fm.index, fm);+ }+ }+ }++ const fallbackW = Math.max(2, Math.round(fallbackDims?.width || 1080));+ const fallbackH = Math.max(2, Math.round(fallbackDims?.height || 1080));++ if (isTauriRuntime()) {+ try {+ const diskList = await invokeTauri<Array<[number, string]>>('timelapse_list_frames', {+ sessionId: documentId,+ });+ if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {+ return { enabled: false, frameCount: 0 };+ }+ let maxIdx = -1;+ for (const [idx, ext] of diskList || []) {+ const fm = metaByIndex.get(idx);+ const mimeType: 'image/webp' | 'image/jpeg' =+ ext === 'jpg' || ext === 'jpeg' || fm?.mimeType === 'image/jpeg'+ ? 'image/jpeg'+ : 'image/webp';+ sess.frames.push({+ id: `tl-${documentId}-${idx}`,+ index: idx,+ timestamp: fm?.timestamp ?? 0,+ width: fm?.width ?? fallbackW,+ height: fm?.height ?? fallbackH,+ mimeType,+ bytes: fm?.bytes ?? 0,+ offloadedToDisk: true,+ });+ if (idx > maxIdx) maxIdx = idx;+ }+ sess.nextIndex = Math.max(maxIdx + 1, metadata.nextIndex ?? 0);+ } catch {+ sess.nextIndex = metadata.nextIndex ?? 0;+ }+ }++ if (!sess.enabled && sess.frames.length === 0) {+ this.sessions.delete(documentId);+ }++ this.notify();+ return { enabled: sess.enabled, frameCount: sess.frames.length };+ }++ /**+ * Returns lightweight JSON metadata for crash-recovery WAL manifests (no binary frame data).+ */+ public getRecoveryMetadata(documentId: string | null): InkTimelapseMetadata | null {+ if (!documentId) return null;+ const sess = this.sessions.get(documentId);+ if (!sess || (!sess.enabled && sess.frames.length === 0)) return null;+ return {+ enabled: sess.enabled,+ frameCount: sess.frames.length,+ nextIndex: sess.nextIndex,+ ...(sess.frames.length > 0+ ? {+ frames: sess.frames.map((f) => ({+ index: f.index,+ path: `timelapse/frame_${String(f.index).padStart(6, '0')}.${+ f.mimeType === 'image/jpeg' ? 'jpg' : 'webp'+ }`,+ timestamp: f.timestamp,+ width: f.width,+ height: f.height,+ mimeType: f.mimeType,+ bytes: f.bytes,+ })),+ }+ : {}),+ };+ }++ /**+ * Builds a lazy persistence provider used by `serializeInkProject` to stream+ * keyframes into a `.ink` archive only when saving in `.ink` format.+ */+ public createPersistenceProvider(documentId: string | null): TimelapsePersistenceProvider | null {+ if (!documentId) return null;+ const frameLookup = new Map<number, TimelapseFrameEntry>();++ return {+ waitForPendingCapture: () => this.waitForPendingCapture(documentId),+ getSessionSnapshot: () => {+ frameLookup.clear();+ const sess = this.sessions.get(documentId);+ if (!sess || (!sess.enabled && sess.frames.length === 0)) {+ return null;+ }+ const frames = sess.frames.map((f) => {+ frameLookup.set(f.index, f);+ return {+ index: f.index,+ timestamp: f.timestamp,+ width: f.width,+ height: f.height,+ mimeType: f.mimeType,+ bytes: f.bytes,+ };+ });+ return {+ enabled: sess.enabled,+ nextIndex: sess.nextIndex,+ frames,+ };+ },+ readFrameBytes: async (frameIndex: number) => {+ const entry =+ frameLookup.get(frameIndex) ??+ this.sessions.get(documentId)?.frames.find((f) => f.index === frameIndex);+ if (!entry) return null;+ return this.loadFrameBytes(documentId, entry);+ },+ };+ }+/*** Captures a throttled low/medium-res WebP/JPEG snapshot of the composited document.*/@@ -311,107 +712,136 @@ export class TimelapseRecorderManager {return false;}+ const gen = sess.generation;sess.pendingCapture = true;sess.lastCaptureAt = now;- try {- const scale = Math.min(- 1,- this.maxCaptureDim / Math.max(dimensions.width, dimensions.height)- );- const outW = Math.max(2, Math.round((dimensions.width * scale) / 2) * 2);- const outH = Math.max(2, Math.round((dimensions.height * scale) / 2) * 2);-- if (!this.captureCanvas) {- this.captureCanvas = document.createElement('canvas');- }- this.captureCanvas.width = outW;- this.captureCanvas.height = outH;-- ViewportCompositor.renderLowResPreview(- this.captureCanvas,- layers,- dimensions,- tileGrid,- { showCheckerboard: false }- );-- let mimeType: 'image/webp' | 'image/jpeg' = 'image/webp';- let blob: Blob;+ let run: Promise<boolean> | null = null;+ run = (async (): Promise<boolean> => {try {- blob = await canvasToBlob(this.captureCanvas, 'image/webp', 0.82);- if (blob.type !== 'image/webp') {- mimeType = 'image/jpeg';+ const scale = Math.min(+ 1,+ this.maxCaptureDim / Math.max(dimensions.width, dimensions.height)+ );+ const outW = Math.max(2, Math.round((dimensions.width * scale) / 2) * 2);+ const outH = Math.max(2, Math.round((dimensions.height * scale) / 2) * 2);++ if (!this.captureCanvas) {+ this.captureCanvas = document.createElement('canvas');}- } catch {- mimeType = 'image/jpeg';- blob = await canvasToBlob(this.captureCanvas, 'image/jpeg', 0.82);- }+ this.captureCanvas.width = outW;+ this.captureCanvas.height = outH;- const idx = sess.nextIndex++;- const entry: TimelapseFrameEntry = {- id: `tl-${documentId}-${idx}`,- index: idx,- timestamp: now,- width: outW,- height: outH,- mimeType,- bytes: blob.size,- offloadedToDisk: false,- blob,- };+ ViewportCompositor.renderLowResPreview(+ this.captureCanvas,+ layers,+ dimensions,+ tileGrid,+ { showCheckerboard: false }+ );- // Offload to Tauri scratch disk when available to keep RAM usage near zero- if (isTauriRuntime()) {+ let mimeType: 'image/webp' | 'image/jpeg' = 'image/webp';+ let blob: Blob;try {- const buf = await blob.arrayBuffer();- await invokeTauriRaw('timelapse_write_frame', buf, {- 'x-session-id': encodeURIComponent(documentId),- 'x-frame-index': String(idx),- 'x-ext': mimeType === 'image/webp' ? 'webp' : 'jpg',- });- entry.offloadedToDisk = true;- entry.blob = undefined;+ blob = await canvasToBlob(this.captureCanvas, 'image/webp', 0.82);+ if (blob.type !== 'image/webp') {+ mimeType = 'image/jpeg';+ }} catch {+ mimeType = 'image/jpeg';+ blob = await canvasToBlob(this.captureCanvas, 'image/jpeg', 0.82);+ }++ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }++ const idx = sess.nextIndex++;+ const entry: TimelapseFrameEntry = {+ id: `tl-${documentId}-${idx}`,+ index: idx,+ timestamp: now,+ width: outW,+ height: outH,+ mimeType,+ bytes: blob.size,+ offloadedToDisk: false,+ blob,+ };++ // Offload to Tauri scratch disk when available to keep RAM usage near zero+ if (isTauriRuntime()) {+ try {+ const buf = await blob.arrayBuffer();+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }+ await invokeTauriRaw('timelapse_write_frame', buf, {+ 'x-session-id': encodeURIComponent(documentId),+ 'x-frame-index': String(idx),+ 'x-ext': mimeType === 'image/webp' ? 'webp' : 'jpg',+ });+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }+ entry.offloadedToDisk = true;+ entry.blob = undefined;+ } catch {+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }+ sess.memoryBytes += entry.bytes;+ }+ } else {sess.memoryBytes += entry.bytes;}- } else {- sess.memoryBytes += entry.bytes;- }- sess.frames.push(entry);-- // Browser memory throttling: thin alternating middle frames if RAM cap exceeded- if (!isTauriRuntime() && sess.memoryBytes > this.maxRamBytes && sess.frames.length > 8) {- const thinned: TimelapseFrameEntry[] = [];- let bytes = 0;- for (let i = 0; i < sess.frames.length; i++) {- const f = sess.frames[i];- const keep = i === 0 || i === sess.frames.length - 1 || i % 2 === 0;- if (keep) {- thinned.push(f);- bytes += f.offloadedToDisk ? 0 : f.bytes;+ sess.frames.push(entry);++ // Browser memory throttling: thin alternating middle frames if RAM cap exceeded+ if (!isTauriRuntime() && sess.memoryBytes > this.maxRamBytes && sess.frames.length > 8) {+ const thinned: TimelapseFrameEntry[] = [];+ let bytes = 0;+ for (let i = 0; i < sess.frames.length; i++) {+ const f = sess.frames[i];+ const keep = i === 0 || i === sess.frames.length - 1 || i % 2 === 0;+ if (keep) {+ thinned.push(f);+ bytes += f.offloadedToDisk ? 0 : f.bytes;+ }}+ sess.frames = thinned;+ sess.memoryBytes = bytes;+ }++ this.notify();+ return true;+ } finally {+ sess.pendingCapture = false;+ if (sess.pendingCapturePromise === run) {+ sess.pendingCapturePromise = null;}- sess.frames = thinned;- sess.memoryBytes = bytes;}+ })();- this.notify();- return true;- } finally {- sess.pendingCapture = false;- }+ sess.pendingCapturePromise = run;+ return run;}/**- * Resolves a frame entry into a Blob (reading back from Tauri scratch disk if offloaded).+ * Resolves a frame entry into raw binary bytes (reading back from Tauri scratch disk if offloaded).*/- public async loadFrameBlob(+ public async loadFrameBytes(documentId: string,frame: TimelapseFrameEntry- ): Promise<Blob | null> {- if (frame.blob) return frame.blob;+ ): Promise<Uint8Array | null> {+ if (frame.blob) {+ try {+ return await blobToUint8Array(frame.blob);+ } catch {+ return null;+ }+ }if (frame.offloadedToDisk && isTauriRuntime()) {try {const raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>(@@ -423,7 +853,7 @@ export class TimelapseRecorderManager {'x-ext': frame.mimeType === 'image/webp' ? 'webp' : 'jpg',});- return new Blob([toArrayBuffer(raw)], { type: frame.mimeType });+ return new Uint8Array(toArrayBuffer(raw));} catch {return null;}@@ -431,6 +861,19 @@ export class TimelapseRecorderManager {return null;}+ /**+ * Resolves a frame entry into a Blob (reading back from Tauri scratch disk if offloaded).+ */+ public async loadFrameBlob(+ documentId: string,+ frame: TimelapseFrameEntry+ ): Promise<Blob | null> {+ if (frame.blob) return frame.blob;+ const bytes = await this.loadFrameBytes(documentId, frame);+ if (!bytes) return null;+ return new Blob([bytes as BlobPart], { type: frame.mimeType });+ }+public async checkFfmpegAvailable(): Promise<boolean> {if (!isTauriRuntime()) return false;try {diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.tsindex 9b80478..142dfa9 100644--- a/src/utils/transformEngine.ts+++ b/src/utils/transformEngine.ts@@ -675,6 +675,37 @@ class WebGlMeshWarpRenderer {return vertexCount;}+ private fillTriangleVertices(+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ triOrder?: Uint32Array+ ): number {+ const triCount = (triangles.length / 3) | 0;+ const vertexCount = triCount * 3;+ const neededFloats = vertexCount * 4;+ if (this.vertexData.length < neededFloats) {+ this.vertexData = new Float32Array(neededFloats);+ }++ const buf = this.vertexData;+ let offset = 0;+ for (let k = 0; k < triCount; k++) {+ const ti = triOrder ? triOrder[k] : k;+ const base = ti * 3;+ const i0 = triangles[base];+ const i1 = triangles[base + 1];+ const i2 = triangles[base + 2];++ buf[offset++] = deformedX[i0]; buf[offset++] = deformedY[i0]; buf[offset++] = uvX[i0]; buf[offset++] = uvY[i0];+ buf[offset++] = deformedX[i1]; buf[offset++] = deformedY[i1]; buf[offset++] = uvX[i1]; buf[offset++] = uvY[i1];+ buf[offset++] = deformedX[i2]; buf[offset++] = deformedY[i2]; buf[offset++] = uvX[i2]; buf[offset++] = uvY[i2];+ }+ return vertexCount;+ }+private ensureFbo(gl: WebGL2RenderingContext, w: number, h: number): boolean {if (!this.fbo || !this.fboTexture) return false;if (this.fboW === w && this.fboH === h) {@@ -923,6 +954,274 @@ class WebGlMeshWarpRenderer {gl.bindFramebuffer(gl.FRAMEBUFFER, null);}}++ /**+ * Renders an arbitrary indexed triangle mesh (Puppet Warp / Cage Transform) to a 2D preview+ * context using WebGL2 Anti-Ringing Lanczos-3 (or WebGL1 bicubic).+ */+ renderTriangles(+ ctx: CanvasRenderingContext2D,+ sourceCanvas: HTMLCanvasElement,+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ triOrder?: Uint32Array+ ): boolean {+ if (!this.ready || !this.gl || !this.canvas || !this.program || !this.vertexBuffer || !this.texture) {+ return false;+ }+ const gl = this.gl;+ if (gl.isContextLost()) {+ this.ready = false;+ return false;+ }++ const sw = sourceCanvas.width;+ const sh = sourceCanvas.height;+ if (sw <= 0 || sh <= 0 || sw > this.maxDim || sh > this.maxDim || triangles.length < 3) {+ return false;+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (let i = 0; i < deformedX.length; i++) {+ const px = deformedX[i];+ const py = deformedY[i];+ if (!Number.isFinite(px) || !Number.isFinite(py)) return false;+ if (px < minX) minX = px;+ if (py < minY) minY = py;+ if (px > maxX) maxX = px;+ if (py > maxY) maxY = py;+ }++ let originX = Math.floor(minX) - 1;+ let originY = Math.floor(minY) - 1;+ let endX = Math.ceil(maxX) + 1;+ let endY = Math.ceil(maxY) + 1;++ if (+ ctx.canvas &&+ ctx.canvas.width > 0 &&+ ctx.canvas.height > 0 &&+ typeof ctx.getTransform === 'function'+ ) {+ const m = ctx.getTransform();+ if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1) {+ originX = Math.max(Math.floor(-m.e), originX);+ originY = Math.max(Math.floor(-m.f), originY);+ endX = Math.min(Math.ceil(ctx.canvas.width - m.e), endX);+ endY = Math.min(Math.ceil(ctx.canvas.height - m.f), endY);+ }+ }++ const outW = endX - originX;+ const outH = endY - originY;+ if (outW <= 0 || outH <= 0) return true;+ if (outW > this.maxDim || outH > this.maxDim) return false;++ const vertexCount = this.fillTriangleVertices(+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ triOrder+ );+ const neededFloats = vertexCount * 4;++ if (this.canvas.width !== outW) this.canvas.width = outW;+ if (this.canvas.height !== outH) this.canvas.height = outH;++ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.viewport(0, 0, outW, outH);+ gl.useProgram(this.program);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, !this.isWebGl2);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);++ gl.uniform1i(this.texLoc, 0);+ gl.uniform2f(this.originLoc, originX, originY);+ gl.uniform2f(this.sizeLoc, outW, outH);+ gl.uniform2f(this.texSizeLoc, sw, sh);+ if (this.flipYLoc) gl.uniform1f(this.flipYLoc, -1.0);+ if (this.outputStraightLoc) gl.uniform1i(this.outputStraightLoc, 0);++ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, this.vertexData.subarray(0, neededFloats), gl.STREAM_DRAW);+ gl.enableVertexAttribArray(this.posLoc);+ gl.vertexAttribPointer(this.posLoc, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(this.uvLoc);+ gl.vertexAttribPointer(this.uvLoc, 2, gl.FLOAT, false, 16, 8);++ gl.disable(gl.CULL_FACE);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);++ ctx.drawImage(this.canvas, originX, originY);+ return true;+ }++ /**+ * Renders an arbitrary indexed triangle mesh directly from straight-alpha pixels into+ * straight-alpha RGBA chunks via WebGL2 FBO + readPixels (Anti-Ringing Lanczos-3).+ */+ renderTrianglesToChunks(+ source: PixelBuffer,+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ destRect: DirtyRect,+ chunkSize: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void,+ triOrder?: Uint32Array+ ): boolean {+ if (+ !this.ready ||+ !this.isWebGl2 ||+ !this.gl ||+ !this.program ||+ !this.vertexBuffer ||+ !this.texture ||+ !this.fbo ||+ !this.fboTexture+ ) {+ return false;+ }+ const gl = this.gl as WebGL2RenderingContext;+ if (gl.isContextLost()) {+ this.ready = false;+ return false;+ }++ const sw = source.width;+ const sh = source.height;+ if (+ sw <= 0 ||+ sh <= 0 ||+ sw > this.maxDim ||+ sh > this.maxDim ||+ chunkSize > this.maxDim ||+ triangles.length < 3+ ) {+ return false;+ }++ for (let i = 0; i < deformedX.length; i++) {+ if (!Number.isFinite(deformedX[i]) || !Number.isFinite(deformedY[i])) return false;+ }++ const vertexCount = this.fillTriangleVertices(+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ triOrder+ );+ const neededFloats = vertexCount * 4;+ const srcBytes =+ source.data instanceof Uint8Array+ ? source.data+ : new Uint8Array(source.data.buffer, source.data.byteOffset, source.data.byteLength);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.texture);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, sw, sh, 0, gl.RGBA, gl.UNSIGNED_BYTE, srcBytes);++ const blendOverlaps = Boolean(triOrder);++ gl.useProgram(this.program);+ gl.uniform1i(this.texLoc, 0);+ gl.uniform2f(this.texSizeLoc, sw, sh);+ if (this.flipYLoc) gl.uniform1f(this.flipYLoc, 1.0);+ if (this.outputStraightLoc) gl.uniform1i(this.outputStraightLoc, blendOverlaps ? 0 : 1);++ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, this.vertexData.subarray(0, neededFloats), gl.STREAM_DRAW);+ gl.enableVertexAttribArray(this.posLoc);+ gl.vertexAttribPointer(this.posLoc, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(this.uvLoc);+ gl.vertexAttribPointer(this.uvLoc, 2, gl.FLOAT, false, 16, 8);++ gl.disable(gl.CULL_FACE);+ if (blendOverlaps) {+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ } else {+ gl.disable(gl.BLEND);+ }++ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;++ try {+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ if (!this.ensureFbo(gl, cw, ch)) return false;++ gl.viewport(0, 0, cw, ch);+ gl.uniform2f(this.originLoc, cx, cy);+ gl.uniform2f(this.sizeLoc, cw, ch);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.texture);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);++ const rawBytes = new Uint8Array(cw * ch * 4);+ gl.readPixels(0, 0, cw, ch, gl.RGBA, gl.UNSIGNED_BYTE, rawBytes);+ const clamped = new Uint8ClampedArray(+ rawBytes.buffer,+ rawBytes.byteOffset,+ rawBytes.byteLength+ );+ if (blendOverlaps) {+ // Un-premultiply straight alpha for tile-grid storage+ for (let i = 0; i < clamped.length; i += 4) {+ const a = clamped[i + 3];+ if (a > 0 && a < 255) {+ const invA = 255 / a;+ clamped[i] = Math.min(255, Math.round(clamped[i] * invA));+ clamped[i + 1] = Math.min(255, Math.round(clamped[i + 1] * invA));+ clamped[i + 2] = Math.min(255, Math.round(clamped[i + 2] * invA));+ }+ }+ }+ onChunk(clamped, cx, cy, cw, ch);+ }+ }+ return true;+ } catch {+ return false;+ } finally {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ }+ }}function renderDeformedGrid(@@ -1028,6 +1327,66 @@ export function renderMeshWarp(renderDeformedGrid(ctx, sourceCanvas, grid, totalRows, totalCols);}+/**+ * Renders sourceCanvas deformed via an arbitrary indexed triangle mesh (Puppet Warp / Cage Transform).+ * Uses WebGL2 Anti-Ringing Lanczos-3 when available, with Canvas 2D affine triangle fallback.+ */+export function renderDeformedTriangles(+ ctx: CanvasRenderingContext2D,+ sourceCanvas: HTMLCanvasElement,+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ triOrder?: Uint32Array+): void {+ const sw = sourceCanvas.width;+ const sh = sourceCanvas.height;+ if (sw <= 0 || sh <= 0 || triangles.length < 3) return;++ if (+ WebGlMeshWarpRenderer.getInstance().renderTriangles(+ ctx,+ sourceCanvas,+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ triOrder+ )+ ) {+ return;+ }++ const triCount = (triangles.length / 3) | 0;+ for (let k = 0; k < triCount; k++) {+ const ti = triOrder ? triOrder[k] : k;+ const base = ti * 3;+ const i0 = triangles[base];+ const i1 = triangles[base + 1];+ const i2 = triangles[base + 2];++ drawAffineTriangle(+ ctx,+ sourceCanvas,+ uvX[i0] * sw,+ uvY[i0] * sh,+ uvX[i1] * sw,+ uvY[i1] * sh,+ uvX[i2] * sw,+ uvY[i2] * sh,+ deformedX[i0],+ deformedY[i0],+ deformedX[i1],+ deformedY[i1],+ deformedX[i2],+ deformedY[i2]+ );+ }+}+/*** Checks if a Catmull-Rom mesh lattice is an exact unmodified integer translation of (sw x sh).*/@@ -1371,17 +1730,315 @@ export function processMeshWarpTransformChunks(}/**- * Creates default 4 perspective corner pins from bounds.- * Order: [TL, TR, BR, BL]+ * High-precision CPU straight-alpha triangle rasterizer using float-premultiplied+ * Anti-Ringing Lanczos-3 with per-triangle analytical Jacobian footprint scaling.+ * Preserves razor-sharp lineart when WebGL2 is unavailable (e.g. software/headless/tests).+ */+export function rasterizeTrianglesCpuLanczos3(+ source: PixelBuffer,+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ chunkX: number,+ chunkY: number,+ chunkW: number,+ chunkH: number,+ triOrder?: Uint32Array+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(chunkW * chunkH * 4);+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || chunkW <= 0 || chunkH <= 0 || triangles.length < 3) return out;++ const srcData = source.data;+ const wxBuf = new Float32Array(20);+ const wyBuf = new Float32Array(20);+ const blendOverlaps = Boolean(triOrder);+ const triCount = (triangles.length / 3) | 0;++ for (let k = 0; k < triCount; k++) {+ const ti = triOrder ? triOrder[k] : k;+ const base = ti * 3;+ const i0 = triangles[base];+ const i1 = triangles[base + 1];+ const i2 = triangles[base + 2];++ const x0 = deformedX[i0] - chunkX;+ const y0 = deformedY[i0] - chunkY;+ const x1 = deformedX[i1] - chunkX;+ const y1 = deformedY[i1] - chunkY;+ const x2 = deformedX[i2] - chunkX;+ const y2 = deformedY[i2] - chunkY;++ const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2)));+ const maxX = Math.min(chunkW - 1, Math.ceil(Math.max(x0, x1, x2)));+ const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2)));+ const maxY = Math.min(chunkH - 1, Math.ceil(Math.max(y0, y1, y2)));+ if (maxX < minX || maxY < minY) continue;++ const det = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);+ if (Math.abs(det) < 1e-6) continue;+ const invDet = 1 / det;++ const u0 = uvX[i0]; const v0 = uvY[i0];+ const u1 = uvX[i1]; const v1 = uvY[i1];+ const u2 = uvX[i2]; const v2 = uvY[i2];++ // Constant per-triangle analytical Jacobian d(sx, sy)/d(px, py)+ const dw0_dx = (y1 - y2) * invDet;+ const dw0_dy = (x2 - x1) * invDet;+ const dw1_dx = (y2 - y0) * invDet;+ const dw1_dy = (x0 - x2) * invDet;+ const dw2_dx = -(dw0_dx + dw1_dx);+ const dw2_dy = -(dw0_dy + dw1_dy);++ const dsx_dx = (u0 * dw0_dx + u1 * dw1_dx + u2 * dw2_dx) * sw;+ const dsx_dy = (u0 * dw0_dy + u1 * dw1_dy + u2 * dw2_dy) * sw;+ const dsy_dx = (v0 * dw0_dx + v1 * dw1_dx + v2 * dw2_dx) * sh;+ const dsy_dy = (v0 * dw0_dy + v1 * dw1_dy + v2 * dw2_dy) * sh;++ const footX = Math.hypot(dsx_dx, dsx_dy);+ const footY = Math.hypot(dsy_dx, dsy_dy);+ const filterScaleX = Math.min(3.0, Math.max(1.0, footX));+ const filterScaleY = Math.min(3.0, Math.max(1.0, footY));+ const invFX = 1.0 / filterScaleX;+ const invFY = 1.0 / filterScaleY;+ const supportX = 3.0 * filterScaleX;+ const supportY = 3.0 * filterScaleY;+ const applyAntiRing = filterScaleX <= 1.25 && filterScaleY <= 1.25;++ for (let py = minY; py <= maxY; py++) {+ const cy = py + 0.5;+ const rowBase = py * chunkW;+ for (let px = minX; px <= maxX; px++) {+ const cx = px + 0.5;+ const w0 = ((x1 - cx) * (y2 - cy) - (y1 - cy) * (x2 - cx)) * invDet;+ if (w0 < -1e-4) continue;+ const w1 = ((x2 - cx) * (y0 - cy) - (y2 - cy) * (x0 - cx)) * invDet;+ if (w1 < -1e-4) continue;+ const w2 = 1 - w0 - w1;+ if (w2 < -1e-4) continue;++ const u = w0 * u0 + w1 * u1 + w2 * u2;+ const v = w0 * v0 + w1 * v1 + w2 * v2;+ const sx = u * sw - 0.5;+ const sy = v * sh - 0.5;+ if (+ sx < -supportX ||+ sx > sw - 1 + supportX ||+ sy < -supportY ||+ sy > sh - 1 + supportY+ ) {+ continue;+ }++ const xStart = Math.ceil(sx - supportX);+ const xEnd = Math.floor(sx + supportX);+ const yStart = Math.ceil(sy - supportY);+ const yEnd = Math.floor(sy + supportY);+ const countX = Math.min(20, Math.max(0, xEnd - xStart + 1));+ const countY = Math.min(20, Math.max(0, yEnd - yStart + 1));+ if (countX <= 0 || countY <= 0) continue;++ let sumWx = 0;+ for (let i = 0; i < countX; i++) {+ const w = lanczos3Weight((xStart + i - sx) * invFX);+ wxBuf[i] = w;+ sumWx += w;+ }+ if (Math.abs(sumWx) < 1e-6) continue;+ const invSumWx = 1.0 / sumWx;+ for (let i = 0; i < countX; i++) wxBuf[i] *= invSumWx;++ let sumWy = 0;+ for (let j = 0; j < countY; j++) {+ const w = lanczos3Weight((yStart + j - sy) * invFY);+ wyBuf[j] = w;+ sumWy += w;+ }+ if (Math.abs(sumWy) < 1e-6) continue;+ const invSumWy = 1.0 / sumWy;+ for (let j = 0; j < countY; j++) wyBuf[j] *= invSumWy;++ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;+ for (let j = 0; j < countY; j++) {+ const iy = yStart + j;+ if (iy < 0 || iy >= sh) continue;+ const wy = wyBuf[j];+ if (wy === 0) continue;+ const sRow = iy * sw;+ let rR = 0;+ let rG = 0;+ let rB = 0;+ let rA = 0;+ for (let i = 0; i < countX; i++) {+ const ix = xStart + i;+ if (ix < 0 || ix >= sw) continue;+ const off = (sRow + ix) << 2;+ const a = srcData[off + 3];+ if (a === 0) continue;+ const wa = wxBuf[i] * (a * (1 / 255));+ rR += srcData[off] * wa;+ rG += srcData[off + 1] * wa;+ rB += srcData[off + 2] * wa;+ rA += wa;+ }+ accR += rR * wy;+ accG += rG * wy;+ accB += rB * wy;+ accA += rA * wy;+ }++ if (applyAntiRing) {+ const bx = Math.floor(sx);+ const by = Math.floor(sy);+ let loR = Infinity; let hiR = -Infinity;+ let loG = Infinity; let hiG = -Infinity;+ let loB = Infinity; let hiB = -Infinity;+ let loA = Infinity; let hiA = -Infinity;+ for (let ny = by; ny <= by + 1; ny++) {+ const yOk = ny >= 0 && ny < sh;+ const sRow = ny * sw;+ for (let nx = bx; nx <= bx + 1; nx++) {+ let nr = 0; let ng = 0; let nb = 0; let na = 0;+ if (yOk && nx >= 0 && nx < sw) {+ const o = (sRow + nx) << 2;+ na = srcData[o + 3] * (1 / 255);+ nr = srcData[o] * na;+ ng = srcData[o + 1] * na;+ nb = srcData[o + 2] * na;+ }+ if (nr < loR) loR = nr; if (nr > hiR) hiR = nr;+ if (ng < loG) loG = ng; if (ng > hiG) hiG = ng;+ if (nb < loB) loB = nb; if (nb > hiB) hiB = nb;+ if (na < loA) loA = na; if (na > hiA) hiA = na;+ }+ }+ if (accR < loR) accR = loR; else if (accR > hiR) accR = hiR;+ if (accG < loG) accG = loG; else if (accG > hiG) accG = hiG;+ if (accB < loB) accB = loB; else if (accB > hiB) accB = hiB;+ if (accA < loA) accA = loA; else if (accA > hiA) accA = hiA;+ }++ if (accA <= 1e-4) continue;+ if (accA > 1.0) accA = 1.0;+ const maxRgb = accA * 255.0;+ if (accR < 0) accR = 0; else if (accR > maxRgb) accR = maxRgb;+ if (accG < 0) accG = 0; else if (accG > maxRgb) accG = maxRgb;+ if (accB < 0) accB = 0; else if (accB > maxRgb) accB = maxRgb;++ const dstOff = (rowBase + px) << 2;+ if (blendOverlaps && out[dstOff + 3] > 0) {+ const dA = out[dstOff + 3] * (1 / 255);+ const invSA = 1 - accA;+ const outA = accA + dA * invSA;+ if (outA > 1e-4) {+ const invOutA = 1 / outA;+ out[dstOff] = Math.min(255, Math.max(0, Math.round((accR + out[dstOff] * dA * invSA) * invOutA)));+ out[dstOff + 1] = Math.min(255, Math.max(0, Math.round((accG + out[dstOff + 1] * dA * invSA) * invOutA)));+ out[dstOff + 2] = Math.min(255, Math.max(0, Math.round((accB + out[dstOff + 2] * dA * invSA) * invOutA)));+ out[dstOff + 3] = Math.min(255, Math.max(0, Math.round(outA * 255.0)));+ }+ } else {+ const invA = 1.0 / accA;+ out[dstOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dstOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dstOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dstOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255.0)));+ }+ }+ }+ }++ return out;+}++/**+ * High-precision chunked indexed triangle mesh commit pipeline (Puppet Warp & Cage Transform):+ * WebGL2 straight-alpha Anti-Ringing Lanczos-3 FBO -> exact CPU Anti-Ringing Lanczos-3 fallback.+ */+export function processDeformedTrianglesTransformChunks(+ source: PixelBuffer,+ deformedX: Float32Array,+ deformedY: Float32Array,+ uvX: Float32Array,+ uvY: Float32Array,+ triangles: Uint32Array,+ destRect: DirtyRect,+ chunkSize: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void,+ triOrder?: Uint32Array+): boolean {+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || triangles.length < 3) return false;++ if (+ WebGlMeshWarpRenderer.getInstance().renderTrianglesToChunks(+ source,+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ destRect,+ chunkSize,+ onChunk,+ triOrder+ )+ ) {+ return true;+ }++ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ onChunk(+ rasterizeTrianglesCpuLanczos3(+ source,+ deformedX,+ deformedY,+ uvX,+ uvY,+ triangles,+ cx,+ cy,+ cw,+ ch,+ triOrder+ ),+ cx,+ cy,+ cw,+ ch+ );+ }+ }+ return true;+}++/**+ * Creates default 4 perspective corner pins from bounds (including rotation and H/V flips).+ * Order: [TL, TR, BR, BL] corresponding to source UVs [(0,0), (1,0), (1,1), (0,1)].*/export function createDefaultPerspectiveQuad(x: number,y: number,width: number,height: number,- rotation = 0+ rotation = 0,+ flipH = false,+ flipV = false): [Point2D, Point2D, Point2D, Point2D] {- if (rotation === 0) {+ if (rotation === 0 && !flipH && !flipV) {return [{ x, y },{ x: x + width, y },@@ -1392,24 +2049,28 @@ export function createDefaultPerspectiveQuad(const cx = x + width / 2;const cy = y + height / 2;+ const hw = width / 2;+ const hh = height / 2;+ const sx = flipH ? -1 : 1;+ const sy = flipV ? -1 : 1;const rad = (rotation * Math.PI) / 180;const cos = Math.cos(rad);const sin = Math.sin(rad);- const rotate = (px: number, py: number): Point2D => {- const rx = px - cx;- const ry = py - cy;+ const mapCorner = (lx: number, ly: number): Point2D => {+ const fx = lx * sx;+ const fy = ly * sy;return {- x: cx + rx * cos - ry * sin,- y: cy + rx * sin + ry * cos,+ x: cx + fx * cos - fy * sin,+ y: cy + fx * sin + fy * cos,};};return [- rotate(x, y),- rotate(x + width, y),- rotate(x + width, y + height),- rotate(x, y + height),+ mapCorner(-hw, -hh),+ mapCorner(hw, -hh),+ mapCorner(hw, hh),+ mapCorner(-hw, hh),];}diff --git a/src/utils/transformModeTransition.ts b/src/utils/transformModeTransition.tsnew file mode 100644index 0000000..681c46c--- /dev/null+++ b/src/utils/transformModeTransition.ts@@ -0,0 +1,1391 @@+import { DirtyRect, Point2D, TransformMode, TransformSession } from '../types/editor';+import { get2DContext } from './canvasUtils';+import { releaseTemporaryCanvas } from './tileEngine';+import {+ computeMeshSubdivisions,+ createDefaultMeshPoints,+ createDefaultPerspectiveQuad,+ evaluateHomography,+ evaluateMeshSurface,+ extractCanvasPixelBuffer,+ getMeshSurfaceBounds,+ getPointsBounds,+ processDeformedTrianglesTransformChunks,+ processMeshWarpTransformChunks,+ processPerspectiveTransformChunks,+ solveUnitSquareToQuad,+ type PixelBuffer,+} from './transformEngine';+import {+ createInitialPuppetState,+ ensurePuppetMesh,+ flipPuppetMesh,+ getDeformedMeshBounds,+ isPuppetDeformed,+ solvePuppetDeformation,+} from './puppetWarpEngine';+import {+ createInitialCageState,+ evaluateCageMesh,+ isCageDeformed,+} from './cageWarpEngine';++const MAX_BAKE_DIM = 8192;+const MAX_BAKE_PIXELS = 64 * 1024 * 1024;+const AFFINE_POS_TOL = 1e-2;+const AFFINE_ORTHO_TOL = 1e-4;+const SNAP_EPS = 1e-4;++function snapNearInt(v: number): number {+ const r = Math.round(v);+ return Math.abs(v - r) < SNAP_EPS ? r : v;+}++/**+ * Generates a (rows x cols) mesh control lattice placed on the exact projective+ * homography of `quad`. Identical to bilinear interpolation when `quad` is affine.+ */+export function createMeshPointsFromPerspectiveQuad(+ quad: [Point2D, Point2D, Point2D, Point2D],+ cols = 4,+ rows = 4+): Point2D[][] {+ const H = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);+ if (Math.abs(H.g) < 1e-7 && Math.abs(H.h) < 1e-7) {+ return createDefaultMeshPoints(quad, cols, rows);+ }++ const points: Point2D[][] = [];+ for (let r = 0; r < rows; r++) {+ const v = rows > 1 ? r / (rows - 1) : 0;+ const row: Point2D[] = [];+ for (let c = 0; c < cols; c++) {+ const u = cols > 1 ? c / (cols - 1) : 0;+ row.push(evaluateHomography(H, u, v));+ }+ points.push(row);+ }+ return points;+}++/**+ * Checks whether a perspective quad is strictly convex and has moderate enough+ * projective foreshortening that a Catmull-Rom mesh lattice placed via homography+ * accurately represents it without baking.+ */+export function isPerspectiveQuadSafeForMesh(+ quad: [Point2D, Point2D, Point2D, Point2D]+): boolean {+ for (const p of quad) {+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) return false;+ }++ // Verify strict convexity (supports both CW normal and CCW flipped quads)+ let winding = 0;+ for (let i = 0; i < 4; i++) {+ const a = quad[i];+ const b = quad[(i + 1) % 4];+ const c = quad[(i + 2) % 4];+ const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);+ if (Math.abs(cross) < 1e-3) return false;+ const s = cross > 0 ? 1 : -1;+ if (winding === 0) winding = s;+ else if (s !== winding) return false;+ }++ const H = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);+ const cornerDenoms = [+ 1,+ H.g + 1,+ H.g + H.h + 1,+ H.h + 1,+ ];+ let minD = Infinity;+ let maxD = -Infinity;+ for (const d of cornerDenoms) {+ if (!Number.isFinite(d)) return false;+ if (d < minD) minD = d;+ if (d > maxD) maxD = d;+ }+ return minD > 0.35 && maxD < 3.0;+}++export interface DecomposedAffineTransform {+ x: number;+ y: number;+ width: number;+ height: number;+ rotation: number;+ flipH: boolean;+ flipV: boolean;+}++/**+ * Attempts to recover an exact affine rectangle (position, size, rotation, H/V flip)+ * from a 4-point quad. Returns null if the quad has perspective distortion, skew, or is degenerate.+ */+export function decomposeQuadToAffine(+ quad: [Point2D, Point2D, Point2D, Point2D],+ preferFlipH = false,+ preferFlipV = false+): DecomposedAffineTransform | null {+ const [p0, p1, p2, p3] = quad;+ for (const p of quad) {+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) return null;+ }++ const ux = p1.x - p0.x;+ const uy = p1.y - p0.y;+ const vx = p3.x - p0.x;+ const vy = p3.y - p0.y;++ const width = Math.hypot(ux, uy);+ const height = Math.hypot(vx, vy);+ if (width < 1e-3 || height < 1e-3) return null;++ // Parallelogram check: p2 must equal p1 + (p3 - p0)+ if (+ Math.abs(p2.x - (p1.x + vx)) > AFFINE_POS_TOL ||+ Math.abs(p2.y - (p1.y + vy)) > AFFINE_POS_TOL+ ) {+ return null;+ }++ // Orthogonality check (rejects skew/shear)+ const cosAngle = (ux * vx + uy * vy) / (width * height);+ if (Math.abs(cosAngle) > AFFINE_ORTHO_TOL) {+ return null;+ }++ const cross = ux * vy - uy * vx;+ let flipH: boolean;+ let flipV: boolean;+ if (cross >= 0) {+ if (preferFlipH && preferFlipV) {+ flipH = true;+ flipV = true;+ } else {+ flipH = false;+ flipV = false;+ }+ } else {+ if (preferFlipV && !preferFlipH) {+ flipH = false;+ flipV = true;+ } else if (preferFlipH && !preferFlipV) {+ flipH = true;+ flipV = false;+ } else if (Math.abs(uy) < SNAP_EPS && ux > 0 && vy < 0) {+ flipH = false;+ flipV = true;+ } else {+ flipH = true;+ flipV = false;+ }+ }++ const sx = flipH ? -1 : 1;+ const cos = (ux / width) * sx;+ const sin = (uy / width) * sx;+ let rotation = (Math.atan2(sin, cos) * 180) / Math.PI;+ rotation = ((rotation % 360) + 360) % 360;+ if (Math.abs(rotation - Math.round(rotation)) < SNAP_EPS) {+ rotation = Math.round(rotation) % 360;+ }++ const cx = (p0.x + p2.x) * 0.5;+ const cy = (p0.y + p2.y) * 0.5;+ const finalW = snapNearInt(width);+ const finalH = snapNearInt(height);+ const finalX = snapNearInt(cx - finalW * 0.5);+ const finalY = snapNearInt(cy - finalH * 0.5);++ return {+ x: finalX,+ y: finalY,+ width: finalW,+ height: finalH,+ rotation,+ flipH,+ flipV,+ };+}++/**+ * Attempts to recover an exact affine rectangle from a mesh lattice if all control points+ * remain unmodified on the bilinear grid of a rectangular boundary.+ */+export function decomposeMeshToAffine(+ meshPoints: Point2D[][],+ preferFlipH = false,+ preferFlipV = false+): DecomposedAffineTransform | null {+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (rows < 2 || cols < 2) return null;++ const q0 = meshPoints[0][0];+ const q1 = meshPoints[0][cols - 1];+ const q2 = meshPoints[rows - 1][cols - 1];+ const q3 = meshPoints[rows - 1][0];+ const quad: [Point2D, Point2D, Point2D, Point2D] = [q0, q1, q2, q3];++ const affine = decomposeQuadToAffine(quad, preferFlipH, preferFlipV);+ if (!affine) return null;++ for (let r = 0; r < rows; r++) {+ const v = r / (rows - 1);+ for (let c = 0; c < cols; c++) {+ const u = c / (cols - 1);+ const ex = (1 - u) * (1 - v) * q0.x + u * (1 - v) * q1.x + u * v * q2.x + (1 - u) * v * q3.x;+ const ey = (1 - u) * (1 - v) * q0.y + u * (1 - v) * q1.y + u * v * q2.y + (1 - u) * v * q3.y;+ const pt = meshPoints[r][c];+ if (Math.abs(pt.x - ex) > AFFINE_POS_TOL || Math.abs(pt.y - ey) > AFFINE_POS_TOL) {+ return null;+ }+ }+ }++ return affine;+}++/**+ * Attempts to recover a 4-point perspective quad from a mesh lattice if all control points+ * match the exact projective homography of its 4 corners.+ */+export function decomposeMeshToPerspectiveQuad(+ meshPoints: Point2D[][]+): [Point2D, Point2D, Point2D, Point2D] | null {+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (rows < 2 || cols < 2) return null;++ const quad: [Point2D, Point2D, Point2D, Point2D] = [+ { ...meshPoints[0][0] },+ { ...meshPoints[0][cols - 1] },+ { ...meshPoints[rows - 1][cols - 1] },+ { ...meshPoints[rows - 1][0] },+ ];+ if (!isPerspectiveQuadSafeForMesh(quad)) return null;++ const H = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);+ for (let r = 0; r < rows; r++) {+ const v = r / (rows - 1);+ for (let c = 0; c < cols; c++) {+ const u = c / (cols - 1);+ const expected = evaluateHomography(H, u, v);+ const pt = meshPoints[r][c];+ if (+ Math.abs(pt.x - expected.x) > AFFINE_POS_TOL ||+ Math.abs(pt.y - expected.y) > AFFINE_POS_TOL+ ) {+ return null;+ }+ }+ }++ return quad;+}++/**+ * CPU straight-alpha triangle rasterizer fallback for Mesh Warp baking when WebGL2 is unavailable.+ */+function rasterizeMeshWarpCpu(+ source: PixelBuffer,+ meshPoints: Point2D[][],+ destRect: DirtyRect,+ subPerCell: number+): Uint8ClampedArray {+ const outW = destRect.width;+ const outH = destRect.height;+ const out = new Uint8ClampedArray(outW * outH * 4);+ const sw = source.width;+ const sh = source.height;+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (sw <= 0 || sh <= 0 || outW <= 0 || outH <= 0 || rows < 2 || cols < 2) return out;++ const totalCols = (cols - 1) * subPerCell;+ const totalRows = (rows - 1) * subPerCell;+ const grid: Point2D[][] = [];+ for (let j = 0; j <= totalRows; j++) {+ const row: Point2D[] = [];+ const v = j / totalRows;+ for (let i = 0; i <= totalCols; i++) {+ const u = i / totalCols;+ row.push(evaluateMeshSurface(meshPoints, u, v));+ }+ grid.push(row);+ }++ const srcData = source.data;+ const ox = destRect.x;+ const oy = destRect.y;++ const sampleBilinearStraight = (sx: number, sy: number, dstOff: number) => {+ const x0 = Math.floor(sx);+ const y0 = Math.floor(sy);+ const fx = sx - x0;+ const fy = sy - y0;+ const x1 = x0 + 1;+ const y1 = y0 + 1;++ const w00 = (1 - fx) * (1 - fy);+ const w10 = fx * (1 - fy);+ const w01 = (1 - fx) * fy;+ const w11 = fx * fy;++ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;++ const addTap = (ix: number, iy: number, w: number) => {+ if (ix < 0 || ix >= sw || iy < 0 || iy >= sh) return;+ const off = (iy * sw + ix) << 2;+ const a = srcData[off + 3];+ if (a === 0) return;+ const wa = w * (a * (1 / 255));+ accR += srcData[off] * wa;+ accG += srcData[off + 1] * wa;+ accB += srcData[off + 2] * wa;+ accA += wa;+ };++ addTap(x0, y0, w00);+ addTap(x1, y0, w10);+ addTap(x0, y1, w01);+ addTap(x1, y1, w11);++ if (accA <= 1e-4) return;+ if (accA > 1) accA = 1;+ const invA = 1 / accA;+ out[dstOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dstOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dstOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dstOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255)));+ };++ const rasterTri = (+ p0: Point2D, u0: number, v0: number,+ p1: Point2D, u1: number, v1: number,+ p2: Point2D, u2: number, v2: number+ ) => {+ const x0 = p0.x - ox;+ const y0 = p0.y - oy;+ const x1 = p1.x - ox;+ const y1 = p1.y - oy;+ const x2 = p2.x - ox;+ const y2 = p2.y - oy;++ const det = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);+ if (Math.abs(det) < 1e-6) return;+ const invDet = 1 / det;++ const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2)));+ const maxX = Math.min(outW - 1, Math.ceil(Math.max(x0, x1, x2)));+ const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2)));+ const maxY = Math.min(outH - 1, Math.ceil(Math.max(y0, y1, y2)));++ for (let py = minY; py <= maxY; py++) {+ const cy = py + 0.5;+ const rowBase = py * outW;+ for (let px = minX; px <= maxX; px++) {+ const cx = px + 0.5;+ const w0 = ((x1 - cx) * (y2 - cy) - (y1 - cy) * (x2 - cx)) * invDet;+ if (w0 < -1e-4) continue;+ const w1 = ((x2 - cx) * (y0 - cy) - (y2 - cy) * (x0 - cx)) * invDet;+ if (w1 < -1e-4) continue;+ const w2 = 1 - w0 - w1;+ if (w2 < -1e-4) continue;++ const u = w0 * u0 + w1 * u1 + w2 * u2;+ const v = w0 * v0 + w1 * v1 + w2 * v2;+ sampleBilinearStraight(u * sw - 0.5, v * sh - 0.5, (rowBase + px) << 2);+ }+ }+ };++ for (let j = 0; j < totalRows; j++) {+ const v0 = j / totalRows;+ const v1 = (j + 1) / totalRows;+ const row0 = grid[j];+ const row1 = grid[j + 1];+ for (let i = 0; i < totalCols; i++) {+ const u0 = i / totalCols;+ const u1 = (i + 1) / totalCols;+ const p00 = row0[i];+ const p10 = row0[i + 1];+ const p11 = row1[i + 1];+ const p01 = row1[i];+ rasterTri(p00, u0, v0, p10, u1, v0, p01, u0, v1);+ rasterTri(p10, u1, v0, p11, u1, v1, p01, u0, v1);+ }+ }++ return out;+}++interface TriangleBakeGeometry {+ deformedX: Float32Array;+ deformedY: Float32Array;+ uvX: Float32Array;+ uvY: Float32Array;+ triangles: Uint32Array;+ triOrder?: Uint32Array;+}++function bakeSingleSourceToRect(+ sourceCanvas: HTMLCanvasElement,+ sourcePixels: PixelBuffer | undefined,+ mode: 'perspective' | 'mesh' | 'puppet' | 'cage',+ quad: [Point2D, Point2D, Point2D, Point2D],+ meshPoints: Point2D[][],+ renderBounds: DirtyRect,+ triGeom?: TriangleBakeGeometry+): { data: Uint8ClampedArray; width: number; height: number } | null {+ const resolved = sourcePixels ?? extractCanvasPixelBuffer(sourceCanvas);+ if (!resolved) return null;++ const w = renderBounds.width;+ const h = renderBounds.height;+ const out = new Uint8ClampedArray(w * h * 4);+ const CHUNK = 1024;++ const writeChunk = (+ chunkData: Uint8ClampedArray,+ cx: number,+ cy: number,+ cw: number,+ ch: number+ ) => {+ const relX = cx - renderBounds.x;+ const relY = cy - renderBounds.y;+ for (let row = 0; row < ch; row++) {+ const dstOff = ((relY + row) * w + relX) * 4;+ const srcOff = row * cw * 4;+ out.set(chunkData.subarray(srcOff, srcOff + cw * 4), dstOff);+ }+ };++ if (mode === 'perspective') {+ processPerspectiveTransformChunks(resolved, quad, renderBounds, CHUNK, 32, writeChunk);+ return { data: out, width: w, height: h };+ }++ if ((mode === 'puppet' || mode === 'cage') && triGeom) {+ processDeformedTrianglesTransformChunks(+ resolved,+ triGeom.deformedX,+ triGeom.deformedY,+ triGeom.uvX,+ triGeom.uvY,+ triGeom.triangles,+ renderBounds,+ CHUNK,+ writeChunk,+ triGeom.triOrder+ );+ return { data: out, width: w, height: h };+ }++ const subPerCell = computeMeshSubdivisions(resolved.width, resolved.height, meshPoints, true);+ if (+ processMeshWarpTransformChunks(+ resolved,+ meshPoints,+ renderBounds,+ CHUNK,+ subPerCell,+ writeChunk+ )+ ) {+ return { data: out, width: w, height: h };+ }++ return {+ data: rasterizeMeshWarpCpu(resolved, meshPoints, renderBounds, subPerCell),+ width: w,+ height: h,+ };+}++function findCombinedNonEmptyBounds(+ buffers: Array<{ data: Uint8ClampedArray; width: number; height: number }>,+ fallbackW: number,+ fallbackH: number+): { x: number; y: number; width: number; height: number } {+ let minX = fallbackW;+ let minY = fallbackH;+ let maxX = -1;+ let maxY = -1;++ for (const buf of buffers) {+ const { data, width, height } = buf;+ for (let y = 0; y < height; y++) {+ const rowOff = y * width * 4;+ for (let x = 0; x < width; x++) {+ if (data[rowOff + x * 4 + 3] > 0) {+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }+ }+ }++ if (maxX < minX || maxY < minY) {+ return { x: 0, y: 0, width: Math.max(1, fallbackW), height: Math.max(1, fallbackH) };+ }+ return {+ x: minX,+ y: minY,+ width: maxX - minX + 1,+ height: maxY - minY + 1,+ };+}++function cropBuffer(+ buf: { data: Uint8ClampedArray; width: number; height: number },+ relX: number,+ relY: number,+ width: number,+ height: number+): { data: Uint8ClampedArray; width: number; height: number } {+ if (relX === 0 && relY === 0 && width === buf.width && height === buf.height) {+ return buf;+ }+ const out = new Uint8ClampedArray(width * height * 4);+ const rowBytes = width * 4;+ for (let y = 0; y < height; y++) {+ const srcOff = ((relY + y) * buf.width + relX) * 4;+ out.set(buf.data.subarray(srcOff, srcOff + rowBytes), y * rowBytes);+ }+ return { data: out, width, height };+}++function createCanvasFromPixelBuffer(buf: {+ data: Uint8ClampedArray;+ width: number;+ height: number;+}): HTMLCanvasElement {+ const canvas = document.createElement('canvas');+ canvas.width = buf.width;+ canvas.height = buf.height;+ const ctx = get2DContext(canvas);+ if (ctx) {+ const img = ctx.createImageData(buf.width, buf.height);+ img.data.set(buf.data);+ ctx.putImageData(img, 0, 0);+ }+ return canvas;+}++/**+ * Bakes the session's current perspective or mesh warp into fresh intermediate source canvas(es)+ * and pixel buffer(s), preserving the original unbaked sources for Reset and retiring superseded+ * intermediate canvases without mutating `session` (React StrictMode safe).+ */+export function bakeTransformSession(+ session: TransformSession,+ targetMode: TransformMode+): TransformSession | null {+ const currentMode = session.mode || 'affine';+ if (+ currentMode !== 'perspective' &&+ currentMode !== 'mesh' &&+ currentMode !== 'puppet' &&+ currentMode !== 'cage'+ ) {+ return null;+ }+ if (typeof document === 'undefined') return null;++ const cols = session.meshCols || 4;+ const rows = session.meshRows || 4;+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const meshPoints = session.meshPoints || createMeshPointsFromPerspectiveQuad(quad, cols, rows);++ let triGeom: TriangleBakeGeometry | undefined;+ let rawBounds: { minX: number; minY: number; maxX: number; maxY: number; width: number; height: number };++ if (currentMode === 'perspective') {+ rawBounds = getPointsBounds(quad);+ } else if (currentMode === 'mesh') {+ rawBounds = getMeshSurfaceBounds(meshPoints, 6);+ } else if (currentMode === 'puppet') {+ const previewPixels = session.sourcePixels ?? extractCanvasPixelBuffer(session.sourceCanvas) ?? undefined;+ const sw = previewPixels?.width ?? session.sourceCanvas.width;+ const sh = previewPixels?.height ?? session.sourceCanvas.height;+ const pMesh = ensurePuppetMesh(session.puppet, previewPixels, sw, sh, quad);+ const solved = solvePuppetDeformation(+ pMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ triGeom = {+ deformedX: solved.x,+ deformedY: solved.y,+ uvX: pMesh.uvX,+ uvY: pMesh.uvY,+ triangles: pMesh.triangles,+ triOrder: solved.triOrder,+ };+ rawBounds = getDeformedMeshBounds(solved.x, solved.y);+ } else {+ const sw = session.sourcePixels?.width ?? session.sourceCanvas.width;+ const sh = session.sourcePixels?.height ?? session.sourceCanvas.height;+ const cageState =+ session.cage ??+ createInitialCageState(+ session.sourcePixels ?? extractCanvasPixelBuffer(session.sourceCanvas) ?? undefined,+ sw,+ sh,+ quad+ );+ const evalRes = evaluateCageMesh(sw, sh, quad, cageState, true);+ triGeom = {+ deformedX: evalRes.deformedX,+ deformedY: evalRes.deformedY,+ uvX: evalRes.uvX,+ uvY: evalRes.uvY,+ triangles: evalRes.triangles,+ };+ rawBounds = getDeformedMeshBounds(evalRes.deformedX, evalRes.deformedY);+ }++ const renderBounds: DirtyRect = {+ x: rawBounds.minX - 1,+ y: rawBounds.minY - 1,+ width: Math.max(1, rawBounds.width + 2),+ height: Math.max(1, rawBounds.height + 2),+ };++ if (+ renderBounds.width > MAX_BAKE_DIM ||+ renderBounds.height > MAX_BAKE_DIM ||+ renderBounds.width * renderBounds.height > MAX_BAKE_PIXELS+ ) {+ return null;+ }++ const bakedPreview = bakeSingleSourceToRect(+ session.sourceCanvas,+ session.sourcePixels,+ currentMode,+ quad,+ meshPoints,+ renderBounds,+ triGeom+ );+ if (!bakedPreview) return null;++ const bakedLayers = new Map<string, { data: Uint8ClampedArray; width: number; height: number }>();+ const allBuffers: Array<{ data: Uint8ClampedArray; width: number; height: number }> = [+ bakedPreview,+ ];++ if (session.layerIds && session.layerIds.length > 0 && session.layerSourceCanvases) {+ for (const lId of session.layerIds) {+ const lCanvas = session.layerSourceCanvases.get(lId);+ if (!lCanvas) continue;+ const lPixels = session.layerSourcePixels?.get(lId);+ const bakedLayer = bakeSingleSourceToRect(+ lCanvas,+ lPixels,+ currentMode,+ quad,+ meshPoints,+ renderBounds,+ triGeom+ );+ if (bakedLayer) {+ bakedLayers.set(lId, bakedLayer);+ allBuffers.push(bakedLayer);+ }+ }+ }++ const tight = findCombinedNonEmptyBounds(allBuffers, renderBounds.width, renderBounds.height);+ const destX = renderBounds.x + tight.x;+ const destY = renderBounds.y + tight.y;+ const destW = tight.width;+ const destH = tight.height;++ const trimmedPreviewPixels = cropBuffer(bakedPreview, tight.x, tight.y, destW, destH);+ const trimmedPreviewCanvas = createCanvasFromPixelBuffer(trimmedPreviewPixels);++ let nextLayerCanvases = session.layerSourceCanvases;+ let nextLayerPixels = session.layerSourcePixels;+ if (bakedLayers.size > 0) {+ nextLayerCanvases = new Map<string, HTMLCanvasElement>();+ nextLayerPixels = new Map<string, { data: Uint8ClampedArray; width: number; height: number }>();+ for (const [lId, buf] of bakedLayers.entries()) {+ const trimmed = cropBuffer(buf, tight.x, tight.y, destW, destH);+ nextLayerPixels.set(lId, trimmed);+ nextLayerCanvases.set(lId, createCanvasFromPixelBuffer(trimmed));+ }+ }++ const originalSourceCanvas = session.originalSourceCanvas ?? session.sourceCanvas;+ const originalSourcePixels = session.originalSourcePixels ?? session.sourcePixels;+ const originalLayerSourceCanvases =+ session.originalLayerSourceCanvases ?? session.layerSourceCanvases;+ const originalLayerSourcePixels =+ session.originalLayerSourcePixels ?? session.layerSourcePixels;++ const retiredCanvases = [...(session.retiredCanvases ?? [])];+ if (session.sourceCanvas !== originalSourceCanvas) {+ retiredCanvases.push(session.sourceCanvas);+ }+ if (+ session.layerSourceCanvases &&+ originalLayerSourceCanvases &&+ session.layerSourceCanvases !== originalLayerSourceCanvases+ ) {+ for (const c of session.layerSourceCanvases.values()) {+ retiredCanvases.push(c);+ }+ }++ const nextQuad = createDefaultPerspectiveQuad(destX, destY, destW, destH, 0, false, false);+ const nextMesh = createDefaultMeshPoints(nextQuad, cols, rows);++ const nextPuppet =+ targetMode === 'puppet'+ ? createInitialPuppetState(trimmedPreviewPixels, destW, destH, nextQuad, {+ density: session.puppet?.density,+ expansion: session.puppet?.expansion,+ rigidity: session.puppet?.rigidity,+ showMesh: session.puppet?.showMesh,+ })+ : undefined;++ const nextCage =+ targetMode === 'cage'+ ? createInitialCageState(trimmedPreviewPixels, destW, destH, nextQuad)+ : undefined;++ return {+ ...session,+ mode: targetMode,+ sourceCanvas: trimmedPreviewCanvas,+ sourcePixels: trimmedPreviewPixels,+ originalSourceCanvas,+ originalSourcePixels,+ layerSourceCanvases: nextLayerCanvases,+ layerSourcePixels: nextLayerPixels,+ originalLayerSourceCanvases,+ originalLayerSourcePixels,+ retiredCanvases,+ x: destX,+ y: destY,+ width: destW,+ height: destH,+ rotation: 0,+ flipH: false,+ flipV: false,+ perspectiveQuad: nextQuad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: nextMesh,+ puppet: nextPuppet,+ cage: nextCage,+ };+}++function buildLosslessTargetSession(+ session: TransformSession,+ targetMode: TransformMode,+ quad: [Point2D, Point2D, Point2D, Point2D],+ affineOverride?: DecomposedAffineTransform+): TransformSession {+ const cols = session.meshCols || 4;+ const rows = session.meshRows || 4;+ const base: TransformSession = affineOverride+ ? {+ ...session,+ x: affineOverride.x,+ y: affineOverride.y,+ width: affineOverride.width,+ height: affineOverride.height,+ rotation: affineOverride.rotation,+ flipH: affineOverride.flipH,+ flipV: affineOverride.flipV,+ }+ : { ...session };++ if (targetMode === 'affine') {+ return {+ ...base,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createDefaultMeshPoints(quad, cols, rows),+ puppet: undefined,+ cage: undefined,+ };+ }++ if (targetMode === 'perspective') {+ return {+ ...base,+ mode: 'perspective',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createMeshPointsFromPerspectiveQuad(quad, cols, rows),+ puppet: undefined,+ cage: undefined,+ };+ }++ if (targetMode === 'mesh') {+ return {+ ...base,+ mode: 'mesh',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createMeshPointsFromPerspectiveQuad(quad, cols, rows),+ puppet: undefined,+ cage: undefined,+ };+ }++ const srcPixels = base.sourcePixels ?? extractCanvasPixelBuffer(base.sourceCanvas) ?? undefined;+ const sw = srcPixels?.width ?? base.sourceCanvas.width;+ const sh = srcPixels?.height ?? base.sourceCanvas.height;++ if (targetMode === 'puppet') {+ return {+ ...base,+ mode: 'puppet',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createDefaultMeshPoints(quad, cols, rows),+ puppet: createInitialPuppetState(srcPixels, sw, sh, quad, {+ density: session.puppet?.density,+ expansion: session.puppet?.expansion,+ rigidity: session.puppet?.rigidity,+ showMesh: session.puppet?.showMesh,+ }),+ cage: undefined,+ };+ }++ // targetMode === 'cage'+ return {+ ...base,+ mode: 'cage',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createDefaultMeshPoints(quad, cols, rows),+ puppet: undefined,+ cage: createInitialCageState(srcPixels, sw, sh, quad),+ };+}++/**+ * Transitions an active TransformSession from its current mode to `newMode`,+ * preserving all edits made so far (move, scale, rotate, flip, perspective, mesh, puppet, cage)+ * so the user can continue seamlessly in the new transformation mode.+ */+export function switchTransformSessionMode(+ session: TransformSession,+ newMode: TransformMode+): TransformSession {+ const currentMode: TransformMode = session.mode || 'affine';+ if (newMode === currentMode) return session;++ const cols = session.meshCols || 4;+ const rows = session.meshRows || 4;++ // 1. Leaving Affine (Free Transform) -> exact lossless geometric transfer+ if (currentMode === 'affine') {+ const quad = createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ return buildLosslessTargetSession(session, newMode, quad);+ }++ // 2. Leaving Perspective+ if (currentMode === 'perspective') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );++ if (newMode === 'mesh') {+ if (isPerspectiveQuadSafeForMesh(quad)) {+ return {+ ...session,+ mode: 'mesh',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createMeshPointsFromPerspectiveQuad(quad, cols, rows),+ puppet: undefined,+ cage: undefined,+ };+ }+ return bakeTransformSession(session, 'mesh') ?? {+ ...session,+ mode: 'mesh',+ perspectiveQuad: quad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createDefaultMeshPoints(quad, cols, rows),+ };+ }++ // perspective -> affine | puppet | cage+ const decomposed = decomposeQuadToAffine(quad, session.flipH, session.flipV);+ if (decomposed) {+ return buildLosslessTargetSession(session, newMode, quad, decomposed);+ }++ const baked = bakeTransformSession(session, newMode);+ if (baked) return baked;++ const b = getPointsBounds(quad);+ const fallbackQuad = createDefaultPerspectiveQuad(b.minX, b.minY, b.width, b.height, 0);+ return buildLosslessTargetSession(session, newMode, fallbackQuad, {+ x: b.minX,+ y: b.minY,+ width: b.width,+ height: b.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ });+ }++ // 3. Leaving Puppet Warp+ if (currentMode === 'puppet') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );++ if (!isPuppetDeformed(session.puppet)) {+ const decomposed = decomposeQuadToAffine(quad, session.flipH, session.flipV);+ return buildLosslessTargetSession(session, newMode, quad, decomposed ?? undefined);+ }++ const baked = bakeTransformSession(session, newMode);+ if (baked) return baked;+ return buildLosslessTargetSession(session, newMode, quad);+ }++ // 4. Leaving Cage Transform+ if (currentMode === 'cage') {+ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );++ if (!isCageDeformed(session.cage)) {+ const decomposed = decomposeQuadToAffine(quad, session.flipH, session.flipV);+ return buildLosslessTargetSession(session, newMode, quad, decomposed ?? undefined);+ }++ const baked = bakeTransformSession(session, newMode);+ if (baked) return baked;+ return buildLosslessTargetSession(session, newMode, quad);+ }++ // 5. Leaving Mesh+ const fallbackQuad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );+ const meshPoints =+ session.meshPoints || createMeshPointsFromPerspectiveQuad(fallbackQuad, cols, rows);++ if (newMode === 'affine' || newMode === 'puppet' || newMode === 'cage') {+ const decomposed = decomposeMeshToAffine(meshPoints, session.flipH, session.flipV);+ if (decomposed) {+ const quad = createDefaultPerspectiveQuad(+ decomposed.x,+ decomposed.y,+ decomposed.width,+ decomposed.height,+ decomposed.rotation,+ decomposed.flipH,+ decomposed.flipV+ );+ return buildLosslessTargetSession(session, newMode, quad, decomposed);+ }++ const baked = bakeTransformSession(session, newMode);+ if (baked) return baked;++ const b = getMeshSurfaceBounds(meshPoints, 6);+ const bQuad = createDefaultPerspectiveQuad(b.minX, b.minY, b.width, b.height, 0);+ return buildLosslessTargetSession(session, newMode, bQuad, {+ x: b.minX,+ y: b.minY,+ width: b.width,+ height: b.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ });+ }++ // mesh -> perspective+ const decomposedQuad = decomposeMeshToPerspectiveQuad(meshPoints);+ if (decomposedQuad) {+ return {+ ...session,+ mode: 'perspective',+ perspectiveQuad: decomposedQuad,+ meshPoints,+ puppet: undefined,+ cage: undefined,+ };+ }++ const baked = bakeTransformSession(session, 'perspective');+ if (baked) return baked;++ const b = getMeshSurfaceBounds(meshPoints, 6);+ return {+ ...session,+ mode: 'perspective',+ perspectiveQuad: createDefaultPerspectiveQuad(b.minX, b.minY, b.width, b.height, 0),+ puppet: undefined,+ cage: undefined,+ };+}++/**+ * Flips an active TransformSession horizontally or vertically in any mode+ * (affine, perspective, mesh, puppet, or cage).+ */+export function flipTransformSession(+ session: TransformSession,+ axis: 'horizontal' | 'vertical'+): TransformSession {+ const mode: TransformMode = session.mode || 'affine';+ const nextFlipH = axis === 'horizontal' ? !session.flipH : session.flipH;+ const nextFlipV = axis === 'vertical' ? !session.flipV : session.flipV;++ if (mode === 'affine') {+ return {+ ...session,+ flipH: nextFlipH,+ flipV: nextFlipV,+ };+ }++ const quad =+ session.perspectiveQuad ||+ createDefaultPerspectiveQuad(+ session.x,+ session.y,+ session.width,+ session.height,+ session.rotation,+ session.flipH,+ session.flipV+ );++ if (mode === 'perspective') {+ let minVal = Infinity;+ let maxVal = -Infinity;+ for (const p of quad) {+ const v = axis === 'horizontal' ? p.x : p.y;+ if (v < minVal) minVal = v;+ if (v > maxVal) maxVal = v;+ }+ const mid = (minVal + maxVal) * 0.5;+ const flippedQuad = quad.map((p) =>+ axis === 'horizontal'+ ? { x: 2 * mid - p.x, y: p.y }+ : { x: p.x, y: 2 * mid - p.y }+ ) as [Point2D, Point2D, Point2D, Point2D];++ return {+ ...session,+ flipH: nextFlipH,+ flipV: nextFlipV,+ perspectiveQuad: flippedQuad,+ };+ }++ if (mode === 'puppet') {+ const srcPixels = session.sourcePixels ?? extractCanvasPixelBuffer(session.sourceCanvas) ?? undefined;+ const sw = srcPixels?.width ?? session.sourceCanvas.width;+ const sh = srcPixels?.height ?? session.sourceCanvas.height;+ const pMesh = ensurePuppetMesh(session.puppet, srcPixels, sw, sh, quad);+ const solved = solvePuppetDeformation(+ pMesh,+ session.puppet?.pins ?? [],+ session.puppet?.rigidity ?? 'normal'+ );+ const bounds = getDeformedMeshBounds(solved.x, solved.y);+ const mid =+ axis === 'horizontal'+ ? (bounds.minX + bounds.maxX) * 0.5+ : (bounds.minY + bounds.maxY) * 0.5;++ const flippedQuad = quad.map((p) =>+ axis === 'horizontal'+ ? { x: 2 * mid - p.x, y: p.y }+ : { x: p.x, y: 2 * mid - p.y }+ ) as [Point2D, Point2D, Point2D, Point2D];++ const flippedMesh = flipPuppetMesh(pMesh, axis, mid);+ const flippedPins = (session.puppet?.pins ?? []).map((pin) => ({+ ...pin,+ restX: axis === 'horizontal' ? 2 * mid - pin.restX : pin.restX,+ restY: axis === 'vertical' ? 2 * mid - pin.restY : pin.restY,+ x: axis === 'horizontal' ? 2 * mid - pin.x : pin.x,+ y: axis === 'vertical' ? 2 * mid - pin.y : pin.y,+ rotation: -pin.rotation,+ }));++ return {+ ...session,+ flipH: nextFlipH,+ flipV: nextFlipV,+ perspectiveQuad: flippedQuad,+ puppet: {+ rigidity: session.puppet?.rigidity ?? 'normal',+ density: session.puppet?.density ?? 'normal',+ expansion: session.puppet?.expansion ?? 6,+ showMesh: session.puppet?.showMesh ?? true,+ selectedPinId: session.puppet?.selectedPinId ?? null,+ pins: flippedPins,+ mesh: flippedMesh,+ },+ };+ }++ if (mode === 'cage') {+ const cage = session.cage;+ const ptsForMid = cage && cage.points.length > 0 ? cage.points : quad;+ let minVal = Infinity;+ let maxVal = -Infinity;+ for (const p of ptsForMid) {+ const v = axis === 'horizontal' ? p.x : p.y;+ if (v < minVal) minVal = v;+ if (v > maxVal) maxVal = v;+ }+ const mid = (minVal + maxVal) * 0.5;+ const flippedQuad = quad.map((p) =>+ axis === 'horizontal'+ ? { x: 2 * mid - p.x, y: p.y }+ : { x: p.x, y: 2 * mid - p.y }+ ) as [Point2D, Point2D, Point2D, Point2D];++ const flippedCage = cage+ ? {+ ...cage,+ points: cage.points.map((pt) => ({+ ...pt,+ restX: axis === 'horizontal' ? 2 * mid - pt.restX : pt.restX,+ restY: axis === 'vertical' ? 2 * mid - pt.restY : pt.restY,+ x: axis === 'horizontal' ? 2 * mid - pt.x : pt.x,+ y: axis === 'vertical' ? 2 * mid - pt.y : pt.y,+ })),+ }+ : undefined;++ return {+ ...session,+ flipH: nextFlipH,+ flipV: nextFlipV,+ perspectiveQuad: flippedQuad,+ cage: flippedCage,+ };+ }++ // mesh mode+ const cols = session.meshCols || 4;+ const rows = session.meshRows || 4;+ const meshPoints = session.meshPoints || createDefaultMeshPoints(quad, cols, rows);+ let minVal = Infinity;+ let maxVal = -Infinity;+ for (const row of meshPoints) {+ for (const p of row) {+ const v = axis === 'horizontal' ? p.x : p.y;+ if (v < minVal) minVal = v;+ if (v > maxVal) maxVal = v;+ }+ }+ const mid = (minVal + maxVal) * 0.5;+ const flippedMesh = meshPoints.map((row) =>+ row.map((p) =>+ axis === 'horizontal'+ ? { x: 2 * mid - p.x, y: p.y }+ : { x: p.x, y: 2 * mid - p.y }+ )+ );++ return {+ ...session,+ flipH: nextFlipH,+ flipV: nextFlipV,+ meshPoints: flippedMesh,+ };+}++/**+ * Resets a TransformSession completely back to its initial unbaked pixels and original bounds.+ */+export function resetTransformSession(session: TransformSession): TransformSession {+ const cols = session.meshCols || 4;+ const rows = session.meshRows || 4;+ const defQuad = createDefaultPerspectiveQuad(+ session.bounds.x,+ session.bounds.y,+ session.bounds.width,+ session.bounds.height,+ 0,+ false,+ false+ );++ const restoredSourceCanvas = session.originalSourceCanvas ?? session.sourceCanvas;+ const restoredSourcePixels = session.originalSourceCanvas+ ? session.originalSourcePixels+ : session.sourcePixels;+ const restoredLayerCanvases =+ session.originalLayerSourceCanvases ?? session.layerSourceCanvases;+ const restoredLayerPixels = session.originalLayerSourceCanvases+ ? session.originalLayerSourcePixels+ : session.layerSourcePixels;++ const retiredCanvases = [...(session.retiredCanvases ?? [])];+ if (session.sourceCanvas !== restoredSourceCanvas) {+ retiredCanvases.push(session.sourceCanvas);+ }+ if (+ session.layerSourceCanvases &&+ restoredLayerCanvases &&+ session.layerSourceCanvases !== restoredLayerCanvases+ ) {+ for (const c of session.layerSourceCanvases.values()) {+ retiredCanvases.push(c);+ }+ }++ const resolvedPixels =+ restoredSourcePixels ?? extractCanvasPixelBuffer(restoredSourceCanvas) ?? undefined;+ const sw = resolvedPixels?.width ?? restoredSourceCanvas.width;+ const sh = resolvedPixels?.height ?? restoredSourceCanvas.height;++ const nextPuppet =+ session.mode === 'puppet'+ ? createInitialPuppetState(resolvedPixels, sw, sh, defQuad, {+ density: session.puppet?.density,+ expansion: session.puppet?.expansion,+ rigidity: session.puppet?.rigidity,+ showMesh: session.puppet?.showMesh,+ })+ : undefined;++ const nextCage =+ session.mode === 'cage'+ ? createInitialCageState(resolvedPixels, sw, sh, defQuad)+ : undefined;++ return {+ ...session,+ sourceCanvas: restoredSourceCanvas,+ sourcePixels: restoredSourcePixels,+ originalSourceCanvas: undefined,+ originalSourcePixels: undefined,+ layerSourceCanvases: restoredLayerCanvases,+ layerSourcePixels: restoredLayerPixels,+ originalLayerSourceCanvases: undefined,+ originalLayerSourcePixels: undefined,+ retiredCanvases,+ x: session.bounds.x,+ y: session.bounds.y,+ width: session.bounds.width,+ height: session.bounds.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ perspectiveQuad: defQuad,+ meshCols: cols,+ meshRows: rows,+ meshPoints: createDefaultMeshPoints(defQuad, cols, rows),+ puppet: nextPuppet,+ cage: nextCage,+ };+}++/**+ * Safely releases all temporary canvases owned by a TransformSession+ * (active, original unbaked, per-layer, and retired intermediate canvases).+ */+export function releaseTransformSessionCanvases(session: TransformSession): void {+ const unique = new Set<HTMLCanvasElement>();+ if (session.sourceCanvas) unique.add(session.sourceCanvas);+ if (session.originalSourceCanvas) unique.add(session.originalSourceCanvas);+ if (session.layerSourceCanvases) {+ for (const c of session.layerSourceCanvases.values()) unique.add(c);+ }+ if (session.originalLayerSourceCanvases) {+ for (const c of session.originalLayerSourceCanvases.values()) unique.add(c);+ }+ if (session.retiredCanvases) {+ for (const c of session.retiredCanvases) unique.add(c);+ }+ for (const canvas of unique) {+ releaseTemporaryCanvas(canvas);+ }+}diff --git a/src/utils/valueCheck.ts b/src/utils/valueCheck.tsnew file mode 100644index 0000000..4e92e17--- /dev/null+++ b/src/utils/valueCheck.ts@@ -0,0 +1,128 @@+import { NavigatorPreviewMode } from '../types/workspace';++export const MIN_NAVIGATOR_SPLIT_RATIO = 0.05;+export const MAX_NAVIGATOR_SPLIT_RATIO = 0.95;+export const DEFAULT_NAVIGATOR_SPLIT_RATIO = 0.5;++const LINEAR_LUT_STEPS = 4096;++/**+ * Precomputed sRGB byte [0..255] -> linear light [0..1] lookup table.+ * Matches `srgbToLinear()` in `softProofShaders.ts` for exact GPU <-> CPU parity.+ */+const SRGB_TO_LINEAR_LUT = new Float32Array(256);+for (let i = 0; i < 256; i++) {+ const c = i / 255;+ SRGB_TO_LINEAR_LUT[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);+}++/**+ * Precomputed linear light [0..1] -> sRGB byte [0..255] lookup table (12-bit precision).+ * Matches `linearToSrgb()` in `softProofShaders.ts`.+ */+const LINEAR_TO_SRGB_LUT = new Uint8Array(LINEAR_LUT_STEPS + 1);+for (let i = 0; i <= LINEAR_LUT_STEPS; i++) {+ const lin = i / LINEAR_LUT_STEPS;+ const srgb = lin <= 0.0031308 ? lin * 12.92 : 1.055 * Math.pow(lin, 1 / 2.4) - 0.055;+ LINEAR_TO_SRGB_LUT[i] = Math.max(0, Math.min(255, Math.round(srgb * 255)));+}++/**+ * Computes perceptual sRGB value (0..255) using true linear-light Rec.709 / CIE Y luminance:+ * Y_lin = 0.2126729 * R_lin + 0.7151522 * G_lin + 0.0721750 * B_lin+ * V_srgb = linearToSrgb(Y_lin)+ *+ * Unlike naive HSL desaturation (which collapses pure blue, red, and yellow to identical 50% gray),+ * this accurately reflects human perceived value contrast while preserving neutral grays identically.+ */+export function computePerceptualLuminanceByte(r: number, g: number, b: number): number {+ const ri = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;+ const gi = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;+ const bi = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;+ const linY =+ 0.2126729 * SRGB_TO_LINEAR_LUT[ri] ++ 0.7151522 * SRGB_TO_LINEAR_LUT[gi] ++ 0.072175 * SRGB_TO_LINEAR_LUT[bi];+ const lutIdx =+ linY <= 0 ? 0 : linY >= 1 ? LINEAR_LUT_STEPS : (linY * LINEAR_LUT_STEPS + 0.5) | 0;+ return LINEAR_TO_SRGB_LUT[lutIdx];+}++/**+ * Converts an ImageData buffer (or horizontal column slice `[startX, endX)`) in-place+ * to perceptual B/W tones without altering alpha values.+ */+export function applyPerceptualGrayscaleToImageData(+ imageData: Pick<ImageData, 'data' | 'width' | 'height'>,+ startX = 0,+ endX = imageData.width+): void {+ const { data, width, height } = imageData;+ const x0 = Math.max(0, Math.min(width, Math.floor(startX)));+ const x1 = Math.max(x0, Math.min(width, Math.ceil(endX)));+ if (x0 >= x1 || height <= 0) return;++ if (x0 === 0 && x1 === width) {+ const len = width * height * 4;+ for (let i = 0; i < len; i += 4) {+ if (data[i + 3] === 0) continue;+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ if (r === g && g === b) continue;+ const linY =+ 0.2126729 * SRGB_TO_LINEAR_LUT[r] ++ 0.7151522 * SRGB_TO_LINEAR_LUT[g] ++ 0.072175 * SRGB_TO_LINEAR_LUT[b];+ const idx =+ linY <= 0 ? 0 : linY >= 1 ? LINEAR_LUT_STEPS : (linY * LINEAR_LUT_STEPS + 0.5) | 0;+ const gray = LINEAR_TO_SRGB_LUT[idx];+ data[i] = gray;+ data[i + 1] = gray;+ data[i + 2] = gray;+ }+ return;+ }++ for (let y = 0; y < height; y++) {+ const rowBase = y * width * 4;+ for (let x = x0; x < x1; x++) {+ const i = rowBase + x * 4;+ if (data[i + 3] === 0) continue;+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ if (r === g && g === b) continue;+ const linY =+ 0.2126729 * SRGB_TO_LINEAR_LUT[r] ++ 0.7151522 * SRGB_TO_LINEAR_LUT[g] ++ 0.072175 * SRGB_TO_LINEAR_LUT[b];+ const idx =+ linY <= 0 ? 0 : linY >= 1 ? LINEAR_LUT_STEPS : (linY * LINEAR_LUT_STEPS + 0.5) | 0;+ const gray = LINEAR_TO_SRGB_LUT[idx];+ data[i] = gray;+ data[i + 1] = gray;+ data[i + 2] = gray;+ }+ }+}++export function clampNavigatorSplitRatio(ratio: number): number {+ if (!Number.isFinite(ratio)) return DEFAULT_NAVIGATOR_SPLIT_RATIO;+ return Math.max(+ MIN_NAVIGATOR_SPLIT_RATIO,+ Math.min(MAX_NAVIGATOR_SPLIT_RATIO, Math.round(ratio * 1000) / 1000)+ );+}++export function nextNavigatorPreviewMode(mode: NavigatorPreviewMode): NavigatorPreviewMode {+ if (mode === 'color') return 'bw';+ if (mode === 'bw') return 'split';+ return 'color';+}++export function getNavigatorPreviewModeLabel(mode: NavigatorPreviewMode): string {+ if (mode === 'bw') return 'Live B/W';+ if (mode === 'split') return 'Split View (Color | B/W)';+ return 'Color';+}diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.tsindex 6a372c8..e9f5512 100644--- a/src/utils/workspacePresets.ts+++ b/src/utils/workspacePresets.ts@@ -1,4 +1,7 @@import { safeLocalStorageSetItem } from './safeStorage';+import { migrateLegacyPresetId } from './brushPresetManager';+import { clampNavigatorSplitRatio, DEFAULT_NAVIGATOR_SPLIT_RATIO } from './valueCheck';+import { BrushPresetId } from '../types/editor';import {ALL_DOCK_PANEL_IDS,COMMAND_CATALOG,@@ -10,9 +13,14 @@ import {DockSide,FloatingPanelLastDock,FloatingPanelState,+ NavigatorPreviewMode,PersistedWorkspaceState,QuickAccessItem,QuickAccessViewMode,+ QuickBrushPanelOrientation,+ QuickBrushPanelState,+ QuickBrushPreviewStyle,+ QuickBrushTileSize,WorkspaceLayout,WorkspacePresetId,} from '../types/workspace';@@ -271,8 +279,41 @@ export const DEFAULT_COMMAND_BAR_IDS: CommandActionId[] = ['clear-layer','merge-down','toggle-palettes',+ 'toggle-quick-brushes',];+export const DEFAULT_QUICK_BRUSH_IDS: BrushPresetId[] = [+ 'g-pen',+ 'real-g-pen',+ 'pencil-hb-2b',+ 'soft-glaze-airbrush',+ 'oil-flat-alla-prima',+ 'blend-oil-bristle',+ 'blend-velvet-soft',+ 'impasto-bristle-oil',+ 'dry-bristle-rake',+];++export function createDefaultQuickBrushPanelState(): QuickBrushPanelState {+ return {+ visible: true,+ orientation: 'vertical',+ position: null,+ locked: false,+ keepVisibleWhenPalettesHidden: true,+ tileSize: 'medium',+ columns: 1,+ previewStyle: 'tip',+ showNames: true,+ showTitle: true,+ title: 'Favorites',+ showCategoryColors: true,+ opacity: 0.95,+ showHideUiButton: false,+ brushIds: [...DEFAULT_QUICK_BRUSH_IDS],+ };+}+export const FLOATING_MIN_X = 8;export const FLOATING_MIN_Y = 38;export const FLOATING_MAX_WIDTH = 720;@@ -1289,6 +1330,86 @@ function attachMigratedPanelToLayout(return togglePanelInLayout(layout, panelId);}+export function sanitizeQuickBrushPanelState(raw: unknown): QuickBrushPanelState {+ const defaults = createDefaultQuickBrushPanelState();+ if (!raw || typeof raw !== 'object') return defaults;+ const r = raw as Record<string, unknown>;++ const orientation: QuickBrushPanelOrientation =+ r.orientation === 'horizontal' ? 'horizontal' : 'vertical';++ const tileSize: QuickBrushTileSize =+ r.tileSize === 'compact' || r.tileSize === 'large' ? r.tileSize : 'medium';++ const previewStyle: QuickBrushPreviewStyle = r.previewStyle === 'stroke' ? 'stroke' : 'tip';++ const columns: 1 | 2 = r.columns === 2 ? 2 : 1;++ let position: { x: number; y: number } | null = null;+ if (r.position && typeof r.position === 'object') {+ const pos = r.position as Record<string, unknown>;+ if (+ typeof pos.x === 'number' &&+ Number.isFinite(pos.x) &&+ typeof pos.y === 'number' &&+ Number.isFinite(pos.y)+ ) {+ position = { x: Math.round(pos.x), y: Math.round(pos.y) };+ }+ }++ const opacity =+ typeof r.opacity === 'number' && Number.isFinite(r.opacity)+ ? Math.max(0.4, Math.min(1, Math.round(r.opacity * 100) / 100))+ : defaults.opacity;++ const title =+ typeof r.title === 'string' && r.title.trim().length > 0+ ? r.title.trim().slice(0, 28)+ : defaults.title;++ let brushIds: BrushPresetId[] = defaults.brushIds;+ if (Array.isArray(r.brushIds)) {+ const seen = new Set<string>();+ const cleaned: BrushPresetId[] = [];+ for (const item of r.brushIds) {+ if (typeof item === 'string' && item.trim()) {+ const migrated = migrateLegacyPresetId(item.trim());+ if (!seen.has(migrated)) {+ seen.add(migrated);+ cleaned.push(migrated);+ }+ }+ }+ brushIds = cleaned;+ }++ return {+ visible: typeof r.visible === 'boolean' ? r.visible : defaults.visible,+ orientation,+ position,+ locked: typeof r.locked === 'boolean' ? r.locked : defaults.locked,+ keepVisibleWhenPalettesHidden:+ typeof r.keepVisibleWhenPalettesHidden === 'boolean'+ ? r.keepVisibleWhenPalettesHidden+ : defaults.keepVisibleWhenPalettesHidden,+ tileSize,+ columns,+ previewStyle,+ showNames: typeof r.showNames === 'boolean' ? r.showNames : defaults.showNames,+ showTitle: typeof r.showTitle === 'boolean' ? r.showTitle : defaults.showTitle,+ title,+ showCategoryColors:+ typeof r.showCategoryColors === 'boolean'+ ? r.showCategoryColors+ : defaults.showCategoryColors,+ opacity,+ showHideUiButton:+ typeof r.showHideUiButton === 'boolean' ? r.showHideUiButton : defaults.showHideUiButton,+ brushIds,+ };+}+export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {return {version: 1,@@ -1297,10 +1418,13 @@ export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {savedCustomLayout: null,quickAccessItems: DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x })),quickAccessViewMode: 'grid',+ quickBrushPanel: createDefaultQuickBrushPanelState(),commandBarIds: [...DEFAULT_COMMAND_BAR_IDS],showStatusBar: true,showDocumentTabs: true,showCommandBar: true,+ navigatorPreviewMode: 'color',+ navigatorSplitRatio: DEFAULT_NAVIGATOR_SPLIT_RATIO,migratedPanels: [...AUTO_MIGRATED_PANELS],};}@@ -1347,7 +1471,16 @@ export function loadWorkspaceState(): PersistedWorkspaceState {const quickAccessItems = sanitizeQuickAccessItems(parsed.quickAccessItems);const quickAccessViewMode: QuickAccessViewMode =parsed.quickAccessViewMode === 'list' ? 'list' : 'grid';+ const quickBrushPanel = sanitizeQuickBrushPanelState(parsed.quickBrushPanel);const commandBarIds = sanitizeCommandBarIds(parsed.commandBarIds);+ const navigatorPreviewMode: NavigatorPreviewMode =+ parsed.navigatorPreviewMode === 'bw' || parsed.navigatorPreviewMode === 'split'+ ? parsed.navigatorPreviewMode+ : 'color';+ const navigatorSplitRatio =+ typeof parsed.navigatorSplitRatio === 'number'+ ? clampNavigatorSplitRatio(parsed.navigatorSplitRatio)+ : DEFAULT_NAVIGATOR_SPLIT_RATIO;return {version: 1,@@ -1356,10 +1489,13 @@ export function loadWorkspaceState(): PersistedWorkspaceState {savedCustomLayout,quickAccessItems,quickAccessViewMode,+ quickBrushPanel,commandBarIds,showStatusBar: typeof parsed.showStatusBar === 'boolean' ? parsed.showStatusBar : true,showDocumentTabs: typeof parsed.showDocumentTabs === 'boolean' ? parsed.showDocumentTabs : true,showCommandBar: typeof parsed.showCommandBar === 'boolean' ? parsed.showCommandBar : true,+ navigatorPreviewMode,+ navigatorSplitRatio,migratedPanels: Array.from(existingMigrated),};} catch {