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
1.2.1
sora2fb44dd8c266
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex efa7e35..9b1ad61 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,67 @@# Changelog+## v1.2.1++### New+- Added 36 new built-in artist brushes across every category+- Added a new `Texture & FX` (`FX`) brush category with 10 illustration and environment brushes+- Added an upgraded Time-lapse Studio with a live in-app preview player so you can watch your time-lapse at `15s`, `30s`, `60s`, `2m`, `Full`, or a custom length right inside the app before exporting+- Added full playback controls to the time-lapse preview, including timeline scrubbing, frame-by-frame stepping, loop toggle, and `0.5×` / `1×` / `2×` playback speed+- Added Full-Screen preview mode (`F` or double-click the preview) with auto-hiding controls and quick clip-length switching (`15s`, `30s`, `60s`, `2m`, `Full`)+- Added a Capture Area selector so you can record `Artwork only` (clean upright canvas), `Canvas view` (your live pan, zoom, rotation, and flip), or `App window` (the entire Ink Studio window and panels), along with a Maximum capture size option (`720p`, `1080p`, `2K`, `4K`)+- Added Watermark support for time-lapses+- Added a local Library tab in Time-lapse Studio to browse, load/continue, or delete saved time-lapse recordings to free up disk space+- Added support for importing Clip Studio Paint color sets (`.cls`) and PNG color palettes (`.png`) in the Color Sets panel (via the menu or drag-and-drop)+- Renamed the `Sub View` panel to `References` and upgraded it with a PureRef-style Board mode so you can place, view, zoom, pan, rotate, and flip multiple reference images in one space+- Added full individual card controls on the References board+- Added 1-click Auto-Arrange layouts (`Pack Grid`, `Horizontal Strip`, and `Vertical Stack`) and direct clipboard pasting (`Ctrl+V` or the Paste button) in the References panel+- Added an automatic Color Palette Extractor (`Key`) in the References panel that pulls the main colors from your active reference into clickable swatches, plus a live value percentage readout (`V%`) when sampling colors+- Added Search & Filter in the Layers panel so you can quickly find layers+- Added Layer Color Labels (8 colors plus None) assignable from the layer header or right-click menu+- Added Solo / Isolate Layer: `Alt+Click` any layer's eye icon (or pick `Solo / Isolate Layer` from the right-click menu) to temporarily hide everything except that layer+- Added a `Discard All Sessions` button to the crash recovery modal+- Added interactive on-canvas cropping and resizing directly inside Resize Canvas (`Edit` -> `Resize Canvas...`) so you can drag corner and edge handles right on your artwork to crop in or expand outward+- Added crop-tool controls on the canvas+- Added a 1-click `Selection` button in Resize Canvas to snap the crop frame to your current selection++### Improvements+- Added full folder mask support so masked folders (including Pass-Through folders and Clip Studio Paint Frame Border Folders) properly clip all layers inside them across the canvas, Navigator preview, and exports+- Imported `.clip` files now keep each layer's Monochrome / Grayscale expression settings, Black & White ink toggles, Layer Color tint, and Frame Border panel outlines+- Built-in brush tips now load in small steps in the background so startup stays fast and smooth even with a much larger brush library+- Time-lapse recordings are no longer stored inside `.ink` project files+- Older `.ink` files that already contain embedded time-lapse frames are automatically moved to local storage when opened+- Optimized time-lapse capture so recording stays out of the way while you draw, skips unchanged frames automatically, and runs smoothly even on large canvases+- Improved time-lapse preview scrubbing and video export smoothness+- Opening a `.ink` file now loads it directly in Ink Studio instead of opening a blank canvas+- Opening a `.ink` file while Ink Studio is already running now opens it in the existing app window instead of launching a second window+- Pressing `Ctrl+S` on a `.ink` file opened from your computer now saves directly back to that file without any problems+- Made saving and resaving (`Ctrl+S`) `.ink` projects faster and safer, using atomic writes to prevent corrupted files+- Save As and Export Image now pick the file location and format before processing, so canceling is instant and switching formats always exports in the selected type+- Resaving the same project after restarting now updates its existing Recent Documents entry instead of creating duplicates+- Reworked text rendering so letters use natural spacing and look crisp and authentic on the canvas, matching what you see while typing+- Your latest text settings (font, size, color, spacing, alignment, style, and outline options) now save automatically and stay remembered across sessions+- Clicking outside the text box or switching to another tool now automatically applies your text instead of losing it+- Turned the Resize Canvas window into a non-blocking, draggable, collapsible floating panel+- Manual crops and canvas expansions now also keep vector layers, text, speech balloons, and manga frames properly aligned++### Bug Fixes+- Fixed Clip Studio Paint (`.clip`) manga files created in real-world units (mm, cm, inches, pt, or Q) opening cropped to a tiny corner instead of their full page+- Fixed black-only Monochrome and Grayscale ink layers in `.clip` files sometimes appearing invisible or pure white when opened+- Fixed Paper and Solid Fill layers (including non-English Paper layers) in `.clip` files sometimes opening with missing or wrong colors+- Fixed layer masks and manga frame masks in `.clip` files sometimes showing the whole page instead of hiding masked areas+- Fixed 1-bit black-and-white manga `.psd` files opening tinted red instead of black and white+- Fixed the page drop shadow appearing as four dark dots at the corners instead of a smooth shadow around the canvas+- Fixed a ghosted duplicate of the canvas (with curved corner cutouts) appearing when opening files, resizing the viewport, or exporting large transparent images+- Fixed the canvas border and drop shadow disappearing while panning, zooming, rotating, or with Layer Stack Caching turned off+- Fixed artwork along the edges of large canvases slightly bleeding past the page border when zoomed out+- Fixed some built-in brush stroke previews occasionally showing up blank in the Sub Tool list until you clicked or scrolled past them+- Fixed filenames accumulating repeated extensions after multiple saves, exports, and restarts (e.g. `file_name.ink.ink.png.ink`)+- Fixed `Ctrl+S` overwriting/renaming issues on reopened files and prevented overlapping saves when pressing `Ctrl+S` rapidly+- Fixed new text accidentally switching to your current brush color (such as black) instead of keeping your saved text color+- Fixed outlines overlapping neighboring letters when Text Outline is turned on+- Fixed text shifting slightly in position or width when applying it to the canvas+- Fixed double-vision ghosting behind the live preview when re-editing an existing text layer+## v1.2.0### Newdiff --git a/README.md b/README.mdindex 8efecc6..d633e63 100644--- a/README.md+++ b/README.md@@ -15,11 +15,11 @@ No subscriptions, no login, and no AI tools. Everything runs offline on your com## Highlights- **Real paint mixing & Brush Studio**: Pigment color mixing across brushes, smudge, blur, and gradients (blue and yellow actually make green), 3D impasto texture, Dual and Ribbon brushes, 26 Decoration brushes, rotating brush outlines, custom brush groups, and a live test scratchpad. Imports Clip Studio Paint `.sut` brushes and saves/loads `.inkb` files.-- **Color & values**: Interactive 3D Color Sphere that can float anywhere over your canvas, 1-click B&W Value Check (`Shift+Y`), live Color / B&W Split View in the Navigator (`Alt+Shift+Y`), Color Wheel, Sliders, and a built-in Sub View reference window.-- **Drawing & editing**: Responsive Wintab and Windows Ink stylus support with stabilization, QuickShape, Enclose and Fill, Paint Unfilled Area, live Lasso Fill, multi-layer Liquify, Puppet Warp (`Ctrl+Shift+T`), Cage Transform, Mesh Warp, rotatable Gradient Meshes, Retouch tools (Smudge, Blur, Dodge, Burn, Clone), editable Vector layers, Tone Curves, Levels, Gradient Maps, Color Balance, and Filters.+- **Color & values**: Interactive 3D Color Sphere that can float anywhere over your canvas, 1-click B&W Value Check (`Shift+Y`), live Color / B&W Split View in the Navigator (`Alt+Shift+Y`), Color Wheel, Sliders, Color Sets (`.cls` & `.png` palette import), and a built-in PureRef-style References board with automatic palette extraction.+- **Drawing & editing**: Responsive Wintab and Windows Ink stylus support with stabilization, QuickShape, Enclose and Fill, Paint Unfilled Area, live Lasso Fill, multi-layer Liquify, Puppet Warp (`Ctrl+Shift+T`), Cage Transform, Mesh Warp, rotatable Gradient Meshes, interactive on-canvas crop & resize, Retouch tools (Smudge, Blur, Dodge, Burn, Clone), editable Vector layers, Tone Curves, Levels, Gradient Maps, Color Balance, and Filters.- **Comics, manga & perspective**: Panel border folders, resizable speech bubbles, horizontal and vertical text, screentones, manga effect lines, straight and 1/2/3-point perspective rulers with brush snapping, plus 9:16 Webtoon preview and chapter slice export.- **3D reference**: Drag and drop `.glb`, `.gltf`, or `.obj` models or add built-in 3D shapes (Cube, Sphere, Capsule, Cylinder, Pyramid), pose the 3D mannequin, adjust lights and ground shadows, sync camera angles to perspective rulers, or bake clean lineart and tones.-- **Animation & time-lapse**: Frame-by-frame cel animation timeline with onion skinning, plus background time-lapse recording saved right inside `.ink` files so recording resumes automatically when you reopen your project.+- **Animation & time-lapse**: Frame-by-frame cel animation timeline with onion skinning, plus an in-app Time-lapse Studio with live preview player, custom capture areas, watermarks, and a local recording library.- **Draw together live**: Start a shared canvas with a short P2P room code (`INK-XXXX-XXXXXX`), over local Wi-Fi, or with a web link so friends can join right from their browser (up to 16 people). Includes live cursors, room chat, Host/Editor/Viewer roles, layer locking, follow-peer view, and sharing brushes live.- **Flexible workspace & Appearance Studio**: Choose from six calibrated dark and light look presets (`Graphite Atelier`, `Obsidian OLED`, `Studio Neutral 18%`, `Warm Paper Light`, `Daylight Crisp`, `Sumi Sepia`), tune OKLCH surface brightness/contrast/warmth, chrome style (`Flat`, `Hairline`, `Islands`), and pigment accents live, switch between `Default Illustration`, `Photoshop Studio`, `Clip Studio`, `Manga Studio`, and `Minimalist Tablet` layouts, or jump into Focus Mode (`Tab`) with floating Atelier HUDs. Detach any panel into a floating window, pin favorite brushes to Quick Brushes (`Shift+B`), scale the interface (`60%` to `200%`), customize any shortcut in Settings (`Ctrl+,`), and rely on automatic crash recovery.diff --git a/package-lock.json b/package-lock.jsonindex 8a34aa2..7937055 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "ink-studio",- "version": "1.2.0",+ "version": "1.2.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "ink-studio",- "version": "1.2.0",+ "version": "1.2.1","license": "GPL-3.0","dependencies": {"@tailwindcss/vite": "^4.3.3",diff --git a/package.json b/package.jsonindex a90f570..19f9e7f 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "ink-studio","private": true,- "version": "1.2.0",+ "version": "1.2.1","description": "Collaborative Drawing Studio","author": "Sora","license": "GPL-3.0",diff --git a/site/index.html b/site/index.htmlindex b3a46a6..6c1acc2 100644--- a/site/index.html+++ b/site/index.html@@ -534,10 +534,10 @@</div><div class="detail-row">- <h3>Built-in Sub View reference panel</h3>+ <h3>Built-in References board</h3><p>- Keep photo references tucked inside Sub View so you can pan, zoom, and eyedrop colors- directly from them while working.+ Arrange photo references on a PureRef-style board inside the References panel so you can+ pan, zoom, extract palettes, and eyedrop colors directly while working.</p></div>diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex c889632..68b7459 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2021,7 +2021,7 @@ dependencies = [[[package]]name = "ink-studio"-version = "1.2.0"+version = "1.2.1"dependencies = ["axum","flate2",@@ -2040,6 +2040,7 @@ dependencies = ["tauri-build","tauri-plugin-opener","tauri-plugin-process",+ "tauri-plugin-single-instance","tauri-plugin-updater","tokio","tower-http 0.5.2",@@ -4433,6 +4434,22 @@ dependencies = ["tauri-plugin",]+[[package]]+name = "tauri-plugin-single-instance"+version = "2.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"+dependencies = [+ "serde",+ "serde_json",+ "tauri",+ "thiserror 2.0.21",+ "tokio",+ "tracing",+ "windows-sys 0.61.2",+ "zbus",+]+[[package]]name = "tauri-plugin-updater"version = "2.14.1"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 82d945f..7dcca2c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "ink-studio"-version = "1.2.0"+version = "1.2.1"description = "Collaborative Drawing Studio"authors = ["Sora"]license = "GPL-3.0"@@ -57,6 +57,7 @@ windows-sys = { version = "0.59", features = [] }[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]+tauri-plugin-single-instance = "2"tauri-plugin-updater = "2"diff --git a/src-tauri/src/clip_parser.rs b/src-tauri/src/clip_parser.rsindex 0af8167..30b3eb8 100644--- a/src-tauri/src/clip_parser.rs+++ b/src-tauri/src/clip_parser.rs@@ -260,7 +260,13 @@ struct ParsedOffscreenAttribute {bitmap_height: u32,block_grid_width: u32,block_grid_height: u32,+ channel_order: u32,+ channel_bytes: u32,+ image_channel_count: u32,+ pixel_bytes: u32,default_fill: u32,+ init_do_initialize: bool,+ init_alpha: u8,init_color: Option<[u8; 4]>,}@@ -274,6 +280,28 @@ fn normalize_color_channel_u64(v: u64) -> u8 {}}+/// Converts a CSP canvas dimension (`CanvasWidth` / `CanvasHeight`) from `CanvasUnit` to pixels.+/// CSP CanvasUnit enum: 0 = px, 1 = cm, 2 = mm, 3 = in, 4 = pt (1/72 in), 5 = Q (0.25 mm).+fn convert_csp_canvas_dim_to_px(raw_val: f64, unit: i64, dpi: f64) -> f64 {+ if !raw_val.is_finite() || raw_val <= 0.0 {+ return raw_val;+ }+ let safe_dpi = if dpi.is_finite() && dpi > 0.0 {+ dpi+ } else {+ 300.0+ };+ match unit {+ 0 => raw_val,+ 1 => raw_val * safe_dpi / 2.54,+ 2 => raw_val * safe_dpi / 25.4,+ 3 => raw_val * safe_dpi,+ 4 => raw_val * safe_dpi / 72.0,+ 5 => raw_val * 0.25 * safe_dpi / 25.4,+ _ => raw_val,+ }+}+fn parse_offscreen_attribute(blob: Option<&[u8]>,fallback_w: u32,@@ -284,7 +312,13 @@ fn parse_offscreen_attribute(bitmap_height: fallback_h,block_grid_width: fallback_w.div_ceil(TILE_SIZE as u32).max(1),block_grid_height: fallback_h.div_ceil(TILE_SIZE as u32).max(1),+ channel_order: 0,+ channel_bytes: 1,+ image_channel_count: 0,+ pixel_bytes: 0,default_fill: 0,+ init_do_initialize: false,+ init_alpha: 0,init_color: None,};@@ -322,8 +356,29 @@ fn parse_offscreen_attribute(def.bitmap_height = read_u32_be(blob, p + 4).unwrap_or(fallback_h);def.block_grid_width = read_u32_be(blob, p + 8).unwrap_or(def.block_grid_width);def.block_grid_height = read_u32_be(blob, p + 12).unwrap_or(def.block_grid_height);- if p + 20 <= blob.len() {- def.default_fill = read_u32_be(blob, p + 16).unwrap_or(0);+ if p + 24 <= blob.len() {+ let v4 = read_u32_be(blob, p + 16).unwrap_or(0);+ let v5 = read_u32_be(blob, p + 20).unwrap_or(0);+ // Real CSP Parameter puts BlockDataChannelOrder at +16 (1, 17, 33, ...) and+ // BlockDataChannelBytes (>= 1) at +20. Only legacy synthetic blobs have v5 == 0+ // with default_fill (0 or 1) at +16.+ if v5 == 0 && v4 <= 1 {+ def.default_fill = v4;+ } else {+ def.channel_order = v4;+ def.channel_bytes = v5;+ if p + 32 <= blob.len() {+ def.image_channel_count = read_u32_be(blob, p + 24).unwrap_or(0);+ def.pixel_bytes = read_u32_be(blob, p + 28).unwrap_or(0);+ }+ }+ } else if p + 20 <= blob.len() {+ let v4 = read_u32_be(blob, p + 16).unwrap_or(0);+ if v4 <= 1 {+ def.default_fill = v4;+ } else {+ def.channel_order = v4;+ }}}}@@ -332,21 +387,76 @@ fn parse_offscreen_attribute(if let Some(init_idx) = find_bytes(blob, t_init, 0) {let p = init_idx + t_init.len();if p + 20 <= blob.len() {- let enabled = read_u32_be(blob, p).unwrap_or(0);- if enabled == 1 {+ let first = read_u32_be(blob, p).unwrap_or(0);+ if first == 20 {+ // Real CSP InitColor chunk layout:+ // [0]: header_bytes (20)+ // [1]: InitColorDataDoInitialize (0 or 1)+ // [2]: InitColorDataAlphaValue (0..0xFFFFFFFF)+ // [3]: InitColorDataImageValueCount (0..4)+ // [4]: element_bytes (4)+ // [5..]: InitColorDataImageValue00..+ let do_init = read_u32_be(blob, p + 4).unwrap_or(0);+ let alpha_raw = read_u32_be(blob, p + 8).unwrap_or(0) as u64;+ let val_count = read_u32_be(blob, p + 12).unwrap_or(0) as usize;+ let elem_size = read_u32_be(blob, p + 16).unwrap_or(4);+ def.init_do_initialize = do_init != 0;+ def.init_alpha = if do_init != 0 {+ normalize_color_channel_u64(alpha_raw)+ } else {+ 0+ };+ def.default_fill = if def.init_do_initialize && def.init_alpha > 0 {+ 1+ } else {+ 0+ };+ if def.init_do_initialize+ && elem_size == 4+ && val_count > 0+ && val_count <= 10+ && p + 20 + val_count * 4 <= blob.len()+ {+ if val_count >= 3 {+ let v0 = read_u32_be(blob, p + 20).unwrap_or(0) as u64;+ let v1 = read_u32_be(blob, p + 24).unwrap_or(0) as u64;+ let v2 = read_u32_be(blob, p + 28).unwrap_or(0) as u64;+ let n0 = normalize_color_channel_u64(v0);+ let n1 = normalize_color_channel_u64(v1);+ let n2 = normalize_color_channel_u64(v2);+ // Color BGRX offscreens store B, G, R, X order+ let (r, g, b) = if def.channel_order == 33 {+ (n2, n1, n0)+ } else {+ (n0, n1, n2)+ };+ def.init_color = Some([r, g, b, def.init_alpha]);+ } else if val_count == 1 {+ let g = normalize_color_channel_u64(+ read_u32_be(blob, p + 20).unwrap_or(0) as u64,+ );+ def.init_color = Some([g, g, g, def.init_alpha]);+ }+ }+ } else if first == 1 {+ // Legacy / compact InitColor layout: [enabled=1, c0, c1, c2, c3]let c0 = read_u32_be(blob, p + 4).unwrap_or(0) as u64;let c1 = read_u32_be(blob, p + 8).unwrap_or(0) as u64;let c2 = read_u32_be(blob, p + 12).unwrap_or(0) as u64;let c3 = read_u32_be(blob, p + 16).unwrap_or(0) as u64;+ let alpha = if c3 > 0 {+ normalize_color_channel_u64(c3)+ } else {+ 255+ };+ def.init_do_initialize = true;+ def.init_alpha = alpha;+ def.default_fill = if alpha > 0 { 1 } else { 0 };def.init_color = Some([normalize_color_channel_u64(c0),normalize_color_channel_u64(c1),normalize_color_channel_u64(c2),- if c3 > 0 {- normalize_color_channel_u64(c3)- } else {- 255- },+ alpha,]);}}@@ -535,8 +645,39 @@ fn parse_block_data_payload_parallel(out}+#[derive(Debug, Clone, Copy)]+struct CspTileDecodeOpts {+ single_plane_ink_white: bool,+ express_black: bool,+ express_white: bool,+ apply_bw_filter: bool,+}++impl Default for CspTileDecodeOpts {+ fn default() -> Self {+ Self {+ single_plane_ink_white: false,+ express_black: true,+ express_white: true,+ apply_bw_filter: false,+ }+ }+}+/// Decodes a decompressed 256x256 CSP tile into RGBA8. Returns None if fully transparent.fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {+ decode_csp_tile_to_rgba_with_opts(+ raw,+ CspTileDecodeOpts {+ single_plane_ink_white: default_fill == 1,+ express_black: true,+ express_white: true,+ apply_bw_filter: false,+ },+ )+}++fn decode_csp_tile_to_rgba_with_opts(raw: &[u8], opts: CspTileDecodeOpts) -> Option<Vec<u8>> {let len = raw.len();let mut out = vec![0u8; BYTES_32BIT];let mut has_pixels = false;@@ -587,24 +728,41 @@ fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {// 3. Grayscale 2-plane: Alpha(65536) + Gray(65536) = 131072if len >= TILE_PIXELS * 2 {let gray = &raw[TILE_PIXELS..];+ if opts.apply_bw_filter && !opts.express_black && !opts.express_white {+ return None;+ }for p in 0..TILE_PIXELS {let a = raw[p];if a != 0 {let g = gray[p];- let di = p << 2;- out[di] = g;- out[di + 1] = g;- out[di + 2] = g;- out[di + 3] = a;- has_pixels = true;+ let (out_g, out_a) = if opts.apply_bw_filter && opts.express_black && !opts.express_white {+ let eff_a = (((a as u32) * (255u32 - g as u32) + 127) / 255) as u8;+ (0u8, eff_a)+ } else if opts.apply_bw_filter && !opts.express_black && opts.express_white {+ let eff_a = (((a as u32) * (g as u32) + 127) / 255) as u8;+ (255u8, eff_a)+ } else {+ (g, a)+ };+ if out_a != 0 {+ let di = p << 2;+ out[di] = out_g;+ out[di + 1] = out_g;+ out[di + 2] = out_g;+ out[di + 3] = out_a;+ has_pixels = true;+ }}}return if has_pixels { Some(out) } else { None };}- // 4. Single-channel 8-bit (65536): Alpha-only ink+ // 4. Single-channel 8-bit (65536): Alpha-only ink (black unless white-only expression color)if len >= TILE_PIXELS {- let ink = if default_fill == 1 { 255u8 } else { 0u8 };+ if opts.apply_bw_filter && !opts.express_black && !opts.express_white {+ return None;+ }+ let ink = if opts.single_plane_ink_white { 255u8 } else { 0u8 };for p in 0..TILE_PIXELS {let a = raw[p];if a != 0 {@@ -619,8 +777,11 @@ fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {return if has_pixels { Some(out) } else { None };}- // 5. Monochrome 2-plane 1-bit (16384)+ // 5. Monochrome 2-plane 1-bit (16384): Alpha bits (8192) + Color bits (8192, 0=black, 1=white)if len >= 16384 {+ if opts.apply_bw_filter && !opts.express_black && !opts.express_white {+ return None;+ }for byte_idx in 0..8192 {let a_byte = raw[byte_idx];if a_byte == 0 {@@ -631,7 +792,13 @@ fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {for bit in 0..8 {let mask = 1u8 << (7 - bit);if (a_byte & mask) != 0 {- let c = if (c_byte & mask) != 0 { 255 } else { 0 };+ let is_white = (c_byte & mask) != 0;+ if opts.apply_bw_filter+ && ((is_white && !opts.express_white) || (!is_white && !opts.express_black))+ {+ continue;+ }+ let c = if is_white { 255 } else { 0 };let di = (base_p + bit) << 2;out[di] = c;out[di + 1] = c;@@ -644,9 +811,12 @@ fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {return if has_pixels { Some(out) } else { None };}- // 6. Monochrome 1-plane 1-bit (8192)+ // 6. Monochrome 1-plane 1-bit (8192): Ink bits (black unless white-only expression color)if len >= 8192 {- let ink = if default_fill == 1 { 255u8 } else { 0u8 };+ if opts.apply_bw_filter && !opts.express_black && !opts.express_white {+ return None;+ }+ let ink = if opts.single_plane_ink_white { 255u8 } else { 0u8 };for byte_idx in 0..8192 {let a_byte = raw[byte_idx];if a_byte == 0 {@@ -832,6 +1002,47 @@ struct MipmapInfoRecord {next_index: i64,}+fn is_csp_fill_or_paper_layer(+ layer_row: &SqlRow,+ attr: Option<&ParsedOffscreenAttribute>,+) -> bool {+ let layer_type = get_i64(layer_row, &["LayerType"], -1);+ let has_mono_fill_info = get_bytes(layer_row, &["MonochromeFillInfo"]).is_some();+ let has_init_fill = attr.map_or(false, |a| a.init_do_initialize && a.init_alpha > 0);+ let name = get_str(layer_row, &["LayerName"], "").trim().to_lowercase();+ let is_paper_name = matches!(+ name.as_str(),+ "paper" | "用紙" | "papier" | "papel" | "бумага" | "紙"+ );+ layer_type == 1584 || layer_type == 1280 || has_mono_fill_info || has_init_fill || is_paper_name+}++fn extract_draw_color_main_hex(layer_row: &SqlRow) -> Option<String> {+ let (r, g, b) = (+ get_opt_i64(layer_row, &["DrawColorMainRed"])?,+ get_opt_i64(layer_row, &["DrawColorMainGreen"])?,+ get_opt_i64(layer_row, &["DrawColorMainBlue"])?,+ );+ Some(rgb_to_hex(+ normalize_color_channel_u64(r.max(0) as u64),+ normalize_color_channel_u64(g.max(0) as u64),+ normalize_color_channel_u64(b.max(0) as u64),+ ))+}++fn extract_draw_color_sub_hex(layer_row: &SqlRow) -> Option<String> {+ let (r, g, b) = (+ get_opt_i64(layer_row, &["DrawColorSubRed"])?,+ get_opt_i64(layer_row, &["DrawColorSubGreen"])?,+ get_opt_i64(layer_row, &["DrawColorSubBlue"])?,+ );+ Some(rgb_to_hex(+ normalize_color_channel_u64(r.max(0) as u64),+ normalize_color_channel_u64(g.max(0) as u64),+ normalize_color_channel_u64(b.max(0) as u64),+ ))+}+fn extract_solid_fill_color(layer_row: &SqlRow,attr: Option<&ParsedOffscreenAttribute>,@@ -863,6 +1074,16 @@ fn extract_solid_fill_color());}}++ let is_fill_or_paper = is_csp_fill_or_paper_layer(layer_row, attr);+ // Real CSP Paper, Solid Fill, and Simple Tone Fill layers (LayerType 1584 / MonochromeFillInfo /+ // InitColor.doInitialize=1) store their fill color in DrawColorMainRed/Green/Blue (0..0xFFFFFFFF).+ if is_fill_or_paper {+ if let Some(hex) = extract_draw_color_main_hex(layer_row) {+ return Some(hex);+ }+ }+if let Some(a) = attr {if let Some(ic) = a.init_color {if ic[3] > 0 {@@ -871,11 +1092,15 @@ fn extract_solid_fill_color(}}let name = get_str(layer_row, &["LayerName"], "").trim().to_lowercase();- let is_paper_name = matches!(name.as_str(), "paper" | "用紙" | "papier" | "papel");+ let is_paper_name = matches!(+ name.as_str(),+ "paper" | "用紙" | "papier" | "papel" | "бумага" | "紙"+ );let layer_type = get_i64(layer_row, &["LayerType"], -1);if is_paper_name|| (is_bottom_most && attr.map_or(false, |a| a.default_fill == 1))|| layer_type == 1280+ || layer_type == 1584{return Some("#ffffff".to_string());}@@ -893,23 +1118,55 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {let conn = open_readonly_mem_sqlite(sqlite_data)?;let tables = get_table_names(&conn);- // 1. Canvas metadata+ // 1. Canvas metadata (converting physical CanvasUnit mm/cm/in/pt/Q -> pixels using CanvasResolution)let mut width = 1440u32;let mut height = 900u32;let mut dpi = 300u32;+ let mut canvas_unit = 0i64;let mut root_folder_id: Option<i64> = None;let canvas_rows = query_table(&conn, &tables, "Canvas");if let Some(c) = canvas_rows.first() {- width = (get_f64(c, &["CanvasWidth"], 1440.0).round() as i64).clamp(1, MAX_CANVAS_DIM as i64)- as u32;- height = (get_f64(c, &["CanvasHeight"], 900.0).round() as i64)- .clamp(1, MAX_CANVAS_DIM as i64) as u32;- dpi = (get_f64(c, &["CanvasResolution", "CanvasDpi"], 300.0).round() as i64).clamp(1, 2400)- as u32;+ let raw_dpi = get_f64(c, &["CanvasResolution", "CanvasDpi"], 300.0);+ dpi = (raw_dpi.round() as i64).clamp(1, 2400) as u32;+ canvas_unit = get_i64(c, &["CanvasUnit"], 0);+ let raw_w = get_f64(c, &["CanvasWidth"], 1440.0);+ let raw_h = get_f64(c, &["CanvasHeight"], 900.0);+ let px_w = convert_csp_canvas_dim_to_px(raw_w, canvas_unit, raw_dpi);+ let px_h = convert_csp_canvas_dim_to_px(raw_h, canvas_unit, raw_dpi);+ width = (px_w.round() as i64).clamp(1, MAX_CANVAS_DIM as i64) as u32;+ height = (px_h.round() as i64).clamp(1, MAX_CANVAS_DIM as i64) as u32;root_folder_id = get_opt_i64(c, &["CanvasRootFolder"]);}+ // Read LayerThumbnail to collect thumbnail offscreen IDs (to exclude from render fallback)+ // and authoritative integer pixel canvas dimensions written by CSP.+ let mut referenced_as_thumbnail_offscreen = HashSet::<i64>::new();+ let mut thumb_canvas_dims: Option<(u32, u32)> = None;+ for row in query_table(&conn, &tables, "LayerThumbnail") {+ let toff = get_i64(&row, &["ThumbnailOffscreen"], 0);+ if toff > 0 {+ referenced_as_thumbnail_offscreen.insert(toff);+ }+ if thumb_canvas_dims.is_none() {+ let tw = get_i64(&row, &["ThumbnailCanvasWidth"], 0);+ let th = get_i64(&row, &["ThumbnailCanvasHeight"], 0);+ if tw > 0 && th > 0 && tw <= MAX_CANVAS_DIM as i64 && th <= MAX_CANVAS_DIM as i64 {+ thumb_canvas_dims = Some((tw as u32, th as u32));+ }+ }+ }+ if let Some((tw, th)) = thumb_canvas_dims {+ // When CanvasUnit is physical (mm/cm/in/pt/Q) or unknown, CSP's ThumbnailCanvasWidth/Height+ // stores CSP's exact integer pixel rounding (avoiding ±1 px unit-conversion drift).+ if canvas_unit != 0+ && (width.abs_diff(tw) <= 8 && height.abs_diff(th) <= 8 || canvas_unit > 5)+ {+ width = tw;+ height = th;+ }+ }+// 2. Preview imagelet mut preview: Option<(Vec<u8>, String)> = None;let preview_rows = query_table(&conn, &tables, "CanvasPreview");@@ -954,7 +1211,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {main_id,MipmapInfoRecord {offscreen_id: get_i64(&row, &["Offscreen"], 0),- this_scale: get_f64(&row, &["ThisScale"], 1.0),+ this_scale: get_f64(&row, &["ThisScale"], 100.0),next_index: get_i64(&row, &["NextIndex"], 0),},);@@ -1005,34 +1262,50 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {}}+ // Resolve full-resolution (highest ThisScale: 100.0 in real CSP or 1.0 in unit-scale files)+ // offscreen from a Mipmap linked list, breaking scale ties in favor of offscreens present in Exta.let resolve_mipmap_to_offscreen = |mipmap_id: i64| -> Option<OffscreenRecord> {if mipmap_id <= 0 {return None;}let mut info_id = *mipmap_base_info.get(&mipmap_id)?;- let mut best: Option<OffscreenRecord> = None;+ let mut best: Option<(f64, bool, OffscreenRecord)> = None;let mut seen = HashSet::new();while info_id > 0 && seen.insert(info_id) {let Some(info) = mipmap_info_by_id.get(&info_id) else {break;};if let Some(off) = offscreen_by_id.get(&info.offscreen_id) {- if (info.this_scale - 1.0).abs() < 0.001 {- return Some(off.clone());- }- if best.is_none() {- best = Some(off.clone());+ let scale = if info.this_scale.is_finite() && info.this_scale > 0.0 {+ info.this_scale+ } else {+ 0.0+ };+ let has_exta =+ !off.block_data_id.is_empty() && exta_chunks.contains_key(&off.block_data_id);+ let replace = match &best {+ None => true,+ Some((best_scale, best_has_exta, _)) => {+ if (scale - *best_scale).abs() < 0.001 {+ has_exta && !*best_has_exta+ } else {+ scale > *best_scale+ }+ }+ };+ if replace {+ best = Some((scale, has_exta, off.clone()));}}info_id = info.next_index;}- best+ best.map(|(_, _, off)| off)};// 5. Layer treelet layer_rows = query_table(&conn, &tables, "Layer");let mut layer_row_by_id = HashMap::<i64, &SqlRow>::new();- let mut referenced_as_mask_offscreen = HashSet::<i64>::new();+ let mut referenced_as_special_offscreen = HashSet::<i64>::new();for row in &layer_rows {let mid = get_i64(row, &["MainId"], -1);if mid < 0 {@@ -1041,7 +1314,30 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {layer_row_by_id.insert(mid, row);let mask_mm = get_i64(row, &["LayerLayerMaskMipmap", "LayerMaskMipmap"], 0);if let Some(off) = resolve_mipmap_to_offscreen(mask_mm) {- referenced_as_mask_offscreen.insert(off.main_id);+ referenced_as_special_offscreen.insert(off.main_id);+ }+ let frame_mm = get_i64(row, &["ComicFrameLineMipmap"], 0);+ if let Some(off) = resolve_mipmap_to_offscreen(frame_mm) {+ referenced_as_special_offscreen.insert(off.main_id);+ }+ }++ // If physical CanvasUnit was used and LayerThumbnail was absent, refine ±1 px rounding against+ // the root folder's or Paper layer's full-scale Offscreen.Attribute bitmap dimensions.+ if canvas_unit != 0 && thumb_canvas_dims.is_none() {+ if let Some(rr) = root_folder_id.and_then(|id| layer_row_by_id.get(&id).copied()) {+ let root_mm = get_i64(rr, &["LayerRenderMipmap"], 0);+ if let Some(off) = resolve_mipmap_to_offscreen(root_mm) {+ let a = parse_offscreen_attribute(off.attribute.as_deref(), width, height);+ if a.bitmap_width > 0+ && a.bitmap_height > 0+ && (width.abs_diff(a.bitmap_width) <= 8 && height.abs_diff(a.bitmap_height) <= 8+ || canvas_unit > 5)+ {+ width = a.bitmap_width;+ height = a.bitmap_height;+ }+ }}}@@ -1069,6 +1365,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {render_offscreen: Option<OffscreenRecord>,row: &'a SqlRow,is_bottom_most_root: bool,+ is_frame_border_overlay: bool,}let resolve_render_offscreen = |row: &SqlRow, main_id: i64| -> Option<OffscreenRecord> {@@ -1086,7 +1383,9 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {let mut best: Option<OffscreenRecord> = None;let mut best_area: u64 = 0;for c in cands {- if referenced_as_mask_offscreen.contains(&c.main_id) {+ if referenced_as_special_offscreen.contains(&c.main_id)+ || referenced_as_thumbnail_offscreen.contains(&c.main_id)+ {continue;}if c.block_data_id.is_empty() || !exta_chunks.contains_key(&c.block_data_id) {@@ -1135,6 +1434,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {seq: &mut usize,plans: &mut Vec<LayerPlan<'a>>,layer_row_by_id: &HashMap<i64, &'a SqlRow>,+ exta_chunks: &HashMap<String, &'a [u8]>,resolve_render: &dyn Fn(&SqlRow, i64) -> Option<OffscreenRecord>,resolve_mipmap: &dyn Fn(i64) -> Option<OffscreenRecord>,) {@@ -1152,6 +1452,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {let lock_val = get_i64(row, &["LayerLock"], 0);let clip_val = get_i64(row, &["LayerClip"], 0);let layer_select = get_opt_i64(row, &["LayerSelect"]);+ let masking_val = get_opt_i64(row, &["LayerMasking"]);let base_ox = parent_ox + get_f64(row, &["LayerOffsetX", "LayerMoveOffsetX"], 0.0);let base_oy = parent_oy + get_f64(row, &["LayerOffsetY", "LayerMoveOffsetY"], 0.0);@@ -1179,17 +1480,15 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {.round() as i32;let render_offscreen = resolve_render(row, main_id);+ let comic_frame_mm = get_i64(row, &["ComicFrameLineMipmap"], 0);+ let comic_frame_offscreen = resolve_mipmap(comic_frame_mm).filter(|off| {+ !off.block_data_id.is_empty() && exta_chunks.contains_key(&off.block_data_id)+ });let is_folder = layer_folder.map_or(false, |v| v != 0)|| first_child_id > 0+ || comic_frame_mm > 0|| (layer_folder.is_none() && layer_type == 0 && render_offscreen.is_none());- *seq += 1;- let id = format!(- "csp-{}-{}-{}",- if is_folder { "folder" } else { "layer" },- main_id,- *seq- );let blend_mode = map_csp_blend_mode(composite_val).to_string();let opacity = (raw_opacity / 256.0).clamp(0.0, 1.0) as f32;let visible = (vis_val & 1) != 0;@@ -1201,13 +1500,66 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {let mask_mm = get_i64(row, &["LayerLayerMaskMipmap", "LayerMaskMipmap"], 0);let mask_offscreen = resolve_mipmap(mask_mm);- let mask_enabled = if row.contains_key("LayerVisibility") {- (vis_val & 2) != 0+ let mask_enabled = if mask_offscreen.is_some() {+ let vis_has_mask_bit = (vis_val & 2) != 0;+ let masking_enabled_bit = masking_val.map_or(false, |m| (m & 1) != 0 || (m & 32) != 0);+ if vis_has_mask_bit || masking_enabled_bit {+ true+ } else if comic_frame_mm > 0 {+ // Frame border folders mask their contents unless explicitly disabled+ !masking_val.map_or(false, |m| (m & 2) != 0 && (m & 1) == 0)+ } else {+ !row.contains_key("LayerVisibility") && !row.contains_key("LayerMasking")+ }} else {- true+ false};let mask_linked = layer_select.map_or(true, |v| (v & 256) != 0);+ // Emit rasterized Comic Frame Border lines immediately ABOVE the frame folder so borders+ // render crisply on top of panel artwork without being clipped by the folder's inner mask.+ if is_folder {+ if let Some(frame_off) = comic_frame_offscreen {+ *seq += 1;+ plans.push(LayerPlan {+ id: format!("csp-frame-border-{}-{}", main_id, *seq),+ name: format!("{} (Border)", name),+ is_folder: false,+ visible,+ opacity,+ blend_mode: if blend_mode == "pass-through" {+ "normal".to_string()+ } else {+ blend_mode.clone()+ },+ locked,+ alpha_locked: false,+ clipped: false,+ collapsed: false,+ parent_id: parent_id.clone(),+ offset_x: base_ox.round() as i32,+ offset_y: base_oy.round() as i32,+ mask_offset_x: 0,+ mask_offset_y: 0,+ mask_enabled: false,+ mask_linked: true,+ mask_offscreen: None,+ render_offscreen: Some(frame_off),+ row,+ is_bottom_most_root: false,+ is_frame_border_overlay: true,+ });+ }+ }++ *seq += 1;+ let id = format!(+ "csp-{}-{}-{}",+ if is_folder { "folder" } else { "layer" },+ main_id,+ *seq+ );+plans.push(LayerPlan {id: id.clone(),name,@@ -1230,6 +1582,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {render_offscreen,row,is_bottom_most_root,+ is_frame_border_overlay: false,});if is_folder && first_child_id > 0 {@@ -1246,6 +1599,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {seq,plans,layer_row_by_id,+ exta_chunks,resolve_render,resolve_mipmap,);@@ -1300,6 +1654,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {&mut seq,&mut plans,&layer_row_by_id,+ &exta_chunks,&resolve_render_offscreen,&resolve_mipmap_to_offscreen,);@@ -1325,6 +1680,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {&mut seq,&mut plans,&layer_row_by_id,+ &exta_chunks,&resolve_render_offscreen,&resolve_mipmap_to_offscreen,);@@ -1341,7 +1697,13 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {// Decode mask if presentlet mask = plan.mask_offscreen.as_ref().map(|mo| {let attr = parse_offscreen_attribute(mo.attribute.as_deref(), width, height);- let default_val = if attr.default_fill != 0 { 255u8 } else { 0u8 };+ let default_val = if attr.init_do_initialize {+ attr.init_alpha+ } else if attr.default_fill != 0 {+ 255u8+ } else {+ 0u8+ };let mut gray = vec![default_val; (width as usize) * (height as usize)];if let Some(&payload) = exta_chunks.get(&mo.block_data_id) {@@ -1407,6 +1769,12 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {collapsed: plan.collapsed,parent_id: plan.parent_id,solid_fill_hex: None,+ expression_color: None,+ mono_express_black: None,+ mono_express_white: None,+ layer_color_enabled: None,+ layer_color: None,+ layer_sub_color: None,tiles: Vec::new(),mask,};@@ -1417,6 +1785,44 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {.as_ref().map(|ro| parse_offscreen_attribute(ro.attribute.as_deref(), width, height));+ // Read CSP expression color & black/white ink flags+ let color_type_idx = if plan.is_frame_border_overlay {+ get_opt_i64(plan.row, &["ComicFrameColorTypeIndex", "LayerColorTypeIndex"])+ } else {+ get_opt_i64(plan.row, &["LayerColorTypeIndex"])+ };+ let black_checked_opt = if plan.is_frame_border_overlay {+ get_opt_i64(+ plan.row,+ &["ComicFrameColorTypeBlackChecked", "LayerColorTypeBlackChecked"],+ )+ } else {+ get_opt_i64(plan.row, &["LayerColorTypeBlackChecked"])+ };+ let white_checked_opt = if plan.is_frame_border_overlay {+ get_opt_i64(+ plan.row,+ &["ComicFrameColorTypeWhiteChecked", "LayerColorTypeWhiteChecked"],+ )+ } else {+ get_opt_i64(plan.row, &["LayerColorTypeWhiteChecked"])+ };+ let express_black = black_checked_opt.map_or(true, |v| v != 0);+ let express_white = white_checked_opt.map_or(true, |v| v != 0);+ let is_bw_expr = matches!(color_type_idx, Some(1 | 2));+ let single_plane_ink_white = if black_checked_opt.is_some() || white_checked_opt.is_some() {+ express_white && !express_black+ } else {+ attr.as_ref().map_or(false, |a| a.default_fill == 1)+ };+ let decode_opts = CspTileDecodeOpts {+ single_plane_ink_white,+ express_black,+ express_white,+ apply_bw_filter: is_bw_expr+ && (black_checked_opt.is_some() || white_checked_opt.is_some()),+ };+let mut tile_map: HashMap<(i32, i32), Vec<u8>> = HashMap::new();if let (Some(ro), Some(a)) = (&plan.render_offscreen, &attr) {if let Some(&payload) = exta_chunks.get(&ro.block_data_id) {@@ -1427,11 +1833,19 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {let valid_right = doc_w_i32.min(plan.offset_x + a.bitmap_width as i32);let valid_bottom = doc_h_i32.min(plan.offset_y + a.bitmap_height as i32);+ let mut populated_indices: HashSet<usize> = HashSet::new();+ if a.init_do_initialize && a.init_alpha > 0 {+ for (bidx, _) in &blocks {+ populated_indices.insert(*bidx);+ }+ }+// Decode tiles in parallellet decoded_tiles: Vec<(usize, Vec<u8>)> = blocks.into_par_iter().filter_map(|(bidx, raw)| {- decode_csp_tile_to_rgba(&raw, a.default_fill).map(|rgba| (bidx, rgba))+ decode_csp_tile_to_rgba_with_opts(&raw, decode_opts)+ .map(|rgba| (bidx, rgba))}).collect();@@ -1449,6 +1863,34 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {valid_bottom,);}++ // If this layer has non-transparent InitColor and only some blocks were written,+ // fill the remaining untouched blocks with the layer's initialized color.+ if a.init_do_initialize && a.init_alpha > 0 && !populated_indices.is_empty() {+ let ic = a.init_color.unwrap_or([255, 255, 255, a.init_alpha]);+ let mut solid_tile = vec![0u8; BYTES_32BIT];+ for px in solid_tile.chunks_exact_mut(4) {+ px.copy_from_slice(&ic);+ }+ let cap_expected = expected.min(MAX_BLOCKS_PER_LAYER);+ for bidx in 0..cap_expected {+ if populated_indices.contains(&bidx) {+ continue;+ }+ let col = (bidx % gw) as i32;+ let row_i = (bidx / gw) as i32;+ let tile_dx = col * TILE_SIZE as i32 + plan.offset_x;+ let tile_dy = row_i * TILE_SIZE as i32 + plan.offset_y;+ blit_offset_tile_into_map(+ &mut tile_map,+ &solid_tile,+ tile_dx,+ tile_dy,+ valid_right,+ valid_bottom,+ );+ }+ }}}@@ -1457,7 +1899,7 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {.map(|((tx, ty), rgba)| RawTile { tx, ty, rgba }).collect();- let solid_fill_hex = if tiles.is_empty() {+ let solid_fill_hex = if tiles.is_empty() && !plan.is_frame_border_overlay {extract_solid_fill_color(plan.row,attr.as_ref(),@@ -1468,6 +1910,36 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {None};+ let is_solid_fill = solid_fill_hex.is_some() && tiles.is_empty();+ let expression_color = if is_solid_fill {+ None+ } else {+ match color_type_idx {+ Some(1) => Some("gray".to_string()),+ Some(2) => Some("monochrome".to_string()),+ _ => None,+ }+ };+ let (mono_express_black, mono_express_white) =+ if expression_color.as_deref() == Some("monochrome") {+ (Some(express_black), Some(express_white))+ } else {+ (None, None)+ };++ let draw_color_tint = !is_solid_fill+ && !is_csp_fill_or_paper_layer(plan.row, attr.as_ref())+ && get_i64(plan.row, &["DrawColorEnable"], 0) != 0;+ let (layer_color_enabled, layer_color, layer_sub_color) = if draw_color_tint {+ (+ Some(true),+ extract_draw_color_main_hex(plan.row),+ extract_draw_color_sub_hex(plan.row).or_else(|| Some("#ffffff".to_string())),+ )+ } else {+ (None, None, None)+ };+AssembledLayer {id: plan.id,name: plan.name,@@ -1481,6 +1953,12 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {collapsed: false,parent_id: plan.parent_id,solid_fill_hex,+ expression_color,+ mono_express_black,+ mono_express_white,+ layer_color_enabled,+ layer_color,+ layer_sub_color,tiles,mask,}@@ -2288,9 +2766,14 @@ fn decode_csp_layer_to_rgba(if let Ok(conn) = open_readonly_mem_sqlite(sqlite_data) {let tables = get_table_names(&conn);+ let mut canvas_unit = 0i64;for c in query_table(&conn, &tables, "Canvas") {- let cw = get_f64(&c, &["CanvasWidth"], 0.0).round() as i64;- let ch = get_f64(&c, &["CanvasHeight"], 0.0).round() as i64;+ let raw_dpi = get_f64(&c, &["CanvasResolution", "CanvasDpi"], 300.0);+ canvas_unit = get_i64(&c, &["CanvasUnit"], 0);+ let raw_w = get_f64(&c, &["CanvasWidth"], 0.0);+ let raw_h = get_f64(&c, &["CanvasHeight"], 0.0);+ let cw = convert_csp_canvas_dim_to_px(raw_w, canvas_unit, raw_dpi).round() as i64;+ let ch = convert_csp_canvas_dim_to_px(raw_h, canvas_unit, raw_dpi).round() as i64;if cw > 0 && ch > 0 {canvas_w_opt = Some(cw.clamp(1, MAX_MATERIAL_DIM as i64) as u32);canvas_h_opt = Some(ch.clamp(1, MAX_MATERIAL_DIM as i64) as u32);@@ -2298,6 +2781,32 @@ fn decode_csp_layer_to_rgba(}}+ let mut thumbnail_offscreens = HashSet::<i64>::new();+ let mut thumb_canvas_dims: Option<(u32, u32)> = None;+ for row in query_table(&conn, &tables, "LayerThumbnail") {+ let toff = get_i64(&row, &["ThumbnailOffscreen"], 0);+ if toff > 0 {+ thumbnail_offscreens.insert(toff);+ }+ if thumb_canvas_dims.is_none() {+ let tw = get_i64(&row, &["ThumbnailCanvasWidth"], 0);+ let th = get_i64(&row, &["ThumbnailCanvasHeight"], 0);+ if tw > 0 && th > 0 && tw <= MAX_MATERIAL_DIM as i64 && th <= MAX_MATERIAL_DIM as i64+ {+ thumb_canvas_dims = Some((tw as u32, th as u32));+ }+ }+ }+ if let (Some((tw, th)), Some(cw), Some(ch)) = (thumb_canvas_dims, canvas_w_opt, canvas_h_opt)+ {+ if canvas_unit != 0+ && ((cw.abs_diff(tw) <= 8 && ch.abs_diff(th) <= 8) || canvas_unit > 5)+ {+ canvas_w_opt = Some(tw);+ canvas_h_opt = Some(th);+ }+ }+let mut mipmap_base_info = HashMap::<i64, i64>::new();for row in query_table(&conn, &tables, "Mipmap") {let id = get_i64(&row, &["MainId"], -1);@@ -2321,8 +2830,10 @@ fn decode_csp_layer_to_rgba(let main_id = get_i64(&row, &["MainId"], -1);if main_id >= 0 {let off_id = get_i64(&row, &["Offscreen"], 0);- let scale = get_f64(&row, &["ThisScale"], 1.0);- if off_id > 0 && (scale - 1.0).abs() < 0.001 {+ let scale = get_f64(&row, &["ThisScale"], 100.0);+ if off_id > 0+ && ((scale - 100.0).abs() < 0.01 || (scale - 1.0).abs() < 0.001)+ {full_scale_offscreens.insert(off_id);}mipmap_info_by_id.insert(@@ -2365,23 +2876,37 @@ fn decode_csp_layer_to_rgba(return None;}let mut info_id = *mipmap_base_info.get(&mipmap_id)?;- let mut best: Option<OffscreenRecord> = None;+ let mut best: Option<(f64, bool, OffscreenRecord)> = None;let mut seen = HashSet::new();while info_id > 0 && seen.insert(info_id) {let Some(info) = mipmap_info_by_id.get(&info_id) else {break;};if let Some(off) = offscreen_by_id.get(&info.offscreen_id) {- if (info.this_scale - 1.0).abs() < 0.001 {- return Some(off.clone());- }- if best.is_none() {- best = Some(off.clone());+ let scale = if info.this_scale.is_finite() && info.this_scale > 0.0 {+ info.this_scale+ } else {+ 0.0+ };+ let has_exta = !off.block_data_id.is_empty()+ && exta_chunks.contains_key(&off.block_data_id);+ let replace = match &best {+ None => true,+ Some((best_scale, best_has_exta, _)) => {+ if (scale - *best_scale).abs() < 0.001 {+ has_exta && !*best_has_exta+ } else {+ scale > *best_scale+ }+ }+ };+ if replace {+ best = Some((scale, has_exta, off.clone()));}}info_id = info.next_index;}- best+ best.map(|(_, _, off)| off)};let fallback_w = canvas_w_opt.or(xml_meta.width).unwrap_or(TILE_SIZE as u32);@@ -2414,7 +2939,8 @@ fn decode_csp_layer_to_rgba(cands.iter().filter(|c| {- !c.block_data_id.is_empty()+ !thumbnail_offscreens.contains(&c.main_id)+ && !c.block_data_id.is_empty()&& exta_chunks.contains_key(&c.block_data_id)}).max_by_key(|c| {@@ -2458,7 +2984,9 @@ fn decode_csp_layer_to_rgba(if let Some(best) = all_offscreens.into_iter().filter(|c| {- !c.block_data_id.is_empty() && exta_chunks.contains_key(&c.block_data_id)+ !thumbnail_offscreens.contains(&c.main_id)+ && !c.block_data_id.is_empty()+ && exta_chunks.contains_key(&c.block_data_id)}).max_by_key(|c| {let a = parse_offscreen_attribute(@@ -5226,4 +5754,277 @@ mod tests {assert_eq!(decoded_color.expression_color.as_deref(), Some("color"));assert!(!decoded_color.has_sub_color);}++ fn build_real_csp_offscreen_attribute(+ w: u32,+ h: u32,+ channel_order: u32,+ do_init: bool,+ init_alpha: u32,+ init_values: &[u32],+ ) -> Vec<u8> {+ let gw = (w + TILE_SIZE as u32 - 1) / TILE_SIZE as u32;+ let gh = (h + TILE_SIZE as u32 - 1) / TILE_SIZE as u32;+ let mut blob = Vec::new();+ blob.extend_from_slice(&88u32.to_be_bytes());+ blob.extend_from_slice(tag_parameter());+ blob.extend_from_slice(&w.to_be_bytes());+ blob.extend_from_slice(&h.to_be_bytes());+ blob.extend_from_slice(&gw.to_be_bytes());+ blob.extend_from_slice(&gh.to_be_bytes());+ blob.extend_from_slice(&channel_order.to_be_bytes()); // BlockDataChannelOrder (1/17/33)+ blob.extend_from_slice(&1u32.to_be_bytes()); // BlockDataChannelBytes = 1+ blob.extend_from_slice(&1u32.to_be_bytes());+ blob.extend_from_slice(&1u32.to_be_bytes());+ blob.extend_from_slice(&8192u32.to_be_bytes());+ blob.extend_from_slice(&[0u8; 20]);+ blob.extend_from_slice(tag_init_color());+ blob.extend_from_slice(&20u32.to_be_bytes()); // real CSP InitColor header bytes+ blob.extend_from_slice(&(if do_init { 1u32 } else { 0u32 }).to_be_bytes());+ blob.extend_from_slice(&init_alpha.to_be_bytes());+ blob.extend_from_slice(&(init_values.len() as u32).to_be_bytes());+ blob.extend_from_slice(&4u32.to_be_bytes());+ for &v in init_values {+ blob.extend_from_slice(&v.to_be_bytes());+ }+ blob+ }++ #[test]+ fn test_manga_clip_physical_units_monochrome_ink_paper_and_frame_folder() {+ // Test physical CanvasUnit = 2 (mm), 600 DPI -> 257x364 mm == 6071x8598 px,+ // scaled down here to 21.674667 mm x 10.837333 mm @ 600 DPI == 512x256 px for fast test tiles.+ let conn = Connection::open_in_memory().unwrap();+ conn.execute_batch(+ "+ CREATE TABLE Canvas (+ CanvasWidth REAL, CanvasHeight REAL, CanvasResolution REAL,+ CanvasUnit INTEGER, CanvasRootFolder INTEGER+ );+ CREATE TABLE LayerThumbnail (+ MainId INTEGER, ThumbnailOffscreen INTEGER,+ ThumbnailCanvasWidth INTEGER, ThumbnailCanvasHeight INTEGER+ );+ CREATE TABLE Layer (+ MainId INTEGER, LayerName TEXT, LayerFolder INTEGER, LayerFirstChildIndex INTEGER,+ LayerNextIndex INTEGER, LayerType INTEGER, LayerComposite INTEGER,+ LayerOpacity INTEGER, LayerVisibility INTEGER, LayerLock INTEGER,+ LayerClip INTEGER, LayerMasking INTEGER,+ LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER, ComicFrameLineMipmap INTEGER,+ LayerOffsetX REAL, LayerOffsetY REAL,+ LayerColorTypeIndex INTEGER, LayerColorTypeBlackChecked INTEGER, LayerColorTypeWhiteChecked INTEGER,+ DrawColorEnable INTEGER, DrawColorMainRed INTEGER, DrawColorMainGreen INTEGER, DrawColorMainBlue INTEGER+ );+ CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);+ CREATE TABLE MipmapInfo (MainId INTEGER, Offscreen INTEGER, ThisScale REAL, NextIndex INTEGER);+ CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);+ ",+ )+ .unwrap();++ // 21.674667 mm @ 600 DPI = 512 px; 10.837333 mm @ 600 DPI = 256 px+ conn.execute(+ "INSERT INTO Canvas VALUES (21.674667, 10.837333, 600.0, 2, 1)",+ [],+ )+ .unwrap();+ // Thumbnail offscreen 999 must be excluded from render fallbacks+ conn.execute("INSERT INTO LayerThumbnail VALUES (1, 999, 512, 256)", [])+ .unwrap();++ // Root (1) -> Paper (2, LayerType=1584, cream DrawColor) -> FrameFolder (3, with mask + border) -> MonoInk (4, child of FrameFolder)+ conn.execute(+ "INSERT INTO Layer VALUES (1, '', 1, 2, 0, 256, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL)",+ [],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Layer VALUES (2, '用紙', 0, 0, 3, 1584, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, 1, 4294967295, 4042322160, 3772834016)",+ [],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Layer VALUES (3, 'Frame 1', 17, 4, 0, 0, 30, 256, 3, 0, 0, 1, 0, 20, 30, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL)",+ [],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Layer VALUES (4, 'MonoInk', 0, 0, 0, 1, 0, 256, 1, 0, 0, 0, 10, 0, 0, 0, 0, 2, 1, 0, NULL, NULL, NULL, NULL)",+ [],+ )+ .unwrap();++ // Mipmaps using real CSP percentage ThisScale = 100.0 (plus a 50.0 lower-res sibling)+ conn.execute("INSERT INTO Mipmap VALUES (10, 100)", []).unwrap();+ conn.execute("INSERT INTO MipmapInfo VALUES (100, 1000, 100.0, 101)", [])+ .unwrap();+ conn.execute("INSERT INTO MipmapInfo VALUES (101, 1001, 50.0, 0)", [])+ .unwrap();++ // Folder mask mipmap (20) & Frame border mipmap (30)+ conn.execute("INSERT INTO Mipmap VALUES (20, 200)", []).unwrap();+ conn.execute("INSERT INTO MipmapInfo VALUES (200, 2000, 100.0, 0)", [])+ .unwrap();+ conn.execute("INSERT INTO Mipmap VALUES (30, 300)", []).unwrap();+ conn.execute("INSERT INTO MipmapInfo VALUES (300, 3000, 100.0, 0)", [])+ .unwrap();++ // Real CSP attributes:+ // - MonoInk offscreen 1000: BlockDataChannelOrder = 1, InitColor doInitialize = 0+ // - Mask offscreen 2000: BlockDataChannelOrder = 1, InitColor doInitialize = 0 (hidden outside panel!)+ // - Frame border offscreen 3000: BlockDataChannelOrder = 1, InitColor doInitialize = 0+ let mono_attr = build_real_csp_offscreen_attribute(512, 256, 1, false, 0, &[]);+ let mask_attr = build_real_csp_offscreen_attribute(512, 256, 1, false, 0, &[]);+ let border_attr = build_real_csp_offscreen_attribute(512, 256, 1, false, 0, &[]);++ conn.execute(+ "INSERT INTO Offscreen VALUES (1000, 4, 'ext_mono', ?1)",+ rusqlite::params![mono_attr.as_slice()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Offscreen VALUES (1001, 4, 'ext_mono_half', NULL)",+ [],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Offscreen VALUES (2000, 3, 'ext_mask', ?1)",+ rusqlite::params![mask_attr.as_slice()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Offscreen VALUES (3000, 3, 'ext_border', ?1)",+ rusqlite::params![border_attr.as_slice()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO Offscreen VALUES (999, 2, 'ext_thumb', NULL)",+ [],+ )+ .unwrap();++ let sqlite_bytes = conn.serialize(DatabaseName::Main).unwrap().to_vec();++ // 1-plane 1-bit black ink tile (8192 bytes): pixel (0, 0) inked+ let mut mono_tile = vec![0u8; 8192];+ mono_tile[0] = 0x80;+ // 1-plane 8-bit mask tile (65536 bytes): pixel (1, 1) revealed (255), pixel (2, 2) hidden (0)+ let mut mask_tile = vec![0u8; TILE_PIXELS];+ mask_tile[TILE_SIZE + 1] = 255;+ // 1-plane 1-bit frame border tile (8192 bytes): pixel (4, 0) inked black+ let mut border_tile = vec![0u8; 8192];+ border_tile[0] = 0x08;++ let mut clip = Vec::new();+ clip.extend_from_slice(b"CSFCHUNK");+ clip.extend_from_slice(&[0u8; 16]);+ clip.extend_from_slice(&build_exta("ext_mono", &build_block_payload(&mono_tile)));+ clip.extend_from_slice(&build_exta("ext_mask", &build_block_payload(&mask_tile)));+ clip.extend_from_slice(&build_exta("ext_border", &build_block_payload(&border_tile)));+ clip.extend_from_slice(&build_chunk(b"SQLi", &sqlite_bytes));+ clip.extend_from_slice(&build_chunk(b"Foot", &[]));++ let wire = parse_clip_to_binary(&clip).expect("parse_clip_to_binary failed");+ let meta_len = u32::from_le_bytes(wire[8..12].try_into().unwrap()) as usize;+ let meta: serde_json::Value = serde_json::from_slice(&wire[12..12 + meta_len]).unwrap();+ let blobs = &wire[12 + meta_len..];++ assert_eq!(meta["width"], 512);+ assert_eq!(meta["height"], 256);+ assert_eq!(meta["dpi"], 600);++ // Top-to-bottom order: Frame 1 (Border), Frame 1 (folder), MonoInk (child), 用紙 (Paper)+ let layers = meta["layers"].as_array().unwrap();+ assert_eq!(layers.len(), 4);++ assert_eq!(layers[0]["name"], "Frame 1 (Border)");+ assert_eq!(layers[0]["type"], "raster");+ let bt = &layers[0]["tiles"][0];+ let b_off = bt["offset"].as_u64().unwrap() as usize;+ let b_len = bt["len"].as_u64().unwrap() as usize;+ let b_rgba = lz4_flex::block::decompress(&blobs[b_off..b_off + b_len], BYTES_32BIT).unwrap();+ assert_eq!(&b_rgba[4 * 4..4 * 4 + 4], &[0, 0, 0, 255]);++ assert_eq!(layers[1]["name"], "Frame 1");+ assert_eq!(layers[1]["type"], "folder");+ let folder_mask = &layers[1]["mask"];+ assert_eq!(folder_mask["enabled"], true);+ assert_eq!(folder_mask["defaultColor"], 0);+ let m_off = folder_mask["offset"].as_u64().unwrap() as usize;+ let m_len = folder_mask["len"].as_u64().unwrap() as usize;+ let m_gray = lz4_flex::block::decompress(&blobs[m_off..m_off + m_len], 512 * 256).unwrap();+ assert_eq!(m_gray[512 + 1], 255); // revealed inside panel+ assert_eq!(m_gray[512 * 2 + 2], 0); // hidden outside panel+ assert_eq!(m_gray[512 * 200 + 400], 0); // untouched block defaults to 0 (NOT 255!)++ assert_eq!(layers[2]["name"], "MonoInk");+ assert_eq!(layers[2]["parentId"], layers[1]["id"]);+ assert_eq!(layers[2]["expressionColor"], "monochrome");+ assert_eq!(layers[2]["monoExpressBlack"], true);+ assert_eq!(layers[2]["monoExpressWhite"], false);+ let mt = &layers[2]["tiles"][0];+ let mt_off = mt["offset"].as_u64().unwrap() as usize;+ let mt_len = mt["len"].as_u64().unwrap() as usize;+ let m_rgba =+ lz4_flex::block::decompress(&blobs[mt_off..mt_off + mt_len], BYTES_32BIT).unwrap();+ // Black-only 1-plane monochrome ink MUST decode as opaque BLACK, not invisible white!+ assert_eq!(&m_rgba[0..4], &[0, 0, 0, 255]);++ // Non-English LayerType=1584 Paper with custom cream DrawColorMain*+ assert_eq!(layers[3]["name"], "用紙");+ assert_eq!(layers[3]["solidFillHex"], "#fff0e0");+ }++ #[test]+ fn test_real_mori_clip_decodes_full_b4_dimensions_and_monochrome_layers() {+ let path = std::path::Path::new(r"C:\Users\sosor\Downloads\AyuGram Desktop\mori.clip");+ if !path.exists() {+ return;+ }+ let bytes = std::fs::read(path).expect("failed to read mori.clip");+ let wire = parse_clip_to_binary(&bytes).expect("parse_clip_to_binary failed on mori.clip");+ assert_eq!(&wire[0..4], b"INKD");+ let meta_len = u32::from_le_bytes(wire[8..12].try_into().unwrap()) as usize;+ let meta: serde_json::Value = serde_json::from_slice(&wire[12..12 + meta_len]).unwrap();+ let blobs = &wire[12 + meta_len..];++ // Exact B4 600 DPI dimensions (257x364 mm -> 6071x8598 px, NOT 257x364!)+ assert_eq!(meta["width"], 6071);+ assert_eq!(meta["height"], 8598);+ assert_eq!(meta["dpi"], 600);+ assert!(meta["preview"].is_object());++ let layers = meta["layers"].as_array().unwrap();+ assert_eq!(layers.len(), 5);++ // Bottom layer is Paper (#ffffff solid fill)+ assert_eq!(layers[4]["name"], "Paper");+ assert_eq!(layers[4]["solidFillHex"], "#ffffff");++ // Top 4 layers are monochrome ink layers with tiles spanning far beyond 257x364+ let mut max_tx = 0i64;+ let mut max_ty = 0i64;+ let mut black_pixels = 0usize;+ for layer in &layers[0..4] {+ assert_eq!(layer["expressionColor"], "monochrome");+ let tiles = layer["tiles"].as_array().unwrap();+ assert!(!tiles.is_empty(), "expected decoded tiles on {}", layer["name"]);+ for t in tiles {+ max_tx = max_tx.max(t["tx"].as_i64().unwrap());+ max_ty = max_ty.max(t["ty"].as_i64().unwrap());+ }+ // Spot-check first tile contains opaque black ink pixels+ let t0 = &tiles[0];+ let off = t0["offset"].as_u64().unwrap() as usize;+ let len = t0["len"].as_u64().unwrap() as usize;+ let rgba = lz4_flex::block::decompress(&blobs[off..off + len], BYTES_32BIT).unwrap();+ black_pixels += rgba+ .chunks_exact(4)+ .filter(|px| px[3] == 255 && px[0] == 0 && px[1] == 0 && px[2] == 0)+ .count();+ }+ assert!(max_tx >= 20, "expected tiles across full 6071px width, max_tx={}", max_tx);+ assert!(max_ty >= 30, "expected tiles across full 8598px height, max_ty={}", max_ty);+ assert!(black_pixels > 1000, "expected black ink pixels in monochrome layers");+ }}diff --git a/src-tauri/src/doc_wire.rs b/src-tauri/src/doc_wire.rsindex 167ca3e..fbb71ab 100644--- a/src-tauri/src/doc_wire.rs+++ b/src-tauri/src/doc_wire.rs@@ -59,6 +59,18 @@ pub struct ParsedLayerMeta {pub collapsed: bool,pub parent_id: Option<String>,pub solid_fill_hex: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub expression_color: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mono_express_black: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mono_express_white: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub layer_color_enabled: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub layer_color: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub layer_sub_color: Option<String>,pub tiles: Vec<ParsedTileRef>,pub mask: Option<ParsedMaskRef>,}@@ -106,6 +118,12 @@ pub struct AssembledLayer {pub collapsed: bool,pub parent_id: Option<String>,pub solid_fill_hex: Option<String>,+ pub expression_color: Option<String>,+ pub mono_express_black: Option<bool>,+ pub mono_express_white: Option<bool>,+ pub layer_color_enabled: Option<bool>,+ pub layer_color: Option<String>,+ pub layer_sub_color: Option<String>,pub tiles: Vec<RawTile>,pub mask: Option<RawMask>,}@@ -412,6 +430,12 @@ pub fn pack_parsed_document(collapsed: cl.layer.collapsed,parent_id: cl.layer.parent_id,solid_fill_hex: cl.layer.solid_fill_hex,+ expression_color: cl.layer.expression_color,+ mono_express_black: cl.layer.mono_express_black,+ mono_express_white: cl.layer.mono_express_white,+ layer_color_enabled: cl.layer.layer_color_enabled,+ layer_color: cl.layer.layer_color,+ layer_sub_color: cl.layer.layer_sub_color,tiles: tile_refs,mask: mask_ref,});diff --git a/src-tauri/src/file_open.rs b/src-tauri/src/file_open.rsnew file mode 100644index 0000000..64d5618--- /dev/null+++ b/src-tauri/src/file_open.rs@@ -0,0 +1,317 @@+use std::collections::HashSet;+use std::path::{Path, PathBuf};+use std::sync::{LazyLock, Mutex};++pub const OPEN_FILES_EVENT: &str = "inkstudio://open-files";++/// Extensions accepted when files are opened via OS file association / CLI args / `RunEvent::Opened`.+pub const OPENABLE_LAUNCH_EXTS: &[&str] = &[+ "ink", "inkb", "psd", "psb", "clip", "csp", "lip", "sut", "sora", "png", "jpg", "jpeg",+ "webp", "bmp", "gif", "svg", "cls",+];++#[derive(Default)]+struct OpenFileQueueState {+ frontend_ready: bool,+ pending: Vec<String>,+}++static OPEN_FILE_QUEUE: LazyLock<Mutex<OpenFileQueueState>> =+ LazyLock::new(|| Mutex::new(OpenFileQueueState::default()));++/// Strip Windows verbatim prefix (`\\?\C:\...` -> `C:\...`, `\\?\UNC\server\share` -> `\\server\share`)+/// so paths sent to the frontend are clean and consistent with user-facing paths.+pub fn normalize_display_path(path: &Path) -> String {+ let raw = path.to_string_lossy();+ #[cfg(target_os = "windows")]+ {+ if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") {+ return format!(r"\\{}", rest);+ }+ if let Some(rest) = raw.strip_prefix(r"\\?\") {+ return rest.to_string();+ }+ }+ raw.into_owned()+}++fn path_dedup_key(path: &str) -> String {+ #[cfg(target_os = "windows")]+ {+ path.replace('/', "\\").to_ascii_lowercase()+ }+ #[cfg(not(target_os = "windows"))]+ {+ path.to_string()+ }+}++fn percent_decode_url_path(input: &str) -> String {+ let bytes = input.as_bytes();+ let mut out = Vec::with_capacity(bytes.len());+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == b'%' && i + 2 < bytes.len() {+ if let (Some(hi), Some(lo)) = (+ (bytes[i + 1] as char).to_digit(16),+ (bytes[i + 2] as char).to_digit(16),+ ) {+ out.push(((hi << 4) | lo) as u8);+ i += 3;+ continue;+ }+ }+ out.push(bytes[i]);+ i += 1;+ }+ String::from_utf8_lossy(&out).into_owned()+}++/// Converts a raw CLI argument or `file://` URL into a candidate filesystem path,+/// resolving relative paths against `cwd` when supplied.+pub fn parse_arg_to_candidate_path(raw: &str, cwd: Option<&Path>) -> Option<PathBuf> {+ let trimmed = raw.trim().trim_matches('"').trim();+ if trimmed.is_empty() || trimmed.contains('\0') {+ return None;+ }++ // Handle file:// URLs (e.g. macOS RunEvent::Opened or desktop launchers)+ if trimmed.len() >= 7 && trimmed[..7].eq_ignore_ascii_case("file://") {+ let rest = &trimmed[7..];+ let without_host = if let Some(after_localhost) = rest+ .strip_prefix("localhost/")+ .or_else(|| rest.strip_prefix("LOCALHOST/"))+ {+ format!("/{}", after_localhost)+ } else {+ rest.to_string()+ };+ let decoded = percent_decode_url_path(&without_host);+ // Strip leading slash before Windows drive letter: "/C:/foo.ink" -> "C:/foo.ink"+ let bytes = decoded.as_bytes();+ let normalized = if bytes.len() >= 3+ && bytes[0] == b'/'+ && bytes[1].is_ascii_alphabetic()+ && bytes[2] == b':'+ {+ &decoded[1..]+ } else {+ &decoded+ };+ return Some(PathBuf::from(normalized));+ }++ // Ignore CLI flags like `--dev` or `-psn_0_1234` unless a literal file with that name exists.+ if trimmed.starts_with('-') {+ let candidate = match cwd {+ Some(dir) => dir.join(trimmed),+ None => PathBuf::from(trimmed),+ };+ return if candidate.is_file() {+ Some(candidate)+ } else {+ None+ };+ }++ let p = PathBuf::from(trimmed);+ if p.is_absolute() {+ Some(p)+ } else if let Some(dir) = cwd {+ Some(dir.join(p))+ } else {+ Some(p)+ }+}++fn has_openable_extension(path: &Path) -> bool {+ path.extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_ascii_lowercase())+ .map(|ext| OPENABLE_LAUNCH_EXTS.contains(&ext.as_str()))+ .unwrap_or(false)+}++/// Filters, validates (regular non-symlink file with supported extension), canonicalizes,+/// registers via `register_allowed`, and deduplicates openable file paths from OS args.+pub fn extract_openable_file_paths<I, S, F>(+ args: I,+ cwd: Option<&Path>,+ mut register_allowed: F,+) -> Vec<String>+where+ I: IntoIterator<Item = S>,+ S: AsRef<str>,+ F: FnMut(&Path),+{+ let mut out = Vec::new();+ let mut seen = HashSet::new();++ for raw in args {+ let Some(candidate) = parse_arg_to_candidate_path(raw.as_ref(), cwd) else {+ continue;+ };+ if !has_openable_extension(&candidate) {+ continue;+ }+ let Ok(meta) = std::fs::symlink_metadata(&candidate) else {+ continue;+ };+ if meta.file_type().is_symlink() || !meta.is_file() {+ continue;+ }+ let Ok(canonical) = std::fs::canonicalize(&candidate) else {+ continue;+ };+ if !has_openable_extension(&canonical) {+ continue;+ }++ let display = normalize_display_path(&canonical);+ let key = path_dedup_key(&display);+ if seen.insert(key) {+ register_allowed(&canonical);+ out.push(display);+ }+ }++ out+}++/// Queues paths before the frontend is ready, or returns the paths to emit immediately+/// if the frontend has already mounted its listener and drained startup files.+pub fn enqueue_or_take_for_emit(paths: Vec<String>) -> Option<Vec<String>> {+ if paths.is_empty() {+ return None;+ }+ let Ok(mut state) = OPEN_FILE_QUEUE.lock() else {+ return Some(paths);+ };+ if state.frontend_ready {+ return Some(paths);+ }++ let mut existing_keys: HashSet<String> =+ state.pending.iter().map(|p| path_dedup_key(p)).collect();+ for p in paths {+ let key = path_dedup_key(&p);+ if existing_keys.insert(key) {+ state.pending.push(p);+ }+ }+ None+}++/// Called once by the frontend after registering its `inkstudio://open-files` event listener.+/// Marks the frontend ready and atomically drains any files queued during cold launch.+pub fn mark_frontend_ready_and_take_pending() -> Vec<String> {+ let Ok(mut state) = OPEN_FILE_QUEUE.lock() else {+ return Vec::new();+ };+ state.frontend_ready = true;+ std::mem::take(&mut state.pending)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_plain_quoted_relative_and_file_urls_and_skips_flags() {+ let cwd = PathBuf::from("/tmp/work");++ assert_eq!(parse_arg_to_candidate_path("", Some(&cwd)), None);+ assert_eq!(parse_arg_to_candidate_path("--inspect", Some(&cwd)), None);+ assert_eq!(parse_arg_to_candidate_path("-psn_0_1234", Some(&cwd)), None);++ assert_eq!(+ parse_arg_to_candidate_path("sketch.ink", Some(&cwd)),+ Some(cwd.join("sketch.ink"))+ );+ assert_eq!(+ parse_arg_to_candidate_path("\"quoted.ink\"", Some(&cwd)),+ Some(cwd.join("quoted.ink"))+ );+ assert_eq!(+ parse_arg_to_candidate_path("file:///C:/Users/Artist/My%20Art.ink", None),+ Some(PathBuf::from("C:/Users/Artist/My Art.ink"))+ );+ }++ #[test]+ fn extracts_only_existing_openable_files_and_deduplicates() {+ let dir = std::env::temp_dir().join(format!(+ "inkstudio_file_open_test_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();++ let ink_file = dir.join("Chapter 1.ink");+ let txt_file = dir.join("notes.txt");+ let brush_file = dir.join("gpen.inkb");+ std::fs::write(&ink_file, b"INK2").unwrap();+ std::fs::write(&txt_file, b"ignored").unwrap();+ std::fs::write(&brush_file, b"brush").unwrap();++ let mut registered: Vec<PathBuf> = Vec::new();+ let args = vec![+ "--flag".to_string(),+ "Chapter 1.ink".to_string(),+ ink_file.to_string_lossy().to_string(), // duplicate of relative arg above+ txt_file.to_string_lossy().to_string(), // unsupported extension+ dir.join("missing.ink").to_string_lossy().to_string(), // does not exist+ brush_file.to_string_lossy().to_string(),+ ];++ let extracted = extract_openable_file_paths(&args, Some(&dir), |p| {+ registered.push(p.to_path_buf());+ });++ assert_eq!(extracted.len(), 2);+ assert!(extracted[0].ends_with("Chapter 1.ink"));+ assert!(extracted[1].ends_with("gpen.inkb"));+ assert_eq!(registered.len(), 2);++ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn queue_buffers_before_ready_and_emits_after_ready() {+ {+ let mut state = OPEN_FILE_QUEUE.lock().unwrap();+ state.frontend_ready = false;+ state.pending.clear();+ }++ // Before frontend ready -> buffered, returns None+ assert_eq!(+ enqueue_or_take_for_emit(vec!["C:\\art\\one.ink".to_string()]),+ None+ );+ // Duplicate buffered path is deduplicated+ assert_eq!(+ enqueue_or_take_for_emit(vec![+ "C:\\art\\one.ink".to_string(),+ "C:\\art\\two.ink".to_string()+ ]),+ None+ );++ // Frontend mounts and drains+ let initial = mark_frontend_ready_and_take_pending();+ assert_eq!(+ initial,+ vec!["C:\\art\\one.ink".to_string(), "C:\\art\\two.ink".to_string()]+ );++ // Subsequent drain is empty+ assert!(mark_frontend_ready_and_take_pending().is_empty());++ // After frontend ready -> returned immediately for event emit+ let warm = enqueue_or_take_for_emit(vec!["C:\\art\\three.ink".to_string()]);+ assert_eq!(warm, Some(vec!["C:\\art\\three.ink".to_string()]));+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex c31b96c..88710fd 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,9 +1,11 @@pub mod clip_parser;mod doc_wire;+mod file_open;mod os_hotkeys;mod psd_parser;mod raster_ops;mod recovery;+mod save_dialog;mod scratch_disk;mod server;mod system_perf;@@ -18,11 +20,16 @@ use server::{use std::collections::HashSet;use std::path::{Path, PathBuf};use std::sync::{LazyLock, RwLock};-use tauri::Manager;+use tauri::{Emitter, Manager};static ALLOWED_PATHS: LazyLock<RwLock<HashSet<PathBuf>>> =LazyLock::new(|| RwLock::new(HashSet::new()));+/// Paths explicitly selected by the user in a native OS Save dialog (may not exist on disk yet).+/// Stored as `canonical_parent.join(file_name)` so path traversal is impossible.+static AUTHORIZED_WRITE_PATHS: LazyLock<RwLock<HashSet<PathBuf>>> =+ LazyLock::new(|| RwLock::new(HashSet::new()));+#[tauri::command]async fn start_collab_server(port: Option<u16>,@@ -98,10 +105,12 @@ fn sanitize_id(raw: &str) -> String {}const ALLOWED_DOCUMENT_EXTS: &[&str] = &[- "ink", "inkb", "psd", "psb", "clip", "csp", "sut", "png", "jpg", "jpeg", "webp", "bmp", "gif",- "svg", "avif", "ico", "glb", "gltf", "obj", "sora", // .sora: read-only legacy migrator+ "ink", "inkb", "psd", "psb", "clip", "csp", "lip", "sut", "png", "jpg", "jpeg", "webp", "bmp",+ "gif", "svg", "avif", "ico", "glb", "gltf", "obj", "cls", "json", "sora", // .sora: read-only legacy migrator];+const DIRECT_SAVE_ALLOWED_EXTS: &[&str] = &["ink", "psd", "psb", "png", "jpg", "jpeg", "webp"];+const DELETE_ALLOWED_EXTS: &[&str] = &["ink", "psd", "psb", "clip", "csp", "png", "jpg", "jpeg", "webp", "bmp", "gif", "svg",];@@ -162,6 +171,23 @@ fn header_parse<T: std::str::FromStr>(.map_err(|_| format!("Failed to parse IPC header: {}", name))}+fn header_opt_str(request: &tauri::ipc::Request<'_>, name: &str) -> Option<String> {+ let raw = request.headers().get(name)?.to_str().ok()?;+ let decoded = percent_decode(raw).ok()?;+ if decoded.is_empty() || decoded.contains('\0') {+ return None;+ }+ Some(decoded)+}++fn header_opt_parse<T: std::str::FromStr>(+ request: &tauri::ipc::Request<'_>,+ name: &str,+) -> Option<T> {+ let raw = request.headers().get(name)?.to_str().ok()?;+ raw.parse::<T>().ok()+}+fn raw_body<'a>(request: &'a tauri::ipc::Request<'_>) -> Result<&'a [u8], String> {match request.body() {tauri::ipc::InvokeBody::Raw(bytes) => Ok(bytes.as_slice()),@@ -204,6 +230,80 @@ fn unregister_allowed_path(canonical: &Path) {if let Ok(mut guard) = ALLOWED_PATHS.write() {guard.remove(canonical);}+ if let Ok(mut guard) = AUTHORIZED_WRITE_PATHS.write() {+ guard.remove(canonical);+ }+}++/// Resolves a target save path (which may not exist yet) to `canonical_parent.join(file_name)`+/// after checking extension, rejecting symlinks/directories, and verifying parent exists.+fn resolve_canonical_target_path(path: &Path, allowed_exts: &[&str]) -> Result<PathBuf, String> {+ if !has_allowed_extension(path, allowed_exts) {+ return Err("Refusing to write file with unsupported save extension".to_string());+ }+ let file_name = path+ .file_name()+ .filter(|n| !n.is_empty())+ .ok_or_else(|| "Invalid target filename".to_string())?;+ let parent = path+ .parent()+ .filter(|p| !p.as_os_str().is_empty())+ .ok_or_else(|| "Target file must include a parent directory".to_string())?;+ let canonical_parent = std::fs::canonicalize(parent)+ .map_err(|_| "Target parent directory does not exist".to_string())?;+ let target = canonical_parent.join(file_name);+ if !has_allowed_extension(&target, allowed_exts) {+ return Err("Refusing to write file with unsupported save extension".to_string());+ }+ if let Ok(meta) = std::fs::symlink_metadata(&target) {+ if meta.file_type().is_symlink() {+ return Err("Refusing to overwrite symbolic link".to_string());+ }+ if !meta.is_file() {+ return Err("Target path is not a regular file".to_string());+ }+ }+ Ok(target)+}++fn register_allowed_write_path(path: &Path) {+ if let Ok(resolved) = resolve_canonical_target_path(path, DIRECT_SAVE_ALLOWED_EXTS) {+ if let Ok(mut guard) = AUTHORIZED_WRITE_PATHS.write() {+ guard.insert(resolved);+ }+ }+}++async fn validate_write_path(+ raw_path: &str,+ allowed_dirs: &[PathBuf],+) -> Result<PathBuf, String> {+ if raw_path.is_empty() || raw_path.contains('\0') {+ return Err("Invalid file path".to_string());+ }+ let p = Path::new(raw_path);+ let resolved = resolve_canonical_target_path(p, DIRECT_SAVE_ALLOWED_EXTS)?;++ let in_write_allowlist = AUTHORIZED_WRITE_PATHS+ .read()+ .map(|g| g.contains(&resolved))+ .unwrap_or(false);+ let in_read_allowlist = if resolved.exists() {+ std::fs::canonicalize(&resolved)+ .map(|canon| is_path_authorized(&canon, allowed_dirs))+ .unwrap_or(false)+ } else {+ resolved+ .parent()+ .map(|parent| allowed_dirs.iter().any(|dir| parent.starts_with(dir)))+ .unwrap_or(false)+ };++ if !in_write_allowlist && !in_read_allowlist {+ return Err("Access denied: file is outside authorized InkStudio save paths".to_string());+ }++ Ok(resolved)}fn get_allowed_base_dirs(app: &tauri::AppHandle) -> Vec<PathBuf> {@@ -397,6 +497,33 @@ async fn read_file_binary(Ok(tauri::ipc::Response::new(bytes))}+#[tauri::command]+fn take_pending_open_files() -> Vec<String> {+ file_open::mark_frontend_ready_and_take_pending()+}++#[tauri::command]+async fn write_allowed_file_binary(+ app: tauri::AppHandle,+ request: tauri::ipc::Request<'_>,+) -> Result<usize, String> {+ let raw_path = header_str(&request, "x-path")?;+ let data = raw_body(&request)?;+ if data.len() as u64 > MAX_READ_FILE_BYTES {+ return Err("File payload exceeds 512 MB safety limit".to_string());+ }+ let allowed_dirs = get_allowed_base_dirs(&app);+ let target = validate_write_path(&raw_path, &allowed_dirs).await?;+ let owned = data.to_vec();+ let written = owned.len();+ let target_for_write = target.clone();+ tokio::task::spawn_blocking(move || save_dialog::write_file_atomic(&target_for_write, &owned))+ .await+ .map_err(|e| format!("Atomic write worker failed: {}", e))??;+ register_allowed_path(&target);+ Ok(written)+}+#[tauri::command]async fn recovery_init_session(app: tauri::AppHandle,@@ -494,41 +621,88 @@ async fn scratch_disk_clear(session_id: String) -> Result<(), String> {}#[tauri::command]-async fn timelapse_write_frame(request: tauri::ipc::Request<'_>) -> Result<(), String> {+async fn timelapse_save_meta(+ app: tauri::AppHandle,+ session_id: String,+ meta_json: String,+) -> Result<(), String> {+ timelapse::save_session_meta(&app, &session_id, &meta_json).await+}++#[tauri::command]+async fn timelapse_load_session(+ app: tauri::AppHandle,+ session_id: String,+) -> Result<timelapse::LoadedTimelapseSession, String> {+ timelapse::load_session(&app, &session_id).await+}++#[tauri::command]+async fn timelapse_list_sessions(+ app: tauri::AppHandle,+) -> Result<Vec<timelapse::StoredTimelapseSummary>, String> {+ timelapse::list_sessions(&app).await+}++#[tauri::command]+async fn timelapse_write_frame(+ app: tauri::AppHandle,+ request: tauri::ipc::Request<'_>,+) -> Result<(), String> {let session_id = header_str(&request, "x-session-id")?;let frame_index: u32 = header_parse(&request, "x-frame-index")?;let ext = header_str(&request, "x-ext")?;let data = raw_body(&request)?;- timelapse::write_frame(&session_id, frame_index, &ext, data).await+ let meta = match (+ header_opt_parse::<u64>(&request, "x-timestamp"),+ header_opt_parse::<u32>(&request, "x-width"),+ header_opt_parse::<u32>(&request, "x-height"),+ ) {+ (Some(timestamp), Some(width), Some(height)) => Some(timelapse::FrameWriteMeta {+ timestamp,+ width,+ height,+ capture_area: header_opt_str(&request, "x-capture-area"),+ }),+ _ => None,+ };+ timelapse::write_frame(&app, &session_id, frame_index, &ext, data, meta).await}#[tauri::command]-async fn timelapse_write_frames_batch(request: tauri::ipc::Request<'_>) -> Result<usize, String> {+async fn timelapse_write_frames_batch(+ app: tauri::AppHandle,+ 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+ timelapse::write_frames_batch(&app, &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+async fn timelapse_list_frames(+ app: tauri::AppHandle,+ session_id: String,+) -> Result<Vec<(u32, String)>, String> {+ timelapse::list_frames(&app, &session_id).await}#[tauri::command]async fn timelapse_read_frame(+ app: tauri::AppHandle,request: tauri::ipc::Request<'_>,) -> Result<tauri::ipc::Response, String> {let session_id = header_str(&request, "x-session-id")?;let frame_index: u32 = header_parse(&request, "x-frame-index")?;let ext = header_str(&request, "x-ext")?;- let bytes = timelapse::read_frame(&session_id, frame_index, &ext).await?;+ let bytes = timelapse::read_frame(&app, &session_id, frame_index, &ext).await?;Ok(tauri::ipc::Response::new(bytes))}#[tauri::command]-async fn timelapse_clear(session_id: String) -> Result<(), String> {- timelapse::clear_session(&session_id).await+async fn timelapse_clear(app: tauri::AppHandle, session_id: String) -> Result<(), String> {+ timelapse::clear_session(&app, &session_id).await}#[tauri::command]@@ -538,6 +712,7 @@ async fn timelapse_check_ffmpeg() -> bool {#[tauri::command]async fn timelapse_export_ffmpeg(+ app: tauri::AppHandle,request: tauri::ipc::Request<'_>,) -> Result<tauri::ipc::Response, String> {let session_id = header_str(&request, "x-session-id")?;@@ -545,13 +720,112 @@ async fn timelapse_export_ffmpeg(let fps: u32 = header_parse(&request, "x-fps")?;let width: u32 = header_parse(&request, "x-width")?;let height: u32 = header_parse(&request, "x-height")?;+ let bg_color = header_opt_str(&request, "x-bg-color").unwrap_or_else(|| "#ffffff".to_string());+ let bg_blur = header_opt_str(&request, "x-bg-blur")+ .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))+ .unwrap_or(false);+ let quality = header_opt_str(&request, "x-quality").unwrap_or_else(|| "high".to_string());+ let wm_len: usize = header_opt_parse(&request, "x-watermark-bytes").unwrap_or(0);+ let wm_x: i32 = header_opt_parse(&request, "x-watermark-x").unwrap_or(0);+ let wm_y: i32 = header_opt_parse(&request, "x-watermark-y").unwrap_or(0);+let body = raw_body(&request)?;- let frame_indices = timelapse::unpack_frame_indices(body)?;- let bytes =- timelapse::export_ffmpeg(&session_id, frame_indices, &ext, fps, width, height).await?;+ if wm_len > body.len() {+ return Err("Invalid watermark byte length header".to_string());+ }+ let indices_len = body.len() - wm_len;+ let frame_indices = timelapse::unpack_frame_indices(&body[..indices_len])?;+ let watermark_png = if wm_len > 0 {+ Some(&body[indices_len..])+ } else {+ None+ };++ let bytes = timelapse::export_ffmpeg(+ &app,+ timelapse::FfmpegExportParams {+ session_id: &session_id,+ frame_indices,+ ext: &ext,+ fps,+ width,+ height,+ bg_color: &bg_color,+ bg_blur,+ quality: &quality,+ watermark_png,+ watermark_x: wm_x,+ watermark_y: wm_y,+ },+ )+ .await?;+ Ok(tauri::ipc::Response::new(bytes))+}++#[tauri::command]+async fn timelapse_capture_app_window(+ app: tauri::AppHandle,+ max_dim: u32,+) -> Result<tauri::ipc::Response, String> {+ let bytes = timelapse::capture_app_window(&app, max_dim).await?;Ok(tauri::ipc::Response::new(bytes))}+#[tauri::command]+async fn native_pick_save_path(+ app: tauri::AppHandle,+ suggested_name: String,+ filters: Vec<save_dialog::SaveFilterSpec>,+ default_filter_index: Option<usize>,+ title: Option<String>,+ initial_dir: Option<String>,+) -> Result<save_dialog::NativePickSavePathResult, String> {+ let res = save_dialog::pick_save_path_with_dialog(+ &app,+ suggested_name,+ filters,+ default_filter_index.unwrap_or(0),+ title,+ initial_dir,+ )+ .await?;+ if !res.canceled {+ if let Some(ref chosen_path) = res.path {+ register_allowed_write_path(Path::new(chosen_path));+ }+ }+ Ok(res)+}++#[tauri::command]+async fn native_save_file_with_dialog(+ app: tauri::AppHandle,+ request: tauri::ipc::Request<'_>,+) -> Result<save_dialog::NativeSaveDialogResult, String> {+ let suggested_name = header_str(&request, "x-suggested-name")?;+ let filter_name = header_opt_str(&request, "x-filter-name").unwrap_or_else(|| "File".to_string());+ let extensions = header_opt_str(&request, "x-extensions").unwrap_or_default();+ let title = header_opt_str(&request, "x-dialog-title");+ let initial_dir = header_opt_str(&request, "x-initial-dir");+ let data = raw_body(&request)?.to_vec();+ let res = save_dialog::save_file_with_dialog(+ &app,+ suggested_name,+ filter_name,+ extensions,+ title,+ initial_dir,+ data,+ )+ .await?;+ if res.saved {+ if let Some(ref saved_path) = res.path {+ register_allowed_path(Path::new(saved_path));+ }+ }+ Ok(res)+}+#[tauri::command]async fn parse_clip_file(request: tauri::ipc::Request<'_>,@@ -951,6 +1225,20 @@ async fn purge_unused_scratch_files(active_session_ids: Vec<String>) -> Result<u.map_err(|e| format!("Failed to purge unused scratch files: {}", e))?}+fn focus_main_window(app: &tauri::AppHandle) {+ if let Some(main_window) = app.get_webview_window("main") {+ let _ = main_window.unminimize();+ let _ = main_window.show();+ let _ = main_window.set_focus();+ }+}++fn deliver_open_files(app: &tauri::AppHandle, paths: Vec<String>) {+ if let Some(to_emit) = file_open::enqueue_or_take_for_emit(paths) {+ let _ = app.emit(file_open::OPEN_FILES_EVENT, to_emit);+ }+}+#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {// Load persisted desktop performance settings BEFORE WebView2 initializes@@ -993,15 +1281,44 @@ pub fn run() {std::env::set_var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", merged);}- // Register any document files explicitly passed via OS file association / CLI args.- for arg in std::env::args_os().skip(1) {- register_allowed_path(Path::new(&arg));- }+ let builder = tauri::Builder::default();- let app = tauri::Builder::default()+ // Register single-instance FIRST so any second launch (e.g. double-clicking a `.ink` file+ // while Ink Studio is already open) forwards its arguments to the running instance and exits+ // immediately without spawning a second window or WebView2 process.+ #[cfg(desktop)]+ let builder = builder.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {+ focus_main_window(app);+ let cwd_path = if cwd.trim().is_empty() {+ None+ } else {+ Some(PathBuf::from(&cwd))+ };+ let paths = file_open::extract_openable_file_paths(+ argv.iter().skip(1),+ cwd_path.as_deref(),+ register_allowed_path,+ );+ deliver_open_files(app, paths);+ }));++ let app = builder.plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_process::init()).setup(|app| {+ // Register and queue any files passed via OS file association / CLI args on cold launch.+ let launch_args: Vec<String> = std::env::args_os()+ .skip(1)+ .map(|s| s.to_string_lossy().into_owned())+ .collect();+ let launch_cwd = std::env::current_dir().ok();+ let launch_paths = file_open::extract_openable_file_paths(+ &launch_args,+ launch_cwd.as_deref(),+ register_allowed_path,+ );+ let _ = file_open::enqueue_or_take_for_emit(launch_paths);+#[cfg(desktop)]{app.handle()@@ -1033,6 +1350,8 @@ pub fn run() {delete_file_from_disk,read_file_from_disk,read_file_binary,+ write_allowed_file_binary,+ take_pending_open_files,recovery_init_session,recovery_append_wal_entry,recovery_checkpoint,@@ -1043,6 +1362,9 @@ pub fn run() {scratch_disk_write_tiles,scratch_disk_read_tile,scratch_disk_clear,+ timelapse_save_meta,+ timelapse_load_session,+ timelapse_list_sessions,timelapse_write_frame,timelapse_write_frames_batch,timelapse_list_frames,@@ -1050,6 +1372,9 @@ pub fn run() {timelapse_clear,timelapse_check_ffmpeg,timelapse_export_ffmpeg,+ timelapse_capture_app_window,+ native_pick_save_path,+ native_save_file_with_dialog,parse_clip_file,parse_sut_sqlite,parse_psd_file,@@ -1073,7 +1398,19 @@ pub fn run() {.build(tauri::generate_context!()).expect("error while building tauri application");- app.run(|_app_handle, event| {+ app.run(|app_handle, event| {+ #[cfg(any(target_os = "macos", target_os = "ios"))]+ if let tauri::RunEvent::Opened { urls } = &event {+ let url_strings: Vec<String> = urls.iter().map(|u| u.as_str().to_string()).collect();+ let paths = file_open::extract_openable_file_paths(+ &url_strings,+ None,+ register_allowed_path,+ );+ focus_main_window(app_handle);+ deliver_open_files(app_handle, paths);+ }+ let _ = app_handle;if let tauri::RunEvent::Exit = event {os_hotkeys::stop_os_hotkeys();tablet_input::stop_tablet_input();@@ -1155,4 +1492,47 @@ mod tests {let _ = std::fs::remove_dir_all(&base);}++ #[tokio::test]+ async fn test_write_path_authorization_requires_explicit_grant_and_allowed_ext() {+ let base = std::env::temp_dir().join(format!(+ "inkstudio_write_auth_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let outside_dir = base.join("outside");+ std::fs::create_dir_all(&outside_dir).unwrap();++ let new_ink = outside_dir.join("FreshArt.ink");+ let bad_ext = outside_dir.join("evil.exe");+ let allowed_dirs: Vec<PathBuf> = Vec::new();++ // Unauthorized new file outside allowed dirs is rejected+ assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)+ .await+ .is_err());++ // Granting via dialog pick authorizes writing this specific new .ink path+ register_allowed_write_path(&new_ink);+ assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)+ .await+ .is_ok());++ // Disallowed extensions can never be granted or written+ register_allowed_write_path(&bad_ext);+ assert!(validate_write_path(bad_ext.to_str().unwrap(), &allowed_dirs)+ .await+ .is_err());++ if let Ok(resolved) = resolve_canonical_target_path(&new_ink, DIRECT_SAVE_ALLOWED_EXTS) {+ unregister_allowed_path(&resolved);+ }+ assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)+ .await+ .is_err());++ let _ = std::fs::remove_dir_all(&base);+ }}diff --git a/src-tauri/src/psd_parser.rs b/src-tauri/src/psd_parser.rsindex 22933bd..60e7e6a 100644--- a/src-tauri/src/psd_parser.rs+++ b/src-tauri/src/psd_parser.rs@@ -375,8 +375,8 @@ fn assemble_rgba_from_channels(let ch_a = find_ch(-1);match color_mode {- 1 => {- // Grayscale+ 0 | 1 => {+ // Bitmap (1-bit) & Grayscalelet ch_g = find_ch(0);for i in 0..pixels {let g = ch_g.and_then(|c| c.get(i).copied()).unwrap_or(0);@@ -819,7 +819,7 @@ fn decode_merged_composite(let mut tagged: Vec<(i16, Vec<u8>)> = Vec::with_capacity(max_channels);for (idx, plane) in raw_planes.into_iter().enumerate() {let ch_id = match color_mode {- 1 => {+ 0 | 1 => {if idx == 0 {0} else {@@ -896,7 +896,11 @@ pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {// 5. Image Data (composite fallback)let image_data_bytes = &bytes[cur.pos..];- let ink_color_mode = if color_mode == 1 { "grayscale" } else { "color" };+ let ink_color_mode = if color_mode == 0 || color_mode == 1 {+ "grayscale"+ } else {+ "color"+ };// Build top-to-bottom Ink Studio layer hierarchy from PSD bottom-to-top records.// In PSD, records are bottom-to-top:@@ -1032,6 +1036,12 @@ pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {collapsed: plan.collapsed,parent_id: plan.parent_id,solid_fill_hex: None,+ expression_color: None,+ mono_express_black: None,+ mono_express_white: None,+ layer_color_enabled: None,+ layer_color: None,+ layer_sub_color: None,tiles: Vec::new(),mask,});@@ -1068,6 +1078,12 @@ pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {collapsed: false,parent_id: plan.parent_id,solid_fill_hex: None,+ expression_color: None,+ mono_express_black: None,+ mono_express_white: None,+ layer_color_enabled: None,+ layer_color: None,+ layer_sub_color: None,tiles,mask,})@@ -1107,6 +1123,12 @@ pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {collapsed: false,parent_id: None,solid_fill_hex: None,+ expression_color: None,+ mono_express_black: None,+ mono_express_white: None,+ layer_color_enabled: None,+ layer_color: None,+ layer_sub_color: None,tiles,mask: None,});@@ -1247,4 +1269,53 @@ mod tests {let px_off = (1 * 256 + 1) * 4;assert_eq!(&decoded[px_off..px_off + 4], &[250, 10, 20, 255]);}++ #[test]+ fn test_parse_1bit_bitmap_manga_psd_decodes_grayscale_not_red() {+ // Minimal 8x2 1-bit Bitmap PSD (color_mode = 0, depth = 1, 1 channel, raw merged image data)+ // PSD 1-bit bitmap convention: bit 1 = black ink, bit 0 = white paper+ let mut psd = Vec::new();+ psd.extend_from_slice(b"8BPS");+ psd.extend_from_slice(&1u16.to_be_bytes()); // v1+ psd.extend_from_slice(&[0u8; 6]);+ psd.extend_from_slice(&1u16.to_be_bytes()); // 1 channel+ psd.extend_from_slice(&2u32.to_be_bytes()); // height = 2+ psd.extend_from_slice(&8u32.to_be_bytes()); // width = 8+ psd.extend_from_slice(&1u16.to_be_bytes()); // depth = 1-bit+ psd.extend_from_slice(&0u16.to_be_bytes()); // color_mode = 0 (Bitmap)+ psd.extend_from_slice(&0u32.to_be_bytes()); // Color Mode Data+ psd.extend_from_slice(&0u32.to_be_bytes()); // Image Resources+ psd.extend_from_slice(&0u32.to_be_bytes()); // Layer and Mask Info (empty -> merged fallback)+ // Image Data: raw compression (0), 2 rows of 1 byte each:+ // Row 0: 0b1000_0000 -> pixel (0,0) black, pixel (1,0) white+ // Row 1: 0b0100_0000 -> pixel (0,1) white, pixel (1,1) black+ psd.extend_from_slice(&0u16.to_be_bytes());+ psd.push(0b1000_0000);+ psd.push(0b0100_0000);++ let wire = parse_psd_to_binary(&psd).expect("parse_psd_to_binary failed on 1-bit bitmap");+ let meta_len = u32::from_le_bytes(wire[8..12].try_into().unwrap()) as usize;+ let meta: serde_json::Value = serde_json::from_slice(&wire[12..12 + meta_len]).unwrap();+ assert_eq!(meta["width"], 8);+ assert_eq!(meta["height"], 2);+ assert_eq!(meta["colorMode"], "grayscale");++ let layers = meta["layers"].as_array().unwrap();+ assert_eq!(layers.len(), 1);+ let t0 = &layers[0]["tiles"][0];+ let b_start = 12 + meta_len + t0["offset"].as_u64().unwrap() as usize;+ let b_len = t0["len"].as_u64().unwrap() as usize;+ let decoded = lz4_flex::block::decompress(&wire[b_start..b_start + b_len], BYTES_32BIT).unwrap();++ // (0,0) = opaque black (0, 0, 0, 255)+ assert_eq!(&decoded[0..4], &[0, 0, 0, 255]);+ // (1,0) = opaque white (255, 255, 255, 255) — NOT red!+ assert_eq!(&decoded[4..8], &[255, 255, 255, 255]);+ // (0,1) = opaque white+ let p01 = (1 * 256) * 4;+ assert_eq!(&decoded[p01..p01 + 4], &[255, 255, 255, 255]);+ // (1,1) = opaque black+ let p11 = (1 * 256 + 1) * 4;+ assert_eq!(&decoded[p11..p11 + 4], &[0, 0, 0, 255]);+ }}diff --git a/src-tauri/src/save_dialog.rs b/src-tauri/src/save_dialog.rsnew file mode 100644index 0000000..678dec4--- /dev/null+++ b/src-tauri/src/save_dialog.rs@@ -0,0 +1,779 @@+use serde::{Deserialize, Serialize};+use std::io::Write;+use std::path::{Path, PathBuf};+use tauri::Manager;++const MAX_SAVE_DIALOG_BYTES: usize = 512 * 1024 * 1024; // 512 MB ceiling++const KNOWN_DOC_EXTS: &[&str] = &[+ "ink", "sora", "psd", "psb", "clip", "csp", "lip", "png", "jpg", "jpeg", "webp", "bmp", "gif",+ "svg",+];++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct NativeSaveDialogResult {+ pub saved: bool,+ pub canceled: bool,+ pub file_name: String,+ pub path: Option<String>,+ pub directory: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct SaveFilterSpec {+ pub name: String,+ pub extensions: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct NativePickSavePathResult {+ pub canceled: bool,+ pub file_name: Option<String>,+ pub path: Option<String>,+ pub directory: Option<String>,+ pub extension: Option<String>,+ pub filter_index: usize,+}++/// Sanitizes a suggested filename (strips directory separators and filesystem-illegal chars,+/// while preserving Unicode characters, spaces, dots in version numbers, etc.).+pub fn sanitize_suggested_filename(raw: &str) -> String {+ let base = Path::new(raw)+ .file_name()+ .and_then(|s| s.to_str())+ .unwrap_or("export");+ let cleaned: String = base+ .chars()+ .filter(|&c| {+ !matches!(+ c,+ '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' | '\0'..='\x1f'+ )+ })+ .collect();+ let trimmed = cleaned.trim().trim_matches('.');+ if trimmed.is_empty() {+ "export".to_string()+ } else {+ trimmed.to_string()+ }+}++/// Strips trailing chained known document/image extensions (e.g. `"art.ink.ink.png.ink"` -> `"art"`),+/// preserving version dots like `"Chapter 1.2"`.+pub fn strip_known_doc_extensions(raw: &str) -> String {+ let mut current = sanitize_suggested_filename(raw);+ loop {+ let Some(dot) = current.rfind('.') else {+ break;+ };+ if dot == 0 {+ break;+ }+ let ext = current[dot + 1..].to_ascii_lowercase();+ if KNOWN_DOC_EXTS.contains(&ext.as_str()) {+ let next = current[..dot].trim_end_matches([' ', '.']);+ if next.is_empty() {+ break;+ }+ current = next.to_string();+ } else {+ break;+ }+ }+ current+}++/// Normalizes a chosen Save As path to prevent chained/doubled extensions such as+/// `foo.ink.ink`, `foo.ink.png`, or `foo.png.ink` produced when switching filters or re-saving.+pub fn normalize_chosen_save_path(chosen: &Path, expected_extensions: &[String]) -> PathBuf {+ let Some(file_name_os) = chosen.file_name() else {+ return chosen.to_path_buf();+ };+ let file_name = file_name_os.to_string_lossy();++ let clean_expected: Vec<String> = expected_extensions+ .iter()+ .map(|e| e.trim().trim_start_matches('.').to_ascii_lowercase())+ .filter(|e| !e.is_empty())+ .collect();++ // Determine final extension: prefer the path's own trailing extension if it matches+ // the expected list or is a known document ext; otherwise append the first expected ext.+ let current_ext = chosen+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_ascii_lowercase());++ let final_ext = match current_ext.as_deref() {+ Some(ext) if clean_expected.is_empty() || clean_expected.iter().any(|e| e == ext) => {+ Some(ext.to_string())+ }+ Some(ext) if KNOWN_DOC_EXTS.contains(&ext) => {+ // If expected_extensions specifies a concrete format (e.g. user selected PNG filter),+ // prefer the expected format; otherwise keep the known extension.+ clean_expected+ .first()+ .cloned()+ .or_else(|| Some(ext.to_string()))+ }+ _ => clean_expected.first().cloned(),+ };++ let Some(target_ext) = final_ext else {+ return chosen.to_path_buf();+ };++ // Strip any chained known document extensions or duplicate expected extensions from the stem+ let mut stem = strip_known_doc_extensions(&file_name);+ loop {+ let Some(dot) = stem.rfind('.') else {+ break;+ };+ if dot == 0 {+ break;+ }+ let tail = stem[dot + 1..].to_ascii_lowercase();+ if tail == target_ext || clean_expected.iter().any(|e| e == &tail) {+ let next = stem[..dot].trim_end_matches([' ', '.']);+ if next.is_empty() {+ break;+ }+ stem = next.to_string();+ } else {+ break;+ }+ }++ let clean_stem = stem.trim().trim_end_matches('.');+ let final_name = if clean_stem.is_empty() {+ format!("Untitled.{}", target_ext)+ } else {+ format!("{}.{}", clean_stem, target_ext)+ };++ match chosen.parent() {+ Some(parent) if !parent.as_os_str().is_empty() => parent.join(final_name),+ _ => PathBuf::from(final_name),+ }+}++/// Atomically writes `data` to `target` using a sibling temporary file + flush + atomic replace,+/// ensuring an existing `.ink` or image file is never truncated or corrupted mid-save.+pub fn write_file_atomic(target: &Path, data: &[u8]) -> Result<(), String> {+ let parent = target+ .parent()+ .filter(|p| !p.as_os_str().is_empty())+ .unwrap_or_else(|| Path::new("."));++ let pid = std::process::id();+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);++ let mut tmp_path = parent.join(format!(".inkstudio_tmp_{}_{}.tmp", pid, nanos));+ let mut attempt: u32 = 0;+ let mut file = loop {+ match std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&tmp_path)+ {+ Ok(f) => break f,+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 16 => {+ attempt += 1;+ tmp_path = parent.join(format!(".inkstudio_tmp_{}_{}_{}.tmp", pid, nanos, attempt));+ }+ Err(e) => {+ return Err(format!(+ "Failed to create temporary save file in \"{}\": {}",+ parent.to_string_lossy(),+ e+ ));+ }+ }+ };++ let write_res = (|| -> Result<(), String> {+ file.write_all(data)+ .map_err(|e| format!("Failed to write file data: {}", e))?;+ file.sync_all()+ .map_err(|e| format!("Failed to flush file data to disk: {}", e))?;+ Ok(())+ })();++ drop(file);++ if let Err(err) = write_res {+ let _ = std::fs::remove_file(&tmp_path);+ return Err(err);+ }++ #[cfg(target_os = "windows")]+ {+ use windows_sys::Win32::Storage::FileSystem::{+ MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,+ };+ let src_wide = to_utf16_null(&tmp_path.to_string_lossy());+ let dst_wide = to_utf16_null(&target.to_string_lossy());+ let moved = unsafe {+ MoveFileExW(+ src_wide.as_ptr(),+ dst_wide.as_ptr(),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,+ )+ };+ if moved == 0 {+ let err = std::io::Error::last_os_error();+ let _ = std::fs::remove_file(&tmp_path);+ return Err(format!(+ "Failed to replace \"{}\": {}",+ target.to_string_lossy(),+ err+ ));+ }+ }++ #[cfg(not(target_os = "windows"))]+ {+ if let Err(err) = std::fs::rename(&tmp_path, target) {+ let _ = std::fs::remove_file(&tmp_path);+ return Err(format!(+ "Failed to replace \"{}\": {}",+ target.to_string_lossy(),+ err+ ));+ }+ }++ Ok(())+}++/// Parses comma-separated extensions (e.g. `".inkb, .json"`) into clean lowercase alphanumeric tokens.+pub fn parse_filter_extensions(raw: &str) -> Vec<String> {+ let mut out = Vec::new();+ for part in raw.split(',') {+ let cleaned: String = part+ .trim()+ .trim_start_matches('*')+ .trim_start_matches('.')+ .to_ascii_lowercase()+ .chars()+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')+ .collect();+ if !cleaned.is_empty() && cleaned.len() <= 24 && !out.contains(&cleaned) {+ out.push(cleaned);+ }+ }+ out+}++/// Builds a double-null-terminated UTF-16 Win32 OPENFILENAMEW filter string for a single filter group.+#[cfg(test)]+pub fn build_win32_filter_utf16(filter_name: &str, extensions: &[String]) -> Vec<u16> {+ let specs = if extensions.is_empty() {+ Vec::new()+ } else {+ vec![SaveFilterSpec {+ name: filter_name.to_string(),+ extensions: extensions.to_vec(),+ }]+ };+ build_win32_multi_filter_utf16(&specs)+}++/// Builds a double-null-terminated UTF-16 Win32 OPENFILENAMEW filter string for multiple filter groups.+pub fn build_win32_multi_filter_utf16(filters: &[SaveFilterSpec]) -> Vec<u16> {+ let mut wide: Vec<u16> = Vec::new();+ for spec in filters {+ let clean_exts: Vec<String> = spec+ .extensions+ .iter()+ .map(|e| {+ e.trim()+ .trim_start_matches('*')+ .trim_start_matches('.')+ .to_ascii_lowercase()+ })+ .filter(|e| !e.is_empty() && e.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))+ .collect();+ if clean_exts.is_empty() {+ continue;+ }+ let pattern = clean_exts+ .iter()+ .map(|e| format!("*.{}", e))+ .collect::<Vec<_>>()+ .join(";");+ let clean_name = spec.name.trim().replace('\0', "");+ let label = if clean_name.is_empty() {+ format!("Files ({})", pattern)+ } else if clean_name.contains("*.") {+ clean_name+ } else {+ format!("{} ({})", clean_name, pattern)+ };+ wide.extend(label.encode_utf16());+ wide.push(0);+ wide.extend(pattern.encode_utf16());+ wide.push(0);+ }+ wide.extend("All Files (*.*)".encode_utf16());+ wide.push(0);+ wide.extend("*.*".encode_utf16());+ wide.push(0);+ wide.push(0); // Double-null terminator+ wide+}++fn to_utf16_null(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(std::iter::once(0)).collect()+}++fn validate_existing_dir(raw: Option<&str>) -> Option<PathBuf> {+ let candidate = raw?.trim();+ if candidate.is_empty() || candidate.contains('\0') {+ return None;+ }+ let p = PathBuf::from(candidate);+ if p.is_dir() {+ Some(p)+ } else {+ None+ }+}++#[cfg(target_os = "windows")]+mod win_save_dialog {+ use super::*;+ use std::ffi::c_void;++ const OFN_OVERWRITEPROMPT: u32 = 0x0000_0002;+ const OFN_NOCHANGEDIR: u32 = 0x0000_0008;+ const OFN_PATHMUSTEXIST: u32 = 0x0000_0800;+ const OFN_EXPLORER: u32 = 0x0008_0000;++ #[repr(C)]+ struct OpenFileNameW {+ l_struct_size: u32,+ hwnd_owner: *mut c_void,+ h_instance: *mut c_void,+ lpstr_filter: *const u16,+ lpstr_custom_filter: *mut u16,+ n_max_cust_filter: u32,+ n_filter_index: u32,+ lpstr_file: *mut u16,+ n_max_file: u32,+ lpstr_file_title: *mut u16,+ n_max_file_title: u32,+ lpstr_initial_dir: *const u16,+ lpstr_title: *const u16,+ flags: u32,+ n_file_offset: u16,+ n_file_extension: u16,+ lpstr_def_ext: *const u16,+ l_cust_data: isize,+ lpfn_hook: *const c_void,+ lp_template_name: *const u16,+ pv_reserved: *mut c_void,+ dw_reserved: u32,+ flags_ex: u32,+ }++ #[link(name = "comdlg32")]+ extern "system" {+ fn GetSaveFileNameW(lpofn: *mut OpenFileNameW) -> i32;+ fn CommDlgExtendedError() -> u32;+ }++ pub fn prompt_pick_path(+ hwnd_raw: isize,+ suggested_name: &str,+ filters: &[SaveFilterSpec],+ default_filter_index: usize,+ title: Option<&str>,+ initial_dir: Option<&Path>,+ ) -> Result<NativePickSavePathResult, String> {+ let safe_initial = sanitize_suggested_filename(suggested_name);+ let filter_wide = build_win32_multi_filter_utf16(filters);+ let title_wide = title+ .map(|t| t.trim())+ .filter(|t| !t.is_empty())+ .map(to_utf16_null);+ let initial_dir_wide = initial_dir.map(|d| to_utf16_null(&d.to_string_lossy()));++ let clamped_idx = if filters.is_empty() {+ 0+ } else {+ default_filter_index.min(filters.len() - 1)+ };+ let def_ext = filters+ .get(clamped_idx)+ .and_then(|f| f.extensions.first())+ .map(|e| e.trim().trim_start_matches('.').to_ascii_lowercase())+ .filter(|e| !e.is_empty());+ let def_ext_wide = def_ext.as_deref().map(to_utf16_null);++ // 4096 UTF-16 code units buffer for returned path+ let mut file_buf: Vec<u16> = vec![0u16; 4096];+ let name_wide: Vec<u16> = safe_initial.encode_utf16().collect();+ let copy_len = name_wide.len().min(file_buf.len().saturating_sub(1));+ file_buf[..copy_len].copy_from_slice(&name_wide[..copy_len]);++ let mut ofn = OpenFileNameW {+ l_struct_size: std::mem::size_of::<OpenFileNameW>() as u32,+ hwnd_owner: hwnd_raw as *mut c_void,+ h_instance: std::ptr::null_mut(),+ lpstr_filter: filter_wide.as_ptr(),+ lpstr_custom_filter: std::ptr::null_mut(),+ n_max_cust_filter: 0,+ n_filter_index: (clamped_idx as u32) + 1, // 1-based for Win32+ lpstr_file: file_buf.as_mut_ptr(),+ n_max_file: file_buf.len() as u32,+ lpstr_file_title: std::ptr::null_mut(),+ n_max_file_title: 0,+ lpstr_initial_dir: initial_dir_wide+ .as_ref()+ .map(|v| v.as_ptr())+ .unwrap_or(std::ptr::null()),+ lpstr_title: title_wide+ .as_ref()+ .map(|v| v.as_ptr())+ .unwrap_or(std::ptr::null()),+ flags: OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER,+ n_file_offset: 0,+ n_file_extension: 0,+ lpstr_def_ext: def_ext_wide+ .as_ref()+ .map(|v| v.as_ptr())+ .unwrap_or(std::ptr::null()),+ l_cust_data: 0,+ lpfn_hook: std::ptr::null(),+ lp_template_name: std::ptr::null(),+ pv_reserved: std::ptr::null_mut(),+ dw_reserved: 0,+ flags_ex: 0,+ };++ let ok = unsafe { GetSaveFileNameW(&mut ofn) };+ if ok == 0 {+ let err_code = unsafe { CommDlgExtendedError() };+ if err_code == 0 {+ return Ok(NativePickSavePathResult {+ canceled: true,+ file_name: None,+ path: None,+ directory: None,+ extension: None,+ filter_index: clamped_idx,+ });+ }+ return Err(format!("Native Save dialog failed (code 0x{:X})", err_code));+ }++ let nul_pos = file_buf+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(file_buf.len());+ let raw_chosen_str = String::from_utf16_lossy(&file_buf[..nul_pos]);+ let selected_filter_idx = ofn.n_filter_index.saturating_sub(1) as usize;+ let expected_exts: Vec<String> = filters+ .get(selected_filter_idx)+ .map(|f| f.extensions.clone())+ .unwrap_or_default();++ let normalized_path = normalize_chosen_save_path(Path::new(&raw_chosen_str), &expected_exts);+ let chosen_str = normalized_path.to_string_lossy().to_string();+ let file_name = normalized_path+ .file_name()+ .and_then(|s| s.to_str())+ .unwrap_or(&safe_initial)+ .to_string();+ let directory = normalized_path+ .parent()+ .map(|p| p.to_string_lossy().to_string());+ let extension = normalized_path+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| format!(".{}", e.to_ascii_lowercase()));++ Ok(NativePickSavePathResult {+ canceled: false,+ file_name: Some(file_name),+ path: Some(chosen_str),+ directory,+ extension,+ filter_index: selected_filter_idx,+ })+ }++ pub fn prompt_and_write(+ hwnd_raw: isize,+ suggested_name: &str,+ filter_name: &str,+ extensions: &[String],+ title: Option<&str>,+ initial_dir: Option<&Path>,+ data: &[u8],+ ) -> Result<NativeSaveDialogResult, String> {+ let filters = if extensions.is_empty() {+ Vec::new()+ } else {+ vec![SaveFilterSpec {+ name: filter_name.to_string(),+ extensions: extensions.to_vec(),+ }]+ };+ let picked = prompt_pick_path(hwnd_raw, suggested_name, &filters, 0, title, initial_dir)?;+ if picked.canceled {+ return Ok(NativeSaveDialogResult {+ saved: false,+ canceled: true,+ file_name: sanitize_suggested_filename(suggested_name),+ path: None,+ directory: None,+ });+ }+ let chosen_str = picked+ .path+ .ok_or_else(|| "Save dialog returned no path".to_string())?;+ let chosen_path = PathBuf::from(&chosen_str);++ write_file_atomic(&chosen_path, data)?;++ Ok(NativeSaveDialogResult {+ saved: true,+ canceled: false,+ file_name: picked+ .file_name+ .unwrap_or_else(|| sanitize_suggested_filename(suggested_name)),+ path: Some(chosen_str),+ directory: picked.directory,+ })+ }+}++pub async fn pick_save_path_with_dialog(+ app: &tauri::AppHandle,+ suggested_name: String,+ filters: Vec<SaveFilterSpec>,+ default_filter_index: usize,+ title: Option<String>,+ initial_dir_raw: Option<String>,+) -> Result<NativePickSavePathResult, String> {+ #[cfg(target_os = "windows")]+ {+ let hwnd_raw = app+ .get_webview_window("main")+ .and_then(|w| w.hwnd().ok())+ .map(|h| h.0 as isize)+ .unwrap_or(0);+ let initial_dir = validate_existing_dir(initial_dir_raw.as_deref());++ tokio::task::spawn_blocking(move || {+ win_save_dialog::prompt_pick_path(+ hwnd_raw,+ &suggested_name,+ &filters,+ default_filter_index,+ title.as_deref(),+ initial_dir.as_deref(),+ )+ })+ .await+ .map_err(|e| format!("Save dialog worker failed: {}", e))?+ }++ #[cfg(not(target_os = "windows"))]+ {+ let _ = (+ app,+ suggested_name,+ filters,+ default_filter_index,+ title,+ initial_dir_raw,+ );+ Err("Native Save dialog is not supported on this platform".to_string())+ }+}++pub async fn save_file_with_dialog(+ app: &tauri::AppHandle,+ suggested_name: String,+ filter_name: String,+ extensions_raw: String,+ title: Option<String>,+ initial_dir_raw: Option<String>,+ data: Vec<u8>,+) -> Result<NativeSaveDialogResult, String> {+ if data.len() > MAX_SAVE_DIALOG_BYTES {+ return Err("File exceeds 512 MB save safety limit".to_string());+ }++ #[cfg(target_os = "windows")]+ {+ let hwnd_raw = app+ .get_webview_window("main")+ .and_then(|w| w.hwnd().ok())+ .map(|h| h.0 as isize)+ .unwrap_or(0);+ let extensions = parse_filter_extensions(&extensions_raw);+ let initial_dir = validate_existing_dir(initial_dir_raw.as_deref());++ tokio::task::spawn_blocking(move || {+ win_save_dialog::prompt_and_write(+ hwnd_raw,+ &suggested_name,+ &filter_name,+ &extensions,+ title.as_deref(),+ initial_dir.as_deref(),+ &data,+ )+ })+ .await+ .map_err(|e| format!("Save dialog worker failed: {}", e))?+ }++ #[cfg(not(target_os = "windows"))]+ {+ let _ = (+ app,+ suggested_name,+ filter_name,+ extensions_raw,+ title,+ initial_dir_raw,+ data,+ );+ Err("Native Save dialog is not supported on this platform".to_string())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_sanitize_suggested_filename() {+ assert_eq!(sanitize_suggested_filename("My Brush.inkb"), "My Brush.inkb");+ assert_eq!(sanitize_suggested_filename("../evil/brush:1?.inkb"), "brush1.inkb");+ assert_eq!(sanitize_suggested_filename(" ... "), "export");+ assert_eq!(sanitize_suggested_filename("イラスト v1.2.ink"), "イラスト v1.2.ink");+ }++ #[test]+ fn test_strip_known_doc_extensions() {+ assert_eq!(strip_known_doc_extensions("Hero.ink.ink.ink.png.ink"), "Hero");+ assert_eq!(strip_known_doc_extensions("Chapter 1.2.ink"), "Chapter 1.2");+ assert_eq!(strip_known_doc_extensions("Cover.PNG"), "Cover");+ assert_eq!(strip_known_doc_extensions("イラスト.psd.ink"), "イラスト");+ }++ #[test]+ fn test_normalize_chosen_save_path_prevents_chained_extensions() {+ let ink = vec!["ink".to_string()];+ let png = vec!["png".to_string()];++ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\Hero.ink.ink.ink.png.ink"), &ink),+ PathBuf::from("C:\\Art\\Hero.ink")+ );+ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\Hero.ink.png"), &png),+ PathBuf::from("C:\\Art\\Hero.png")+ );+ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\Hero.png.ink"), &ink),+ PathBuf::from("C:\\Art\\Hero.ink")+ );+ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\Chapter 1.2"), &ink),+ PathBuf::from("C:\\Art\\Chapter 1.2.ink")+ );+ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\Chapter 1.2.ink"), &ink),+ PathBuf::from("C:\\Art\\Chapter 1.2.ink")+ );+ // Compound color-set JSON extension stays clean when expected is json+ let json = vec!["json".to_string()];+ assert_eq!(+ normalize_chosen_save_path(Path::new("C:\\Art\\palette.inkcolorset.json"), &json),+ PathBuf::from("C:\\Art\\palette.inkcolorset.json")+ );+ }++ #[test]+ fn test_write_file_atomic_creates_and_overwrites_cleanly() {+ let dir = std::env::temp_dir().join(format!(+ "inkstudio_atomic_write_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let target = dir.join("artwork.ink");++ write_file_atomic(&target, b"first version").unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"first version");++ write_file_atomic(&target, b"second version overwritten").unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"second version overwritten");++ // Ensure no leftover .tmp files remain+ let entries: Vec<_> = std::fs::read_dir(&dir)+ .unwrap()+ .flatten()+ .map(|e| e.file_name().to_string_lossy().to_string())+ .collect();+ assert_eq!(entries, vec!["artwork.ink".to_string()]);++ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn test_parse_filter_extensions() {+ assert_eq!(+ parse_filter_extensions(".inkb, *.JSON, .inktheme, .inkb"),+ vec!["inkb", "json", "inktheme"]+ );+ assert!(parse_filter_extensions(" , . , ").is_empty());+ }++ #[test]+ fn test_build_win32_filter_utf16_double_null() {+ let exts = vec!["inkworkspace".to_string(), "json".to_string()];+ let wide = build_win32_filter_utf16("Ink Studio Workspace", &exts);+ assert!(wide.len() >= 4);+ assert_eq!(&wide[wide.len() - 2..], &[0u16, 0u16]);+ let decoded = String::from_utf16_lossy(&wide);+ assert!(decoded.contains("Ink Studio Workspace (*.inkworkspace;*.json)"));+ assert!(decoded.contains("*.inkworkspace;*.json"));+ assert!(decoded.contains("All Files (*.*)"));+ }++ #[test]+ fn test_build_win32_multi_filter_utf16() {+ let specs = vec![+ SaveFilterSpec {+ name: "Ink Studio Project".to_string(),+ extensions: vec!["ink".to_string()],+ },+ SaveFilterSpec {+ name: "PNG Image".to_string(),+ extensions: vec!["png".to_string()],+ },+ ];+ let wide = build_win32_multi_filter_utf16(&specs);+ let decoded = String::from_utf16_lossy(&wide);+ assert!(decoded.contains("Ink Studio Project (*.ink)"));+ assert!(decoded.contains("PNG Image (*.png)"));+ assert!(decoded.contains("All Files (*.*)"));+ }+}diff --git a/src-tauri/src/timelapse.rs b/src-tauri/src/timelapse.rsindex 2a9fb67..c702e64 100644--- a/src-tauri/src/timelapse.rs+++ b/src-tauri/src/timelapse.rs@@ -1,15 +1,31 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::io::Write;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use tauri::Manager;use tokio::process::Command;#[cfg(windows)]const CREATE_NO_WINDOW: u32 = 0x08000000;-const MAX_TIMELAPSE_FRAME_BYTES: usize = 8 * 1024 * 1024; // 8 MB ceiling per keyframe+const MAX_TIMELAPSE_FRAME_BYTES: usize = 12 * 1024 * 1024; // 12 MB ceiling per keyframe (supports 4K)const 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 MAX_WATERMARK_PNG_BYTES: usize = 8 * 1024 * 1024; // 8 MB ceiling for watermark overlay PNGconst MIN_BATCH_RECORD_BYTES: usize = 4 + 1 + 4; // frame_index(u32) + ext_code(u8) + data_len(u32)+static TMP_META_SEQ: AtomicU64 = AtomicU64::new(1);++fn default_capture_area() -> String {+ "artwork".to_string()+}++fn default_capture_resolution() -> String {+ "1080p".to_string()+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct FrameBatchEntry {pub frame_index: u32,@@ -17,6 +33,85 @@ pub struct FrameBatchEntry {pub data: Vec<u8>,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct TimelapseSessionMeta {+ pub recording_id: String,+ #[serde(default)]+ pub document_name: String,+ #[serde(default)]+ pub enabled: bool,+ #[serde(default = "default_capture_area")]+ pub capture_area: String,+ #[serde(default = "default_capture_resolution")]+ pub capture_resolution: String,+ #[serde(default)]+ pub next_index: u32,+ #[serde(default)]+ pub created_at: u64,+ #[serde(default)]+ pub updated_at: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct TimelapseFrameRecord {+ pub index: u32,+ pub timestamp: u64,+ pub width: u32,+ pub height: u32,+ pub mime_type: String,+ pub bytes: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub capture_area: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LoadedTimelapseSession {+ pub meta: Option<TimelapseSessionMeta>,+ pub frames: Vec<TimelapseFrameRecord>,+ pub total_bytes: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct StoredTimelapseSummary {+ pub recording_id: String,+ pub document_name: String,+ pub enabled: bool,+ pub capture_area: String,+ pub capture_resolution: String,+ pub frame_count: usize,+ pub total_bytes: u64,+ pub created_at: u64,+ pub updated_at: u64,+}++#[derive(Debug, Clone)]+pub struct FrameWriteMeta {+ pub timestamp: u64,+ pub width: u32,+ pub height: u32,+ pub capture_area: Option<String>,+}++#[derive(Debug, Clone)]+pub struct FfmpegExportParams<'a> {+ pub session_id: &'a str,+ pub frame_indices: Vec<u32>,+ pub ext: &'a str,+ pub fps: u32,+ pub width: u32,+ pub height: u32,+ pub bg_color: &'a str,+ pub bg_blur: bool,+ pub quality: &'a str,+ pub watermark_png: Option<&'a [u8]>,+ pub watermark_x: i32,+ pub watermark_y: i32,+}+fn ext_to_code(ext: &str) -> Result<u8, String> {match sanitize_ext(ext)? {"webp" => Ok(0),@@ -35,6 +130,14 @@ fn code_to_ext(code: u8) -> Result<&'static str, String> {}}+fn ext_to_mime(ext: &str) -> &'static str {+ match ext {+ "jpg" | "jpeg" => "image/jpeg",+ "png" => "image/png",+ _ => "image/webp",+ }+}+/// 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)]@@ -45,7 +148,7 @@ pub fn pack_frame_batch(entries: &[FrameBatchEntry]) -> Result<Vec<u8>, 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());+ return Err("Timelapse frame exceeds safety size limit".to_string());}let _ = ext_to_code(entry.ext)?;total = total@@ -68,7 +171,7 @@ pub fn pack_frame_batch(entries: &[FrameBatchEntry]) -> Result<Vec<u8>, String>Ok(out)}-/// Unpacks a binary timelapse frame batch written by the frontend during `.ink` restore.+/// Unpacks a binary timelapse frame batch written by the frontend during migration/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());@@ -160,12 +263,117 @@ fn sanitize_ext(ext: &str) -> Result<&'static str, String> {}}-fn session_dir(session_id: &str) -> PathBuf {+/// Sanitizes hex color `#RRGGBB` into FFmpeg `0xRRGGBB` notation.+pub fn sanitize_ffmpeg_hex_color(raw: &str) -> String {+ let trimmed = raw.trim().trim_start_matches('#');+ if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_hexdigit()) {+ format!("0x{}", trimmed.to_ascii_lowercase())+ } else {+ "0xffffff".to_string()+ }+}++/// Maps quality preset string into FFmpeg `(crf, preset)` tuple.+pub fn quality_to_ffmpeg_crf_preset(quality: &str) -> (&'static str, &'static str) {+ match quality.to_ascii_lowercase().as_str() {+ "standard" | "low" => ("26", "veryfast"),+ "ultra" => ("15", "medium"),+ "lossless" | "max" => ("10", "medium"),+ _ => ("20", "fast"), // "high" default+ }+}++/// Builds the FFmpeg `-vf` / `-filter_complex` expression and output map flag.+pub fn build_ffmpeg_filtergraph(+ width: u32,+ height: u32,+ bg_color: &str,+ bg_blur: bool,+ has_watermark: bool,+ watermark_x: i32,+ watermark_y: i32,+) -> (bool, String) {+ let safe_w = width.clamp(64, 3840) & !1;+ let safe_h = height.clamp(64, 3840) & !1;+ let safe_color = sanitize_ffmpeg_hex_color(bg_color);+ let wx = watermark_x.clamp(0, safe_w as i32);+ let wy = watermark_y.clamp(0, safe_h as i32);++ if bg_blur {+ let base_chain = format!(+ "[0:v]split=2[bg][fg];[bg]scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},boxblur=20:2[bgb];[fg]scale={w}:{h}:force_original_aspect_ratio=decrease[fgs];[bgb][fgs]overlay=(W-w)/2:(H-h)/2,setsar=1[base]",+ w = safe_w,+ h = safe_h+ );+ if has_watermark {+ let full = format!(+ "{};[base][1:v]overlay={}:{}:format=auto[out]",+ base_chain, wx, wy+ );+ (true, full)+ } else {+ let full = base_chain.replace("[base]", "[out]");+ (true, full)+ }+ } else if has_watermark {+ let full = format!(+ "[0:v]scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={c},setsar=1[base];[base][1:v]overlay={x}:{y}:format=auto[out]",+ w = safe_w,+ h = safe_h,+ c = safe_color,+ x = wx,+ y = wy+ );+ (true, full)+ } else {+ let vf = format!(+ "scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={c},setsar=1",+ w = safe_w,+ h = safe_h,+ c = safe_color+ );+ (false, vf)+ }+}++/// Persistent root directory for external time-lapse storage (survives app restarts & OS temp cleanup).+pub fn get_timelapse_root(app: Option<&tauri::AppHandle>) -> PathBuf {+ #[cfg(target_os = "windows")]+ {+ if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {+ return PathBuf::from(local_app_data).join("inkstudio_timelapse");+ }+ }+ if let Some(app_handle) = app {+ if let Ok(dir) = app_handle.path().app_local_data_dir() {+ return dir.join("inkstudio_timelapse");+ }+ }+ std::env::temp_dir().join("inkstudio_timelapse")+}++fn legacy_temp_session_dir(session_id: &str) -> PathBuf {std::env::temp_dir().join("inkstudio_timelapse").join(sanitize_session_id(session_id))}+fn session_dir_in(root: &Path, session_id: &str) -> PathBuf {+ root.join(sanitize_session_id(session_id))+}++fn resolve_existing_session_dir(root: &Path, session_id: &str) -> PathBuf {+ let primary = session_dir_in(root, session_id);+ if primary.exists() {+ return primary;+ }+ let legacy = legacy_temp_session_dir(session_id);+ if legacy != primary && legacy.exists() {+ return legacy;+ }+ primary+}+/// Normalize Windows separators (`\` -> `/`) and escape single quotes (`'` -> `'\''`)/// per FFmpeg concat demuxer single-quoted token syntax.fn escape_ffmpeg_concat_path(path: &Path) -> String {@@ -174,83 +382,374 @@ fn escape_ffmpeg_concat_path(path: &Path) -> String {.replace('\'', "'\\''")}-pub async fn write_frame(+fn append_ndjson_records_sync(dir: &Path, records: &[TimelapseFrameRecord]) -> Result<(), String> {+ if records.is_empty() {+ return Ok(());+ }+ let index_path = dir.join("frames.ndjson");+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&index_path)+ .map_err(|e| format!("Failed to open timelapse frame index: {}", e))?;+ for rec in records {+ let line = serde_json::to_string(rec).map_err(|e| e.to_string())?;+ writeln!(file, "{}", line).map_err(|e| e.to_string())?;+ }+ Ok(())+}++fn parse_ndjson_index_sync(dir: &Path) -> HashMap<u32, TimelapseFrameRecord> {+ let mut map = HashMap::new();+ let index_path = dir.join("frames.ndjson");+ let Ok(contents) = std::fs::read_to_string(&index_path) else {+ return map;+ };+ for line in contents.lines() {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Ok(rec) = serde_json::from_str::<TimelapseFrameRecord>(trimmed) {+ map.insert(rec.index, rec);+ }+ }+ map+}++fn atomic_write_json_sync(path: &Path, data: &[u8]) -> Result<(), String> {+ let seq = TMP_META_SEQ.fetch_add(1, Ordering::Relaxed);+ let tmp_name = format!(+ ".{}.tmp.{}.{}",+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("meta.json"),+ std::process::id(),+ seq+ );+ let tmp_path = path.with_file_name(tmp_name);+ std::fs::write(&tmp_path, data).map_err(|e| e.to_string())?;+ if let Err(rename_err) = std::fs::rename(&tmp_path, path) {+ // Windows rename onto an existing destination can fail on some FS drivers; fallback cleanly.+ let _ = std::fs::remove_file(path);+ if std::fs::rename(&tmp_path, path).is_err() {+ let _ = std::fs::remove_file(&tmp_path);+ std::fs::write(path, data)+ .map_err(|e| format!("Failed to save metadata ({}): {}", rename_err, e))?;+ }+ }+ Ok(())+}++pub async fn save_session_meta_in(+ root: PathBuf,+ session_id: &str,+ meta_json: &str,+) -> Result<(), String> {+ let dir = session_dir_in(&root, session_id);+ let parsed: TimelapseSessionMeta = serde_json::from_str(meta_json)+ .map_err(|e| format!("Invalid timelapse session metadata: {}", e))?;+ let serialized = serde_json::to_vec(&parsed).map_err(|e| e.to_string())?;+ tokio::task::spawn_blocking(move || -> Result<(), String> {+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ atomic_write_json_sync(&dir.join("meta.json"), &serialized)+ })+ .await+ .map_err(|e| format!("Timelapse meta save worker failed: {}", e))?+}++pub async fn save_session_meta(+ app: &tauri::AppHandle,+ session_id: &str,+ meta_json: &str,+) -> Result<(), String> {+ save_session_meta_in(get_timelapse_root(Some(app)), session_id, meta_json).await+}++pub async fn write_frame_in(+ root: PathBuf,session_id: &str,frame_index: u32,ext: &str,- data: &[u8],+ data: Vec<u8>,+ meta: Option<FrameWriteMeta>,) -> Result<(), String> {if data.len() > MAX_TIMELAPSE_FRAME_BYTES {- return Err("Timelapse frame exceeds 8 MB safety limit".to_string());+ return Err("Timelapse frame exceeds 12 MB safety limit".to_string());}let safe_ext = sanitize_ext(ext)?;- let dir = session_dir(session_id);- tokio::fs::create_dir_all(&dir)- .await- .map_err(|e| e.to_string())?;- let path = dir.join(format!("frame_{:06}.{}", frame_index, safe_ext));- tokio::fs::write(path, data)- .await- .map_err(|e| e.to_string())?;- Ok(())+ let dir = session_dir_in(&root, session_id);+ tokio::task::spawn_blocking(move || -> Result<(), String> {+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ let path = dir.join(format!("frame_{:06}.{}", frame_index, safe_ext));+ std::fs::write(&path, &data).map_err(|e| e.to_string())?;+ if let Some(m) = meta {+ let record = TimelapseFrameRecord {+ index: frame_index,+ timestamp: m.timestamp,+ width: m.width.max(2),+ height: m.height.max(2),+ mime_type: ext_to_mime(safe_ext).to_string(),+ bytes: data.len() as u64,+ capture_area: m.capture_area,+ };+ let _ = append_ndjson_records_sync(&dir, &[record]);+ }+ Ok(())+ })+ .await+ .map_err(|e| format!("Timelapse frame write worker failed: {}", e))?}-pub async fn write_frames_batch(+pub async fn write_frame(+ app: &tauri::AppHandle,+ session_id: &str,+ frame_index: u32,+ ext: &str,+ data: &[u8],+ meta: Option<FrameWriteMeta>,+) -> Result<(), String> {+ write_frame_in(+ get_timelapse_root(Some(app)),+ session_id,+ frame_index,+ ext,+ data.to_vec(),+ meta,+ )+ .await+}++pub async fn write_frames_batch_in(+ root: PathBuf,session_id: &str,entries: Vec<FrameBatchEntry>,+ records: Option<Vec<TimelapseFrameRecord>>,) -> Result<usize, String> {if entries.is_empty() {return Ok(0);}- let dir = session_dir(session_id);+ let dir = session_dir_in(&root, 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())?;+ let mut fallback_records: Vec<TimelapseFrameRecord> = Vec::new();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())?;+ std::fs::write(&path, &entry.data).map_err(|e| e.to_string())?;+ if records.is_none() {+ fallback_records.push(TimelapseFrameRecord {+ index: entry.frame_index,+ timestamp: 0,+ width: 0,+ height: 0,+ mime_type: ext_to_mime(safe_ext).to_string(),+ bytes: entry.data.len() as u64,+ capture_area: None,+ });+ }}+ let to_append = records.as_deref().unwrap_or(&fallback_records);+ let _ = append_ndjson_records_sync(&dir, to_append);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);+pub async fn write_frames_batch(+ app: &tauri::AppHandle,+ session_id: &str,+ entries: Vec<FrameBatchEntry>,+) -> Result<usize, String> {+ write_frames_batch_in(get_timelapse_root(Some(app)), session_id, entries, None).await+}++fn scan_disk_frames_sync(dir: &Path) -> Result<Vec<(u32, String, u64)>, String> {+ if !dir.exists() {+ return Ok(Vec::new());+ }+ let mut found: Vec<(u32, String, u64)> = 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) {+ let size = entry.metadata().map(|m| m.len()).unwrap_or(0);+ found.push((idx, safe_ext.to_string(), size));+ }+ }+ found.sort_by_key(|(idx, _, _)| *idx);+ Ok(found)+}++pub async fn list_frames_in(root: PathBuf, session_id: &str) -> Result<Vec<(u32, String)>, String> {+ let dir = resolve_existing_session_dir(&root, session_id);tokio::task::spawn_blocking(move || -> Result<Vec<(u32, String)>, String> {+ let scanned = scan_disk_frames_sync(&dir)?;+ Ok(scanned.into_iter().map(|(idx, ext, _)| (idx, ext)).collect())+ })+ .await+ .map_err(|e| format!("Timelapse list worker failed: {}", e))?+}++pub async fn list_frames(+ app: &tauri::AppHandle,+ session_id: &str,+) -> Result<Vec<(u32, String)>, String> {+ list_frames_in(get_timelapse_root(Some(app)), session_id).await+}++pub async fn load_session_in(+ root: PathBuf,+ session_id: &str,+) -> Result<LoadedTimelapseSession, String> {+ let dir = resolve_existing_session_dir(&root, session_id);+ tokio::task::spawn_blocking(move || -> Result<LoadedTimelapseSession, String> {if !dir.exists() {+ return Ok(LoadedTimelapseSession {+ meta: None,+ frames: Vec::new(),+ total_bytes: 0,+ });+ }++ let meta = std::fs::read_to_string(dir.join("meta.json"))+ .ok()+ .and_then(|s| serde_json::from_str::<TimelapseSessionMeta>(&s).ok());++ let ndjson_map = parse_ndjson_index_sync(&dir);+ let disk_frames = scan_disk_frames_sync(&dir)?;++ let mut frames = Vec::with_capacity(disk_frames.len());+ let mut total_bytes: u64 = 0;++ for (idx, ext, file_size) in disk_frames {+ total_bytes = total_bytes.saturating_add(file_size);+ if let Some(rec) = ndjson_map.get(&idx) {+ let mut merged = rec.clone();+ merged.bytes = file_size;+ merged.mime_type = ext_to_mime(&ext).to_string();+ frames.push(merged);+ } else {+ frames.push(TimelapseFrameRecord {+ index: idx,+ timestamp: 0,+ width: 0,+ height: 0,+ mime_type: ext_to_mime(&ext).to_string(),+ bytes: file_size,+ capture_area: None,+ });+ }+ }++ Ok(LoadedTimelapseSession {+ meta,+ frames,+ total_bytes,+ })+ })+ .await+ .map_err(|e| format!("Timelapse load worker failed: {}", e))?+}++pub async fn load_session(+ app: &tauri::AppHandle,+ session_id: &str,+) -> Result<LoadedTimelapseSession, String> {+ load_session_in(get_timelapse_root(Some(app)), session_id).await+}++pub async fn list_sessions_in(root: PathBuf) -> Result<Vec<StoredTimelapseSummary>, String> {+ tokio::task::spawn_blocking(move || -> Result<Vec<StoredTimelapseSummary>, String> {+ if !root.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())?;+ let mut summaries = Vec::new();+ let entries = std::fs::read_dir(&root).map_err(|e| e.to_string())?;for entry in entries.flatten() {- let path = entry.path();- if !path.is_file() {+ let dir = entry.path();+ if !dir.is_dir() {continue;}- let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {- continue;- };- let Some(num_str) = stem.strip_prefix("frame_") else {+ let Some(dir_name) = dir.file_name().and_then(|s| s.to_str()) else {continue;};- let Ok(idx) = num_str.parse::<u32>() else {+ let meta = std::fs::read_to_string(dir.join("meta.json"))+ .ok()+ .and_then(|s| serde_json::from_str::<TimelapseSessionMeta>(&s).ok());+ let disk_frames = scan_disk_frames_sync(&dir).unwrap_or_default();+ if disk_frames.is_empty() && meta.as_ref().map(|m| !m.enabled).unwrap_or(true) {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()));+ }+ let total_bytes: u64 = disk_frames.iter().map(|(_, _, sz)| *sz).sum();+ let dir_mtime = entry+ .metadata()+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0);++ if let Some(m) = meta {+ summaries.push(StoredTimelapseSummary {+ recording_id: if m.recording_id.is_empty() {+ dir_name.to_string()+ } else {+ m.recording_id+ },+ document_name: if m.document_name.is_empty() {+ "Untitled".to_string()+ } else {+ m.document_name+ },+ enabled: m.enabled,+ capture_area: m.capture_area,+ capture_resolution: m.capture_resolution,+ frame_count: disk_frames.len(),+ total_bytes,+ created_at: if m.created_at > 0 { m.created_at } else { dir_mtime },+ updated_at: if m.updated_at > 0 { m.updated_at } else { dir_mtime },+ });+ } else {+ summaries.push(StoredTimelapseSummary {+ recording_id: dir_name.to_string(),+ document_name: "Recovered Recording".to_string(),+ enabled: false,+ capture_area: default_capture_area(),+ capture_resolution: default_capture_resolution(),+ frame_count: disk_frames.len(),+ total_bytes,+ created_at: dir_mtime,+ updated_at: dir_mtime,+ });}}- found.sort_by_key(|(idx, _)| *idx);- Ok(found)+ summaries.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));+ Ok(summaries)}).await- .map_err(|e| format!("Timelapse list worker failed: {}", e))?+ .map_err(|e| format!("Timelapse sessions list worker failed: {}", e))?+}++pub async fn list_sessions(app: &tauri::AppHandle) -> Result<Vec<StoredTimelapseSummary>, String> {+ list_sessions_in(get_timelapse_root(Some(app))).await}fn resolve_frame_path(dir: &Path, idx: u32, preferred_ext: &str) -> Option<PathBuf> {@@ -270,20 +769,44 @@ fn resolve_frame_path(dir: &Path, idx: u32, preferred_ext: &str) -> Option<PathBNone}-pub async fn read_frame(session_id: &str, frame_index: u32, ext: &str) -> Result<Vec<u8>, String> {+pub async fn read_frame_in(+ root: PathBuf,+ 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));+ let dir = resolve_existing_session_dir(&root, session_id);+ let path = resolve_frame_path(&dir, frame_index, safe_ext)+ .unwrap_or_else(|| dir.join(format!("frame_{:06}.{}", frame_index, safe_ext)));tokio::fs::read(path).await.map_err(|e| e.to_string())}-pub async fn clear_session(session_id: &str) -> Result<(), String> {- let dir = session_dir(session_id);+pub async fn read_frame(+ app: &tauri::AppHandle,+ session_id: &str,+ frame_index: u32,+ ext: &str,+) -> Result<Vec<u8>, String> {+ read_frame_in(get_timelapse_root(Some(app)), session_id, frame_index, ext).await+}++pub async fn clear_session_in(root: PathBuf, session_id: &str) -> Result<(), String> {+ let dir = session_dir_in(&root, session_id);if dir.exists() {let _ = tokio::fs::remove_dir_all(&dir).await;}+ let legacy = legacy_temp_session_dir(session_id);+ if legacy != dir && legacy.exists() {+ let _ = tokio::fs::remove_dir_all(&legacy).await;+ }Ok(())}+pub async fn clear_session(app: &tauri::AppHandle, session_id: &str) -> Result<(), String> {+ clear_session_in(get_timelapse_root(Some(app)), session_id).await+}+pub async fn check_ffmpeg() -> bool {let mut cmd = Command::new("ffmpeg");cmd.arg("-version");@@ -296,44 +819,68 @@ pub async fn check_ffmpeg() -> bool {}pub async fn export_ffmpeg(- session_id: &str,- frame_indices: Vec<u32>,- ext: &str,- fps: u32,- width: u32,- height: u32,+ app: &tauri::AppHandle,+ params: FfmpegExportParams<'_>,) -> Result<Vec<u8>, String> {- if frame_indices.is_empty() {+ if params.frame_indices.is_empty() {return Err("No frames to export".to_string());}- let safe_ext = sanitize_ext(ext)?;- let safe_fps = fps.clamp(1, 60);- let safe_w = width.clamp(64, 3840) & !1;- let safe_h = height.clamp(64, 3840) & !1;- let dir = session_dir(session_id);- let list_path = dir.join("concat_list.txt");- let out_path = dir.join("timelapse_out.mp4");+ let safe_ext = sanitize_ext(params.ext)?;+ let safe_fps = params.fps.clamp(1, 60);+ let safe_w = params.width.clamp(64, 3840) & !1;+ let safe_h = params.height.clamp(64, 3840) & !1;+ let root = get_timelapse_root(Some(app));+ let dir = resolve_existing_session_dir(&root, params.session_id);+ let seq = TMP_META_SEQ.fetch_add(1, Ordering::Relaxed);+ let list_path = dir.join(format!("concat_list_{}.txt", seq));+ let out_path = dir.join(format!("timelapse_out_{}.mp4", seq));+ let wm_path = dir.join(format!("watermark_{}.png", seq));let mut manifest = String::new();let frame_dur = 1.0 / (safe_fps as f64);- for idx in &frame_indices {+ let mut last_escaped: Option<String> = None;+ for idx in ¶ms.frame_indices {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));+ last_escaped = Some(escaped);}}+ // FFmpeg concat demuxer requires repeating the final file directive so the last frame keeps its duration.+ if let Some(last) = last_escaped {+ manifest.push_str(&format!("file '{}'\n", last));+ }if manifest.is_empty() {- return Err("No readable frames found on scratch disk".to_string());+ return Err("No readable frames found in local time-lapse storage".to_string());}tokio::fs::write(&list_path, manifest).await.map_err(|e| e.to_string())?;- let vf = format!(- "scale={}:{}:force_original_aspect_ratio=decrease,pad={}:{}:(ow-iw)/2:(oh-ih)/2:color=white",- safe_w, safe_h, safe_w, safe_h+ let has_watermark = if let Some(wm_bytes) = params.watermark_png {+ if !wm_bytes.is_empty() && wm_bytes.len() <= MAX_WATERMARK_PNG_BYTES {+ tokio::fs::write(&wm_path, wm_bytes)+ .await+ .map_err(|e| e.to_string())?;+ true+ } else {+ false+ }+ } else {+ false+ };++ let (use_complex, filter_expr) = build_ffmpeg_filtergraph(+ safe_w,+ safe_h,+ params.bg_color,+ params.bg_blur,+ has_watermark,+ params.watermark_x,+ params.watermark_y,);+ let (crf, preset) = quality_to_ffmpeg_crf_preset(params.quality);let mut cmd = Command::new("ffmpeg");cmd.args([@@ -344,12 +891,24 @@ pub async fn export_ffmpeg("0","-i",list_path.to_string_lossy().as_ref(),- "-vf",- &vf,+ ]);+ if has_watermark {+ cmd.args(["-i", wm_path.to_string_lossy().as_ref()]);+ }+ if use_complex {+ cmd.args(["-filter_complex", &filter_expr, "-map", "[out]"]);+ } else {+ cmd.args(["-vf", &filter_expr]);+ }+ cmd.args(["-r",&safe_fps.to_string(),"-c:v","libx264",+ "-preset",+ preset,+ "-crf",+ crf,"-pix_fmt","yuv420p","-movflags",@@ -364,7 +923,13 @@ pub async fn export_ffmpeg(.await.map_err(|e| format!("Failed to launch ffmpeg: {}", e))?;+ let _ = tokio::fs::remove_file(&list_path).await;+ if has_watermark {+ let _ = tokio::fs::remove_file(&wm_path).await;+ }+if !output.status.success() {+ let _ = tokio::fs::remove_file(&out_path).await;let stderr = String::from_utf8_lossy(&output.stderr);return Err(format!("FFmpeg failed: {}", stderr));}@@ -372,21 +937,279 @@ pub async fn export_ffmpeg(let bytes = tokio::fs::read(&out_path).await.map_err(|e| e.to_string())?;- let _ = tokio::fs::remove_file(&list_path).await;let _ = tokio::fs::remove_file(&out_path).await;Ok(bytes)}+/// Converts and downscales a top-down 32-bit BGRA buffer to an even-dimension RGBA buffer+/// bounded by `max_dim`, packed with an 8-byte header `[width: u32 LE][height: u32 LE][rgba...]`.+pub fn downscale_bgra_to_packed_rgba(+ bgra: &[u8],+ src_w: u32,+ src_h: u32,+ max_dim: u32,+) -> Result<Vec<u8>, String> {+ let sw = src_w as usize;+ let sh = src_h as usize;+ if sw == 0 || sh == 0 || bgra.len() < sw.saturating_mul(sh).saturating_mul(4) {+ return Err("Invalid source BGRA buffer dimensions".to_string());+ }++ let clamped_max = max_dim.clamp(64, 3840) as f64;+ let longest = (src_w.max(src_h)) as f64;+ let scale = if longest > clamped_max {+ clamped_max / longest+ } else {+ 1.0+ };+ let out_w = ((((src_w as f64) * scale).round() as u32).max(2) & !1).max(2) as usize;+ let out_h = ((((src_h as f64) * scale).round() as u32).max(2) & !1).max(2) as usize;++ let mut packed = Vec::with_capacity(8 + out_w * out_h * 4);+ packed.extend_from_slice(&(out_w as u32).to_le_bytes());+ packed.extend_from_slice(&(out_h as u32).to_le_bytes());++ if out_w == sw && out_h == sh {+ for px in bgra[..sw * sh * 4].chunks_exact(4) {+ packed.push(px[2]); // R+ packed.push(px[1]); // G+ packed.push(px[0]); // B+ packed.push(255); // Opaque window capture+ }+ return Ok(packed);+ }++ // Fast box/bilinear downscaler for crisp UI text & canvas strokes+ let scale_x = (sw as f64) / (out_w as f64);+ let scale_y = (sh as f64) / (out_h as f64);+ for oy in 0..out_h {+ let sy0 = ((oy as f64) * scale_y).floor() as usize;+ let sy1 = ((((oy + 1) as f64) * scale_y).ceil() as usize).clamp(sy0 + 1, sh);+ for ox in 0..out_w {+ let sx0 = ((ox as f64) * scale_x).floor() as usize;+ let sx1 = ((((ox + 1) as f64) * scale_x).ceil() as usize).clamp(sx0 + 1, sw);+ let mut sum_r: u32 = 0;+ let mut sum_g: u32 = 0;+ let mut sum_b: u32 = 0;+ let mut count: u32 = 0;+ for sy in sy0..sy1 {+ let row_off = sy * sw * 4;+ for sx in sx0..sx1 {+ let off = row_off + sx * 4;+ sum_b += bgra[off] as u32;+ sum_g += bgra[off + 1] as u32;+ sum_r += bgra[off + 2] as u32;+ count += 1;+ }+ }+ let c = count.max(1);+ packed.push((sum_r / c) as u8);+ packed.push((sum_g / c) as u8);+ packed.push((sum_b / c) as u8);+ packed.push(255);+ }+ }+ Ok(packed)+}++#[cfg(target_os = "windows")]+mod win_capture {+ use super::downscale_bgra_to_packed_rgba;+ use std::ffi::c_void;+ use windows_sys::Win32::Foundation::{HWND, RECT};+ use windows_sys::Win32::Graphics::Gdi::{+ BitBlt, CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC, ReleaseDC,+ SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HDC, HGDIOBJ, SRCCOPY,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetClientRect, IsIconic};++ const PW_CLIENTONLY: u32 = 0x0000_0001;+ const PW_RENDERFULLCONTENT: u32 = 0x0000_0002;++ extern "system" {+ fn PrintWindow(hwnd: HWND, hdc_blt: HDC, n_flags: u32) -> i32;+ }++ struct WindowDcGuard(HWND, HDC);+ impl Drop for WindowDcGuard {+ fn drop(&mut self) {+ if !self.1.is_null() {+ unsafe {+ ReleaseDC(self.0, self.1);+ }+ }+ }+ }++ struct MemDcGuard(HDC);+ impl Drop for MemDcGuard {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe {+ DeleteDC(self.0);+ }+ }+ }+ }++ struct BitmapGuard(HDC, HGDIOBJ, HGDIOBJ);+ impl Drop for BitmapGuard {+ fn drop(&mut self) {+ unsafe {+ if !self.0.is_null() && !self.1.is_null() {+ SelectObject(self.0, self.1);+ }+ if !self.2.is_null() {+ DeleteObject(self.2);+ }+ }+ }+ }++ pub fn capture_hwnd_rgba(hwnd_raw: isize, max_dim: u32) -> Result<Vec<u8>, String> {+ let hwnd = hwnd_raw as HWND;+ if hwnd.is_null() {+ return Err("Invalid window handle".to_string());+ }++ unsafe {+ if IsIconic(hwnd) != 0 {+ return Err("App window is minimized".to_string());+ }++ let mut rect = RECT {+ left: 0,+ top: 0,+ right: 0,+ bottom: 0,+ };+ if GetClientRect(hwnd, &mut rect) == 0 {+ return Err("Failed to query app window client rect".to_string());+ }+ let width = rect.right - rect.left;+ let height = rect.bottom - rect.top;+ if width <= 0 || height <= 0 || width > 16384 || height > 16384 {+ return Err("App window has invalid capture dimensions".to_string());+ }++ let win_dc = GetDC(hwnd);+ if win_dc.is_null() {+ return Err("Failed to acquire window DC".to_string());+ }+ let _win_dc_guard = WindowDcGuard(hwnd, win_dc);++ let mem_dc = CreateCompatibleDC(win_dc);+ if mem_dc.is_null() {+ return Err("Failed to create compatible memory DC".to_string());+ }+ let _mem_dc_guard = MemDcGuard(mem_dc);++ let mut bmi: BITMAPINFO = std::mem::zeroed();+ bmi.bmiHeader = BITMAPINFOHEADER {+ biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: width,+ biHeight: -height, // Top-down DIB+ biPlanes: 1,+ biBitCount: 32,+ biCompression: BI_RGB,+ biSizeImage: 0,+ biXPelsPerMeter: 0,+ biYPelsPerMeter: 0,+ biClrUsed: 0,+ biClrImportant: 0,+ };++ let mut bits_ptr: *mut c_void = std::ptr::null_mut();+ let hbmp = CreateDIBSection(+ win_dc,+ &bmi,+ DIB_RGB_COLORS,+ &mut bits_ptr,+ std::ptr::null_mut(),+ 0,+ );+ if hbmp.is_null() || bits_ptr.is_null() {+ return Err("Failed to allocate capture DIB section".to_string());+ }+ let old_obj = SelectObject(mem_dc, hbmp as HGDIOBJ);+ let _bmp_guard = BitmapGuard(mem_dc, old_obj, hbmp as HGDIOBJ);++ let byte_len = (width as usize) * (height as usize) * 4;+ std::ptr::write_bytes(bits_ptr as *mut u8, 0, byte_len);++ let ok_pw = PrintWindow(hwnd, mem_dc, PW_CLIENTONLY | PW_RENDERFULLCONTENT) != 0;+ let pixels = std::slice::from_raw_parts(bits_ptr as *const u8, byte_len);++ // Verify PrintWindow produced non-empty content; otherwise fallback to BitBlt+ let mut has_content = false;+ if ok_pw {+ let stride = (byte_len / 64).max(4) & !3;+ let mut i = 0usize;+ while i + 3 < byte_len {+ if pixels[i] != 0 || pixels[i + 1] != 0 || pixels[i + 2] != 0 {+ has_content = true;+ break;+ }+ i += stride;+ }+ }++ if !has_content {+ let _ = BitBlt(mem_dc, 0, 0, width, height, win_dc, 0, 0, SRCCOPY);+ }++ downscale_bgra_to_packed_rgba(pixels, width as u32, height as u32, max_dim)+ }+ }+}++pub async fn capture_app_window(+ app: &tauri::AppHandle,+ max_dim: u32,+) -> Result<Vec<u8>, String> {+ #[cfg(target_os = "windows")]+ {+ let window = app+ .get_webview_window("main")+ .ok_or_else(|| "Main app window not available".to_string())?;+ let hwnd = window+ .hwnd()+ .map_err(|e| format!("Failed to obtain window handle: {}", e))?;+ let hwnd_raw = hwnd.0 as isize;+ tokio::task::spawn_blocking(move || win_capture::capture_hwnd_rgba(hwnd_raw, max_dim))+ .await+ .map_err(|e| format!("App window capture worker failed: {}", e))?+ }+ #[cfg(not(target_os = "windows"))]+ {+ let _ = (app, max_dim);+ Err("Native app window capture is not supported on this platform".to_string())+ }+}+#[cfg(test)]mod tests {use super::*;+ fn make_test_root(tag: &str) -> PathBuf {+ std::env::temp_dir().join(format!(+ "inkstudio_tl_test_{}_{}",+ tag,+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ))+ }+#[test]fn test_escape_ffmpeg_concat_path_windows_and_quotes() {- let p = Path::new(r"C:\Users\O'Brien\AppData\Local\Temp\inkstudio_timelapse\s1\frame_000001.png");+ let p = Path::new(+ r"C:\Users\O'Brien\AppData\Local\inkstudio_timelapse\s1\frame_000001.png",+ );assert_eq!(escape_ffmpeg_concat_path(p),- "C:/Users/O'\\''Brien/AppData/Local/Temp/inkstudio_timelapse/s1/frame_000001.png"+ "C:/Users/O'\\''Brien/AppData/Local/inkstudio_timelapse/s1/frame_000001.png");}@@ -418,7 +1241,6 @@ mod tests {let unpacked = unpack_frame_batch(&packed).expect("unpack failed");assert_eq!(unpacked, entries);- // Truncated header & trailing bytes rejectedassert!(unpack_frame_batch(&[1, 2]).is_err());assert!(unpack_frame_batch(&packed[..packed.len() - 1]).is_err());let mut with_trailing = packed.clone();@@ -426,15 +1248,149 @@ mod tests {assert!(unpack_frame_batch(&with_trailing).is_err());}+ #[test]+ fn test_ffmpeg_filtergraph_colors_blur_watermark_and_quality() {+ assert_eq!(sanitize_ffmpeg_hex_color("#141414"), "0x141414");+ assert_eq!(sanitize_ffmpeg_hex_color("bad;rm -rf"), "0xffffff");++ assert_eq!(quality_to_ffmpeg_crf_preset("standard"), ("26", "veryfast"));+ assert_eq!(quality_to_ffmpeg_crf_preset("high"), ("20", "fast"));+ assert_eq!(quality_to_ffmpeg_crf_preset("ultra"), ("15", "medium"));+ assert_eq!(quality_to_ffmpeg_crf_preset("lossless"), ("10", "medium"));++ let (complex1, expr1) =+ build_ffmpeg_filtergraph(1920, 1080, "#141414", false, false, 0, 0);+ assert!(!complex1);+ assert!(expr1.contains("color=0x141414"));+ assert!(expr1.contains("setsar=1"));++ let (complex2, expr2) =+ build_ffmpeg_filtergraph(1920, 1080, "#ffffff", false, true, 1600, 960);+ assert!(complex2);+ assert!(expr2.contains("[base][1:v]overlay=1600:960:format=auto[out]"));++ let (complex3, expr3) =+ build_ffmpeg_filtergraph(1080, 1920, "#000000", true, true, 24, 32);+ assert!(complex3);+ assert!(expr3.contains("boxblur=20:2"));+ assert!(expr3.contains("overlay=24:32:format=auto[out]"));+ }++ #[test]+ fn test_downscale_bgra_to_packed_rgba() {+ // 4x4 uniform BGRA=(10, 20, 30, 255) -> RGBA=(30, 20, 10, 255)+ let mut bgra = Vec::with_capacity(4 * 4 * 4);+ for _ in 0..16 {+ bgra.extend_from_slice(&[10, 20, 30, 255]);+ }+ let packed = downscale_bgra_to_packed_rgba(&bgra, 4, 4, 1080).unwrap();+ let w = u32::from_le_bytes(packed[0..4].try_into().unwrap());+ let h = u32::from_le_bytes(packed[4..8].try_into().unwrap());+ assert_eq!((w, h), (4, 4));+ assert_eq!(&packed[8..12], &[30, 20, 10, 255]);++ // Downscaling 200x100 to max_dim=100 -> 100x50+ let mut big = Vec::with_capacity(200 * 100 * 4);+ for _ in 0..(200 * 100) {+ big.extend_from_slice(&[50, 100, 200, 255]);+ }+ let scaled = downscale_bgra_to_packed_rgba(&big, 200, 100, 100).unwrap();+ let sw = u32::from_le_bytes(scaled[0..4].try_into().unwrap());+ let sh = u32::from_le_bytes(scaled[4..8].try_into().unwrap());+ assert_eq!((sw, sh), (100, 50));+ assert_eq!(sw % 2, 0);+ assert_eq!(sh % 2, 0);+ assert_eq!(&scaled[8..12], &[200, 100, 50, 255]);+ }+#[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()+ async fn test_persistent_meta_ndjson_load_list_and_self_heal() {+ let root = make_test_root("persist");+ let sid = "rec-persist-1";++ let meta = TimelapseSessionMeta {+ recording_id: sid.to_string(),+ document_name: "Illustration.ink".to_string(),+ enabled: true,+ capture_area: "canvas-view".to_string(),+ capture_resolution: "4k".to_string(),+ next_index: 2,+ created_at: 1000,+ updated_at: 2000,+ };+ save_session_meta_in(root.clone(), sid, &serde_json::to_string(&meta).unwrap())+ .await+ .expect("save meta");++ write_frame_in(+ root.clone(),+ sid,+ 0,+ "webp",+ b"webp-frame-0".to_vec(),+ Some(FrameWriteMeta {+ timestamp: 1010,+ width: 1920,+ height: 1080,+ capture_area: Some("canvas-view".to_string()),+ }),+ )+ .await+ .expect("write frame 0");++ write_frame_in(+ root.clone(),+ sid,+ 1,+ "jpg",+ b"jpg-frame-1-longer".to_vec(),+ Some(FrameWriteMeta {+ timestamp: 1020,+ width: 1920,+ height: 1080,+ capture_area: Some("artwork".to_string()),+ }),+ )+ .await+ .expect("write frame 1");++ let loaded = load_session_in(root.clone(), sid).await.expect("load");+ assert_eq!(loaded.meta.as_ref(), Some(&meta));+ assert_eq!(loaded.frames.len(), 2);+ assert_eq!(loaded.frames[0].width, 1920);+ assert_eq!(loaded.frames[0].capture_area.as_deref(), Some("canvas-view"));+ assert_eq!(loaded.frames[1].mime_type, "image/jpeg");+ assert_eq!(+ loaded.total_bytes,+ (b"webp-frame-0".len() + b"jpg-frame-1-longer".len()) as u64);++ // Mixed-ext read works even if caller passes webp for jpg frame+ assert_eq!(+ read_frame_in(root.clone(), sid, 1, "webp").await.unwrap(),+ b"jpg-frame-1-longer"+ );++ let sessions = list_sessions_in(root.clone()).await.expect("list sessions");+ assert_eq!(sessions.len(), 1);+ assert_eq!(sessions[0].recording_id, sid);+ assert_eq!(sessions[0].frame_count, 2);+ assert_eq!(sessions[0].document_name, "Illustration.ink");++ // Self-heal when frames.ndjson is removed: still discovers both frames on disk!+ let _ = std::fs::remove_file(session_dir_in(&root, sid).join("frames.ndjson"));+ let healed = load_session_in(root.clone(), sid).await.expect("healed load");+ assert_eq!(healed.frames.len(), 2);++ clear_session_in(root.clone(), sid).await.expect("clear");+ assert!(list_frames_in(root.clone(), sid).await.unwrap().is_empty());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn test_write_frames_batch_list_and_mixed_ext_resolution() {+ let root = make_test_root("batch");+ let sid = "test_tl_batch";let entries = vec![FrameBatchEntry {frame_index: 0,@@ -447,24 +1403,32 @@ mod tests {data: b"jpg-frame-1".to_vec(),},];- let written = write_frames_batch(&sid, entries).await.expect("batch write");+ let written = write_frames_batch_in(root.clone(), sid, entries, None)+ .await+ .expect("batch write");assert_eq!(written, 2);- let listed = list_frames(&sid).await.expect("list frames");+ let listed = list_frames_in(root.clone(), 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");+ assert_eq!(+ read_frame_in(root.clone(), sid, 0, "webp").await.unwrap(),+ b"webp-frame-0"+ );+ assert_eq!(+ read_frame_in(root.clone(), 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 dir = session_dir_in(&root, 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());+ clear_session_in(root.clone(), sid).await.expect("clear");+ assert!(list_frames_in(root.clone(), sid).await.unwrap().is_empty());+ let _ = std::fs::remove_dir_all(&root);}}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex eb6fa5a..34ac9c8 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.2.0",+ "version": "1.2.1","identifier": "com.inkstudio.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/App.tsx b/src/App.tsxindex 3631d9a..60d1b81 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { AnimationTimeline, BlendMode, ExpressionColor, FilterType, LayerItem, LayerTreeDelta } from './types/editor';+import { AnimationTimeline, BlendMode, ExpressionColor, FilterType, LayerColorLabel, LayerItem, LayerTreeDelta } from './types/editor';import {createDefaultAnimationTimeline,removeFrameCel,@@ -8,10 +8,11 @@ import {import { screenToCanvas } from './utils/canvasUtils';import { createDefaultPageFrame } from './utils/frameEngine';import { AutoAction, AutoActionExecutionContext, executeAutoAction } from './utils/autoActionEngine';-import { globalTimelapseManager } from './utils/timelapseEngine';+import { globalTimelapseManager, TimelapseLiveCaptureContext } from './utils/timelapseEngine';import { globalTileGrid, TileSnapshotEntry } from './utils/tileEngine';import { documentStore } from './utils/documentStore';import { multiplayerService } from './services/multiplayerService';+import { recoveryService } from './services/recoveryService';import { updaterService } from './services/updaterService';import { useCanvasDrawing } from './hooks/useCanvasDrawing';import {@@ -807,6 +808,22 @@ export function App() {[checkCollabLayerEdit, layerMgr.toggleLayerColor]);+ const handleGuardedSetLayerColorLabel = useCallback(+ (id: string, colorLabel: LayerColorLabel) => {+ if (!checkCollabLayerEdit(id)) return;+ layerMgr.setLayerColorLabel(id, colorLabel);+ },+ [checkCollabLayerEdit, layerMgr.setLayerColorLabel]+ );++ const handleGuardedSoloLayer = useCallback(+ (id: string) => {+ if (!checkCollabLayerEdit(id)) return;+ layerMgr.toggleSoloLayer(id);+ },+ [checkCollabLayerEdit, layerMgr.toggleSoloLayer]+ );+const handleGuardedAddLayerMask = useCallback((...args: Parameters<typeof layerMgr.addLayerMask>) => {if (!checkCollabLayerEdit(args[0])) return;@@ -1052,26 +1069,61 @@ export function App() {});}, [activeDocumentId]);+ const getTimelapseCaptureContext = useCallback((): TimelapseLiveCaptureContext => {+ const docState = useDocumentStore.getState();+ const uiState = useUiStore.getState();+ return {+ viewportElement: nav.viewportRef.current,+ camera: nav.navigation.getCameraState(),+ showCheckerboard: uiState.appSettings.showCheckerboard,+ valueCheckEnabled: docState.valueCheckEnabled,+ isDrawingActive: () => recoveryService.getIsDrawingActive(),+ documentName: docState.documentName,+ };+ }, [nav.viewportRef, nav.navigation]);+const handleCaptureTimelapseNow = useCallback(() => {if (!activeDocumentId) return;globalTimelapseManager- .captureKeyframe(activeDocumentId, layerMgr.layers, dimensions, activeTileGrid, true)+ .captureKeyframe(+ activeDocumentId,+ layerMgr.layers,+ dimensions,+ activeTileGrid,+ true,+ getTimelapseCaptureContext()+ ).catch(() => {});- }, [activeDocumentId, layerMgr.layers, dimensions, activeTileGrid]);+ }, [activeDocumentId, layerMgr.layers, dimensions, activeTileGrid, getTimelapseCaptureContext]);const handleToggleTimelapseRecording = useCallback(() => {if (!activeDocumentId) return;- const next = globalTimelapseManager.toggleRecording(activeDocumentId);+ const docName = useDocumentStore.getState().documentName;+ const next = globalTimelapseManager.toggleRecording(activeDocumentId, docName);documentStoreActions.markDocumentDirty(activeDocumentId, true);if (next) {globalTimelapseManager- .captureKeyframe(activeDocumentId, layerMgr.layers, dimensions, activeTileGrid, true)+ .captureKeyframe(+ activeDocumentId,+ layerMgr.layers,+ dimensions,+ activeTileGrid,+ true,+ getTimelapseCaptureContext()+ ).catch(() => {});- showToast('Time-lapse recording started');+ showToast('Time-lapse recording started (saved locally)');} else {showToast('Time-lapse recording paused');}- }, [activeDocumentId, layerMgr.layers, dimensions, activeTileGrid, showToast]);+ }, [+ activeDocumentId,+ layerMgr.layers,+ dimensions,+ activeTileGrid,+ getTimelapseCaptureContext,+ showToast,+ ]);// Mark active document dirty & record time-lapse keyframe whenever a new history step is committedconst lastHistoryMetaRef = useRef<{ docId: string | null; itemId: string | null }>({@@ -1092,12 +1144,27 @@ export function App() {documentStoreActions.markDocumentDirty(activeDocumentId, true);if (globalTimelapseManager.isRecording(activeDocumentId)) {globalTimelapseManager- .captureKeyframe(activeDocumentId, layerMgr.layers, dimensions, activeTileGrid)+ .captureKeyframe(+ activeDocumentId,+ layerMgr.layers,+ dimensions,+ activeTileGrid,+ false,+ getTimelapseCaptureContext()+ ).catch(() => {});}}lastHistoryMetaRef.current = { docId: activeDocumentId, itemId: currentItemId };- }, [activeDocumentId, drawing.historyList, drawing.historyIndex, layerMgr.layers, dimensions, activeTileGrid]);+ }, [+ activeDocumentId,+ drawing.historyList,+ drawing.historyIndex,+ layerMgr.layers,+ dimensions,+ activeTileGrid,+ getTimelapseCaptureContext,+ ]);// Unified Pointer Dispatcher reading tool imperatively from useToolStoreconst handlePointerDown = useCallback(@@ -1447,8 +1514,10 @@ export function App() {onCancelTransform: selectionTools.handleCancelTransform,textSession: shapeFillTools.textSession,setTextSession: shapeFillTools.setTextSession,+ textDragPreview: shapeFillTools.textDragPreview,onConfirmText: shapeFillTools.handleConfirmText,onCancelText: shapeFillTools.handleCancelText,+ onDeleteText: shapeFillTools.handleDeleteText,onInsertRasterLayer: tonalActions.handleInsert3DRasterLayer,activeBalloon: shapeFillTools.activeBalloon,setActiveBalloon: shapeFillTools.setActiveBalloon,@@ -1475,11 +1544,13 @@ export function App() {onAddAnimationCel: handleAddAnimationCel,onDeleteAnimationCel: handleDeleteAnimationCel,onSelectCelLayer: layerMgr.setActiveLayerId,+ onApplyResizeCanvas: docLifecycle.handleResizeCanvas,}),[nav,docLifecycle.handleViewportReady,docLifecycle.handlePasteSelectedLayer,+ docLifecycle.handleResizeCanvas,drawing.isHovering,drawing.cursorPos,drawing.handlePointerEnter,@@ -1505,8 +1576,10 @@ export function App() {tonalActions.handleInsert3DRasterLayer,shapeFillTools.textSession,shapeFillTools.setTextSession,+ shapeFillTools.textDragPreview,shapeFillTools.handleConfirmText,shapeFillTools.handleCancelText,+ shapeFillTools.handleDeleteText,shapeFillTools.activeBalloon,shapeFillTools.setActiveBalloon,shapeFillTools.handleConfirmBalloon,@@ -1618,6 +1691,10 @@ export function App() {duplicateLayer={handleRecordedDuplicateLayer}handleDeleteLayer={collab.handleDeleteLayer}handleToggleVisibility={collab.handleToggleVisibility}+ soloLayerId={layerMgr.soloLayerId}+ handleSoloLayer={handleGuardedSoloLayer}+ handleExitSoloLayer={layerMgr.exitSoloLayer}+ setLayerColorLabel={handleGuardedSetLayerColorLabel}handleSetOpacity={handleRecordedSetOpacity}setBlendMode={handleRecordedSetBlendMode}toggleLock={collab.handleToggleLock}@@ -1661,10 +1738,12 @@ export function App() {activeLayerId={layerMgr.activeLayerId}needsAdaptiveFitRef={docLifecycle.needsAdaptiveFitRef}pendingFitDimsRef={docLifecycle.pendingFitDimsRef}+ autoCreatedInitialDocIdRef={docLifecycle.autoCreatedInitialDocIdRef}resetToNewCanvas={layerMgr.resetToNewCanvas}resetZoomAndCenter={nav.resetZoomAndCenter}resetHistory={drawing.resetHistory}onSelectDocument={docLifecycle.handleSelectDocument}+ onOpenFilePaths={docLifecycle.handleOpenFilePaths}/><GlobalShortcutListener@@ -1728,9 +1807,11 @@ export function App() {isLayerEffectivelyVisible={layerMgr.isLayerEffectivelyVisible}handleCreateNewCanvas={docLifecycle.handleCreateNewCanvas}handleResizeCanvas={docLifecycle.handleResizeCanvas}+ selectionBounds={selectionTools.selection?.bounds ?? null}handleUpdateSettings={docLifecycle.handleUpdateSettings}handleRestoreCrashedSession={docLifecycle.handleRestoreCrashedSession}handleDiscardCrashedSession={docLifecycle.handleDiscardCrashedSession}+ handleDiscardAllCrashedSessions={docLifecycle.handleDiscardAllCrashedSessions}handleTonalCancel={tonalActions.handleTonalCancel}handleTonalApply={tonalActions.handleTonalApply}handleTonalPreviewChange={tonalActions.handleTonalPreviewChange}diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsxindex 6ae9c15..fb43c2a 100644--- a/src/components/AnimationTimeline.tsx+++ b/src/components/AnimationTimeline.tsx@@ -16,7 +16,7 @@ import {exportAnimationToApng,exportAnimationToVideo,exportAnimationToPngZip,- downloadBlob,+ saveAnimationBlob,} from '../utils/animationEngine';export interface AnimationTimelineProps {@@ -210,7 +210,10 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({filename += '.zip';}- downloadBlob(blob, filename);+ const saveRes = await saveAnimationBlob(blob, filename);+ if (saveRes.canceled) {+ return;+ }setShowExportModal(false);} catch (err) {console.error('[Animation Export Failed]:', err);diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsxindex daef075..8e719ad 100644--- a/src/components/AppShell.tsx+++ b/src/components/AppShell.tsx@@ -5,6 +5,7 @@ import {CanvasSelection,ExpressionColor,HistoryItemMeta,+ LayerColorLabel,LayerItem,MenuSection,NewCanvasOptions,@@ -20,14 +21,16 @@ import type { QuickShapePreviewState } from '../utils/quickShapeEngine';import { CollabPeer } from '../types/multiplayer';import { SparseTileGrid } from '../utils/tileEngine';import { RecentDocument } from '../utils/recentDocumentsManager';-import { ModifierAction } from '../types/settings';+import { ModifierAction, ResizeCanvasOptions } from '../types/settings';import { applyAppearanceTokens } from '../utils/themeEngine';import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';import {TextPlacementSession,+ TextDragPreview,FrameDragPreview,LassoFillPreview,} from '../hooks/drawing/useShapeAndFillTools';+import { extractPersistableTextStyle } from '../utils/textSettings';import type { GradientMeshMarqueeRect } from '../hooks/drawing/useGradientTool';import { AutoAction } from '../utils/autoActionEngine';import {@@ -147,8 +150,10 @@ interface CanvasAreaContainerProps {onCancelTransform: () => void;textSession: TextPlacementSession | null;setTextSession: React.Dispatch<React.SetStateAction<TextPlacementSession | null>>;+ textDragPreview?: TextDragPreview | null;onConfirmText: () => void;onCancelText: () => void;+ onDeleteText?: () => void;onInsertRasterLayer: (layer: LayerItem, canvas: HTMLCanvasElement) => void;activeBalloon: SpeechBalloon | null;setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;@@ -177,6 +182,7 @@ interface CanvasAreaContainerProps {onSelectCelLayer: (layerId: string) => void;isExternalFileDropActive?: boolean;externalFileDropKind?: ExternalFileDropPayloadKind;+ onApplyResizeCanvas?: (options: ResizeCanvasOptions) => void;}/**@@ -236,11 +242,32 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propconst handleUpdateTextSettings = useCallback((updater: (prev: TextPlacementSession['settings']) => TextPlacementSession['settings']) => {- props.setTextSession((prev) => (prev ? { ...prev, settings: updater(prev.settings) } : null));+ props.setTextSession((prev) => {+ if (!prev) return null;+ const nextSettings = updater(prev.settings);+ const prevStyle = extractPersistableTextStyle(prev.settings);+ const nextStyle = extractPersistableTextStyle(nextSettings);+ const styleChanged = (Object.keys(nextStyle) as Array<keyof typeof nextStyle>).some(+ (k) => prevStyle[k] !== nextStyle[k]+ );+ if (styleChanged) {+ toolStoreActions.updateTextSettings(nextStyle);+ }+ return { ...prev, settings: nextSettings };+ });},[props.setTextSession]);+ const editingTextLayerId = props.textSession?.editingLayerId ?? null;+ const effectiveCanvasLayerVisibility = useCallback(+ (layer: LayerItem) => {+ if (editingTextLayerId && layer.id === editingTextLayerId) return false;+ return props.isLayerEffectivelyVisible(layer);+ },+ [editingTextLayerId, props.isLayerEffectivelyVisible]+ );+const handleMoveTextSession = useCallback((newX: number, newY: number) => {props.setTextSession((prev) => (prev ? { ...prev, x: newX, y: newY } : null));@@ -294,7 +321,7 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propcolorMode={colorMode}tileGrid={props.tileGrid}getEffectiveOpacity={props.getEffectiveOpacity}- isLayerEffectivelyVisible={props.isLayerEffectivelyVisible}+ isLayerEffectivelyVisible={effectiveCanvasLayerVisibility}interactionRef={props.interactionRef}showCheckerboard={showCheckerboard}showCursorCoordinates={showCursorCoordinates}@@ -342,6 +369,8 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proponMoveTextSession={handleMoveTextSession}onConfirmText={props.onConfirmText}onCancelText={props.onCancelText}+ onDeleteText={props.onDeleteText}+ textDragPreview={props.textDragPreview}perspectiveRuler={hasOpenDocument ? perspectiveRuler : null}onUpdatePerspectiveRuler={documentStoreActions.setPerspectiveRuler}straightRuler={hasOpenDocument ? straightRuler : null}@@ -384,6 +413,7 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propvalueCheckEnabled={valueCheckEnabled}isExternalFileDropActive={props.isExternalFileDropActive}externalFileDropKind={props.externalFileDropKind}+ onApplyResizeCanvas={props.onApplyResizeCanvas}/>);});@@ -501,6 +531,10 @@ export interface AppShellProps {duplicateLayer: (id: string) => void;handleDeleteLayer: (id: string) => void;handleToggleVisibility: (id: string) => void;+ soloLayerId?: string | null;+ handleSoloLayer?: (id: string) => void;+ handleExitSoloLayer?: () => void;+ setLayerColorLabel?: (id: string, colorLabel: LayerColorLabel) => void;handleSetOpacity: (id: string, opacity: number) => void;setBlendMode: (id: string, blendMode: BlendMode) => void;toggleLock: (id: string) => void;@@ -600,6 +634,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(duplicateLayer,handleDeleteLayer,handleToggleVisibility,+ soloLayerId = null,+ handleSoloLayer,+ handleExitSoloLayer,+ setLayerColorLabel,handleSetOpacity,setBlendMode,toggleLock,@@ -868,6 +906,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(onDuplicateLayer: duplicateLayer,onDeleteLayer: handleDeleteLayer,onToggleVisibility: handleToggleVisibility,+ soloLayerId,+ onSoloLayer: handleSoloLayer,+ onExitSoloLayer: handleExitSoloLayer,+ onSetLayerColorLabel: setLayerColorLabel,onSetOpacity: handleSetOpacity,onSetBlendMode: setBlendMode,onToggleLock: toggleLock,@@ -941,6 +983,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(duplicateLayer,handleDeleteLayer,handleToggleVisibility,+ soloLayerId,+ handleSoloLayer,+ handleExitSoloLayer,+ setLayerColorLabel,handleSetOpacity,setBlendMode,toggleLock,diff --git a/src/components/AppearanceStudioDrawer.tsx b/src/components/AppearanceStudioDrawer.tsxindex 86bc9f3..e4de356 100644--- a/src/components/AppearanceStudioDrawer.tsx+++ b/src/components/AppearanceStudioDrawer.tsx@@ -64,6 +64,7 @@ import {} from '../utils/interfaceScale';import { selectIsAnyModalOpen, uiStoreActions, useUiStore } from '../stores';import { acquireWorkspaceInteractionLock } from '../utils/workspacePointerGuard';+import { saveFileWithDialog } from '../utils/fileSaveDialog';import {HairlineTabs,IconButton,@@ -775,7 +776,7 @@ const AppearanceStudioPanel: React.FC<AppearanceStudioDrawerProps> = ({ showToasnotify('Custom token overrides cleared');}, [commitAppearanceReplace, notify]);- const handleExportThemeFile = useCallback(() => {+ const handleExportThemeFile = useCallback(async () => {const cur = latestAppearanceRef.current;const baseName =cur.lookPreset === 'custom'@@ -788,16 +789,17 @@ const AppearanceStudioPanel: React.FC<AppearanceStudioDrawerProps> = ({ showToas});const fileName = `${slugifyThemeName(baseName)}.inktheme`;try {- const blob = new Blob([json], { type: 'application/json;charset=utf-8' });- const url = URL.createObjectURL(blob);- const anchor = document.createElement('a');- anchor.href = url;- anchor.download = fileName;- document.body.appendChild(anchor);- anchor.click();- document.body.removeChild(anchor);- setTimeout(() => URL.revokeObjectURL(url), 1000);- notify(`Exported ${fileName}`);+ const res = await saveFileWithDialog({+ data: json,+ suggestedName: fileName,+ mimeType: 'application/json;charset=utf-8',+ description: 'Ink Studio Theme',+ extensions: ['.inktheme', '.json'],+ category: 'theme',+ title: 'Save Theme As',+ });+ if (res.canceled) return;+ notify(`Exported ${res.fileName}`);} catch {notify('Unable to export .inktheme file');}diff --git a/src/components/AutoActionPanel.tsx b/src/components/AutoActionPanel.tsxindex 88c1483..6ddcfe5 100644--- a/src/components/AutoActionPanel.tsx+++ b/src/components/AutoActionPanel.tsx@@ -17,7 +17,7 @@ import {importAutoActionSetsJson,} from '../utils/autoActionEngine';import { autoActionStoreActions, useAutoActionStore } from '../stores';-import { downloadFile } from '../utils/saveManager';+import { saveFileWithDialog } from '../utils/fileSaveDialog';export interface AutoActionPanelProps {hasOpenDocument: boolean;@@ -68,10 +68,23 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(}};- const handleExportJson = () => {- const json = exportAutoActionSetsJson(sets);- downloadFile(new Blob([json], { type: 'application/json' }), 'inkstudio-auto-actions.json', 'application/json');- showToast?.('Exported Auto Action sets');+ const handleExportJson = async () => {+ try {+ const json = exportAutoActionSetsJson(sets);+ const res = await saveFileWithDialog({+ data: json,+ suggestedName: 'inkstudio-auto-actions.json',+ mimeType: 'application/json',+ description: 'Ink Studio Auto Actions',+ extensions: ['.json'],+ category: 'auto-action',+ title: 'Save Auto Actions As',+ });+ if (res.canceled) return;+ showToast?.(`Exported ${res.fileName}`);+ } catch {+ showToast?.('Failed to export Auto Action sets');+ }};const handleImportJson = () => {diff --git a/src/components/BrushPreview.tsx b/src/components/BrushPreview.tsxindex 73cfc9c..a80c470 100644--- a/src/components/BrushPreview.tsx+++ b/src/components/BrushPreview.tsx@@ -1,6 +1,7 @@import React, { useRef, useEffect, useState } from 'react';import { BrushSettings, BrushPresetId, CspSubTip } from '../types/editor';import { renderBrushStrokePreview, BrushPreviewOptions } from '../utils/brushPreview';+import { getBuiltinBrushConfig } from '../utils/presetBrushes';import { getPreloadedTipImage, preloadTipImage } from '../utils/brushStorage';import { DEFAULT_BRUSH_PRESET_ID } from '../utils/brushPresetManager';@@ -178,18 +179,69 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({}}+ // Ensure newly created procedural built-in tip/dual/paper HTMLImageElements+ // trigger a clean preview re-render as soon as browser PNG decoding completes.+ const pendingListeners: Array<{ img: HTMLImageElement; fn: () => void }> = [];+ const watchPendingImage = (img?: HTMLImageElement) => {+ if (!img) return;+ if (img.complete && (img.naturalWidth || img.width) > 0) return;+ const onLoaded = () => bump();+ if (typeof img.addEventListener === 'function') {+ img.addEventListener('load', onLoaded, { once: true });+ pendingListeners.push({ img, fn: onLoaded });+ }+ if (typeof img.decode === 'function') {+ img.decode().then(bump).catch(() => {});+ }+ };++ watchPendingImage(customTipImage);+ watchPendingImage(settings?.customTipImage);+ watchPendingImage(explicitDual);+ watchPendingImage(settings?.paperTextureImage);+ if (settings?.subTipImages) {+ for (const img of settings.subTipImages) watchPendingImage(img);+ }++ if (+ isVisible &&+ preset &&+ !customTipImage &&+ !settings?.customTipImage &&+ typeof canvasRef.current?.getContext === 'function'+ ) {+ const builtinCfg = getBuiltinBrushConfig(preset);+ if (builtinCfg) {+ watchPendingImage(builtinCfg.customTipImage);+ watchPendingImage(builtinCfg.dualTipImage ?? builtinCfg.dualBrushConfig?.tipImage);+ watchPendingImage(builtinCfg.paperTextureImage);+ if (builtinCfg.subTipImages) {+ for (const img of builtinCfg.subTipImages) watchPendingImage(img);+ }+ }+ }+return () => {cancelled = true;+ for (const entry of pendingListeners) {+ if (typeof entry.img.removeEventListener === 'function') {+ entry.img.removeEventListener('load', entry.fn);+ }+ }};}, [+ isVisible,+ preset,customTipImage,tipUrl,dualTipUrl,paperUrl,+ settings?.customTipImage,settings?.dualTipImage,settings?.dualBrushConfig?.tipImage,settings?.paperTextureImage,settings?.subTips,+ settings?.subTipImages,settings?.dualSubTips,settings?.dualBrushConfig?.subTips,]);diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsxindex ba50113..3cb2c56 100644--- a/src/components/CanvasArea.tsx+++ b/src/components/CanvasArea.tsx@@ -1,7 +1,8 @@import React, { useState, useRef } from 'react';import { globalTileGrid } from '../utils/tileEngine';-import { useWorkspaceStore } from '../stores';+import { useUiStore, useWorkspaceStore } from '../stores';import { FloatingBrushPill } from './FloatingBrushPill';+import { CanvasResizeMarqueeBackdrop } from './CanvasResizeOverlay';import {CanvasAreaProps,extractCoalescedEvents,@@ -70,6 +71,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;const localPredictedCanvasRef = useRef<HTMLCanvasElement | null>(null);const effectivePredictedCanvasRef = predictedCanvasRef || localPredictedCanvasRef;+ const isResizeCanvasOpen = useUiStore((s) => s.isResizeCanvasModalOpen);const activeLayer = layers.find((l) => l.id === activeLayerId);const isMonochromeActive = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome' || brushSettings.antiAlias === 0;@@ -220,6 +222,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {isRotateModifier,isPanning,isSpaceDown,+ isResizeCanvasOpen,tool,fillMethod: fillSettings?.method,};@@ -247,6 +250,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {const showFloatingPill =!palettesHidden &&+ !isResizeCanvasOpen &&(tool === 'brush' ||tool === 'decoration' ||tool === 'eraser' ||@@ -318,6 +322,29 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {}}/>+ {/* Full-Viewport Outside-Frame Crop Marquee Capture (active only during Resize Canvas in Bounds mode) */}+ <CanvasResizeMarqueeBackdrop+ dimensions={dimensions}+ viewportRef={viewportRef}+ navigation={navigation}+ pan={livePan}+ zoom={liveZoom}+ rotation={liveRotation}+ flipX={liveFlipX}+ flipY={liveFlipY}+ isSpaceDown={isSpaceDown}+ isNavigationActive={+ isSpaceDown ||+ isPanning ||+ isRotating ||+ isZoomDragging ||+ isRotateModifier ||+ heldModifierAction === 'pan' ||+ heldModifierAction === 'rotate' ||+ heldModifierAction === 'zoom-drag'+ }+ />+{/* Artboard Container with 2D Affine Transformation (Pan, Zoom, Rotation, and Non-Destructive View Flip) */}<CanvasArtboardOverlayscanvasProps={props}diff --git a/src/components/CanvasResizeOverlay.tsx b/src/components/CanvasResizeOverlay.tsxnew file mode 100644index 0000000..dccc47b--- /dev/null+++ b/src/components/CanvasResizeOverlay.tsx@@ -0,0 +1,998 @@+import React, { useEffect, useRef, useState, useCallback, useId } from 'react';+import { createPortal } from 'react-dom';+import {+ Check,+ X,+ RotateCcw,+ Grid3X3,+ ArrowLeftRight,+ SlidersHorizontal,+ Lock,+} from 'lucide-react';+import { CanvasDimensions } from '../types/editor';+import { ResizeCanvasOptions } from '../types/settings';+import { CanvasNavigationHandle, CameraTransformState } from '../hooks/useCanvasNavigation';+import { screenToCanvas } from '../utils/canvasUtils';+import { resolvePointerModifierAction } from '../utils/shortcutManager';+import { uiStoreActions, useUiStore } from '../stores';+import {+ CropGridMode,+ CropHandleId,+ CropRect,+ CropResizeHandleId,+ SnapGuides,+ applyCropRectToDraft,+ applyResetCropToDraft,+ applySwapDimensionsToDraft,+ createCropRectFromDrag,+ cycleCropGridMode,+ draftToResizeCanvasOptions,+ getRotatedResizeCursor,+ isCropModified,+ moveCropRect,+ resizeCropRectByHandle,+} from '../utils/canvasResizeCrop';++export interface CanvasResizeOverlayProps {+ dimensions: CanvasDimensions;+ viewportRef: React.RefObject<HTMLDivElement | null>;+ navigation?: CanvasNavigationHandle;+ pan: { x: number; y: number };+ zoom: number;+ rotation: number;+ flipX?: boolean;+ flipY?: boolean;+ isNavigationActive?: boolean;+ onApply?: (options: ResizeCanvasOptions) => void;+ onCancel?: () => void;+}++const CORNER_HANDLES: CropResizeHandleId[] = ['nw', 'ne', 'se', 'sw'];+const EDGE_HANDLES: CropResizeHandleId[] = ['n', 'e', 's', 'w'];+const SNAP_THRESHOLD_SCREEN_PX = 6;+const MARQUEE_DRAG_THRESHOLD_PX = 4;++function isNavigationPointerDown(e: React.PointerEvent, isSpaceDown: boolean): boolean {+ if (e.button !== 0 || isSpaceDown) return true;+ const modSettings = useUiStore.getState().appSettings.modifierKeys;+ const resolved = resolvePointerModifierAction(+ {+ button: e.button,+ pointerType: e.pointerType,+ ctrlKey: e.ctrlKey,+ metaKey: e.metaKey,+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ isSpaceDown,+ },+ modSettings+ );+ return (+ resolved?.action === 'pan' ||+ resolved?.action === 'rotate' ||+ resolved?.action === 'zoom-drag'+ );+}++function getGridLabel(mode: CropGridMode): string {+ if (mode === 'thirds') return 'Rule of Thirds';+ if (mode === 'golden') return 'Golden Ratio';+ return 'No Grid';+}++function getGridFractions(mode: CropGridMode): [number, number] | null {+ if (mode === 'thirds') return [1 / 3, 2 / 3];+ if (mode === 'golden') return [0.381966, 0.618034];+ return null;+}++/**+ * Full-viewport capture backdrop (mounted between canvas interaction surface and artboard overlays)+ * allowing the user to click-drag outside the existing crop rectangle to draw a brand-new crop box,+ * just like Photoshop's Crop tool. Navigation modifiers & non-primary buttons pass through.+ */+export const CanvasResizeMarqueeBackdrop: React.FC<{+ dimensions: CanvasDimensions;+ viewportRef: React.RefObject<HTMLDivElement | null>;+ navigation?: CanvasNavigationHandle;+ pan: { x: number; y: number };+ zoom: number;+ rotation: number;+ flipX?: boolean;+ flipY?: boolean;+ isSpaceDown?: boolean;+ isNavigationActive?: boolean;+}> = ({+ dimensions,+ viewportRef,+ navigation,+ pan,+ zoom,+ rotation,+ flipX = false,+ flipY = false,+ isSpaceDown = false,+ isNavigationActive = false,+}) => {+ const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);+ const scaleContent = useUiStore((s) => s.canvasResizeDraft?.scaleContent ?? false);+ const cleanupRef = useRef<(() => void) | null>(null);++ useEffect(() => {+ return () => {+ cleanupRef.current?.();+ cleanupRef.current = null;+ };+ }, []);++ if (!isOpen || scaleContent || isNavigationActive) return null;++ const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {+ if (isNavigationPointerDown(e, isSpaceDown)) {+ return;+ }+ const draft = useUiStore.getState().canvasResizeDraft;+ if (!draft || draft.scaleContent) return;++ e.preventDefault();+ e.stopPropagation();++ cleanupRef.current?.();++ const startClientX = e.clientX;+ const startClientY = e.clientY;++ const getCam = (): CameraTransformState =>+ navigation ? navigation.getCameraState() : { pan, zoom, rotation, flipX, flipY };+ const getRect = (): DOMRect =>+ viewportRef.current?.getBoundingClientRect() ?? new DOMRect(0, 0, 0, 0);++ const startCam = getCam();+ const startViewportRect = getRect();+ const startDoc = screenToCanvas(+ startClientX,+ startClientY,+ startViewportRect,+ startCam.pan,+ startCam.zoom,+ startCam.rotation,+ dimensions,+ startCam.flipX,+ startCam.flipY+ );++ let hasStartedDrag = false;++ const handleMove = (ev: PointerEvent) => {+ const dist = Math.hypot(ev.clientX - startClientX, ev.clientY - startClientY);+ if (!hasStartedDrag) {+ if (dist < MARQUEE_DRAG_THRESHOLD_PX) return;+ hasStartedDrag = true;+ }++ const curDraft = useUiStore.getState().canvasResizeDraft;+ if (!curDraft || curDraft.scaleContent) return;++ const cam = getCam();+ const vpRect = getRect();+ const curDoc = screenToCanvas(+ ev.clientX,+ ev.clientY,+ vpRect,+ cam.pan,+ cam.zoom,+ cam.rotation,+ dimensions,+ cam.flipX,+ cam.flipY+ );++ const snapThreshold = SNAP_THRESHOLD_SCREEN_PX / Math.max(0.05, cam.zoom);+ const snapTargets =+ ev.ctrlKey || ev.metaKey+ ? null+ : {+ x: [0, dimensions.width / 2, dimensions.width],+ y: [0, dimensions.height / 2, dimensions.height],+ threshold: snapThreshold,+ };++ const lockAspect = curDraft.lockRatio || ev.shiftKey;+ const aspectRatio = curDraft.lockRatio+ ? curDraft.ratioX / Math.max(1, curDraft.ratioY)+ : 1;++ const { rect } = createCropRectFromDrag(startDoc, curDoc, {+ lockAspect,+ aspectRatio,+ fromCenter: ev.altKey,+ snapTargets,+ });++ uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));+ };++ const handleUp = () => {+ window.removeEventListener('pointermove', handleMove);+ window.removeEventListener('pointerup', handleUp);+ window.removeEventListener('pointercancel', handleUp);+ cleanupRef.current = null;+ };++ cleanupRef.current = handleUp;+ window.addEventListener('pointermove', handleMove);+ window.addEventListener('pointerup', handleUp);+ window.addEventListener('pointercancel', handleUp);+ };++ return (+ <div+ data-testid="canvas-crop-marquee-backdrop"+ onPointerDown={handlePointerDown}+ className="absolute inset-0 z-[18] cursor-crosshair"+ />+ );+};++export const CanvasResizeOverlay: React.FC<CanvasResizeOverlayProps> = ({+ dimensions,+ viewportRef,+ navigation,+ pan,+ zoom,+ rotation,+ flipX = false,+ flipY = false,+ isNavigationActive = false,+ onApply,+ onCancel,+}) => {+ const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);+ const draft = useUiStore((s) => s.canvasResizeDraft);+ const isInspectorCollapsed = useUiStore((s) => s.isResizeInspectorCollapsed);+ const patternId = useId();++ const [activeHandle, setActiveHandle] = useState<CropHandleId | null>(null);+ const [hoveredHandle, setHoveredHandle] = useState<CropHandleId | null>(null);+ const [snapGuides, setSnapGuides] = useState<SnapGuides>({});+ const dragCleanupRef = useRef<(() => void) | null>(null);++ useEffect(() => {+ return () => {+ dragCleanupRef.current?.();+ dragCleanupRef.current = null;+ };+ }, []);++ useEffect(() => {+ if (!isOpen) {+ dragCleanupRef.current?.();+ dragCleanupRef.current = null;+ setActiveHandle(null);+ setHoveredHandle(null);+ setSnapGuides({});+ }+ }, [isOpen]);++ const handleConfirm = useCallback(() => {+ const current = useUiStore.getState().canvasResizeDraft;+ if (!current) return;+ const options = draftToResizeCanvasOptions(current);+ onApply?.(options);+ uiStoreActions.setResizeCanvasModalOpen(false);+ }, [onApply]);++ const handleCancel = useCallback(() => {+ if (onCancel) {+ onCancel();+ } else {+ uiStoreActions.setResizeCanvasModalOpen(false);+ }+ }, [onCancel]);++ const startHandleDrag = useCallback(+ (handle: CropHandleId, e: React.PointerEvent) => {+ if (isNavigationPointerDown(e, isNavigationActive)) {+ return;+ }+ const curDraft = useUiStore.getState().canvasResizeDraft;+ if (!curDraft || curDraft.scaleContent) return;++ e.preventDefault();+ e.stopPropagation();++ dragCleanupRef.current?.();++ const startRect: CropRect = {+ x: curDraft.cropX,+ y: curDraft.cropY,+ width: curDraft.width,+ height: curDraft.height,+ };+ const startAspect = curDraft.lockRatio+ ? curDraft.ratioX / Math.max(1, curDraft.ratioY)+ : startRect.width / Math.max(1, startRect.height);++ const getCam = (): CameraTransformState =>+ navigation ? navigation.getCameraState() : { pan, zoom, rotation, flipX, flipY };+ const getRect = (): DOMRect =>+ viewportRef.current?.getBoundingClientRect() ?? new DOMRect(0, 0, 0, 0);++ const startCam = getCam();+ const startVpRect = getRect();+ const startDoc = screenToCanvas(+ e.clientX,+ e.clientY,+ startVpRect,+ startCam.pan,+ startCam.zoom,+ startCam.rotation,+ dimensions,+ startCam.flipX,+ startCam.flipY+ );++ setActiveHandle(handle);++ const handleMove = (ev: PointerEvent) => {+ const latestDraft = useUiStore.getState().canvasResizeDraft;+ if (!latestDraft || latestDraft.scaleContent) return;++ const cam = getCam();+ const vpRect = getRect();+ const curDoc = screenToCanvas(+ ev.clientX,+ ev.clientY,+ vpRect,+ cam.pan,+ cam.zoom,+ cam.rotation,+ dimensions,+ cam.flipX,+ cam.flipY+ );++ const dx = curDoc.x - startDoc.x;+ const dy = curDoc.y - startDoc.y;++ const snapThreshold = SNAP_THRESHOLD_SCREEN_PX / Math.max(0.05, cam.zoom);+ const snapTargets =+ ev.ctrlKey || ev.metaKey+ ? null+ : {+ x: [0, dimensions.width / 2, dimensions.width],+ y: [0, dimensions.height / 2, dimensions.height],+ threshold: snapThreshold,+ };++ if (handle === 'move') {+ const { rect, snapGuides: nextGuides } = moveCropRect(startRect, dx, dy, {+ constrainAxis: ev.shiftKey,+ snapTargets,+ });+ setSnapGuides(nextGuides);+ uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));+ return;+ }++ const lockAspect = latestDraft.lockRatio || ev.shiftKey;+ const aspectRatio = latestDraft.lockRatio+ ? latestDraft.ratioX / Math.max(1, latestDraft.ratioY)+ : startAspect;++ const { rect, snapGuides: nextGuides } = resizeCropRectByHandle(+ startRect,+ handle,+ dx,+ dy,+ {+ lockAspect,+ aspectRatio,+ fromCenter: ev.altKey,+ snapTargets,+ }+ );+ setSnapGuides(nextGuides);+ uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));+ };++ const handleUp = () => {+ window.removeEventListener('pointermove', handleMove);+ window.removeEventListener('pointerup', handleUp);+ window.removeEventListener('pointercancel', handleUp);+ dragCleanupRef.current = null;+ setActiveHandle(null);+ setSnapGuides({});+ };++ dragCleanupRef.current = handleUp;+ window.addEventListener('pointermove', handleMove);+ window.addEventListener('pointerup', handleUp);+ window.addEventListener('pointercancel', handleUp);+ },+ [dimensions, flipX, flipY, isNavigationActive, navigation, pan, rotation, viewportRef, zoom]+ );++ if (!isOpen || !draft) return null;++ const invZoom = 1 / Math.max(0.05, zoom);+ const origW = dimensions.width;+ const origH = dimensions.height;+ const cropX = draft.cropX;+ const cropY = draft.cropY;+ const cropW = draft.width;+ const cropH = draft.height;+ const modified = isCropModified(draft);+ const isDragging = activeHandle !== null;+ const pointerClass = isNavigationActive ? 'pointer-events-none' : 'pointer-events-auto';++ // Compute intersection of crop rect and original canvas for evenodd masks+ const ix0 = Math.max(0, cropX);+ const iy0 = Math.max(0, cropY);+ const ix1 = Math.min(origW, cropX + cropW);+ const iy1 = Math.min(origH, cropY + cropH);+ const hasIntersection = ix1 > ix0 && iy1 > iy0;++ // Dimmed mask covering cropped-away portion of the original canvas+ const croppedScrimPath = hasIntersection+ ? `M 0 0 H ${origW} V ${origH} H 0 Z M ${ix0} ${iy0} H ${ix1} V ${iy1} H ${ix0} Z`+ : `M 0 0 H ${origW} V ${origH} H 0 Z`;++ // Expanded region outside the original canvas bounds+ const hasExpansion =+ cropX < 0 || cropY < 0 || cropX + cropW > origW || cropY + cropH > origH;+ const expansionAreaPath = hasExpansion+ ? hasIntersection+ ? `M ${cropX} ${cropY} H ${cropX + cropW} V ${cropY + cropH} H ${cropX} Z M ${ix0} ${iy0} H ${ix1} V ${iy1} H ${ix0} Z`+ : `M ${cropX} ${cropY} H ${cropX + cropW} V ${cropY + cropH} H ${cropX} Z`+ : '';++ const gridFractions = getGridFractions(draft.gridMode);+ const patSize = Math.max(4, 14 * invZoom);+ const halfPat = patSize / 2;++ // Handle sizing in document pixels (constant screen size)+ const cornerHitSize = 24 * invZoom;+ const edgeHitThick = 16 * invZoom;+ const cornerArmLen = Math.min(18 * invZoom, Math.max(4 * invZoom, Math.min(cropW, cropH) * 0.32));+ const cornerArmThick = 3.5 * invZoom;+ const edgePillLen = Math.min(26 * invZoom, Math.max(6 * invZoom, Math.min(cropW, cropH) * 0.35));+ const edgePillThick = 4.5 * invZoom;++ // Counter-transform for upright readable badges+ const uprightBadgeTransform = `scale(${invZoom}) scale(${flipX ? -1 : 1}, ${flipY ? -1 : 1}) rotate(${-rotation}deg)`;++ const getCornerBracketPath = (corner: CropResizeHandleId): string => {+ const t = cornerArmThick;+ const len = cornerArmLen;+ switch (corner) {+ case 'nw':+ return `M ${cropX - t * 0.5} ${cropY - t * 0.5} h ${len} v ${t} h ${-(len - t)} v ${len - t} h ${-t} Z`;+ case 'ne':+ return `M ${cropX + cropW + t * 0.5} ${cropY - t * 0.5} h ${-len} v ${t} h ${len - t} v ${len - t} h ${t} Z`;+ case 'se':+ return `M ${cropX + cropW + t * 0.5} ${cropY + cropH + t * 0.5} h ${-len} v ${-t} h ${len - t} v ${-(len - t)} h ${t} Z`;+ case 'sw':+ return `M ${cropX - t * 0.5} ${cropY + cropH + t * 0.5} h ${len} v ${-t} h ${-(len - t)} v ${-(len - t)} h ${-t} Z`;+ default:+ return '';+ }+ };++ const getCornerHitPos = (corner: CropResizeHandleId): { left: number; top: number } => {+ const half = cornerHitSize / 2;+ switch (corner) {+ case 'nw':+ return { left: cropX - half, top: cropY - half };+ case 'ne':+ return { left: cropX + cropW - half, top: cropY - half };+ case 'se':+ return { left: cropX + cropW - half, top: cropY + cropH - half };+ case 'sw':+ default:+ return { left: cropX - half, top: cropY + cropH - half };+ }+ };++ const getEdgeHitStyle = (edge: CropResizeHandleId): React.CSSProperties => {+ const cornerInset = Math.min(cornerHitSize * 0.5, Math.min(cropW, cropH) * 0.25);+ const halfT = edgeHitThick / 2;+ switch (edge) {+ case 'n':+ return {+ left: `${cropX + cornerInset}px`,+ top: `${cropY - halfT}px`,+ width: `${Math.max(2 * invZoom, cropW - cornerInset * 2)}px`,+ height: `${edgeHitThick}px`,+ };+ case 's':+ return {+ left: `${cropX + cornerInset}px`,+ top: `${cropY + cropH - halfT}px`,+ width: `${Math.max(2 * invZoom, cropW - cornerInset * 2)}px`,+ height: `${edgeHitThick}px`,+ };+ case 'w':+ return {+ left: `${cropX - halfT}px`,+ top: `${cropY + cornerInset}px`,+ width: `${edgeHitThick}px`,+ height: `${Math.max(2 * invZoom, cropH - cornerInset * 2)}px`,+ };+ case 'e':+ default:+ return {+ left: `${cropX + cropW - halfT}px`,+ top: `${cropY + cornerInset}px`,+ width: `${edgeHitThick}px`,+ height: `${Math.max(2 * invZoom, cropH - cornerInset * 2)}px`,+ };+ }+ };++ const getEdgePillRect = (edge: CropResizeHandleId) => {+ const cx = cropX + cropW / 2;+ const cy = cropY + cropH / 2;+ if (edge === 'n') {+ return {+ x: cx - edgePillLen / 2,+ y: cropY - edgePillThick / 2,+ width: edgePillLen,+ height: edgePillThick,+ };+ }+ if (edge === 's') {+ return {+ x: cx - edgePillLen / 2,+ y: cropY + cropH - edgePillThick / 2,+ width: edgePillLen,+ height: edgePillThick,+ };+ }+ if (edge === 'w') {+ return {+ x: cropX - edgePillThick / 2,+ y: cy - edgePillLen / 2,+ width: edgePillThick,+ height: edgePillLen,+ };+ }+ return {+ x: cropX + cropW - edgePillThick / 2,+ y: cy - edgePillLen / 2,+ width: edgePillThick,+ height: edgePillLen,+ };+ };++ const snapGuideMinY = Math.min(0, cropY) - 36 * invZoom;+ const snapGuideMaxY = Math.max(origH, cropY + cropH) + 36 * invZoom;+ const snapGuideMinX = Math.min(0, cropX) - 36 * invZoom;+ const snapGuideMaxX = Math.max(origW, cropX + cropW) + 36 * invZoom;++ const percentW = Math.round((cropW / Math.max(1, origW)) * 100);+ const percentH = Math.round((cropH / Math.max(1, origH)) * 100);++ return (+ <>+ {draft.scaleContent ? (+ /* Scale Content (Resample) Non-Cropping Reference Frame */+ <div+ data-testid="canvas-resize-scale-preview"+ className="absolute inset-0 pointer-events-none z-35"+ >+ <svg+ className="absolute inset-0 w-full h-full overflow-visible pointer-events-none"+ viewBox={`0 0 ${origW} ${origH}`}+ >+ <rect+ x={0}+ y={0}+ width={origW}+ height={origH}+ fill="none"+ stroke="var(--ui-accent)"+ strokeWidth={1.75 * invZoom}+ strokeDasharray={`${6 * invZoom} ${4 * invZoom}`}+ />+ </svg>+ <div+ className="absolute pointer-events-none px-2 py-0.5 rounded-ui-xs bg-ui-floating/95 border border-ui-default text-ui-primary shadow-ui-floating font-ui-mono tabular-nums text-[10px] whitespace-nowrap flex items-center gap-1.5"+ style={{+ left: `${origW / 2}px`,+ top: `${-16 * invZoom}px`,+ transform: `translate(-50%, -100%) ${uprightBadgeTransform}`,+ transformOrigin: 'center bottom',+ }}+ >+ <span className="text-ui-accent font-medium">Resample</span>+ <span>+ {cropW} × {cropH} px+ </span>+ <span className="text-ui-muted">+ ({percentW}% × {percentH}%)+ </span>+ </div>+ </div>+ ) : (+ /* Interactive Crop & Resize Canvas Bounds Overlay */+ <div+ data-testid="canvas-resize-crop-overlay"+ className="absolute inset-0 pointer-events-none z-35"+ >+ {/* 1. SVG Scrim, Expanded Preview, Guides, Frame Border & Handle Visuals */}+ <svg+ className="absolute inset-0 w-full h-full overflow-visible pointer-events-none"+ viewBox={`0 0 ${origW} ${origH}`}+ >+ <defs>+ <pattern+ id={`crop-expand-checker-${patternId}`}+ width={patSize}+ height={patSize}+ patternUnits="userSpaceOnUse"+ >+ <rect width={patSize} height={patSize} fill="rgba(255,255,255,0.12)" />+ <rect width={halfPat} height={halfPat} fill="rgba(255,255,255,0.22)" />+ <rect+ x={halfPat}+ y={halfPat}+ width={halfPat}+ height={halfPat}+ fill="rgba(255,255,255,0.22)"+ />+ </pattern>+ </defs>++ {/* Darkened scrim over cropped-out areas of the original canvas */}+ <path+ data-testid="canvas-crop-scrim"+ d={croppedScrimPath}+ fillRule="evenodd"+ fill={isDragging ? 'rgba(0, 0, 0, 0.64)' : 'rgba(0, 0, 0, 0.52)'}+ />++ {/* Expanded canvas area preview outside the original canvas */}+ {hasExpansion && expansionAreaPath && (+ <path+ data-testid="canvas-crop-expansion-area"+ d={expansionAreaPath}+ fillRule="evenodd"+ fill={`url(#crop-expand-checker-${patternId})`}+ />+ )}++ {/* Original canvas reference outline when modified */}+ {modified && (+ <>+ <rect+ x={0}+ y={0}+ width={origW}+ height={origH}+ fill="none"+ stroke="rgba(0, 0, 0, 0.45)"+ strokeWidth={1.6 * invZoom}+ strokeDasharray={`${5 * invZoom} ${4 * invZoom}`}+ />+ <rect+ x={0}+ y={0}+ width={origW}+ height={origH}+ fill="none"+ stroke="rgba(255, 255, 255, 0.55)"+ strokeWidth={1 * invZoom}+ strokeDasharray={`${5 * invZoom} ${4 * invZoom}`}+ />+ </>+ )}++ {/* Composition Grid (Rule of Thirds / Golden Ratio) */}+ {gridFractions && (+ <g opacity={isDragging ? 0.72 : 0.34}>+ {gridFractions.map((f, idx) => {+ const gx = cropX + cropW * f;+ const gy = cropY + cropH * f;+ return (+ <React.Fragment key={idx}>+ <line+ x1={gx}+ y1={cropY}+ x2={gx}+ y2={cropY + cropH}+ stroke="rgba(0, 0, 0, 0.45)"+ strokeWidth={1.8 * invZoom}+ />+ <line+ x1={gx}+ y1={cropY}+ x2={gx}+ y2={cropY + cropH}+ stroke="#ffffff"+ strokeWidth={0.9 * invZoom}+ />+ <line+ x1={cropX}+ y1={gy}+ x2={cropX + cropW}+ y2={gy}+ stroke="rgba(0, 0, 0, 0.45)"+ strokeWidth={1.8 * invZoom}+ />+ <line+ x1={cropX}+ y1={gy}+ x2={cropX + cropW}+ y2={gy}+ stroke="#ffffff"+ strokeWidth={0.9 * invZoom}+ />+ </React.Fragment>+ );+ })}+ </g>+ )}++ {/* Magnetic Snap Guide Lines */}+ {snapGuides.x !== undefined && (+ <line+ x1={snapGuides.x}+ y1={snapGuideMinY}+ x2={snapGuides.x}+ y2={snapGuideMaxY}+ stroke="var(--ui-accent)"+ strokeWidth={1.4 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}+ {snapGuides.y !== undefined && (+ <line+ x1={snapGuideMinX}+ y1={snapGuides.y}+ x2={snapGuideMaxX}+ y2={snapGuides.y}+ stroke="var(--ui-accent)"+ strokeWidth={1.4 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ )}++ {/* Crop Frame Double-Contrast Border */}+ <rect+ data-testid="canvas-crop-frame-rect"+ x={cropX}+ y={cropY}+ width={cropW}+ height={cropH}+ fill="none"+ stroke="rgba(0, 0, 0, 0.72)"+ strokeWidth={2.6 * invZoom}+ />+ <rect+ x={cropX}+ y={cropY}+ width={cropW}+ height={cropH}+ fill="none"+ stroke={isDragging ? 'var(--ui-accent)' : '#ffffff'}+ strokeWidth={1.35 * invZoom}+ />++ {/* 4 Edge Pill Handle Visuals */}+ {EDGE_HANDLES.map((edge) => {+ const r = getEdgePillRect(edge);+ const isHot = activeHandle === edge || hoveredHandle === edge;+ return (+ <rect+ key={edge}+ x={r.x}+ y={r.y}+ width={r.width}+ height={r.height}+ rx={edgePillThick * 0.45}+ ry={edgePillThick * 0.45}+ fill={isHot ? 'var(--ui-accent)' : '#ffffff'}+ stroke="rgba(0, 0, 0, 0.78)"+ strokeWidth={1.1 * invZoom}+ />+ );+ })}++ {/* 4 Corner L-Bracket Visuals */}+ {CORNER_HANDLES.map((corner) => {+ const isHot = activeHandle === corner || hoveredHandle === corner;+ return (+ <path+ key={corner}+ d={getCornerBracketPath(corner)}+ fill={isHot ? 'var(--ui-accent)' : '#ffffff'}+ stroke="rgba(0, 0, 0, 0.8)"+ strokeWidth={1.1 * invZoom}+ strokeLinejoin="miter"+ />+ );+ })}+ </svg>++ {/* 2. Interactive Interior Drag-to-Move Region */}+ <div+ data-testid="canvas-crop-move-area"+ onPointerDown={(e) => startHandleDrag('move', e)}+ onDoubleClick={(e) => {+ e.stopPropagation();+ handleConfirm();+ }}+ onPointerEnter={() => setHoveredHandle('move')}+ onPointerLeave={() => setHoveredHandle((prev) => (prev === 'move' ? null : prev))}+ className={`absolute ${pointerClass}`}+ style={{+ left: `${cropX}px`,+ top: `${cropY}px`,+ width: `${cropW}px`,+ height: `${cropH}px`,+ cursor: activeHandle === 'move' ? 'grabbing' : 'move',+ }}+ title="Drag to reposition canvas frame · Double-click to apply"+ />++ {/* 3. Interactive Edge Hit Strips */}+ {EDGE_HANDLES.map((edge) => (+ <div+ key={edge}+ data-testid={`canvas-crop-handle-${edge}`}+ onPointerDown={(e) => startHandleDrag(edge, e)}+ onPointerEnter={() => setHoveredHandle(edge)}+ onPointerLeave={() => setHoveredHandle((prev) => (prev === edge ? null : prev))}+ className={`absolute ${pointerClass}`}+ style={{+ ...getEdgeHitStyle(edge),+ cursor: getRotatedResizeCursor(edge, rotation, flipX, flipY),+ }}+ />+ ))}++ {/* 4. Interactive Corner Hit Targets */}+ {CORNER_HANDLES.map((corner) => {+ const pos = getCornerHitPos(corner);+ return (+ <div+ key={corner}+ data-testid={`canvas-crop-handle-${corner}`}+ onPointerDown={(e) => startHandleDrag(corner, e)}+ onPointerEnter={() => setHoveredHandle(corner)}+ onPointerLeave={() => setHoveredHandle((prev) => (prev === corner ? null : prev))}+ className={`absolute ${pointerClass}`}+ style={{+ left: `${pos.left}px`,+ top: `${pos.top}px`,+ width: `${cornerHitSize}px`,+ height: `${cornerHitSize}px`,+ cursor: getRotatedResizeCursor(corner, rotation, flipX, flipY),+ }}+ />+ );+ })}++ {/* 5. Upright Live Dimension Readout Badge */}+ <div+ data-testid="canvas-crop-dimension-badge"+ className="absolute pointer-events-none px-2 py-0.5 rounded-ui-xs bg-ui-floating/95 border border-ui-default text-ui-primary shadow-ui-floating font-ui-mono tabular-nums text-[10px] whitespace-nowrap flex items-center gap-1.5"+ style={{+ left: `${cropX + cropW / 2}px`,+ top: `${cropY - 12 * invZoom}px`,+ transform: `translate(-50%, -100%) ${uprightBadgeTransform}`,+ transformOrigin: 'center bottom',+ }}+ >+ {draft.lockRatio && <Lock className="w-2.5 h-2.5 text-ui-accent shrink-0" />}+ <span className="font-medium">+ {cropW} × {cropH} px+ </span>+ {(cropX !== 0 || cropY !== 0) && (+ <span className="text-ui-muted">+ · X {cropX}, Y {cropY}+ </span>+ )}+ </div>+ </div>+ )}++ {/* Viewport-Anchored Bottom Crop / Resize Action Bar */}+ {typeof document !== 'undefined' &&+ createPortal(+ <div+ data-testid="canvas-crop-action-bar"+ className="fixed bottom-9 left-1/2 -translate-x-1/2 z-[48] max-w-[95vw] bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-floating px-2 py-1 flex flex-wrap items-center justify-center gap-1 select-none text-[11px] text-ui-primary"+ onPointerDown={(e) => e.stopPropagation()}+ >+ {!draft.scaleContent && (+ <>+ <button+ type="button"+ onClick={() =>+ uiStoreActions.updateCanvasResizeDraft((prev) => ({+ ...prev,+ gridMode: cycleCropGridMode(prev.gridMode),+ }))+ }+ title={`Crop guide: ${getGridLabel(draft.gridMode)} (click to cycle)`}+ className="px-2 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1.5 transition-colors cursor-pointer"+ >+ <Grid3X3 className="w-3.5 h-3.5" />+ <span className="hidden sm:inline">{getGridLabel(draft.gridMode)}</span>+ </button>++ <button+ type="button"+ disabled={!modified}+ onClick={() =>+ uiStoreActions.updateCanvasResizeDraft((prev) => applyResetCropToDraft(prev))+ }+ title="Reset crop frame to original canvas"+ className={`px-2 py-1 rounded-ui-xs flex items-center gap-1 transition-colors ${+ modified+ ? 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer'+ : 'text-ui-disabled cursor-default opacity-50'+ }`}+ >+ <RotateCcw className="w-3.5 h-3.5" />+ <span>Reset</span>+ </button>+ </>+ )}++ <button+ type="button"+ onClick={() =>+ uiStoreActions.updateCanvasResizeDraft((prev) => applySwapDimensionsToDraft(prev))+ }+ title="Swap Width and Height"+ className="px-1.5 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1 transition-colors cursor-pointer"+ >+ <ArrowLeftRight className="w-3.5 h-3.5" />+ </button>++ <button+ type="button"+ onClick={() => uiStoreActions.setResizeInspectorCollapsed(!isInspectorCollapsed)}+ title={isInspectorCollapsed ? 'Show Resize Canvas settings panel' : 'Hide Resize Canvas settings panel'}+ className={`px-2 py-1 rounded-ui-xs flex items-center gap-1 transition-colors cursor-pointer ${+ !isInspectorCollapsed+ ? 'bg-ui-accent-subtle text-ui-accent border border-ui-accent-border'+ : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'+ }`}+ >+ <SlidersHorizontal className="w-3.5 h-3.5" />+ <span className="hidden sm:inline">+ {isInspectorCollapsed ? 'Show Panel' : 'Panel'}+ </span>+ </button>++ <div className="w-px h-4 bg-ui-subtle mx-0.5" />++ <button+ type="button"+ onClick={handleCancel}+ title="Cancel (Esc)"+ className="px-2 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1 transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ <span>Cancel</span>+ </button>++ <button+ type="button"+ onClick={handleConfirm}+ title="Apply Resize / Crop (Enter)"+ className="px-2.5 py-1 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium flex items-center gap-1 transition-opacity cursor-pointer"+ >+ <Check className="w-3.5 h-3.5" />+ <span>{draft.scaleContent ? 'Resize' : 'Apply'}</span>+ </button>+ </div>,+ document.body+ )}+ </>+ );+};diff --git a/src/components/ColorSetsPanel.tsx b/src/components/ColorSetsPanel.tsxindex b0edf01..353b608 100644--- a/src/components/ColorSetsPanel.tsx+++ b/src/components/ColorSetsPanel.tsx@@ -27,6 +27,16 @@ import {uiStoreActions,} from '../stores';import { IconButton } from './ui';+import { saveFileWithDialog } from '../utils/fileSaveDialog';+import {+ COLOR_SET_IMPORT_ACCEPT,+ isSupportedColorSetFilename,+} from '../utils/colorSetImport';+import {+ extractFilenameFromPath,+ isExternalFileDrag,+ readTauriFileBytes,+} from '../utils/fileDropImport';export interface ColorSetsPanelProps {colorMode?: CanvasColorMode;@@ -87,7 +97,11 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(const [dragIndex, setDragIndex] = useState<number | null>(null);const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);- // Hidden file input for JSON import+ // External file drop state (.json, .cls, .png)+ const panelRef = useRef<HTMLDivElement | null>(null);+ const [isDragOverFiles, setIsDragOverFiles] = useState(false);++ // Hidden file input for color set import (.json, .cls, .png)const fileInputRef = useRef<HTMLInputElement | null>(null);// Auto-focus inline input when entering create/rename mode@@ -143,7 +157,7 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(if (!prev) {const rect = setMenuBtnRef.current?.getBoundingClientRect();if (rect) {- setSetMenuPos(clampPopoverPosition(rect.right - 168, rect.bottom + 4, 168, 210));+ setSetMenuPos(clampPopoverPosition(rect.right - 208, rect.bottom + 4, 208, 210));} else {setSetMenuPos({ left: 16, top: 64 });}@@ -192,54 +206,232 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(setSetMenuOpen(false);}, [activeSet, sets.length]);- const handleExportSet = useCallback(() => {+ const handleExportSet = useCallback(async () => {if (!activeSet) return;setSetMenuOpen(false);const json = colorSetsStoreActions.exportSetJson(activeSet.id);if (!json) return;try {- const blob = new Blob([json], { type: 'application/json' });- const url = URL.createObjectURL(blob);- const a = document.createElement('a');const safeFileName = activeSet.name.toLowerCase().replace(/[^a-z0-9-_]+/g, '-').replace(/^-+|-+$/g, '');- a.href = url;- a.download = `${safeFileName || 'color-set'}.inkcolorset.json`;- document.body.appendChild(a);- a.click();- a.remove();- URL.revokeObjectURL(url);+ const suggestedName = `${safeFileName || 'color-set'}.inkcolorset.json`;+ const res = await saveFileWithDialog({+ data: json,+ suggestedName,+ mimeType: 'application/json',+ description: 'Ink Studio Color Set',+ extensions: ['.json'],+ category: 'color-set',+ title: 'Save Color Set As',+ });+ if (res.canceled) return;uiStoreActions.showToast(`Exported color set "${activeSet.name}"`);} catch {- // Fallback when Blob URLs are unavailableuiStoreActions.showToast('Could not export color set.');}}, [activeSet]);+ const importColorSetFiles = useCallback(async (files: File[]) => {+ if (files.length === 0) return;++ if (files.length === 1) {+ try {+ const result = await colorSetsStoreActions.importSetFile(files[0]);+ if (result.ok) {+ uiStoreActions.showToast(+ `Imported "${result.set.name}" (${result.set.swatches.length} colors)`+ );+ } else {+ uiStoreActions.showToast(result.error);+ }+ } catch {+ uiStoreActions.showToast('Failed to read color set file.');+ }+ return;+ }++ let importedCount = 0;+ let lastImportedName = '';+ let lastSwatchCount = 0;+ let failedCount = 0;+ let lastError = '';++ for (const file of files) {+ try {+ const result = await colorSetsStoreActions.importSetFile(file);+ if (result.ok) {+ importedCount += 1;+ lastImportedName = result.set.name;+ lastSwatchCount = result.set.swatches.length;+ } else {+ failedCount += 1;+ lastError = result.error;+ }+ } catch {+ failedCount += 1;+ lastError = 'Failed to read color set file.';+ }+ }++ if (importedCount === 1 && failedCount === 0) {+ uiStoreActions.showToast(`Imported "${lastImportedName}" (${lastSwatchCount} colors)`);+ } else if (importedCount > 0) {+ const suffix = failedCount > 0 ? ` (${failedCount} skipped)` : '';+ uiStoreActions.showToast(+ `Imported ${importedCount} color set${importedCount === 1 ? '' : 's'}${suffix}`+ );+ } else {+ uiStoreActions.showToast(lastError || 'Failed to import color set files.');+ }+ }, []);+const handleTriggerImport = useCallback(() => {setSetMenuOpen(false);fileInputRef.current?.click();}, []);- const handleImportFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- e.target.value = '';- if (!file) return;- try {- const text = await file.text();- const result = colorSetsStoreActions.importSetJson(text);- if (result.ok) {- uiStoreActions.showToast(- `Imported "${result.set.name}" (${result.set.swatches.length} colors)`- );- } else {- uiStoreActions.showToast(result.error);+ const handleImportFileChange = useCallback(+ async (e: React.ChangeEvent<HTMLInputElement>) => {+ const files = e.target.files ? Array.from(e.target.files) : [];+ e.target.value = '';+ await importColorSetFiles(files);+ },+ [importColorSetFiles]+ );++ const handlePanelDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {+ if (!isExternalFileDrag(e.dataTransfer)) return;+ e.preventDefault();+ e.stopPropagation();+ e.dataTransfer.dropEffect = 'copy';+ setIsDragOverFiles(true);+ }, []);++ const handlePanelDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {+ if (!isDragOverFiles) return;+ const related = e.relatedTarget as Node | null;+ if (related && panelRef.current?.contains(related)) return;+ setIsDragOverFiles(false);+ }, [isDragOverFiles]);++ const handlePanelDrop = useCallback(+ (e: React.DragEvent<HTMLDivElement>) => {+ if (!isExternalFileDrag(e.dataTransfer)) return;+ e.preventDefault();+ e.stopPropagation();+ setIsDragOverFiles(false);+ const files = e.dataTransfer.files ? Array.from(e.dataTransfer.files) : [];+ if (files.length > 0) {+ void importColorSetFiles(files);}- } catch {- uiStoreActions.showToast('Failed to read color set file.');- }+ },+ [importColorSetFiles]+ );++ // Native Tauri v2 OS drag-and-drop listener for dropping .cls / .png / .json onto Color Sets+ useEffect(() => {+ if (typeof window === 'undefined') return;+ if (!(window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__) return;++ let cancelled = false;+ let unlisten: (() => void) | null = null;+ let hasSupportedPaths = false;++ const isPointInPanel = (pos: { x: number; y: number }): boolean => {+ const el = panelRef.current;+ if (!el) return false;+ const dpr = window.devicePixelRatio || 1;+ const x = pos.x / dpr;+ const y = pos.y / dpr;+ const rect = el.getBoundingClientRect();+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;+ };++ void (async () => {+ try {+ const { getCurrentWebview } = await import('@tauri-apps/api/webview');+ if (cancelled) return;+ const stop = await getCurrentWebview().onDragDropEvent((event) => {+ if (cancelled) return;+ const payload = event.payload;+ if (payload.type === 'enter') {+ hasSupportedPaths =+ payload.paths.length === 0 ||+ payload.paths.some((p) => isSupportedColorSetFilename(p));+ setIsDragOverFiles(hasSupportedPaths && isPointInPanel(payload.position));+ } else if (payload.type === 'over') {+ setIsDragOverFiles(hasSupportedPaths && isPointInPanel(payload.position));+ } else if (payload.type === 'leave') {+ hasSupportedPaths = false;+ setIsDragOverFiles(false);+ } else if (payload.type === 'drop') {+ hasSupportedPaths = false;+ setIsDragOverFiles(false);+ if (!isPointInPanel(payload.position) || payload.paths.length === 0) return;++ void (async () => {+ let importedCount = 0;+ let lastImportedName = '';+ let lastSwatchCount = 0;+ let failedCount = 0;+ let lastError = '';++ for (const filePath of payload.paths) {+ const filename = extractFilenameFromPath(filePath);+ if (!isSupportedColorSetFilename(filename)) {+ failedCount += 1;+ lastError =+ 'Unsupported color set format. Use .json, Clip Studio .cls, or .png palette files.';+ continue;+ }+ try {+ const bytes = await readTauriFileBytes(filePath);+ const result = colorSetsStoreActions.importSetBytes(bytes, filename);+ if (result.ok) {+ importedCount += 1;+ lastImportedName = result.set.name;+ lastSwatchCount = result.set.swatches.length;+ } else {+ failedCount += 1;+ lastError = result.error;+ }+ } catch {+ failedCount += 1;+ lastError = 'Failed to read color set file.';+ }+ }++ if (importedCount === 1 && failedCount === 0) {+ uiStoreActions.showToast(+ `Imported "${lastImportedName}" (${lastSwatchCount} colors)`+ );+ } else if (importedCount > 0) {+ const suffix = failedCount > 0 ? ` (${failedCount} skipped)` : '';+ uiStoreActions.showToast(+ `Imported ${importedCount} color set${importedCount === 1 ? '' : 's'}${suffix}`+ );+ } else if (lastError) {+ uiStoreActions.showToast(lastError);+ }+ })();+ }+ });+ if (cancelled) {+ stop();+ } else {+ unlisten = stop;+ }+ } catch {+ // Ignore when Tauri webview API is unavailable+ }+ })();++ return () => {+ cancelled = true;+ unlisten?.();+ };}, []);const handleAddCurrentColor = useCallback(() => {@@ -298,15 +490,22 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(return (<div+ ref={panelRef}data-testid="color-sets-panel"- className="flex flex-col h-full w-full min-h-0 select-none bg-ui-panel text-ui-primary overflow-hidden"+ onDragOver={handlePanelDragOver}+ onDragLeave={handlePanelDragLeave}+ onDrop={handlePanelDrop}+ className={`flex flex-col h-full w-full min-h-0 select-none bg-ui-panel text-ui-primary overflow-hidden ${+ isDragOverFiles ? 'ring-2 ring-inset ring-ui-accent bg-ui-accent-subtle' : ''+ }`}>- {/* Hidden JSON import input */}+ {/* Hidden color set import input (.json, .cls, .png) */}<inputref={fileInputRef}data-testid="color-sets-import-input"type="file"- accept=".json,application/json"+ accept={COLOR_SET_IMPORT_ACCEPT}+ multipleonChange={handleImportFileChange}className="hidden"/>@@ -531,7 +730,7 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(left: setMenuPos?.left ?? 16,top: setMenuPos?.top ?? 64,}}- className="w-44 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"+ className="w-52 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"><buttontype="button"@@ -569,10 +768,11 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(type="button"data-testid="color-sets-action-import"onClick={handleTriggerImport}+ title="Import Color Set (.json, Clip Studio .cls, or .png palette)"className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left">- <Upload className="w-3 h-3 text-ui-icon-muted" />- <span>Import Set (JSON)...</span>+ <Upload className="w-3 h-3 text-ui-icon-muted shrink-0" />+ <span>Import Set (.json, .cls, .png)...</span></button><button@@ -628,6 +828,9 @@ export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(<span className="font-ui-mono tabular-nums uppercase truncate">{swatchMenu.swatch.hex}</span>+ {swatchMenu.swatch.name && (+ <span className="truncate text-ui-secondary">· {swatchMenu.swatch.name}</span>+ )}</div><div className="my-0.5 border-t border-ui-subtle" />diff --git a/src/components/CrashRecoveryModal.tsx b/src/components/CrashRecoveryModal.tsxindex e7cbbc9..a9094dc 100644--- a/src/components/CrashRecoveryModal.tsx+++ b/src/components/CrashRecoveryModal.tsx@@ -15,6 +15,7 @@ interface CrashRecoveryModalProps {sessions: CrashedSessionInfo[];onRestore: (session: CrashedSessionInfo) => Promise<void>;onDiscard: (session: CrashedSessionInfo) => Promise<void>;+ onDiscardAll: (sessions: CrashedSessionInfo[]) => Promise<void>;onClose?: () => void;}@@ -41,13 +42,15 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({sessions,onRestore,onDiscard,+ onDiscardAll,onClose,}) => {const [selectedIndex, setSelectedIndex] = useState<number>(0);const [isRestoring, setIsRestoring] = useState<boolean>(false);const [isDiscarding, setIsDiscarding] = useState<boolean>(false);+ const [isDiscardingAll, setIsDiscardingAll] = useState<boolean>(false);- const isBusy = isRestoring || isDiscarding;+ const isBusy = isRestoring || isDiscarding || isDiscardingAll;useEffect(() => {if (sessions.length > 0 && selectedIndex >= sessions.length) {@@ -108,6 +111,16 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({}};+ const handleDiscardAllClick = async () => {+ if (isBusy) return;+ setIsDiscardingAll(true);+ try {+ await onDiscardAll(sessions);+ } finally {+ setIsDiscardingAll(false);+ }+ };+return (<divrole="dialog"@@ -294,27 +307,55 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({</div>{/* Modal Action Footer */}- <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-between gap-2 shrink-0">- <button- type="button"- disabled={isBusy}- onClick={handleDiscardClick}- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-control hover:bg-ui-danger/15 border border-ui-default hover:border-ui-danger/40 text-ui-danger transition-colors disabled:opacity-50 cursor-pointer"- >- {isDiscarding ? (- <Loader2 className="w-3.5 h-3.5 animate-spin" />- ) : (- <Trash2 className="w-3.5 h-3.5" />- )}- <span>{isDiscarding ? 'Discarding...' : 'Discard & Start Fresh'}</span>- </button>+ <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-between gap-2 flex-wrap shrink-0">+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ disabled={isBusy}+ onClick={handleDiscardClick}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-control hover:bg-ui-danger/15 border border-ui-default hover:border-ui-danger/40 text-ui-danger transition-colors disabled:opacity-50 cursor-pointer"+ >+ {isDiscarding ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <Trash2 className="w-3.5 h-3.5" />+ )}+ <span>{isDiscarding ? 'Discarding...' : 'Discard & Start Fresh'}</span>+ </button>++ <button+ type="button"+ disabled={isBusy}+ onClick={handleDiscardAllClick}+ data-testid="discard-all-sessions-btn"+ title={+ sessions.length > 1+ ? `Permanently discard all ${sessions.length} unsaved sessions`+ : 'Permanently discard all unsaved sessions'+ }+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-danger/15 hover:bg-ui-danger/25 border border-ui-danger/40 hover:border-ui-danger/60 text-ui-danger transition-colors disabled:opacity-50 cursor-pointer"+ >+ {isDiscardingAll ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <Trash2 className="w-3.5 h-3.5" />+ )}+ <span>+ {isDiscardingAll+ ? 'Discarding All...'+ : sessions.length > 1+ ? `Discard All Sessions (${sessions.length})`+ : 'Discard All Sessions'}+ </span>+ </button>+ </div><buttontype="button"autoFocusdisabled={isBusy}onClick={handleRestoreClick}- className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-accent text-ui-accent-contrast hover:opacity-90 disabled:opacity-50 transition-opacity cursor-pointer"+ className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-accent text-ui-accent-contrast hover:opacity-90 disabled:opacity-50 transition-opacity cursor-pointer shrink-0">{isRestoring ? (<Loader2 className="w-3.5 h-3.5 animate-spin" />diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex 0c575d6..05db773 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -10,8 +10,10 @@ import {import { AppSettings, ResizeCanvasOptions } from '../types/settings';import { openFile } from '../utils/imageLoader';import {+ getParentDirectory,promptExportPngImage,promptSaveAs,+ sanitizeDocumentStem,SaveDocumentData,SaveProgress,saveToExistingHandle,@@ -35,6 +37,7 @@ import { shortcutManager } from '../utils/shortcutManager';import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';import { multiplayerService } from '../services/multiplayerService';import {+ colorSetsStoreActions,documentStoreActions,toolStoreActions,uiStoreActions,@@ -49,6 +52,12 @@ import {isFinalizingAppClose,requestAppClose,} from '../utils/appCloseFlow';+import {+ findOpenDocumentBySourcePath,+ listenForOpenFiles,+ readTauriPathAsFile,+ takePendingOpenFiles,+} from '../utils/osFileOpen';function hasMeaningfulLayerEdit(prev: LayerItem[], next: LayerItem[]): boolean {if (prev === next) return false;@@ -155,6 +164,16 @@ const DIRECT_SAVE_EXTENSIONS = new Set(['.webp',]);+function isRealNativeDiskPath(p: string | null | undefined): p is string {+ if (!p || typeof p !== 'string') return false;+ const trimmed = p.trim();+ if (!trimmed) return false;+ // Ignore legacy placeholder display paths that were never real disk paths+ if (trimmed.startsWith('InkStudio\\') || trimmed.startsWith('InkStudio/')) return false;+ if (trimmed.startsWith('C:\\Users\\Artist\\Documents\\InkStudio\\')) return false;+ return /^[a-zA-Z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\\\') || trimmed.startsWith('/');+}+const OPEN_FILE_PICKER_TYPES = [{description: 'Ink Studio & Image Files',@@ -259,6 +278,9 @@ export function useDocumentLifecycle({const import3DFileInputRef = useRef<HTMLInputElement>(null);const needsAdaptiveFitRef = useRef<boolean>(true);const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);+ const autoCreatedInitialDocIdRef = useRef<string | null>(null);+ const openFileQueueRef = useRef<Promise<void>>(Promise.resolve());+ const savingDocIdsRef = useRef<Set<string>>(new Set());const layersRef = useRef<LayerItem[]>(layers);layersRef.current = layers;@@ -279,6 +301,9 @@ export function useDocumentLifecycle({const handleCreateNewCanvas = useCallback((options: NewCanvasOptions) => {+ if (useUiStore.getState().isResizeCanvasModalOpen) {+ uiStoreActions.setResizeCanvasModalOpen(false);+ }const newDims: CanvasDimensions = {width: options.width,height: options.height,@@ -448,6 +473,7 @@ export function useDocumentLifecycle({};resizeCanvas(newDims, options);+ onDeselectAfterPaste?.();documentStoreActions.setDimensions(newDims);documentStoreActions.markDocumentDirty(useDocumentStore.getState().activeDocumentId, true);pendingFitDimsRef.current = newDims;@@ -459,7 +485,7 @@ export function useDocumentLifecycle({}showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);},- [resetHistory, resetZoomAndCenter, resizeCanvas, showToast]+ [onDeselectAfterPaste, resetHistory, resetZoomAndCenter, resizeCanvas, showToast]);const handleUpdateSettings = useCallback((newSettings: AppSettings) => {@@ -516,6 +542,26 @@ export function useDocumentLifecycle({showToast(`Importing 3D model "${file.name}" into 3D stage...`);return;}+ if (lowerName.endsWith('.cls')) {+ try {+ uiStoreActions.setLoading(true, `Importing Color Set: ${file.name}...`);+ const res = await colorSetsStoreActions.importSetFile(file);+ if (res.ok) {+ showToast(`Imported color set "${res.set.name}" (${res.set.swatches.length} colors)`);+ } else {+ showToast(res.error);+ }+ } catch {+ showToast('Failed to import color set file.');+ } finally {+ uiStoreActions.setLoading(false, '');+ if (fileInputRef.current) {+ fileInputRef.current.value = '';+ }+ }+ return;+ }+if (isSupportedBrushFileName(file.name)) {try {uiStoreActions.setLoading(true, `Importing Brush: ${file.name}...`);@@ -557,10 +603,21 @@ export function useDocumentLifecycle({? file.name.slice(file.name.lastIndexOf('.')).toLowerCase(): '';const fileHandle = options?.handle ?? undefined;+ const fileWithPath = file as FileWithOptionalPath;+ const candidateSourcePath = options?.sourcePath || fileWithPath.path || null;+ const realDiskPath = isRealNativeDiskPath(candidateSourcePath)+ ? candidateSourcePath+ : null;const initialSavedInfo =- fileHandle && DIRECT_SAVE_EXTENSIONS.has(openedExt)- ? { name: file.name, handle: fileHandle, extension: openedExt }+ (fileHandle || realDiskPath) && DIRECT_SAVE_EXTENSIONS.has(openedExt)+ ? {+ name: file.name,+ ...(fileHandle ? { handle: fileHandle } : {}),+ ...(realDiskPath ? { path: realDiskPath } : {}),+ extension: openedExt,+ }: null;+ const resolvedSourcePath = realDiskPath;documentStoreActions.setDimensions(doc.dimensions);documentStoreActions.setColorMode(doc.colorMode);@@ -577,30 +634,32 @@ export function useDocumentLifecycle({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.+ // Reconnect external persistent time-lapse recording (or migrate legacy embedded `.ink` frames)+ // before activating the tab so recording seamlessly resumes after restarts.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})...`);- }- }+ const frameTotal = doc.timelapseFrames?.length ?? 0;+ if (frameTotal > 0) {+ uiStoreActions.setLoading(+ true,+ `Migrating time-lapse to local storage (${frameTotal} frame${frameTotal === 1 ? '' : 's'})...`);- } else {- await globalTimelapseManager.removeSession(newDocId).catch(() => {});}+ restoredTimelapse = await globalTimelapseManager.attachOrRestoreSession(newDocId, {+ documentName: doc.name,+ metadata: doc.timelapse ?? null,+ legacyFrames: doc.timelapseFrames,+ linkedDocId: options?.docId ?? null,+ sourcePath: resolvedSourcePath,+ fallbackDims: doc.dimensions,+ onProgress: (done, total) => {+ if (frameTotal > 0 && total > 0) {+ uiStoreActions.setLoading(+ true,+ `Migrating time-lapse to local storage (${done}/${total})...`+ );+ }+ },+ });const newDoc: DocumentTab = {id: newDocId,@@ -610,6 +669,7 @@ export function useDocumentLifecycle({layers: doc.layers,activeLayerId: topEditableLayer?.id || doc.layers[0]?.id || 'layer-1',perspectiveRuler: doc.perspectiveRuler ?? null,+ sourcePath: resolvedSourcePath ?? undefined,savedFileInfo: initialSavedInfo ?? undefined,workTimeMs: restoredWorkTimeMs,};@@ -619,17 +679,39 @@ export function useDocumentLifecycle({if (doc.animationTimeline !== undefined) {documentStoreActions.setAnimationTimeline(doc.animationTimeline);}- documentStoreActions.setDocuments((prev) => [...prev, newDoc]);+ // If the only open tab was the untouched auto-created initial blank canvas, replace it+ // cleanly so opening a `.ink` file doesn't leave an unwanted blank "Untitled*" tab behind.+ let replacedAutoDocId: string | null = null;+ documentStoreActions.setDocuments((prev) => {+ const autoId = autoCreatedInitialDocIdRef.current;+ if (+ autoId &&+ prev.length === 1 &&+ prev[0].id === autoId &&+ !prev[0].isDirty &&+ !prev[0].savedFileInfo &&+ !prev[0].sourcePath+ ) {+ replacedAutoDocId = autoId;+ autoCreatedInitialDocIdRef.current = null;+ return [newDoc];+ }+ return [...prev, newDoc];+ });+ if (replacedAutoDocId) {+ artworkTimeTracker.removeDocument(replacedAutoDocId);+ globalTimelapseManager.detachSession(replacedAutoDocId).catch(console.warn);+ documentStore.closeSession(replacedAutoDocId).catch(console.warn);+ recoveryService.closeSession(replacedAutoDocId).catch(console.warn);+ }documentStoreActions.setActiveDocumentId(newDocId);uiStoreActions.setAppView('workspace');- const fileWithPath = file as FileWithOptionalPath;saveRecentDocument({id: newDocId,title: file.name,path:- options?.sourcePath ||- fileWithPath.path ||+ resolvedSourcePath ||`C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,size: file.size || 1048576,coverUrl: doc.previewDataUrl || doc.layers[0]?.thumbnailUrl,@@ -678,6 +760,9 @@ export function useDocumentLifecycle({}const doc = storeState.documents.find((d) => d.id === id);if (!doc) return;+ if (useUiStore.getState().isResizeCanvasModalOpen) {+ uiStoreActions.setResizeCanvasModalOpen(false);+ }uiStoreActions.setAppView('workspace');documentStoreActions.setDimensions(doc.dimensions);documentStoreActions.setColorMode(doc.colorMode);@@ -689,6 +774,7 @@ export function useDocumentLifecycle({documentStoreActions.setSavedFileInfo({name: doc.savedFileInfo.name,handle: doc.savedFileInfo.handle,+ ...(doc.savedFileInfo.path ? { path: doc.savedFileInfo.path } : {}),extension: doc.savedFileInfo.extension,});} else {@@ -707,6 +793,9 @@ export function useDocumentLifecycle({const handleCloseDocument = useCallback((id: string) => {+ if (id === activeDocumentId && useUiStore.getState().isResizeCanvasModalOpen) {+ uiStoreActions.setResizeCanvasModalOpen(false);+ }documentStoreActions.setDocuments((prev) => {const next = prev.filter((d) => d.id !== id);if (id === activeDocumentId) {@@ -721,6 +810,7 @@ export function useDocumentLifecycle({documentStoreActions.setSavedFileInfo({name: nextActive.savedFileInfo.name,handle: nextActive.savedFileInfo.handle,+ ...(nextActive.savedFileInfo.path ? { path: nextActive.savedFileInfo.path } : {}),extension: nextActive.savedFileInfo.extension,});} else {@@ -756,7 +846,7 @@ export function useDocumentLifecycle({});if (id) {artworkTimeTracker.removeDocument(id);- globalTimelapseManager.removeSession(id).catch(console.warn);+ globalTimelapseManager.detachSession(id).catch(console.warn);documentStore.closeSession(id).catch(console.warn);recoveryService.closeSession(id).catch(console.warn);}@@ -861,13 +951,15 @@ export function useDocumentLifecycle({try {await recoveryService.discardCrashedSession(session.session_id);await globalTimelapseManager.removeSession(session.session_id).catch(() => {});+ let remainingCount = 0;uiStoreActions.setCrashedSessions((prev) => {const next = prev.filter((s) => s.session_id !== session.session_id);- if (next.length === 0) {- uiStoreActions.setRecoveryModal(false);- }+ remainingCount = next.length;return next;});+ if (remainingCount === 0) {+ uiStoreActions.setRecoveryModal(false);+ }showToast('Crashed session discarded');} catch (err: unknown) {console.warn('[Recovery] Discard error:', err);@@ -876,11 +968,57 @@ export function useDocumentLifecycle({[showToast]);+ const handleDiscardAllCrashedSessions = useCallback(+ async (sessionsToDiscard: CrashedSessionInfo[]) => {+ if (!sessionsToDiscard || sessionsToDiscard.length === 0) {+ uiStoreActions.setCrashedSessions([]);+ uiStoreActions.setRecoveryModal(false);+ return;+ }+ try {+ const sessionIds = sessionsToDiscard.map((s) => s.session_id);+ const { discardedIds, failedIds } =+ await recoveryService.discardAllCrashedSessions(sessionIds);+ const discardedSet = new Set(discardedIds);++ await Promise.allSettled(+ discardedIds.map((sessionId) => globalTimelapseManager.removeSession(sessionId))+ );++ let remainingCount = 0;+ uiStoreActions.setCrashedSessions((prev) => {+ const next = prev.filter((s) => !discardedSet.has(s.session_id));+ remainingCount = next.length;+ return next;+ });+ if (remainingCount === 0) {+ uiStoreActions.setRecoveryModal(false);+ }++ if (failedIds.length > 0) {+ showToast(+ `Discarded ${discardedIds.length} of ${sessionIds.length} crashed sessions`+ );+ } else {+ showToast(+ discardedIds.length === 1+ ? 'Crashed session discarded'+ : `Discarded all ${discardedIds.length} crashed sessions`+ );+ }+ } catch (err: unknown) {+ console.warn('[Recovery] Discard all error:', err);+ }+ },+ [showToast]+ );+const handleRenameDocument = useCallback((id: string, newName: string) => {documentStoreActions.setDocuments((prev) =>prev.map((d) => (d.id === id ? { ...d, name: newName } : d)));+ globalTimelapseManager.setDocumentName(id, newName);if (id === activeDocumentId) {documentStoreActions.setDocumentName(newName);}@@ -925,9 +1063,9 @@ export function useDocumentLifecycle({const buildSaveData = useCallback((onProgress?: (p: SaveProgress) => void): SaveDocumentData => {- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';+ const cleanNameForSave = sanitizeDocumentStem(documentName, 'Untitled');const docStoreState = useDocumentStore.getState();- const tlStats = globalTimelapseManager.getStats(activeDocumentId);+ const tlMeta = globalTimelapseManager.getRecoveryMetadata(activeDocumentId);artworkTimeTracker.flush(activeDocumentId);const workTimeMs = artworkTimeTracker.getWorkTimeMs(activeDocumentId);return {@@ -941,10 +1079,7 @@ export function useDocumentLifecycle({tabId: activeDocumentId || undefined,perspectiveRuler: docStoreState.perspectiveRuler,animationTimeline: docStoreState.animationTimeline,- timelapse:- tlStats.enabled || tlStats.frameCount > 0- ? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }- : null,+ timelapse: tlMeta,timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(activeDocumentId),workTimeMs,onProgress,@@ -963,153 +1098,178 @@ export function useDocumentLifecycle({const handleSaveDocumentById = useCallback(async (docId: string): Promise<SaveDocumentResult> => {+ if (savingDocIdsRef.current.has(docId)) {+ return 'canceled';+ }const storeState = useDocumentStore.getState();const targetDoc = storeState.documents.find((d) => d.id === docId);if (!targetDoc) return 'error';- const isActive = storeState.activeDocumentId === docId;- const docLayers = isActive ? layersRef.current : targetDoc.layers;- const docSavedInfo = isActive- ? storeState.savedFileInfo ?? targetDoc.savedFileInfo ?? null- : targetDoc.savedFileInfo ?? null;- const docTileGrid =- documentStore.getSession(docId)?.tileGrid ?? documentStore.getActiveTileGrid();- const cleanNameForSave = targetDoc.name.replace(/\*+$/, '') || 'Untitled';- const tlStats = globalTimelapseManager.getStats(docId);- artworkTimeTracker.flush(docId);- const docWorkTimeMs = artworkTimeTracker.getWorkTimeMs(docId);-- const onProgress = (p: SaveProgress) => {- uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);- };+ savingDocIdsRef.current.add(docId);+ try {+ const isActive = storeState.activeDocumentId === docId;+ const docLayers = isActive ? layersRef.current : targetDoc.layers;+ const docSavedInfo = isActive+ ? storeState.savedFileInfo ?? targetDoc.savedFileInfo ?? null+ : targetDoc.savedFileInfo ?? null;+ const docTileGrid =+ documentStore.getSession(docId)?.tileGrid ?? documentStore.getActiveTileGrid();+ const cleanNameForSave = sanitizeDocumentStem(+ docSavedInfo?.name || targetDoc.name,+ 'Untitled'+ );+ const tlMeta = globalTimelapseManager.getRecoveryMetadata(docId);+ artworkTimeTracker.flush(docId);+ const docWorkTimeMs = artworkTimeTracker.getWorkTimeMs(docId);- const docData: SaveDocumentData = {- name: cleanNameForSave,- dimensions: targetDoc.dimensions,- colorMode: targetDoc.colorMode,- layers: docLayers,- tileGrid: docTileGrid,- getEffectiveOpacity: (layer) => computeEffectiveOpacityForLayers(docLayers, layer),- isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(docLayers, layer),- tabId: docId,- perspectiveRuler: isActive- ? storeState.perspectiveRuler- : targetDoc.perspectiveRuler ?? null,- animationTimeline:- targetDoc.animation !== undefined- ? targetDoc.animation- : isActive- ? storeState.animationTimeline- : null,- timelapse:- tlStats.enabled || tlStats.frameCount > 0- ? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }- : null,- timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(docId),- workTimeMs: docWorkTimeMs,- onProgress,- };+ const onProgress = (p: SaveProgress) => {+ uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);+ };- const preferredExt =- docSavedInfo?.extension && docSavedInfo.extension.toLowerCase() !== '.sora'- ? docSavedInfo.extension- : '.ink';+ const docData: SaveDocumentData = {+ name: cleanNameForSave,+ dimensions: targetDoc.dimensions,+ colorMode: targetDoc.colorMode,+ layers: docLayers,+ tileGrid: docTileGrid,+ getEffectiveOpacity: (layer) => computeEffectiveOpacityForLayers(docLayers, layer),+ isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(docLayers, layer),+ tabId: docId,+ perspectiveRuler: isActive+ ? storeState.perspectiveRuler+ : targetDoc.perspectiveRuler ?? null,+ animationTimeline:+ targetDoc.animation !== undefined+ ? targetDoc.animation+ : isActive+ ? storeState.animationTimeline+ : null,+ timelapse: tlMeta,+ timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(docId),+ workTimeMs: docWorkTimeMs,+ onProgress,+ };- const applySavedMetadata = (- info: { name: string; handle?: any; extension: string; size?: number; previewDataUrl?: string },- updateHandle: boolean- ) => {- const latestActiveId = useDocumentStore.getState().activeDocumentId;- if (latestActiveId === docId) {- if (updateHandle) {- documentStoreActions.setSavedFileInfo(info);+ const preferredExt =+ docSavedInfo?.extension && docSavedInfo.extension.toLowerCase() !== '.sora'+ ? docSavedInfo.extension+ : '.ink';+ const initialDir = getParentDirectory(docSavedInfo?.path ?? targetDoc.sourcePath);++ const applySavedMetadata = (+ info: {+ name: string;+ handle?: any;+ path?: string;+ extension: string;+ size?: number;+ previewDataUrl?: string;+ },+ updateHandle: boolean+ ) => {+ const latestActiveId = useDocumentStore.getState().activeDocumentId;+ if (latestActiveId === docId) {+ if (updateHandle) {+ documentStoreActions.setSavedFileInfo(info);+ }+ documentStoreActions.setDocumentName(info.name);}- documentStoreActions.setDocumentName(info.name);- }- documentStoreActions.setDocuments((prev) =>- prev.map((d) =>- d.id === docId- ? {- ...d,- name: info.name,- ...(updateHandle ? { savedFileInfo: info } : {}),- isDirty: false,- workTimeMs: docWorkTimeMs,- }- : d- )+ documentStoreActions.setDocuments((prev) =>+ prev.map((d) =>+ d.id === docId+ ? {+ ...d,+ name: info.name,+ ...(updateHandle ? { savedFileInfo: info } : {}),+ ...(info.path ? { sourcePath: info.path } : {}),+ isDirty: false,+ workTimeMs: docWorkTimeMs,+ }+ : d+ )+ );+ globalTimelapseManager.linkDocumentSave(docId, {+ documentName: info.name,+ sourcePath: info.path || `InkStudio\\${info.name}`,+ });+ saveRecentDocument({+ id: docId,+ title: info.name,+ path: info.path || `InkStudio\\${info.name}`,+ size: info.size || 1572864,+ coverUrl: info.previewDataUrl || docLayers[0]?.thumbnailUrl,+ isStarred: false,+ fileType: info.extension,+ width: targetDoc.dimensions?.width,+ height: targetDoc.dimensions?.height,+ dpi: targetDoc.dimensions?.dpi,+ isSaved: true,+ handle: info.handle,+ }).catch(console.warn);+ showToast(`Saved to ${info.name}`);+ };++ const hasDirectTarget = Boolean(+ docSavedInfo?.handle || isRealNativeDiskPath(docSavedInfo?.path));- saveRecentDocument({- id: docId,- title: info.name,- path: `InkStudio\\${info.name}`,- size: info.size || 1572864,- coverUrl: info.previewDataUrl || docLayers[0]?.thumbnailUrl,- isStarred: false,- fileType: info.extension,- width: targetDoc.dimensions?.width,- height: targetDoc.dimensions?.height,- dpi: targetDoc.dimensions?.dpi,- isSaved: true,- handle: info.handle,- }).catch(console.warn);- showToast(`Saved to ${info.name}`);- };+ if (!hasDirectTarget || docSavedInfo?.extension?.toLowerCase() === '.sora') {+ try {+ const info = await promptSaveAs(docData, preferredExt, true, { initialDir });+ applySavedMetadata(info, true);+ return 'saved';+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ if (msg === 'Save canceled') {+ return 'canceled';+ }+ void uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Failed to save file.',+ detail: msg,+ });+ return 'error';+ } finally {+ uiStoreActions.setLoading(false, '');+ }+ }- if (!docSavedInfo?.handle || docSavedInfo.extension?.toLowerCase() === '.sora') {try {- const info = await promptSaveAs(docData, preferredExt);- applySavedMetadata(info, true);+ const saveRes = await saveToExistingHandle(docData, docSavedInfo!);+ applySavedMetadata(+ {+ name: docSavedInfo!.name,+ handle: docSavedInfo!.handle,+ ...(docSavedInfo!.path ? { path: docSavedInfo!.path } : {}),+ extension: docSavedInfo!.extension,+ size: saveRes.size,+ previewDataUrl: saveRes.previewDataUrl,+ },+ false+ );return 'saved';} catch (err: unknown) {- const msg = err instanceof Error ? err.message : String(err);- if (msg === 'Save canceled') {- return 'canceled';+ console.warn('Direct handle/path save failed, prompting with Save As:', err);+ try {+ const info = await promptSaveAs(docData, preferredExt, true, { initialDir });+ applySavedMetadata(info, true);+ return 'saved';+ } catch (e: unknown) {+ const msg = e instanceof Error ? e.message : String(e);+ if (msg === 'Save canceled') {+ return 'canceled';+ }+ void uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Failed to save file.',+ detail: msg,+ });+ return 'error';}- void uiStoreActions.alertDialog({- title: 'Save Failed',- message: 'Failed to save file.',- detail: msg,- });- return 'error';} finally {uiStoreActions.setLoading(false, '');}- }-- try {- const saveRes = await saveToExistingHandle(docData, docSavedInfo);- applySavedMetadata(- {- name: docSavedInfo.name,- handle: docSavedInfo.handle,- extension: docSavedInfo.extension,- size: saveRes.size,- previewDataUrl: saveRes.previewDataUrl,- },- false- );- return 'saved';- } catch (err: unknown) {- console.warn('Direct handle save failed, prompting with Save As:', err);- try {- const info = await promptSaveAs(docData, preferredExt);- applySavedMetadata(info, true);- return 'saved';- } catch (e: unknown) {- const msg = e instanceof Error ? e.message : String(e);- if (msg === 'Save canceled') {- return 'canceled';- }- void uiStoreActions.alertDialog({- title: 'Save Failed',- message: 'Failed to save file.',- detail: msg,- });- return 'error';- }} finally {- uiStoreActions.setLoading(false, '');+ savingDocIdsRef.current.delete(docId);}},[showToast]@@ -1122,6 +1282,10 @@ export function useDocumentLifecycle({}, [handleSaveDocumentById]);const handleSaveAs = useCallback(async () => {+ const currentId = activeDocumentId;+ if (currentId && savingDocIdsRef.current.has(currentId)) return;+ if (currentId) savingDocIdsRef.current.add(currentId);+const onProgress = (p: SaveProgress) => {uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);};@@ -1132,20 +1296,36 @@ export function useDocumentLifecycle({savedFileInfo?.extension && savedFileInfo.extension.toLowerCase() !== '.sora'? savedFileInfo.extension: '.ink';- const info = await promptSaveAs(docData, defaultExt);+ const activeDoc = useDocumentStore+ .getState()+ .documents.find((d) => d.id === activeDocumentId);+ const initialDir = getParentDirectory(savedFileInfo?.path ?? activeDoc?.sourcePath);++ const info = await promptSaveAs(docData, defaultExt, true, { initialDir });documentStoreActions.setSavedFileInfo(info);documentStoreActions.setDocumentName(info.name);documentStoreActions.setDocuments((prev) =>prev.map((d) =>d.id === activeDocumentId- ? { ...d, name: info.name, savedFileInfo: info, isDirty: false, workTimeMs: docData.workTimeMs }+ ? {+ ...d,+ name: info.name,+ savedFileInfo: info,+ ...(info.path ? { sourcePath: info.path } : {}),+ isDirty: false,+ workTimeMs: docData.workTimeMs,+ }: d));+ globalTimelapseManager.linkDocumentSave(activeDocumentId, {+ documentName: info.name,+ sourcePath: info.path || `InkStudio\\${info.name}`,+ });saveRecentDocument({id: activeDocumentId || `doc-${Date.now()}`,title: info.name,- path: `InkStudio\\${info.name}`,+ path: info.path || `InkStudio\\${info.name}`,size: info.size || 1572864,coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,isStarred: false,@@ -1167,19 +1347,24 @@ export function useDocumentLifecycle({});}} finally {+ if (currentId) savingDocIdsRef.current.delete(currentId);uiStoreActions.setLoading(false, '');}- }, [activeDocumentId, buildSaveData, layers, savedFileInfo, showToast]);+ }, [activeDocumentId, buildSaveData, dimensions.dpi, dimensions.height, dimensions.width, layers, savedFileInfo, showToast]);const handleExportImage = useCallback(async () => {- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';+ const cleanNameForSave = sanitizeDocumentStem(documentName, 'artwork');const onProgress = (p: SaveProgress) => {uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);};const docData = buildSaveData(onProgress);+ const activeDoc = useDocumentStore+ .getState()+ .documents.find((d) => d.id === activeDocumentId);+ const initialDir = getParentDirectory(savedFileInfo?.path ?? activeDoc?.sourcePath);try {- const exportedName = await promptExportPngImage(docData, cleanNameForSave);+ const exportedName = await promptExportPngImage(docData, cleanNameForSave, { initialDir });showToast(`Exported image to ${exportedName}`);} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);@@ -1193,11 +1378,14 @@ export function useDocumentLifecycle({} finally {uiStoreActions.setLoading(false, '');}- }, [buildSaveData, documentName, showToast]);+ }, [activeDocumentId, buildSaveData, documentName, savedFileInfo?.path, showToast]);const handleSelectWelcomeDocument = useCallback(async (doc: RecentDocument) => {- const openDoc = useDocumentStore.getState().documents.find((d) => d.id === doc.id);+ const openDocs = useDocumentStore.getState().documents;+ const openDoc =+ openDocs.find((d) => d.id === doc.id) ??+ (doc.path ? findOpenDocumentBySourcePath(openDocs, doc.path) : undefined);if (openDoc) {handleSelectDocument(openDoc.id);return;@@ -1267,12 +1455,55 @@ export function useDocumentLifecycle({[handleProcessFile, handleSelectDocument, handleTriggerOpenFile, showToast]);+ const handleOpenFilePaths = useCallback(+ (paths: readonly string[]): Promise<void> => {+ const validPaths = paths.filter(+ (p): p is string => typeof p === 'string' && p.trim().length > 0+ );+ if (validPaths.length === 0) return Promise.resolve();++ const run = async () => {+ for (const filePath of validPaths) {+ // If this file is already open in a tab, focus that tab instead of duplicating it.+ const existing = findOpenDocumentBySourcePath(+ useDocumentStore.getState().documents,+ filePath+ );+ if (existing) {+ handleSelectDocument(existing.id);+ showToast(`Switched to ${existing.name}`);+ continue;+ }++ try {+ const file = await readTauriPathAsFile(filePath);+ await handleProcessFile(file, { sourcePath: filePath });+ } catch (err: unknown) {+ console.error('Failed to open file from OS path:', filePath, err);+ const errMsg = err instanceof Error ? err.message : String(err);+ void uiStoreActions.alertDialog({+ title: 'Could Not Open File',+ message: `Could not open "${filePath}".`,+ detail: errMsg || 'File could not be read.',+ });+ }+ }+ };++ const next = openFileQueueRef.current.then(run, run);+ openFileQueueRef.current = next;+ return next;+ },+ [handleProcessFile, handleSelectDocument, showToast]+ );+return {fileInputRef,pasteFileInputRef,import3DFileInputRef,needsAdaptiveFitRef,pendingFitDimsRef,+ autoCreatedInitialDocIdRef,handleViewportReady,handleCreateNewCanvas,handleCopySelectedLayer,@@ -1285,10 +1516,12 @@ export function useDocumentLifecycle({handleResizeCanvas,handleUpdateSettings,handleProcessFile,+ handleOpenFilePaths,handleSelectDocument,handleCloseDocument,handleRestoreCrashedSession,handleDiscardCrashedSession,+ handleDiscardAllCrashedSessions,handleRenameDocument,handleTriggerOpenFile,handleFileInputChange,@@ -1305,6 +1538,7 @@ export interface DocumentLifecycleManagerProps {activeLayerId: string;needsAdaptiveFitRef: React.MutableRefObject<boolean>;pendingFitDimsRef: React.MutableRefObject<CanvasDimensions | null>;+ autoCreatedInitialDocIdRef?: React.MutableRefObject<string | null>;resetToNewCanvas: (dims: CanvasDimensions,bgColor: string,@@ -1315,12 +1549,14 @@ export interface DocumentLifecycleManagerProps {resetZoomAndCenter: (dims?: CanvasDimensions) => void;resetHistory: (targetDocumentId?: string) => void;onSelectDocument: (id: string) => void;+ onOpenFilePaths?: (paths: readonly string[]) => Promise<void>;}/*** Headless lifecycle coordinator: handles startup crash recovery detection,- * initial canvas creation, WAL checkpointing, tile memory budget sync,- * active document tab metadata synchronization, and app close confirmation guard.+ * OS file-association launch & single-instance file open events, initial canvas creation,+ * WAL checkpointing, tile memory budget sync, active document tab metadata synchronization,+ * and app close confirmation guard.*/export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> = React.memo(({@@ -1328,10 +1564,12 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =activeLayerId,needsAdaptiveFitRef,pendingFitDimsRef,+ autoCreatedInitialDocIdRef,resetToNewCanvas,resetZoomAndCenter,resetHistory,onSelectDocument,+ onOpenFilePaths,}) => {const documents = useDocumentStore((s) => s.documents);const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);@@ -1415,18 +1653,21 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =};}, []);- // 3. Auto-create initial white canvas on launch+ // 3. Open OS-associated launch files (cold + single-instance warm events) or auto-create initial white canvasconst hasAutoCreatedInitialDocRef = useRef(false);- useEffect(() => {- if (hasAutoCreatedInitialDocRef.current || documents.length > 0) return;- hasAutoCreatedInitialDocRef.current = true;+ const onOpenFilePathsRef = useRef(onOpenFilePaths);+ onOpenFilePathsRef.current = onOpenFilePaths;++ const createInitialBlankCanvas = useCallback(() => {+ if (useDocumentStore.getState().documents.length > 0) return;+ const latestSettings = useUiStore.getState().appSettings;const initDims: CanvasDimensions = {- width: appSettings.defaultWidth || 1920,- height: appSettings.defaultHeight || 1080,- dpi: appSettings.defaultDpi || 300,+ width: latestSettings.defaultWidth || 1920,+ height: latestSettings.defaultHeight || 1080,+ dpi: latestSettings.defaultDpi || 300,};- const initColorMode = appSettings.defaultColorMode || 'color';- const initBg = appSettings.defaultBgColor || '#ffffff';+ const initColorMode = latestSettings.defaultColorMode || 'color';+ const initBg = latestSettings.defaultBgColor || '#ffffff';const initName = 'Untitled*';const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;documentStoreActions.setDimensions(initDims);@@ -1444,6 +1685,9 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =resetZoomAndCenter(initDims);resetHistory(newDocId);artworkTimeTracker.initDocument(newDocId, 0);+ if (autoCreatedInitialDocIdRef) {+ autoCreatedInitialDocIdRef.current = newDocId;+ }documentStoreActions.setDocuments([{id: newDocId,@@ -1460,12 +1704,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =documentStoreActions.setActiveDocumentId(newDocId);uiStoreActions.setAppView('workspace');}, [- appSettings.defaultBgColor,- appSettings.defaultColorMode,- appSettings.defaultDpi,- appSettings.defaultHeight,- appSettings.defaultWidth,- documents.length,+ autoCreatedInitialDocIdRef,needsAdaptiveFitRef,pendingFitDimsRef,resetHistory,@@ -1473,6 +1712,59 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =resetZoomAndCenter,]);+ useEffect(() => {+ if (!isTauriEnvironment()) {+ if (hasAutoCreatedInitialDocRef.current || useDocumentStore.getState().documents.length > 0) {+ return;+ }+ hasAutoCreatedInitialDocRef.current = true;+ createInitialBlankCanvas();+ return;+ }++ let disposed = false;+ let unlisten: (() => void) | undefined;++ void (async () => {+ // 1) Attach single-instance warm open-file listener FIRST so no event is missed+ const stop = await listenForOpenFiles((paths) => {+ if (disposed) return;+ void onOpenFilePathsRef.current?.(paths);+ });+ if (disposed) {+ stop();+ return;+ }+ unlisten = stop;++ // 2) Atomically mark frontend ready and drain any cold-launch OS file args (e.g. double-clicked .ink)+ const pendingPaths = await takePendingOpenFiles();+ if (disposed) return;++ if (pendingPaths.length > 0 && onOpenFilePathsRef.current) {+ hasAutoCreatedInitialDocRef.current = true;+ await onOpenFilePathsRef.current(pendingPaths);+ if (disposed) return;+ // Fall back to a blank canvas only if none of the launch files opened a document tab+ // (e.g. launching with a `.inkb` brush or `.cls` color set, or a corrupt file).+ if (useDocumentStore.getState().documents.length === 0) {+ createInitialBlankCanvas();+ }+ return;+ }++ if (!hasAutoCreatedInitialDocRef.current && useDocumentStore.getState().documents.length === 0) {+ hasAutoCreatedInitialDocRef.current = true;+ createInitialBlankCanvas();+ }+ })();++ return () => {+ disposed = true;+ unlisten?.();+ };+ }, [createInitialBlankCanvas]);+// 4. Sync active document recovery session & WAL periodic checkpointingconst recoveryStateRef = useRef({documents,diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsxindex c3efd9d..8663bd5 100644--- a/src/components/GlobalShortcutListener.tsx+++ b/src/components/GlobalShortcutListener.tsx@@ -756,6 +756,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReamodKey === 'Alt' &&tempTool === 'pipette' &&(Boolean(p.transformSession?.active) ||+ Boolean(p.textSession) ||(curState.tool === 'retouch' && curState.retouchSettings.mode === 'clone-stamp') ||curState.tool === 'pen' ||curState.tool === '3d');diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsxindex 302a7c9..6140724 100644--- a/src/components/ModalHost.tsx+++ b/src/components/ModalHost.tsx@@ -49,9 +49,11 @@ export interface ModalHostProps {isLayerEffectivelyVisible: (layer: LayerItem) => boolean;handleCreateNewCanvas: (options: NewCanvasOptions) => void;handleResizeCanvas: (options: ResizeCanvasOptions) => void;+ selectionBounds?: { x: number; y: number; width: number; height: number } | null;handleUpdateSettings: (newSettings: AppSettings) => void;handleRestoreCrashedSession: (session: CrashedSessionInfo) => Promise<void>;handleDiscardCrashedSession: (session: CrashedSessionInfo) => Promise<void>;+ handleDiscardAllCrashedSessions: (sessions: CrashedSessionInfo[]) => Promise<void>;handleTonalCancel: () => void;handleTonalApply: (type: TonalCorrectionType, params: AnyTonalParams) => void;handleTonalPreviewChange: (@@ -139,9 +141,11 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(isLayerEffectivelyVisible,handleCreateNewCanvas,handleResizeCanvas,+ selectionBounds = null,handleUpdateSettings,handleRestoreCrashedSession,handleDiscardCrashedSession,+ handleDiscardAllCrashedSessions,handleTonalCancel,handleTonalApply,handleTonalPreviewChange,@@ -249,6 +253,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(sessions={crashedSessions}onRestore={handleRestoreCrashedSession}onDiscard={handleDiscardCrashedSession}+ onDiscardAll={handleDiscardAllCrashedSessions}onClose={() => uiStoreActions.setRecoveryModal(false)}/>@@ -268,6 +273,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(onClose={() => uiStoreActions.setResizeCanvasModalOpen(false)}currentDimensions={dimensions}onResize={handleResizeCanvas}+ selectionBounds={selectionBounds}/><SettingsModaldiff --git a/src/components/ResizeCanvasModal.tsx b/src/components/ResizeCanvasModal.tsxindex 356f126..59643a0 100644--- a/src/components/ResizeCanvasModal.tsx+++ b/src/components/ResizeCanvasModal.tsx@@ -1,4 +1,4 @@-import React, { useState, useId, useMemo, useEffect, useCallback } from 'react';+import React, { useState, useId, useMemo, useEffect, useCallback, useRef } from 'react';import {X,Lock,@@ -7,6 +7,12 @@ import {Printer,Maximize2,Check,+ Crop,+ RotateCcw,+ GripHorizontal,+ Grid3X3,+ PanelRightClose,+ SquareDashed,ArrowUpLeft,ArrowUp,ArrowUpRight,@@ -19,6 +25,30 @@ import {} from 'lucide-react';import { CanvasDimensions } from '../types/editor';import { AnchorPosition, ResizeCanvasOptions } from '../types/settings';+import { uiStoreActions, useUiStore } from '../stores';+import {+ CanvasResizeDraft,+ CropGridMode,+ MAX_CANVAS_DIM,+ MIN_CANVAS_DIM,+ RATIO_PRESETS,+ applyAnchorToDraft,+ applyCropXToDraft,+ applyCropYToDraft,+ applyFitBoundsToDraft,+ applyHeightToDraft,+ applyLockRatioToggleToDraft,+ applyRatioPresetToDraft,+ applyResetCropToDraft,+ applyScaleContentToggleToDraft,+ applySwapDimensionsToDraft,+ applyWidthToDraft,+ createInitialCanvasResizeDraft,+ cycleCropGridMode,+ draftToResizeCanvasOptions,+ isCropModified,+ nudgeCropDraft,+} from '../utils/canvasResizeCrop';import { DPI_PRESETS } from './NewCanvasModal';function gcd(a: number, b: number): number {@@ -27,16 +57,6 @@ function gcd(a: number, b: number): number {return b ? gcd(b, a % b) : a;}-const RATIO_PRESETS = [- { label: '16:9', x: 16, y: 9 },- { label: '1:1', x: 1, y: 1 },- { label: '4:3', x: 4, y: 3 },- { label: '3:2', x: 3, y: 2 },- { label: '9:16', x: 9, y: 16 },- { label: '2:3', x: 2, y: 3 },- { label: '21:9', x: 21, y: 9 },-];-const ANCHOR_GRID: { id: AnchorPosition; label: string; icon: React.ReactNode }[] = [{ id: 'top-left', label: 'Top Left', icon: <ArrowUpLeft className="w-3.5 h-3.5" /> },{ id: 'top', label: 'Top Center', icon: <ArrowUp className="w-3.5 h-3.5" /> },@@ -49,11 +69,92 @@ const ANCHOR_GRID: { id: AnchorPosition; label: string; icon: React.ReactNode }[{ id: 'bottom-right', label: 'Bottom Right', icon: <ArrowDownRight className="w-3.5 h-3.5" /> },];+const ANCHOR_LABELS: Record<AnchorPosition, string> = {+ 'top-left': 'Top Left',+ top: 'Top Center',+ 'top-right': 'Top Right',+ left: 'Middle Left',+ center: 'Center',+ right: 'Middle Right',+ 'bottom-left': 'Bottom Left',+ bottom: 'Bottom Center',+ 'bottom-right': 'Bottom Right',+};++function formatGridMode(mode: CropGridMode): string {+ if (mode === 'thirds') return 'Thirds';+ if (mode === 'golden') return 'Golden';+ return 'Off';+}++interface NumericDraftInputProps {+ id: string;+ value: number;+ min: number;+ max: number;+ onCommit: (val: number) => void;+ className?: string;+}++const NumericDraftInput: React.FC<NumericDraftInputProps> = ({+ id,+ value,+ min,+ max,+ onCommit,+ className,+}) => {+ const [editingText, setEditingText] = useState<string | null>(null);+ const isFocusedRef = useRef(false);++ const displayed = editingText !== null ? editingText : String(value);++ return (+ <input+ id={id}+ type="number"+ min={min}+ max={max}+ value={displayed}+ onFocus={() => {+ isFocusedRef.current = true;+ setEditingText(String(value));+ }}+ onChange={(e) => {+ const raw = e.target.value;+ if (isFocusedRef.current) {+ setEditingText(raw);+ }+ const trimmed = raw.trim();+ if (trimmed === '' || trimmed === '-') return;+ const parsed = Number(trimmed);+ if (Number.isFinite(parsed)) {+ // For positive-only dimensions, wait for blur if typed value is < min (e.g. typing "800" starting with "0")+ if (min >= 1 && parsed < min) return;+ onCommit(parsed);+ }+ }}+ onBlur={() => {+ isFocusedRef.current = false;+ if (editingText !== null) {+ const parsed = Number(editingText.trim());+ if (editingText.trim() !== '' && Number.isFinite(parsed)) {+ onCommit(parsed);+ }+ setEditingText(null);+ }+ }}+ className={className}+ />+ );+};+interface ResizeCanvasModalProps {isOpen: boolean;onClose: () => void;currentDimensions: CanvasDimensions;onResize: (options: ResizeCanvasOptions) => void;+ selectionBounds?: { x: number; y: number; width: number; height: number } | null;}export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({@@ -61,62 +162,160 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({onClose,currentDimensions,onResize,+ selectionBounds = null,}) => {const widthInputId = useId();const heightInputId = useId();+ const cropXInputId = useId();+ const cropYInputId = useId();const dpiInputId = useId();- const [width, setWidth] = useState<number>(currentDimensions.width);- const [height, setHeight] = useState<number>(currentDimensions.height);- const [dpi, setDpi] = useState<number>(currentDimensions.dpi || 300);- const [lockRatio, setLockRatio] = useState<boolean>(true);- const [scaleContent, setScaleContent] = useState<boolean>(false);- const [anchor, setAnchor] = useState<AnchorPosition>('center');+ const storeDraft = useUiStore((s) => s.canvasResizeDraft);+ const isInspectorCollapsed = useUiStore((s) => s.isResizeInspectorCollapsed);- // Keep track of locked aspect ratio values- const [ratioX, setRatioX] = useState<number>(currentDimensions.width);- const [ratioY, setRatioY] = useState<number>(currentDimensions.height);+ const userToggledLockRef = useRef(false);+ const [pos, setPos] = useState<{ x: number; y: number }>({ x: 0, y: 0 });+ const isDraggingWindowRef = useRef(false);+ const dragStartRef = useRef({ startX: 0, startY: 0, initX: 0, initY: 0 });- // Synchronize when opening+ // Ensure draft is initialized and synchronized whenever openeduseEffect(() => {- if (isOpen) {- setWidth(currentDimensions.width);- setHeight(currentDimensions.height);- setDpi(currentDimensions.dpi || 300);- setRatioX(currentDimensions.width);- setRatioY(currentDimensions.height);+ if (!isOpen) return;+ userToggledLockRef.current = false;+ setPos({ x: 0, y: 0 });+ const existing = useUiStore.getState().canvasResizeDraft;+ if (+ !existing ||+ existing.originWidth !== currentDimensions.width ||+ existing.originHeight !== currentDimensions.height+ ) {+ uiStoreActions.updateCanvasResizeDraft(createInitialCanvasResizeDraft(currentDimensions));}}, [isOpen, currentDimensions]);+ const draft: CanvasResizeDraft = useMemo(+ () => storeDraft ?? createInitialCanvasResizeDraft(currentDimensions),+ [storeDraft, currentDimensions]+ );++ const updateDraft = useCallback(+ (updater: (prev: CanvasResizeDraft) => CanvasResizeDraft) => {+ const current =+ useUiStore.getState().canvasResizeDraft ??+ createInitialCanvasResizeDraft(currentDimensions);+ uiStoreActions.updateCanvasResizeDraft(updater(current));+ },+ [currentDimensions]+ );+const handleApplyResize = useCallback(() => {- onResize({- width,- height,- dpi: Math.max(1, Math.round(dpi)),- scaleContent,- anchor,- });+ const latest =+ useUiStore.getState().canvasResizeDraft ??+ createInitialCanvasResizeDraft(currentDimensions);+ onResize(draftToResizeCanvasOptions(latest));onClose();- }, [onResize, width, height, dpi, scaleContent, anchor, onClose]);+ }, [currentDimensions, onResize, onClose]);useEffect(() => {if (!isOpen) return;const handleKeyDown = (e: KeyboardEvent) => {+ const target = e.target as HTMLElement | null;+ const tag = target?.tagName;+ const isTextLike =+ tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || Boolean(target?.isContentEditable);+if (e.key === 'Escape') {e.preventDefault();e.stopPropagation();onClose();- } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {+ return;+ }++ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {e.preventDefault();e.stopPropagation();+ if (target && tag === 'INPUT') {+ target.blur();+ }handleApplyResize();+ return;+ }++ if (e.key === 'Enter' && tag !== 'BUTTON' && tag !== 'SELECT' && tag !== 'TEXTAREA') {+ e.preventDefault();+ e.stopPropagation();+ if (target && tag === 'INPUT') {+ target.blur();+ }+ handleApplyResize();+ return;+ }++ if (!isTextLike && !e.ctrlKey && !e.metaKey && !e.altKey) {+ const step = e.shiftKey ? 10 : 1;+ if (e.key === 'ArrowLeft') {+ e.preventDefault();+ e.stopPropagation();+ updateDraft((prev) => nudgeCropDraft(prev, -step, 0));+ } else if (e.key === 'ArrowRight') {+ e.preventDefault();+ e.stopPropagation();+ updateDraft((prev) => nudgeCropDraft(prev, step, 0));+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ e.stopPropagation();+ updateDraft((prev) => nudgeCropDraft(prev, 0, -step));+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ e.stopPropagation();+ updateDraft((prev) => nudgeCropDraft(prev, 0, step));+ }}};window.addEventListener('keydown', handleKeyDown, true);return () => window.removeEventListener('keydown', handleKeyDown, true);- }, [isOpen, onClose, handleApplyResize]);+ }, [isOpen, onClose, handleApplyResize, updateDraft]);++ // Floating window drag handlers+ const handleWindowDragStart = (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) return;+ if ((e.target as HTMLElement).closest('button')) return;+ isDraggingWindowRef.current = true;+ dragStartRef.current = {+ startX: e.clientX,+ startY: e.clientY,+ initX: pos.x,+ initY: pos.y,+ };+ try {+ e.currentTarget.setPointerCapture(e.pointerId);+ } catch {+ // Ignore synthetic capture error+ }+ };++ const handleWindowDragMove = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!isDraggingWindowRef.current) return;+ const dx = e.clientX - dragStartRef.current.startX;+ const dy = e.clientY - dragStartRef.current.startY;+ setPos({+ x: dragStartRef.current.initX + dx,+ y: dragStartRef.current.initY + dy,+ });+ };++ const handleWindowDragEnd = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!isDraggingWindowRef.current) return;+ isDraggingWindowRef.current = false;+ try {+ e.currentTarget.releasePointerCapture(e.pointerId);+ } catch {+ // Ignore+ }+ };++ const { width, height, dpi, lockRatio, scaleContent, anchor, cropX, cropY, gridMode } = draft;- // Simplified aspect ratio stringconst simplifiedRatio = useMemo(() => {if (width <= 0 || height <= 0) return '1:1';const divisor = gcd(width, height);@@ -129,21 +328,18 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({return `${dec}:1`;}, [width, height]);- // Dimension scaling percentages relative to current canvas- const percentW = useMemo(() => {- return Math.round((width / (currentDimensions.width || 1)) * 100);- }, [width, currentDimensions.width]);+ const percentW = useMemo(+ () => Math.round((width / (currentDimensions.width || 1)) * 100),+ [width, currentDimensions.width]+ );- const percentH = useMemo(() => {- return Math.round((height / (currentDimensions.height || 1)) * 100);- }, [height, currentDimensions.height]);+ const percentH = useMemo(+ () => Math.round((height / (currentDimensions.height || 1)) * 100),+ [height, currentDimensions.height]+ );- // Megapixels- const megapixels = useMemo(() => {- return ((width * height) / 1000000).toFixed(2);- }, [width, height]);+ const megapixels = useMemo(() => ((width * height) / 1000000).toFixed(2), [width, height]);- // Physical print sizesconst printDimensionsCm = useMemo(() => {const safeDpi = Math.max(1, dpi);return {@@ -152,79 +348,130 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({};}, [width, height, dpi]);- const handleWidthChange = (val: number) => {- const newW = Math.max(1, Math.min(16384, Math.round(val)));- setWidth(newW);- if (lockRatio && ratioX > 0 && ratioY > 0) {- const newH = Math.max(1, Math.round((newW * ratioY) / ratioX));- setHeight(newH);- }- };+ const modified = isCropModified(draft);- const handleHeightChange = (val: number) => {- const newH = Math.max(1, Math.min(16384, Math.round(val)));- setHeight(newH);- if (lockRatio && ratioX > 0 && ratioY > 0) {- const newW = Math.max(1, Math.round((newH * ratioX) / ratioY));- setWidth(newW);- }+ const handleToggleLockRatio = () => {+ userToggledLockRef.current = true;+ updateDraft((prev) => applyLockRatioToggleToDraft(prev, !prev.lockRatio));};- const handleSwapDimensions = () => {- const prevW = width;- const prevH = height;- setWidth(prevH);- setHeight(prevW);- setRatioX(ratioY);- setRatioY(ratioX);+ const handleSetScaleContent = (nextScale: boolean) => {+ const shouldAutoLock = nextScale && !userToggledLockRef.current;+ updateDraft((prev) => applyScaleContentToggleToDraft(prev, nextScale, shouldAutoLock));};- const handleApplyRatioPreset = (x: number, y: number) => {- setRatioX(x);- setRatioY(y);- const newH = Math.max(1, Math.round((width * y) / x));- setHeight(newH);- };+ if (!isOpen || isInspectorCollapsed) return null;- if (!isOpen) return null;+ const isCropping = !scaleContent;+ const applyButtonLabel = isCropping && modified ? 'Apply Crop & Resize' : 'Resize Canvas';return (<div- role="dialog"- aria-modal="true"- aria-labelledby="resize-canvas-modal-title"- className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"- onClick={onClose}+ className="fixed inset-0 z-[49] pointer-events-none flex items-start justify-end p-3 sm:p-4 pt-12 sm:pt-14 select-none"><div- onClick={(e) => e.stopPropagation()}- className="bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover w-full max-w-[600px] flex flex-col overflow-hidden text-xs text-ui-primary"+ role="dialog"+ aria-modal="false"+ aria-labelledby="resize-canvas-modal-title"+ data-allow-canvas-nav="true"+ onPointerDown={(e) => e.stopPropagation()}+ style={{+ transform: `translate3d(${pos.x}px, ${pos.y}px, 0)`,+ }}+ className="pointer-events-auto bg-ui-panel/98 backdrop-blur-sm border border-ui-default rounded-ui-lg shadow-ui-popover w-[360px] max-w-[92vw] flex flex-col overflow-hidden text-xs text-ui-primary">- {/* Header */}- <div className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between shrink-0">- <div className="flex items-center gap-2">- <Maximize2 className="w-3.5 h-3.5 text-ui-accent" />- <h2 id="resize-canvas-modal-title" className="text-xs font-medium text-ui-primary tracking-wide">+ {/* Draggable Header */}+ <div+ onPointerDown={handleWindowDragStart}+ onPointerMove={handleWindowDragMove}+ onPointerUp={handleWindowDragEnd}+ onPointerCancel={handleWindowDragEnd}+ onDoubleClick={() => setPos({ x: 0, y: 0 })}+ className="h-9 px-3 bg-ui-header border-b border-ui-subtle flex items-center justify-between shrink-0 cursor-move"+ title="Drag to move panel · Double-click to reset position"+ >+ <div className="flex items-center gap-2 min-w-0">+ {isCropping ? (+ <Crop className="w-3.5 h-3.5 text-ui-accent shrink-0" />+ ) : (+ <Maximize2 className="w-3.5 h-3.5 text-ui-accent shrink-0" />+ )}+ <h2+ id="resize-canvas-modal-title"+ className="text-xs font-medium text-ui-primary tracking-wide truncate"+ >Resize Canvas</h2>+ <GripHorizontal className="w-3.5 h-3.5 text-ui-disabled shrink-0" />+ </div>++ <div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ onClick={() => uiStoreActions.setResizeInspectorCollapsed(true)}+ aria-label="Collapse panel"+ title="Hide panel while cropping on canvas"+ className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"+ >+ <PanelRightClose className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button></div>- <button- type="button"- onClick={onClose}- aria-label="Close"- title="Cancel (Esc)"- className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"- >- <X className="w-3.5 h-3.5" />- </button></div>{/* Body */}- <div className="p-4 space-y-3.5 max-h-[82vh] overflow-y-auto">- {/* Current Canvas Status Bar */}- <div className="bg-ui-header border border-ui-subtle rounded-ui-md px-3.5 py-2 flex items-center justify-between">- <span className="text-ui-muted text-[11px]">Current Dimensions</span>- <div className="flex items-center gap-2 font-ui-mono tabular-nums text-xs">+ <div className="p-3 space-y-2.5 max-h-[calc(100vh-150px)] overflow-y-auto">+ {/* Mode Toggle */}+ <div className="grid grid-cols-2 gap-1.5">+ <button+ type="button"+ onClick={() => handleSetScaleContent(false)}+ className={`p-2 rounded-ui-md border text-left transition-colors cursor-pointer ${+ isCropping+ ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'+ : 'bg-ui-header border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ <div className="flex items-center gap-1.5 font-medium text-[11px] text-ui-primary mb-0.5">+ <Crop className="w-3 h-3 text-ui-accent shrink-0" />+ <span>Canvas Bounds</span>+ </div>+ <p className="text-[10px] text-ui-muted leading-tight">+ Crop or expand directly on canvas without distorting pixels.+ </p>+ </button>++ <button+ type="button"+ onClick={() => handleSetScaleContent(true)}+ className={`p-2 rounded-ui-md border text-left transition-colors cursor-pointer ${+ scaleContent+ ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'+ : 'bg-ui-header border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ <div className="flex items-center gap-1.5 font-medium text-[11px] text-ui-primary mb-0.5">+ <Maximize2 className="w-3 h-3 text-ui-accent shrink-0" />+ <span>Scale Content</span>+ </div>+ <p className="text-[10px] text-ui-muted leading-tight">+ Resamples and scales all artwork to new dimensions.+ </p>+ </button>+ </div>++ {/* Current Dimensions Status Bar */}+ <div className="bg-ui-header border border-ui-subtle rounded-ui-md px-3 py-1.5 flex items-center justify-between">+ <span className="text-ui-muted text-[11px]">Current</span>+ <div className="flex items-center gap-1.5 font-ui-mono tabular-nums text-[11px]"><span className="text-ui-primary font-medium">{currentDimensions.width} × {currentDimensions.height} px</span>@@ -233,53 +480,62 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({</div></div>- {/* New Dimensions & Keep Aspect Ratio */}- <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-3.5 space-y-3">+ {/* New Dimensions & Aspect Ratio */}+ <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2.5"><div className="flex items-center justify-between"><span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">New Dimensions</span>- <div className="flex items-center gap-1.5">+ <div className="flex items-center gap-1"><buttontype="button"- onClick={() => setLockRatio(!lockRatio)}- className={`flex items-center gap-1.5 px-2.5 py-1 rounded-ui-sm text-[11px] transition-colors border cursor-pointer ${+ onClick={handleToggleLockRatio}+ className={`flex items-center gap-1 px-2 py-0.5 rounded-ui-sm text-[10px] transition-colors border cursor-pointer ${lockRatio? 'bg-ui-accent-subtle border-ui-accent-border text-ui-accent font-medium': 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'}`}- title={lockRatio ? 'Keep aspect ratio: editing width updates height' : 'Aspect ratio unlocked'}+ title={+ lockRatio+ ? 'Keep aspect ratio locked (Shift also locks while dragging)'+ : 'Aspect ratio free (hold Shift while dragging handles to lock)'+ }>- {lockRatio ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3 text-ui-icon-muted" />}+ {lockRatio ? (+ <Lock className="w-2.5 h-2.5" />+ ) : (+ <Unlock className="w-2.5 h-2.5 text-ui-icon-muted" />+ )}<span>{lockRatio ? 'Keep Aspect Ratio' : 'Ratio Free'}</span></button><buttontype="button"- onClick={handleSwapDimensions}+ onClick={() => updateDraft((prev) => applySwapDimensionsToDraft(prev))}className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"title="Swap Width and Height (Landscape ⇄ Portrait)">- <ArrowLeftRight className="w-3.5 h-3.5" />+ <ArrowLeftRight className="w-3 h-3" /></button></div></div>- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-2 gap-2.5"><div className="space-y-1"><div className="flex items-center justify-between"><label htmlFor={widthInputId} className="text-[11px] text-ui-muted">Width (px)</label>- <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">{percentW}%</span>+ <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">+ {percentW}%+ </span></div>- <input+ <NumericDraftInputid={widthInputId}- type="number"- min="64"- max="16384"+ min={MIN_CANVAS_DIM}+ max={MAX_CANVAS_DIM}value={width}- onChange={(e) => handleWidthChange(Number(e.target.value))}- className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-3 py-1.5 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"+ onCommit={(val) => updateDraft((prev) => applyWidthToDraft(prev, val))}+ className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"/></div>@@ -288,192 +544,263 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({<label htmlFor={heightInputId} className="text-[11px] text-ui-muted">Height (px)</label>- <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">{percentH}%</span>+ <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">+ {percentH}%+ </span></div>- <input+ <NumericDraftInputid={heightInputId}- type="number"- min="64"- max="16384"+ min={MIN_CANVAS_DIM}+ max={MAX_CANVAS_DIM}value={height}- onChange={(e) => handleHeightChange(Number(e.target.value))}- className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-3 py-1.5 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"+ onCommit={(val) => updateDraft((prev) => applyHeightToDraft(prev, val))}+ className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"/></div></div>{/* Quick Ratio Presets */}- <div className="flex items-center gap-2 pt-0.5">- <span className="text-[11px] text-ui-muted whitespace-nowrap">Ratio Presets:</span>- <div className="flex flex-wrap gap-1.5">- {RATIO_PRESETS.map((r) => {- const isActive = Math.abs(width / height - r.x / r.y) < 0.01;- return (+ <div className="flex flex-wrap items-center gap-1 pt-0.5">+ <button+ type="button"+ onClick={() => {+ userToggledLockRef.current = true;+ updateDraft((prev) => applyLockRatioToggleToDraft(prev, false));+ }}+ className={`px-1.5 py-0.5 rounded-ui-sm text-[10px] font-medium transition-colors border cursor-pointer ${+ !lockRatio+ ? 'bg-ui-accent border-transparent text-ui-accent-contrast'+ : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ Free+ </button>+ {RATIO_PRESETS.map((r) => {+ const isActive = lockRatio && Math.abs(width / Math.max(1, height) - r.x / r.y) < 0.015;+ return (+ <button+ key={r.label}+ type="button"+ onClick={() => {+ userToggledLockRef.current = true;+ updateDraft((prev) => applyRatioPresetToDraft(prev, r.x, r.y));+ }}+ className={`px-1.5 py-0.5 rounded-ui-sm text-[10px] font-ui-mono tabular-nums transition-colors border cursor-pointer ${+ isActive+ ? 'bg-ui-accent border-transparent text-ui-accent-contrast font-medium'+ : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ {r.label}+ </button>+ );+ })}+ </div>+ </div>++ {/* Interactive Crop Bounds & Anchor (Canvas Bounds Mode) */}+ {isCropping && (+ <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2.5">+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">+ Crop Frame & Anchor+ </span>+ <span className="text-[10px] text-ui-accent font-medium truncate">+ {anchor ? ANCHOR_LABELS[anchor] : 'Custom Crop'}+ </span>+ </div>++ {/* Crop Offset X / Y */}+ <div className="grid grid-cols-2 gap-2.5">+ <div className="space-y-0.5">+ <label htmlFor={cropXInputId} className="text-[10px] text-ui-muted block">+ Crop X (px)+ </label>+ <NumericDraftInput+ id={cropXInputId}+ min={-MAX_CANVAS_DIM}+ max={MAX_CANVAS_DIM}+ value={cropX}+ onCommit={(val) => updateDraft((prev) => applyCropXToDraft(prev, val))}+ className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"+ />+ </div>+ <div className="space-y-0.5">+ <label htmlFor={cropYInputId} className="text-[10px] text-ui-muted block">+ Crop Y (px)+ </label>+ <NumericDraftInput+ id={cropYInputId}+ min={-MAX_CANVAS_DIM}+ max={MAX_CANVAS_DIM}+ value={cropY}+ onCommit={(val) => updateDraft((prev) => applyCropYToDraft(prev, val))}+ className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"+ />+ </div>+ </div>++ {/* 3x3 Anchor Grid + On-Canvas Crop Shortcuts */}+ <div className="pt-2 border-t border-ui-subtle flex items-center justify-between gap-2">+ <div className="space-y-1.5 min-w-0 flex-1">+ <p className="text-[10px] text-ui-muted leading-snug">+ Drag handles on canvas to crop or expand. Drag inside to move, or drag outside to draw a new crop.+ </p>+ <div className="flex flex-wrap items-center gap-1"><button- key={r.label}type="button"- onClick={() => handleApplyRatioPreset(r.x, r.y)}- className={`px-2 py-0.5 rounded-ui-sm text-[11px] font-ui-mono tabular-nums transition-colors border cursor-pointer ${- isActive- ? 'bg-ui-accent border-transparent text-ui-accent-contrast font-medium'- : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'+ disabled={!modified}+ onClick={() => updateDraft((prev) => applyResetCropToDraft(prev))}+ className={`inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs border text-[10px] transition-colors ${+ modified+ ? 'bg-ui-control hover:bg-ui-control-hover border-ui-subtle text-ui-primary cursor-pointer'+ : 'bg-ui-input border-ui-subtle text-ui-disabled cursor-default opacity-60'}`}+ title="Reset crop box to current canvas dimensions"+ >+ <RotateCcw className="w-3 h-3" />+ <span>Reset</span>+ </button>++ <button+ type="button"+ onClick={() =>+ updateDraft((prev) => ({+ ...prev,+ gridMode: cycleCropGridMode(prev.gridMode),+ }))+ }+ className="inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer"+ title="Cycle crop composition guide grid">- {r.label}+ <Grid3X3 className="w-3 h-3" />+ <span>Grid: {formatGridMode(gridMode)}</span></button>- );- })}++ {selectionBounds && selectionBounds.width >= 1 && selectionBounds.height >= 1 && (+ <button+ type="button"+ onClick={() =>+ updateDraft((prev) => applyFitBoundsToDraft(prev, selectionBounds))+ }+ className="inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs bg-ui-accent-subtle hover:bg-ui-accent-hover border border-ui-accent-border text-[10px] text-ui-accent font-medium transition-colors cursor-pointer"+ title="Snap crop frame to active selection bounds"+ >+ <SquareDashed className="w-3 h-3" />+ <span>Selection</span>+ </button>+ )}+ </div>+ </div>++ <div className="grid grid-cols-3 gap-0.5 bg-ui-panel p-1 rounded-ui-md border border-ui-subtle shrink-0">+ {ANCHOR_GRID.map((item) => {+ const isSelected = anchor === item.id;+ return (+ <button+ key={item.id}+ type="button"+ onClick={() => updateDraft((prev) => applyAnchorToDraft(prev, item.id))}+ className={`w-6 h-6 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${+ isSelected+ ? 'bg-ui-accent text-ui-accent-contrast'+ : 'bg-ui-input text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ title={item.label}+ >+ {item.icon}+ </button>+ );+ })}+ </div></div></div>- </div>+ )}{/* Resolution (DPI) */}- <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-3.5 space-y-2.5">+ <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2"><div className="flex items-center justify-between"><div className="flex items-center gap-1.5">- <Printer className="w-3.5 h-3.5 text-ui-icon-muted" />+ <Printer className="w-3 h-3 text-ui-icon-muted" /><span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">- Resolution (DPI / PPI)+ Resolution (DPI)</span></div>- <span className="font-ui-mono tabular-nums text-[11px] text-ui-accent">- Print: {printDimensionsCm.w} × {printDimensionsCm.h} cm+ <span className="font-ui-mono tabular-nums text-[10px] text-ui-accent">+ {printDimensionsCm.w} × {printDimensionsCm.h} cm</span></div>- <div className="grid grid-cols-3 sm:grid-cols-6 gap-1.5">+ <div className="grid grid-cols-6 gap-1">{DPI_PRESETS.map((p) => {const isSelected = dpi === p.dpi;return (<buttonkey={p.dpi}type="button"- onClick={() => setDpi(p.dpi)}- className={`flex flex-col items-center justify-center py-1.5 px-1 rounded-ui-sm border transition-colors cursor-pointer ${+ onClick={() => updateDraft((prev) => ({ ...prev, dpi: p.dpi }))}+ className={`flex flex-col items-center justify-center py-1 px-0.5 rounded-ui-sm border transition-colors cursor-pointer ${isSelected? 'bg-ui-accent border-transparent text-ui-accent-contrast font-medium': 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'}`}>- <span className="font-ui-mono tabular-nums text-xs font-semibold">{p.dpi}</span>- <span className="text-[9px] opacity-75">{p.desc}</span>+ <span className="font-ui-mono tabular-nums text-[10px] font-semibold">+ {p.dpi}+ </span></button>);})}</div>- <div className="pt-2 border-t border-ui-subtle flex items-center justify-between">- <div className="flex items-center gap-2">- <label htmlFor={dpiInputId} className="text-[11px] text-ui-muted">+ <div className="pt-1.5 border-t border-ui-subtle flex items-center justify-between">+ <div className="flex items-center gap-1.5">+ <label htmlFor={dpiInputId} className="text-[10px] text-ui-muted">Manual DPI:</label>- <input+ <NumericDraftInputid={dpiInputId}- type="number"- min="1"- max="4800"+ min={1}+ max={4800}value={dpi}- onChange={(e) => setDpi(Math.max(1, Math.min(4800, Number(e.target.value) || 1)))}- className="w-20 bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 text-center font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"+ onCommit={(val) =>+ updateDraft((prev) => ({+ ...prev,+ dpi: Math.max(1, Math.min(4800, Math.round(val) || 1)),+ }))+ }+ className="w-16 bg-ui-input border border-ui-default rounded-ui-sm px-2 py-0.5 text-center font-ui-mono tabular-nums text-[11px] text-ui-primary focus:border-ui-focus"/></div>- <span className="text-[11px] text-ui-muted font-ui-mono tabular-nums">Total Pixels: {megapixels} MP</span>- </div>- </div>-- {/* Mode & Anchor Grid */}- <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-3.5 space-y-3">- <span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider block">- Resize Behavior & Anchor- </span>-- {/* Mode Toggle */}- <div className="grid grid-cols-2 gap-2">- <button- type="button"- onClick={() => setScaleContent(false)}- className={`p-2.5 rounded-ui-md border text-left transition-colors cursor-pointer ${- !scaleContent- ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'- : 'bg-ui-panel border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'- }`}- >- <div className="font-medium text-xs text-ui-primary mb-0.5">Canvas Bounds (Anchor)</div>- <p className="text-[10px] text-ui-muted leading-snug">- Expands or crops canvas area around artwork without distorting pixels.- </p>- </button>-- <button- type="button"- onClick={() => setScaleContent(true)}- className={`p-2.5 rounded-ui-md border text-left transition-colors cursor-pointer ${- scaleContent- ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'- : 'bg-ui-panel border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'- }`}- >- <div className="font-medium text-xs text-ui-primary mb-0.5">Scale Content (Resample)</div>- <p className="text-[10px] text-ui-muted leading-snug">- Stretches and scales all layer artwork to match the new dimensions.- </p>- </button>+ <span className="text-[10px] text-ui-muted font-ui-mono tabular-nums">+ {megapixels} MP+ </span></div>-- {/* 3x3 Anchor Grid when Canvas Bounds is active */}- {!scaleContent && (- <div className="pt-2.5 border-t border-ui-subtle flex items-center justify-between">- <div>- <span className="text-xs text-ui-primary font-medium block">Anchor Position</span>- <span className="text-[11px] text-ui-muted">Choose where existing artwork remains</span>- </div>-- <div className="grid grid-cols-3 gap-1 bg-ui-panel p-1.5 rounded-ui-md border border-ui-subtle">- {ANCHOR_GRID.map((item) => {- const isSelected = anchor === item.id;- return (- <button- key={item.id}- type="button"- onClick={() => setAnchor(item.id)}- className={`w-7 h-7 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${- isSelected- ? 'bg-ui-accent text-ui-accent-contrast'- : 'bg-ui-input text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'- }`}- title={item.label}- >- {item.icon}- </button>- );- })}- </div>- </div>- )}</div></div>{/* Footer */}- <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-between shrink-0">- <span className="text-[11px] text-ui-muted hidden sm:block">- Ratio: <span className="font-ui-mono tabular-nums text-ui-primary">{simplifiedRatio}</span>+ <div className="px-3 py-2 bg-ui-header border-t border-ui-subtle flex items-center justify-between shrink-0 gap-2">+ <span className="text-[10px] text-ui-muted truncate">+ Ratio:{' '}+ <span className="font-ui-mono tabular-nums text-ui-primary">{simplifiedRatio}</span></span>- <div className="flex items-center gap-2 ml-auto">+ <div className="flex items-center gap-1.5 shrink-0"><buttontype="button"onClick={onClose}- className="px-3.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-xs font-medium text-ui-primary transition-colors cursor-pointer"+ className="px-3 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[11px] font-medium text-ui-primary transition-colors cursor-pointer">Cancel</button><buttontype="button"onClick={handleApplyResize}- className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-xs font-medium transition-opacity cursor-pointer"+ className="inline-flex items-center gap-1 px-3 py-1 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer"><Check className="w-3.5 h-3.5" />- <span>Resize Canvas</span>+ <span>{applyButtonLabel}</span></button></div></div>diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsxindex 92fd8ed..414790d 100644--- a/src/components/RightSidebar.tsx+++ b/src/components/RightSidebar.tsx@@ -1,4 +1,4 @@-import React, { useState, useRef, useEffect } from 'react';+import React, { useState, useRef, useEffect, useMemo } from 'react';import {Eye,EyeOff,@@ -24,9 +24,15 @@ import {Shield,Layers,Scaling,+ Search,+ Filter,+ Tag,+ X,+ Ban,} from 'lucide-react';import {HistoryItemMeta,+ LayerColorLabel,LayerItem,BlendMode,ToolType,@@ -37,6 +43,14 @@ import {} from '../types/editor';import { HalftoneDotShape } from '../utils/screentoneEngine';import { BLEND_MODES } from '../utils/canvasUtils';+import {+ DEFAULT_LAYER_FILTER_CRITERIA,+ LAYER_COLOR_LABEL_PRESETS,+ LayerFilterCriteria,+ LayerKindFilter,+ filterLayerTree,+ getLayerColorLabelPreset,+} from '../utils/layerOrganization';import { ColorPanel } from './ColorPanel';import { useToolStore, toolStoreActions, useUiStore } from '../stores';import type { LayerThumbSize } from '../types/appearance';@@ -143,6 +157,10 @@ export interface RightSidebarProps {onDuplicateLayer: (id: string) => void;onDeleteLayer: (id: string) => void;onToggleVisibility: (id: string) => void;+ soloLayerId?: string | null;+ onSoloLayer?: (id: string) => void;+ onExitSoloLayer?: () => void;+ onSetLayerColorLabel?: (id: string, colorLabel: LayerColorLabel) => void;onSetOpacity: (id: string, opacity: number) => void;onSetBlendMode: (id: string, blendMode: BlendMode) => void;onToggleLock: (id: string) => void;@@ -308,6 +326,10 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({onDuplicateLayer,onDeleteLayer,onToggleVisibility,+ soloLayerId = null,+ onSoloLayer,+ onExitSoloLayer,+ onSetLayerColorLabel,onSetOpacity,onSetBlendMode,onToggleLock,@@ -372,9 +394,35 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({const [isExpressionAccordionOpen, setIsExpressionAccordionOpen] = useState(false);const [isEffectsAccordionOpen, setIsEffectsAccordionOpen] = useState(false);+ // Layer Organization: Search/Filter state + active-layer color label popover+ const [layerFilter, setLayerFilter] = useState<LayerFilterCriteria>(+ DEFAULT_LAYER_FILTER_CRITERIA+ );+ const [isFilterStripOpen, setIsFilterStripOpen] = useState(false);+ const [isColorLabelPickerOpen, setIsColorLabelPickerOpen] = useState(false);+ const colorLabelPickerRef = useRef<HTMLDivElement>(null);+const [contextMenu, setContextMenu] = useState<{ layerId: string; x: number; y: number } | null>(null);const contextMenuRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!isColorLabelPickerOpen) return;+ const handleOutside = (e: MouseEvent) => {+ if (colorLabelPickerRef.current && !colorLabelPickerRef.current.contains(e.target as Node)) {+ setIsColorLabelPickerOpen(false);+ }+ };+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') setIsColorLabelPickerOpen(false);+ };+ window.addEventListener('pointerdown', handleOutside);+ window.addEventListener('keydown', handleKey);+ return () => {+ window.removeEventListener('pointerdown', handleOutside);+ window.removeEventListener('keydown', handleKey);+ };+ }, [isColorLabelPickerOpen]);+useEffect(() => {if (!contextMenu) return;const handleOutsideClick = (e: MouseEvent) => {@@ -420,6 +468,16 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({const thumbMetrics = LAYER_THUMB_METRICS[layerThumbSize] ?? LAYER_THUMB_METRICS.standard;const activeLayer = hasOpenDocument ? layers.find((l) => l.id === activeLayerId) || layers[0] : undefined;+ const activeLayerColorPreset = getLayerColorLabelPreset(activeLayer?.colorLabel);+ const soloedLayer = useMemo(+ () => (soloLayerId ? layers.find((l) => l.id === soloLayerId) ?? null : null),+ [layers, soloLayerId]+ );+ const filterResult = useMemo(() => filterLayerTree(layers, layerFilter), [layers, layerFilter]);+ const hasSecondaryFilter = layerFilter.colorLabel !== 'all' || layerFilter.kind !== 'all';+ const resetLayerFilter = () => {+ setLayerFilter(DEFAULT_LAYER_FILTER_CRITERIA);+ };const activeLayerHasMask = Boolean(activeLayer &&(activeLayer.maskCanvas ||@@ -479,7 +537,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({}, []);const handleLayerPointerDown = (e: React.PointerEvent<HTMLDivElement>, layerId: string) => {- if (e.button !== 0 || editingLayerId !== null) return;+ if (e.button !== 0 || editingLayerId !== null || filterResult.isActive) return;const target = e.target as HTMLElement | null;if (target?.closest('button, input, select, textarea, [data-no-drag]')) return;@@ -669,7 +727,11 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({<div className="h-7 px-1.5 flex items-center justify-between shrink-0 border-b border-ui-subtle bg-ui-header">{isDockedSingle ? (<span className="text-[10px] uppercase tracking-[0.06em] text-ui-muted font-medium tabular-nums px-1">- {effectiveTab === 'layers' ? `${layers.length} Layers` : `${historyList.length} Steps`}+ {effectiveTab === 'layers'+ ? filterResult.isActive+ ? `${filterResult.matchCount}/${layers.length} Layers`+ : `${layers.length} Layers`+ : `${historyList.length} Steps`}</span>) : (<HairlineTabs<'layers' | 'history'>@@ -687,7 +749,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({{effectiveTab === 'layers' && hasOpenDocument && !isDockedSingle && (<span className="text-[9.5px] font-ui-mono tabular-nums text-ui-muted px-1">- {layers.length}+ {filterResult.isActive ? `${filterResult.matchCount}/${layers.length}` : layers.length}</span>)}@@ -841,6 +903,71 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({title="Reference Layer"icon={<Compass className="w-3 h-3" />}/>+ {onSetLayerColorLabel && (+ <div ref={colorLabelPickerRef} className="relative">+ <IconButton+ size="xs"+ data-testid="active-layer-color-label-btn"+ active={Boolean(activeLayerColorPreset) || isColorLabelPickerOpen}+ onClick={() => setIsColorLabelPickerOpen((p) => !p)}+ title={+ activeLayerColorPreset+ ? `Layer Color Label: ${activeLayerColorPreset.name}`+ : 'Set Layer Color Label'+ }+ icon={+ activeLayerColorPreset ? (+ <span+ className="w-2.5 h-2.5 rounded-full border border-white/40 shrink-0"+ style={{ backgroundColor: activeLayerColorPreset.swatchHex }}+ />+ ) : (+ <Tag className="w-3 h-3" />+ )+ }+ />+ {isColorLabelPickerOpen && (+ <div+ data-testid="active-layer-color-label-popover"+ className="absolute left-0 top-6 z-40 p-1.5 rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover flex items-center gap-1"+ >+ {LAYER_COLOR_LABEL_PRESETS.map((preset) => {+ const currentLabel: LayerColorLabel =+ activeLayer.colorLabel && activeLayer.colorLabel !== 'none'+ ? activeLayer.colorLabel+ : 'none';+ const isPicked = currentLabel === preset.id;+ return (+ <button+ key={preset.id}+ type="button"+ data-testid={`active-color-label-option-${preset.id}`}+ onClick={() => {+ onSetLayerColorLabel(activeLayer.id, preset.id);+ setIsColorLabelPickerOpen(false);+ }}+ title={preset.name}+ className={`w-4 h-4 rounded-full flex items-center justify-center transition-transform hover:scale-110 cursor-pointer ${+ isPicked+ ? 'ring-2 ring-ui-accent ring-offset-1 ring-offset-[var(--ui-bg-elevated)]'+ : 'border border-ui-default'+ }`}+ style={+ preset.id !== 'none'+ ? { backgroundColor: preset.swatchHex }+ : undefined+ }+ >+ {preset.id === 'none' && (+ <Ban className="w-2.5 h-2.5 text-ui-muted" />+ )}+ </button>+ );+ })}+ </div>+ )}+ </div>+ )}{isCollabActive && onToggleOwnerLock && activeLayer.id !== 'layer-bg' && (<IconButtonsize="xs"@@ -897,15 +1024,229 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({</div>)}+ {/* Layer Search & Filter Organization Bar */}+ <div+ data-testid="layers-search-bar"+ className="shrink-0 px-1.5 py-1 border-b border-ui-subtle bg-ui-panel space-y-1"+ >+ <div className="flex items-center gap-1">+ <div className="relative flex-1 min-w-0 flex items-center">+ <Search className="w-3 h-3 text-ui-muted absolute left-1.5 pointer-events-none" />+ <input+ type="text"+ data-testid="layer-search-input"+ value={layerFilter.query}+ onChange={(e) =>+ setLayerFilter((prev) => ({ ...prev, query: e.target.value }))+ }+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === 'Escape') {+ setLayerFilter((prev) => ({ ...prev, query: '' }));+ e.currentTarget.blur();+ }+ }}+ placeholder="Search layers..."+ aria-label="Search layers"+ autoComplete="off"+ spellCheck={false}+ className="w-full h-5 pl-5 pr-4 rounded-ui-xs bg-ui-input border border-ui-subtle focus:border-ui-focus focus:outline-none text-[10.5px] text-ui-primary placeholder:text-ui-muted"+ />+ {layerFilter.query && (+ <button+ type="button"+ data-testid="layer-search-clear"+ onClick={() => setLayerFilter((prev) => ({ ...prev, query: '' }))}+ title="Clear search"+ className="absolute right-1 text-ui-muted hover:text-ui-primary cursor-pointer"+ >+ <X className="w-2.5 h-2.5" />+ </button>+ )}+ </div>++ <button+ type="button"+ data-testid="layer-filter-toggle"+ aria-pressed={isFilterStripOpen || hasSecondaryFilter}+ onClick={() => setIsFilterStripOpen((p) => !p)}+ title="Filter layers by color label or type"+ className={`relative h-5 w-5 rounded-ui-xs border flex items-center justify-center shrink-0 transition-colors cursor-pointer ${+ isFilterStripOpen || hasSecondaryFilter+ ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'+ : 'bg-ui-input text-ui-icon-muted hover:text-ui-primary border-ui-subtle hover:bg-ui-control-hover'+ }`}+ >+ <Filter className="w-3 h-3" />+ {hasSecondaryFilter && (+ <span className="absolute -top-0.5 -right-0.5 w-1.5 h-1.5 rounded-full bg-ui-accent" />+ )}+ </button>+ </div>++ {/* Collapsible Color Label & Kind Filter Strip */}+ {(isFilterStripOpen || hasSecondaryFilter) && (+ <div data-testid="layer-filter-strip" className="space-y-1 pt-0.5">+ <div className="flex items-center justify-between gap-0.5 flex-wrap">+ <button+ type="button"+ data-testid="layer-filter-color-all"+ aria-pressed={layerFilter.colorLabel === 'all'}+ onClick={() =>+ setLayerFilter((prev) => ({ ...prev, colorLabel: 'all' }))+ }+ title="All Color Labels"+ className={`h-4 px-1 rounded-ui-xs text-[9px] cursor-pointer transition-colors ${+ layerFilter.colorLabel === 'all'+ ? 'bg-ui-accent-subtle text-ui-accent font-medium'+ : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ All+ </button>+ {LAYER_COLOR_LABEL_PRESETS.filter((p) => p.id !== 'none').map((preset) => {+ const isSelectedColor = layerFilter.colorLabel === preset.id;+ return (+ <button+ key={preset.id}+ type="button"+ data-testid={`layer-filter-color-${preset.id}`}+ aria-pressed={isSelectedColor}+ onClick={() =>+ setLayerFilter((prev) => ({+ ...prev,+ colorLabel: prev.colorLabel === preset.id ? 'all' : preset.id,+ }))+ }+ title={`Filter: ${preset.name}`}+ className={`w-3.5 h-3.5 rounded-full transition-transform hover:scale-110 cursor-pointer ${+ isSelectedColor+ ? 'ring-2 ring-ui-accent ring-offset-1 ring-offset-[var(--ui-bg-panel)] scale-110'+ : 'opacity-80 hover:opacity-100'+ }`}+ style={{ backgroundColor: preset.swatchHex }}+ />+ );+ })}+ <button+ type="button"+ data-testid="layer-filter-color-none"+ aria-pressed={layerFilter.colorLabel === 'none'}+ onClick={() =>+ setLayerFilter((prev) => ({+ ...prev,+ colorLabel: prev.colorLabel === 'none' ? 'all' : 'none',+ }))+ }+ title="Filter: Unlabeled Layers"+ className={`w-3.5 h-3.5 rounded-full border flex items-center justify-center cursor-pointer transition-colors ${+ layerFilter.colorLabel === 'none'+ ? 'border-ui-accent bg-ui-accent-subtle text-ui-accent'+ : 'border-ui-default text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Ban className="w-2 h-2" />+ </button>+ </div>++ <div className="flex items-center gap-1">+ <select+ data-testid="layer-kind-filter"+ aria-label="Filter by layer type"+ value={layerFilter.kind}+ onChange={(e) =>+ setLayerFilter((prev) => ({+ ...prev,+ kind: e.target.value as LayerKindFilter,+ }))+ }+ className="flex-1 min-w-0 h-5 px-1 rounded-ui-xs bg-ui-input border border-ui-subtle text-[10px] text-ui-primary cursor-pointer"+ >+ <option value="all" className="bg-ui-elevated text-ui-primary">All Kinds</option>+ <option value="raster" className="bg-ui-elevated text-ui-primary">Raster Layers</option>+ <option value="folder" className="bg-ui-elevated text-ui-primary">Folders</option>+ <option value="text" className="bg-ui-elevated text-ui-primary">Text / Balloons</option>+ <option value="adjustment" className="bg-ui-elevated text-ui-primary">Adjustments</option>+ <option value="tone" className="bg-ui-elevated text-ui-primary">Screentone</option>+ <option value="masked" className="bg-ui-elevated text-ui-primary">Masked</option>+ <option value="reference" className="bg-ui-elevated text-ui-primary">Reference</option>+ <option value="locked" className="bg-ui-elevated text-ui-primary">Locked</option>+ <option value="hidden" className="bg-ui-elevated text-ui-primary">Hidden</option>+ </select>+ {filterResult.isActive && (+ <button+ type="button"+ data-testid="layer-filter-reset"+ onClick={resetLayerFilter}+ className="h-5 px-1.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[9.5px] text-ui-secondary hover:text-ui-primary shrink-0 cursor-pointer transition-colors"+ >+ Reset+ </button>+ )}+ </div>+ </div>+ )}+ </div>++ {/* Solo / Isolate Layer Active Banner */}+ {soloedLayer && (+ <div+ data-testid="layer-solo-banner"+ className="shrink-0 px-2 py-1 border-b border-ui-warning/30 bg-ui-warning/10 flex items-center justify-between gap-1.5 text-[10px]"+ >+ <div className="flex items-center gap-1 min-w-0 text-ui-warning">+ <Eye className="w-3 h-3 shrink-0" />+ <span className="truncate font-medium" title={`Isolated: ${soloedLayer.name}`}>+ Solo: {soloedLayer.name}+ </span>+ </div>+ <button+ type="button"+ data-testid="layer-solo-restore-btn"+ onClick={() => {+ if (onExitSoloLayer) onExitSoloLayer();+ else onSoloLayer?.(soloedLayer.id);+ }}+ className="px-1.5 py-0.5 rounded-ui-xs bg-ui-warning/20 hover:bg-ui-warning/30 text-ui-warning font-medium shrink-0 cursor-pointer transition-colors"+ >+ Restore+ </button>+ </div>+ )}+{/* Spacious Scrollable Layer Stack */}<divref={layerListContainerRef}data-testid="layers-scroll-stack"className="flex-1 overflow-y-auto px-1.5 py-1 space-y-0.5 min-h-0">+ {filterResult.isActive && filterResult.matchCount === 0 && (+ <div+ data-testid="layers-filter-empty"+ className="py-6 px-3 text-center flex flex-col items-center gap-1.5 text-ui-muted"+ >+ <span className="text-[10.5px]">No layers match filter</span>+ <button+ type="button"+ onClick={resetLayerFilter}+ className="px-2 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer transition-colors"+ >+ Clear filter+ </button>+ </div>+ )}{layers.map((layer) => {const { depth, hiddenByAncestor } = getLayerTreeInfo(layer);- if (hiddenByAncestor) return null;+ if (filterResult.isActive) {+ if (!filterResult.visibleLayerIds.has(layer.id)) return null;+ } else if (hiddenByAncestor) {+ return null;+ }++ const isAncestorContextOnly =+ filterResult.isActive && filterResult.ancestorOnlyIds.has(layer.id);+ const isSoloed = soloLayerId === layer.id;+ const colorLabelPreset = getLayerColorLabelPreset(layer.colorLabel);const isActive = layer.id === activeLayerId;const isSelected = selectedLayerIds ? selectedLayerIds.includes(layer.id) : isActive;@@ -961,6 +1302,13 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({data-layer-folder={isFolder ? 'true' : 'false'}data-layer-depth={depth}data-layer-active={isActive ? 'true' : 'false'}+ data-layer-color-label={layer.colorLabel || 'none'}+ data-layer-solo={isSoloed ? 'true' : undefined}+ style={+ colorLabelPreset && !isSelected && !isDropInside+ ? { backgroundColor: colorLabelPreset.rowTint }+ : undefined+ }onPointerDown={(e) => handleLayerPointerDown(e, layer.id)}onClick={(e) => {if (justDraggedRef.current) return;@@ -1002,7 +1350,9 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({? 'bg-ui-accent-subtle text-ui-primary border-ui-accent-border/40': 'bg-ui-accent-subtle/55 text-ui-primary border-transparent': 'border-transparent text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'- } ${isBeingDragged ? 'opacity-40 cursor-grabbing' : 'cursor-grab'}`}+ } ${isBeingDragged ? 'opacity-40 cursor-grabbing' : filterResult.isActive ? 'cursor-pointer' : 'cursor-grab'} ${+ isAncestorContextOnly ? 'opacity-65' : ''+ }`}>{/* Crisp 2px Leading Accent Bar on Selected Rows */}{isSelected && (@@ -1021,23 +1371,47 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({<div className="absolute -bottom-0.5 left-0 right-0 h-[2px] rounded-full z-30 pointer-events-none bg-ui-accent" />)}- {/* Fixed Left-Aligned Visibility Eye Rail */}+ {/* Fixed Left-Aligned Visibility Eye Rail (Alt+Click = Solo/Isolate Layer) */}<buttontype="button"+ data-testid={`layer-eye-${layer.id}`}+ data-solo-active={isSoloed ? 'true' : undefined}onClick={(e) => {e.stopPropagation();- onToggleVisibility(layer.id);+ if (e.altKey && onSoloLayer) {+ onSoloLayer(layer.id);+ } else {+ onToggleVisibility(layer.id);+ }}}- title={layer.visible ? 'Hide Layer' : 'Show Layer'}+ title={+ isSoloed+ ? 'Soloed — Alt+Click to Restore All'+ : layer.visible+ ? 'Hide Layer (Alt+Click to Solo)'+ : 'Show Layer (Alt+Click to Solo)'+ }className={`p-0.5 rounded-ui-xs transition-colors shrink-0 cursor-pointer ${- layer.visible- ? 'text-ui-icon-muted hover:text-ui-primary'- : 'text-ui-disabled hover:text-ui-muted'+ isSoloed+ ? 'text-ui-warning bg-ui-warning/15 ring-1 ring-ui-warning/60'+ : layer.visible+ ? 'text-ui-icon-muted hover:text-ui-primary'+ : 'text-ui-disabled hover:text-ui-muted'}`}>{layer.visible ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}</button>+ {/* Layer Color Label Pill Indicator */}+ {colorLabelPreset && (+ <span+ data-testid={`layer-color-tag-${layer.id}`}+ title={`Color Label: ${colorLabelPreset.name}`}+ className="w-[3.5px] h-3.5 rounded-full shrink-0 -ml-0.5"+ style={{ backgroundColor: colorLabelPreset.swatchHex }}+ />+ )}+{/* Nested Folder Vertical Tree Guide Hairlines */}{depth > 0 && (<div@@ -1717,6 +2091,64 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({<div className="px-2.5 py-1 text-[10px] text-ui-muted truncate">{targetLayer.name}</div>++ {/* Layer Color Label Quick Picker */}+ {onSetLayerColorLabel && (+ <div+ data-testid="context-menu-color-labels"+ className="px-2 py-1 flex items-center gap-1"+ >+ {LAYER_COLOR_LABEL_PRESETS.map((preset) => {+ const currentLabel: LayerColorLabel =+ targetLayer.colorLabel && targetLayer.colorLabel !== 'none'+ ? targetLayer.colorLabel+ : 'none';+ const isPicked = currentLabel === preset.id;+ return (+ <button+ key={preset.id}+ type="button"+ data-testid={`context-color-label-${preset.id}`}+ onClick={() => {+ onSetLayerColorLabel(targetLayer.id, preset.id);+ setContextMenu(null);+ }}+ title={`Color Label: ${preset.name}`}+ className={`w-3.5 h-3.5 rounded-full flex items-center justify-center transition-transform hover:scale-110 cursor-pointer ${+ isPicked+ ? 'ring-2 ring-ui-accent ring-offset-1 ring-offset-[var(--ui-bg-elevated)]'+ : 'border border-ui-default'+ }`}+ style={+ preset.id !== 'none'+ ? { backgroundColor: preset.swatchHex }+ : undefined+ }+ >+ {preset.id === 'none' && <Ban className="w-2 h-2 text-ui-muted" />}+ </button>+ );+ })}+ </div>+ )}++ {onSoloLayer && (+ <button+ type="button"+ data-testid="context-menu-solo-btn"+ onClick={() => {+ onSoloLayer(targetLayer.id);+ setContextMenu(null);+ }}+ className="w-full text-left px-2.5 py-1 rounded-ui-xs hover:bg-ui-control-hover flex items-center justify-between cursor-pointer"+ >+ <span>+ {soloLayerId === targetLayer.id ? 'Exit Solo Mode' : 'Solo / Isolate Layer'}+ </span>+ <span className="text-[9px] text-ui-muted font-ui-mono">Alt+Eye</span>+ </button>+ )}+<div className="my-0.5 border-t border-ui-subtle" />{targetLayer.type !== 'folder' && (diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsxindex 23298a9..460208a 100644--- a/src/components/SubToolList.tsx+++ b/src/components/SubToolList.tsx@@ -243,6 +243,7 @@ function renderGroupIcon(icon: SubToolGroupIconId | undefined, color?: string |function shortBuiltinTabLabel(id: BrushCategory, fallback: string): string {if (id === 'natural-paint') return 'Natural';+ if (id === 'texture-fx') return 'FX';return fallback;}@@ -523,6 +524,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(brush: [],blend: [],'natural-paint': [],+ 'texture-fx': [],'deco-background': [],'deco-clothing': [],'deco-effect': [],@@ -671,7 +673,10 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(try {const liveSettings = useToolStore.getState().brushSettings;const brush = buildExportableBrush(presetId, customBrushes, liveSettings);- await exportBrushToInkbFile(brush);+ const res = await exportBrushToInkbFile(brush);+ if (res.exported) {+ uiStoreActions.showToast(`Saved brush "${res.fileName}"`);+ }} catch (err: unknown) {const msg = err instanceof Error ? err.message : 'Failed to export brush.';void uiStoreActions.alertDialog({diff --git a/src/components/SubViewPanel.tsx b/src/components/SubViewPanel.tsxindex 3ad0a7b..bedefc3 100644--- a/src/components/SubViewPanel.tsx+++ b/src/components/SubViewPanel.tsx@@ -10,17 +10,38 @@ import {RotateCcw,RotateCw,FlipHorizontal,+ FlipVertical,Pipette,Hand,List,ImagePlus,RefreshCw,+ LayoutGrid,+ Square,+ Contrast,+ Columns2,+ Grid3x3,+ SlidersHorizontal,+ Palette,+ ClipboardPaste,+ MousePointer2,+ Lock,+ Unlock,+ Copy,+ BringToFront,+ SendToBack,+ Focus,+ X,+ Rows3,+ Columns3,+ Sparkles,} from 'lucide-react';import { CanvasColorMode } from '../types/editor';import { ThemePreset } from '../types/settings';import {SUB_VIEW_MAX_ZOOM,SUB_VIEW_MIN_ZOOM,+ SubViewBoardLayoutMode,SubViewImageItem,SubViewTransform,hydrateSubViewImages,@@ -28,48 +49,53 @@ import {useSubViewStore,} from '../stores/useSubViewStore';import { toolStoreActions } from '../stores/useToolStore';+import {+ CardHandleKind,+ ExtractedSwatch,+ PixelCoord,+ SubViewGridMode,+ SubViewStudyFilter,+ SubViewValueSteps,+ boardPointToStagePoint,+ buildFilteredReferenceCanvas,+ clampBoardCardScale,+ clampSubViewZoom,+ computeBoardFitTransform,+ computeSubViewFitZoom,+ drawProportionalGrid,+ extractDominantColorsFromCanvas,+ getCardStageOverlay,+ getStudyFilterSignature,+ hitTestBoardCards,+ hitTestCardHandle,+ isStudyFilterVisualActive,+ stageDeltaToBoardDelta,+ stagePointToBoardPoint,+ subViewPointToImagePixel,+} from '../utils/subViewEngine';+import { clampNavigatorSplitRatio, computePerceptualLuminanceByte } from '../utils/valueCheck';++export type { PixelCoord };+export { subViewPointToImagePixel, computeSubViewFitZoom };const DND_PANEL_MIME = 'application/x-inkstudio-panel';const VALID_IMAGE_EXT_RE = /\.(png|jpe?g|webp|gif|bmp|avif|ico|svg)$/i;-export interface PixelCoord {- x: number;- y: number;-}--/**- * Inverse-maps a point `(localX, localY)` inside the Sub View stage into- * integer source image pixel coordinates `(x, y)` accounting for pan, zoom, rotation, and flipX.- * Returns `null` if the point lies outside the image bounds.- */-export function subViewPointToImagePixel(- localX: number,- localY: number,- stageW: number,- stageH: number,- imgW: number,- imgH: number,- transform: SubViewTransform-): PixelCoord | null {- if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return null;- const safeZoom = Math.max(1e-4, transform.zoom);- const dx = localX - (stageW / 2 + transform.pan.x);- const dy = localY - (stageH / 2 + transform.pan.y);-- const rad = (transform.rotation * Math.PI) / 180;- const cos = Math.cos(rad);- const sin = Math.sin(rad);-- const unrotX = dx * cos + dy * sin;- const unrotY = -dx * sin + dy * cos;- const fx = transform.flipX ? -1 : 1;-- const px = Math.floor(imgW / 2 + (fx * unrotX) / safeZoom);- const py = Math.floor(imgH / 2 + unrotY / safeZoom);-- if (px < 0 || py < 0 || px >= imgW || py >= imgH) return null;- return { x: px, y: py };-}+const GRID_MODE_LABELS: Record<SubViewGridMode, string> = {+ none: 'Off',+ thirds: '3×3',+ grid4: '4×4',+ grid8: '8×8',+ golden: 'φ',+ crosshair: '+',+};++const VALUE_STEP_LABELS: Record<SubViewValueSteps, string> = {+ 0: 'Val',+ 2: '2V',+ 3: '3V',+ 5: '5V',+};/*** Safely samples a `#rrggbb` hex color at `(px, py)` from an owned offscreen 2D canvas.@@ -99,18 +125,13 @@ export function samplePixelHexFromCanvas(}}-export function computeSubViewFitZoom(- stageW: number,- stageH: number,- imgW: number,- imgH: number,- padding = 12-): number {- if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return 1;- const availW = Math.max(16, stageW - padding * 2);- const availH = Math.max(16, stageH - padding * 2);- const fit = Math.min(availW / imgW, availH / imgH);- return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, fit));+function hexToPerceptualValuePercent(hex: string): number | null {+ const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);+ if (!m) return null;+ const r = parseInt(m[1], 16);+ const g = parseInt(m[2], 16);+ const b = parseInt(m[3], 16);+ return Math.round((computePerceptualLuminanceByte(r, g, b) / 255) * 100);}function isImageFile(file: File): boolean {@@ -118,7 +139,9 @@ function isImageFile(file: File): boolean {return VALID_IMAGE_EXT_RE.test(file.name);}-function readLocalImageFile(file: File): Promise<{ name: string; src: string; width: number; height: number }> {+function readLocalImageFile(+ file: File+): Promise<{ name: string; src: string; width: number; height: number }> {return new Promise((resolve, reject) => {const reader = new FileReader();reader.onerror = () => reject(new Error(`Failed to read ${file.name}`));@@ -144,32 +167,108 @@ function readLocalImageFile(file: File): Promise<{ name: string; src: string; wi});}+function drawBoardBackgroundDots(+ ctx: CanvasRenderingContext2D,+ sw: number,+ sh: number,+ t: SubViewTransform+): void {+ // Subtle PureRef-style spatial dot grid that moves/scales/rotates with the board camera+ const baseSpacing = 40;+ let step = baseSpacing;+ while (step * t.zoom < 18) step *= 2;+ while (step * t.zoom > 72) step /= 2;++ const corners = [+ stagePointToBoardPoint(0, 0, sw, sh, t),+ stagePointToBoardPoint(sw, 0, sw, sh, t),+ stagePointToBoardPoint(sw, sh, sw, sh, t),+ stagePointToBoardPoint(0, sh, sw, sh, t),+ ];+ let minX = Infinity;+ let maxX = -Infinity;+ let minY = Infinity;+ let maxY = -Infinity;+ for (const c of corners) {+ if (c.x < minX) minX = c.x;+ if (c.x > maxX) maxX = c.x;+ if (c.y < minY) minY = c.y;+ if (c.y > maxY) maxY = c.y;+ }++ const startX = Math.floor(minX / step) * step;+ const startY = Math.floor(minY / step) * step;+ const maxDots = 2400;+ const cols = Math.ceil((maxX - startX) / step) + 1;+ const rows = Math.ceil((maxY - startY) / step) + 1;+ if (cols * rows > maxDots) return;++ ctx.save();+ ctx.fillStyle = 'rgba(255, 255, 255, 0.11)';+ for (let y = startY; y <= maxY; y += step) {+ for (let x = startX; x <= maxX; x += step) {+ const p = boardPointToStagePoint(x, y, sw, sh, t);+ ctx.fillRect(p.x - 0.75, p.y - 0.75, 1.5, 1.5);+ }+ }+ ctx.restore();+}+export interface SubViewPanelProps {colorMode?: CanvasColorMode;themePreset?: ThemePreset;}+interface FilteredCacheEntry {+ sig: string;+ srcCanvas: HTMLCanvasElement;+ filteredCanvas: HTMLCanvasElement;+}++type LiveCardPatch = {+ id: string;+ boardX: number;+ boardY: number;+ boardScale: number;+ boardRotation: number;+};+export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(({ colorMode = 'color', themePreset = 'modern' }) => {-const items = useSubViewStore((s) => s.items);const activeId = useSubViewStore((s) => s.activeId);+ const viewMode = useSubViewStore((s) => s.viewMode);+ const boardTool = useSubViewStore((s) => s.boardTool);+ const boardTransform = useSubViewStore((s) => s.boardTransform);+ const boardNeedsInitialFit = useSubViewStore((s) => s.boardNeedsInitialFit);+ const studyFilter = useSubViewStore((s) => s.studyFilter);+ const sampleDisplayTone = useSubViewStore((s) => s.sampleDisplayTone);const autoEyedropper = useSubViewStore((s) => s.autoEyedropper);const manualEyedropper = useSubViewStore((s) => s.manualEyedropper);const showList = useSubViewStore((s) => s.showList);+ const showPalette = useSubViewStore((s) => s.showPalette);const activeIndex = useMemo(() => Math.max(0, items.findIndex((i) => i.id === activeId)),[items, activeId]);- const activeItem: SubViewImageItem | null = items.length > 0 ? items[activeIndex] ?? items[0] : null;+ const activeItem: SubViewImageItem | null =+ items.length > 0 ? items[activeIndex] ?? items[0] : null;+ const panelRef = useRef<HTMLDivElement | null>(null);const stageRef = useRef<HTMLDivElement | null>(null);const displayCanvasRef = useRef<HTMLCanvasElement | null>(null);- const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);const reloadInputRef = useRef<HTMLInputElement | null>(null);+ // Owned offscreen decoded canvases keyed by item.id+ const sourceCanvasMapRef = useRef<Map<string, { src: string; canvas: HTMLCanvasElement }>>(+ new Map()+ );+ // Filtered canvas cache keyed by item.id (and separate split-bw B/W cache)+ const filteredCacheRef = useRef<Map<string, FilteredCacheEntry>>(new Map());+ const splitBwCacheRef = useRef<Map<string, FilteredCacheEntry>>(new Map());+const [stageSize, setStageSize] = useState<{ width: number; height: number }>({width: 200,height: 140,@@ -181,22 +280,44 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(const [isAltHeld, setIsAltHeld] = useState(false);const [sampledHex, setSampledHex] = useState<string | null>(null);const [loadError, setLoadError] = useState<string | null>(null);-- // Live mutable transform during drag/pan/wheel so Sub View stays silky-smooth- const liveTransformRef = useRef<SubViewTransform>({+ const [showTonePopover, setShowTonePopover] = useState(false);+ const [showArrangeMenu, setShowArrangeMenu] = useState(false);+ const [isDraggingSplit, setIsDraggingSplit] = useState(false);+ const [extractedSwatches, setExtractedSwatches] = useState<ExtractedSwatch[]>([]);+ const [activeInteractionKind, setActiveInteractionKind] = useState<+ 'none' | 'pan' | 'eyedrop' | 'card-move' | 'card-resize' | 'card-rotate'+ >('none');++ // Live mutable transforms during drags/wheel for zero-lag 60fps interaction+ const liveSingleTransformRef = useRef<SubViewTransform>({+ zoom: 1,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+ });+ const liveBoardTransformRef = useRef<SubViewTransform>({zoom: 1,pan: { x: 0, y: 0 },rotation: 0,flipX: false,});+ const liveCardPatchRef = useRef<LiveCardPatch | null>(null);const interactionRef = useRef<{- mode: 'none' | 'pan' | 'eyedrop';+ mode: 'none' | 'pan' | 'eyedrop' | 'card-move' | 'card-resize' | 'card-rotate';pointerId: number | null;startClientX: number;startClientY: number;startPanX: number;startPanY: number;+ cardId: string | null;+ startCardX: number;+ startCardY: number;+ startCardScale: number;+ startCardRotation: number;+ startCardDist: number;+ startCardAngle: number;+ handleKind: CardHandleKind | null;}>({mode: 'none',pointerId: null,@@ -204,23 +325,52 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(startClientY: 0,startPanX: 0,startPanY: 0,+ cardId: null,+ startCardX: 0,+ startCardY: 0,+ startCardScale: 1,+ startCardRotation: 0,+ startCardDist: 1,+ startCardAngle: 0,+ handleKind: null,+ });++ const splitDragRef = useRef<{+ active: boolean;+ pointerId: number | null;+ latestRatio: number;+ }>({+ active: false,+ pointerId: null,+ latestRatio: 0.5,});+ const itemsRef = useRef<SubViewImageItem[]>(items);+ itemsRef.current = items;const activeItemRef = useRef<SubViewImageItem | null>(activeItem);activeItemRef.current = activeItem;-+ const viewModeRef = useRef(viewMode);+ viewModeRef.current = viewMode;+ const boardToolRef = useRef(boardTool);+ boardToolRef.current = boardTool;+ const studyFilterRef = useRef<SubViewStudyFilter>(studyFilter);+ studyFilterRef.current = studyFilter;+ const sampleDisplayToneRef = useRef(sampleDisplayTone);+ sampleDisplayToneRef.current = sampleDisplayTone;const stageSizeRef = useRef(stageSize);stageSizeRef.current = stageSize;+ const isHoveringStageRef = useRef(isHoveringStage);+ isHoveringStageRef.current = isHoveringStage;- // Hydrate Sub View image data URLs from IndexedDB on mount+ // Hydrate image data URLs from IndexedDB on mountuseEffect(() => {void hydrateSubViewImages();}, []);- // Sync live transform ref whenever active item changes+ // Sync live transform refs from storeuseEffect(() => {if (!activeItem) return;- liveTransformRef.current = {+ liveSingleTransformRef.current = {zoom: activeItem.zoom,pan: { x: activeItem.pan.x, y: activeItem.pan.y },rotation: activeItem.rotation,@@ -228,6 +378,15 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(};}, [activeItem]);+ useEffect(() => {+ liveBoardTransformRef.current = {+ zoom: boardTransform.zoom,+ pan: { x: boardTransform.pan.x, y: boardTransform.pan.y },+ rotation: boardTransform.rotation,+ flipX: boardTransform.flipX,+ };+ }, [boardTransform]);+// Track stage dimensions via ResizeObserveruseEffect(() => {const el = stageRef.current;@@ -248,90 +407,196 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(return () => ro?.disconnect();}, []);- // Track Space / Alt while hovering Sub View for quick pan/eyedropper override- useEffect(() => {- if (!isHoveringStage) {- setIsSpaceHeld(false);- setIsAltHeld(false);- return;- }- const onKeyDown = (e: KeyboardEvent) => {- if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(true);- if (e.key === 'Alt') setIsAltHeld(true);- };- const onKeyUp = (e: KeyboardEvent) => {- if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(false);- if (e.key === 'Alt') setIsAltHeld(false);- };- const onBlur = () => {- setIsSpaceHeld(false);- setIsAltHeld(false);- };- window.addEventListener('keydown', onKeyDown);- window.addEventListener('keyup', onKeyUp, true);- window.addEventListener('blur', onBlur);- return () => {- window.removeEventListener('keydown', onKeyDown);- window.removeEventListener('keyup', onKeyUp, true);- window.removeEventListener('blur', onBlur);- };- }, [isHoveringStage]);+ // Decode all reference images into owned offscreen 2D canvases for CORS-safe sampling & fast board rendering+ const itemsSrcKey = useMemo(+ () => items.map((i) => `${i.id}:${i.src ? i.src.length : 0}:${i.width}x${i.height}`).join('|'),+ [items]+ );- // Decode active reference into an owned offscreen 2D canvas for CORS-safe pixel samplinguseEffect(() => {let cancelled = false;setLoadError(null);- if (!activeItem || !activeItem.src) {- sourceCanvasRef.current = null;- setSourceVersion((v) => v + 1);- return;+ const currentIds = new Set(items.map((i) => i.id));+ for (const cachedId of Array.from(sourceCanvasMapRef.current.keys())) {+ if (!currentIds.has(cachedId)) {+ sourceCanvasMapRef.current.delete(cachedId);+ filteredCacheRef.current.delete(cachedId);+ splitBwCacheRef.current.delete(cachedId);+ }}- const img = new Image();- img.crossOrigin = 'anonymous';- img.onload = () => {- if (cancelled) return;- const w = Math.max(1, img.naturalWidth || img.width || activeItem.width || 1);- const h = Math.max(1, img.naturalHeight || img.height || activeItem.height || 1);- const off = document.createElement('canvas');- off.width = w;- off.height = h;- const ctx = off.getContext('2d', { willReadFrequently: true });- if (ctx) {- ctx.clearRect(0, 0, w, h);- ctx.drawImage(img, 0, 0, w, h);- }- sourceCanvasRef.current = off;- setSourceVersion((v) => v + 1);+ let pendingDecodeCount = 0;- if (activeItem.needsInitialFit) {- const { width: sw, height: sh } = stageSizeRef.current;- const fitZoom = computeSubViewFitZoom(sw, sh, w, h);- liveTransformRef.current = { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false };- subViewStoreActions.updateImageTransform(- activeItem.id,- { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },- true- );+ for (const item of items) {+ if (!item.src) {+ sourceCanvasMapRef.current.delete(item.id);+ continue;}- };- img.onerror = () => {- if (cancelled) return;- sourceCanvasRef.current = null;- setLoadError('Failed to decode image');+ const existing = sourceCanvasMapRef.current.get(item.id);+ if (existing && existing.src === item.src) {+ // Already decoded; ensure initial fit in Single mode if needed+ if (item.id === activeItemRef.current?.id && item.needsInitialFit) {+ const { width: sw, height: sh } = stageSizeRef.current;+ const fitZoom = computeSubViewFitZoom(sw, sh, existing.canvas.width, existing.canvas.height);+ liveSingleTransformRef.current = {+ zoom: fitZoom,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+ };+ subViewStoreActions.updateImageTransform(+ item.id,+ { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },+ true+ );+ }+ continue;+ }++ pendingDecodeCount += 1;+ const itemId = item.id;+ const itemSrc = item.src;+ const itemW = item.width;+ const itemH = item.height;+ const itemNeedsFit = item.needsInitialFit;++ const img = new Image();+ img.crossOrigin = 'anonymous';+ img.onload = () => {+ if (cancelled) return;+ const w = Math.max(1, img.naturalWidth || img.width || itemW || 1);+ const h = Math.max(1, img.naturalHeight || img.height || itemH || 1);+ const off = document.createElement('canvas');+ off.width = w;+ off.height = h;+ const ctx = off.getContext('2d', { willReadFrequently: true });+ if (ctx) {+ ctx.clearRect(0, 0, w, h);+ ctx.drawImage(img, 0, 0, w, h);+ }+ sourceCanvasMapRef.current.set(itemId, { src: itemSrc, canvas: off });+ filteredCacheRef.current.delete(itemId);+ splitBwCacheRef.current.delete(itemId);+ setSourceVersion((v) => v + 1);++ if (itemNeedsFit) {+ const { width: sw, height: sh } = stageSizeRef.current;+ const fitZoom = computeSubViewFitZoom(sw, sh, w, h);+ if (activeItemRef.current?.id === itemId) {+ liveSingleTransformRef.current = {+ zoom: fitZoom,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+ };+ }+ subViewStoreActions.updateImageTransform(+ itemId,+ { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },+ true+ );+ }+ };+ img.onerror = () => {+ if (cancelled) return;+ sourceCanvasMapRef.current.delete(itemId);+ if (activeItemRef.current?.id === itemId) {+ setLoadError('Failed to decode image');+ }+ setSourceVersion((v) => v + 1);+ };+ img.src = itemSrc;+ }++ if (pendingDecodeCount === 0) {setSourceVersion((v) => v + 1);- };- img.src = activeItem.src;+ }return () => {cancelled = true;};- }, [activeItem?.id, activeItem?.src]);+ }, [itemsSrcKey]);- // Render Sub View display canvas from owned offscreen source canvas+ // Auto-fit PureRef board when first populated or after Auto-Arrange+ useEffect(() => {+ if (viewMode !== 'board' || !boardNeedsInitialFit || items.length === 0) return;+ const { width: sw, height: sh } = stageSizeRef.current;+ if (sw < 20 || sh < 20) return;+ const fit = computeBoardFitTransform(items, sw, sh, 18);+ liveBoardTransformRef.current = fit;+ subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);+ }, [viewMode, boardNeedsInitialFit, items, stageSize]);++ // Extract dominant color swatches whenever palette drawer is open and active item changes+ useEffect(() => {+ if (!showPalette || !activeItem) {+ setExtractedSwatches([]);+ return;+ }+ const entry = sourceCanvasMapRef.current.get(activeItem.id);+ if (!entry) {+ setExtractedSwatches([]);+ return;+ }+ setExtractedSwatches(extractDominantColorsFromCanvas(entry.canvas, 7));+ }, [showPalette, activeItem?.id, sourceVersion]);++ // Resolve cached filtered canvas for an item+ const getDrawableCanvasForItem = useCallback(+ (+ item: SubViewImageItem,+ filter: SubViewStudyFilter,+ forceGrayscaleOverride?: boolean+ ): HTMLCanvasElement | null => {+ const srcEntry = sourceCanvasMapRef.current.get(item.id);+ if (!srcEntry) return null;+ const srcCanvas = srcEntry.canvas;++ const effectiveFilter =+ forceGrayscaleOverride === undefined+ ? filter+ : { ...filter, grayscale: forceGrayscaleOverride };+ const itemGray = forceGrayscaleOverride === false ? false : item.grayscale;++ if (!isStudyFilterVisualActive(effectiveFilter, itemGray)) {+ return srcCanvas;+ }++ const cacheMap =+ forceGrayscaleOverride === true ? splitBwCacheRef.current : filteredCacheRef.current;+ const sig = getStudyFilterSignature(effectiveFilter, itemGray);+ const cached = cacheMap.get(item.id);+ if (cached && cached.sig === sig && cached.srcCanvas === srcCanvas) {+ return cached.filteredCanvas;+ }++ const filteredCanvas = buildFilteredReferenceCanvas(srcCanvas, effectiveFilter, itemGray);+ cacheMap.set(item.id, { sig, srcCanvas, filteredCanvas });+ return filteredCanvas;+ },+ []+ );++ const getEffectiveCards = useCallback((): SubViewImageItem[] => {+ const livePatch = liveCardPatchRef.current;+ if (!livePatch) return itemsRef.current;+ return itemsRef.current.map((it) =>+ it.id === livePatch.id+ ? {+ ...it,+ boardX: livePatch.boardX,+ boardY: livePatch.boardY,+ boardScale: livePatch.boardScale,+ boardRotation: livePatch.boardRotation,+ }+ : it+ );+ }, []);++ // Render Single OR PureRef Board display canvas (including Split Color | B/W and proportional grids)const renderDisplayCanvas = useCallback(- (overrideTransform?: SubViewTransform) => {+ (overrideTransform?: SubViewTransform, overrideSplitRatio?: number) => {const display = displayCanvasRef.current;if (!display) return;const ctx = display.getContext('2d');@@ -346,81 +611,395 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(display.height = targetH;}+ const filter = studyFilterRef.current;+ const mode = viewModeRef.current;+ctx.save();ctx.setTransform(dpr, 0, 0, dpr, 0, 0);ctx.clearRect(0, 0, sw, sh);- const src = sourceCanvasRef.current;- if (!src) {+ if (mode === 'single') {+ const active = activeItemRef.current;+ if (!active) {+ ctx.restore();+ return;+ }+ const t = overrideTransform ?? liveSingleTransformRef.current;+ const srcEntry = sourceCanvasMapRef.current.get(active.id);+ if (!srcEntry) {+ ctx.restore();+ return;+ }+ const imgW = srcEntry.canvas.width;+ const imgH = srcEntry.canvas.height;++ const drawSinglePass = (drawable: HTMLCanvasElement) => {+ ctx.save();+ ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);+ ctx.rotate((t.rotation * Math.PI) / 180);+ ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);+ ctx.imageSmoothingEnabled = t.zoom < 2;+ ctx.drawImage(drawable, -imgW / 2, -imgH / 2, imgW, imgH);+ ctx.restore();+ };++ if (filter.splitBw) {+ const splitX = sw * clampNavigatorSplitRatio(overrideSplitRatio ?? filter.splitRatio);+ const colorCanvas = getDrawableCanvasForItem(active, filter, false);+ const bwCanvas = getDrawableCanvasForItem(active, filter, true);+ if (colorCanvas) {+ ctx.save();+ ctx.beginPath();+ ctx.rect(0, 0, splitX, sh);+ ctx.clip();+ drawSinglePass(colorCanvas);+ ctx.restore();+ }+ if (bwCanvas) {+ ctx.save();+ ctx.beginPath();+ ctx.rect(splitX, 0, Math.max(0, sw - splitX), sh);+ ctx.clip();+ drawSinglePass(bwCanvas);+ ctx.restore();+ }+ } else {+ const drawable = getDrawableCanvasForItem(active, filter);+ if (drawable) drawSinglePass(drawable);+ }++ if (filter.gridMode !== 'none') {+ ctx.save();+ ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);+ ctx.rotate((t.rotation * Math.PI) / 180);+ ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);+ drawProportionalGrid(ctx, imgW, imgH, filter.gridMode, t.zoom);+ ctx.restore();+ }+ctx.restore();return;}- const t = overrideTransform ?? liveTransformRef.current;- ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);- ctx.rotate((t.rotation * Math.PI) / 180);- ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);- ctx.imageSmoothingEnabled = t.zoom < 2;- ctx.drawImage(src, -src.width / 2, -src.height / 2);+ // PureRef Board Mode+ const t = overrideTransform ?? liveBoardTransformRef.current;+ const cards = getEffectiveCards();++ drawBoardBackgroundDots(ctx, sw, sh, t);++ if (cards.length === 0) {+ ctx.restore();+ return;+ }++ const sortedCards = cards+ .map((card, idx) => ({ card, idx }))+ .sort((a, b) => a.card.zIndex - b.card.zIndex || a.idx - b.idx)+ .map((e) => e.card);++ const drawBoardCardsPass = (forceGrayscaleOverride?: boolean) => {+ ctx.save();+ ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);+ ctx.rotate((t.rotation * Math.PI) / 180);+ ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);++ for (const card of sortedCards) {+ const drawable = getDrawableCanvasForItem(card, filter, forceGrayscaleOverride);+ const w = Math.max(1, card.width);+ const h = Math.max(1, card.height);+ ctx.save();+ ctx.translate(card.boardX, card.boardY);+ ctx.rotate((card.boardRotation * Math.PI) / 180);+ ctx.scale(+ card.boardFlipX ? -card.boardScale : card.boardScale,+ card.boardFlipY ? -card.boardScale : card.boardScale+ );+ ctx.globalAlpha = card.opacity;+ ctx.imageSmoothingEnabled = t.zoom * card.boardScale < 2;++ if (drawable) {+ ctx.drawImage(drawable, -w / 2, -h / 2, w, h);+ } else {+ // Metadata-only placeholder card+ ctx.fillStyle = 'rgba(40, 40, 44, 0.9)';+ ctx.fillRect(-w / 2, -h / 2, w, h);+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.25)';+ ctx.lineWidth = 1 / Math.max(0.1, t.zoom * card.boardScale);+ ctx.strokeRect(-w / 2, -h / 2, w, h);+ }++ if (filter.gridMode !== 'none' && card.id === activeItemRef.current?.id) {+ ctx.globalAlpha = 1;+ drawProportionalGrid(ctx, w, h, filter.gridMode, t.zoom * card.boardScale);+ }+ ctx.restore();+ }+ ctx.restore();+ };++ if (filter.splitBw) {+ const splitX = sw * clampNavigatorSplitRatio(overrideSplitRatio ?? filter.splitRatio);+ ctx.save();+ ctx.beginPath();+ ctx.rect(0, 0, splitX, sh);+ ctx.clip();+ drawBoardCardsPass(false);+ ctx.restore();++ ctx.save();+ ctx.beginPath();+ ctx.rect(splitX, 0, Math.max(0, sw - splitX), sh);+ ctx.clip();+ drawBoardCardsPass(true);+ ctx.restore();+ } else {+ drawBoardCardsPass(undefined);+ }++ // Draw crisp screen-space selection frame & handles for active card in Board mode+ const selectedCard = sortedCards.find((c) => c.id === activeItemRef.current?.id);+ if (selectedCard) {+ const ov = getCardStageOverlay(selectedCard, sw, sh, t);+ ctx.save();+ ctx.strokeStyle = selectedCard.locked+ ? 'rgba(225, 169, 72, 0.85)'+ : 'rgba(96, 165, 250, 0.92)';+ ctx.lineWidth = 1.25;+ ctx.beginPath();+ ctx.moveTo(ov.tl.x, ov.tl.y);+ ctx.lineTo(ov.tr.x, ov.tr.y);+ ctx.lineTo(ov.br.x, ov.br.y);+ ctx.lineTo(ov.bl.x, ov.bl.y);+ ctx.closePath();+ ctx.stroke();++ // Show interactive resize & rotate handles when in Arrange/Select mode and card is unlocked+ if (!selectedCard.locked && boardToolRef.current === 'select') {+ // Rotation stem + lollipop+ ctx.beginPath();+ ctx.moveTo(ov.topMid.x, ov.topMid.y);+ ctx.lineTo(ov.rotHandle.x, ov.rotHandle.y);+ ctx.stroke();++ ctx.fillStyle = '#18181b';+ if (typeof ctx.arc === 'function') {+ ctx.beginPath();+ ctx.arc(ov.rotHandle.x, ov.rotHandle.y, 4, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();+ } else {+ ctx.fillRect(ov.rotHandle.x - 4, ov.rotHandle.y - 4, 8, 8);+ ctx.strokeRect(ov.rotHandle.x - 4, ov.rotHandle.y - 4, 8, 8);+ }++ // 4 corner handles+ for (const corner of [ov.tl, ov.tr, ov.br, ov.bl]) {+ ctx.fillStyle = '#ffffff';+ ctx.fillRect(corner.x - 3.5, corner.y - 3.5, 7, 7);+ ctx.strokeRect(corner.x - 3.5, corner.y - 3.5, 7, 7);+ }+ }+ ctx.restore();+ }+ctx.restore();},- []+ [getDrawableCanvasForItem, getEffectiveCards]);useEffect(() => {renderDisplayCanvas();- }, [activeItem, stageSize, sourceVersion, renderDisplayCanvas]);+ }, [+ items,+ activeItem,+ viewMode,+ boardTool,+ boardTransform,+ studyFilter,+ stageSize,+ sourceVersion,+ renderDisplayCanvas,+ ]);// Determine effective interaction mode on hover/clickconst isEyedropperActive = useMemo(() => {if (isSpaceHeld) return false;if (isAltHeld) return true;+ if (viewMode === 'board') {+ return boardTool === 'eyedrop';+ }return autoEyedropper || manualEyedropper;- }, [autoEyedropper, manualEyedropper, isSpaceHeld, isAltHeld]);+ }, [viewMode, boardTool, autoEyedropper, manualEyedropper, isSpaceHeld, isAltHeld]);const sampleColorAtClientPos = useCallback((clientX: number, clientY: number, commit: boolean): string | null => {const stage = stageRef.current;- const src = sourceCanvasRef.current;- if (!stage || !src) return null;+ if (!stage) return null;const rect = stage.getBoundingClientRect();const localX = clientX - rect.left;const localY = clientY - rect.top;- const pxCoord = subViewPointToImagePixel(+ const sw = rect.width || stageSizeRef.current.width;+ const sh = rect.height || stageSizeRef.current.height;+ const filter = studyFilterRef.current;+ const useFiltered = sampleDisplayToneRef.current;++ if (viewModeRef.current === 'single') {+ const active = activeItemRef.current;+ if (!active) return null;+ const srcEntry = sourceCanvasMapRef.current.get(active.id);+ if (!srcEntry) return null;+ const src = srcEntry.canvas;+ const pxCoord = subViewPointToImagePixel(+ localX,+ localY,+ sw,+ sh,+ src.width,+ src.height,+ liveSingleTransformRef.current+ );+ if (!pxCoord) return null;+ const sampleCanvas = useFiltered+ ? getDrawableCanvasForItem(active, filter) ?? src+ : src;+ const sx = Math.min(+ sampleCanvas.width - 1,+ Math.max(0, Math.floor((pxCoord.x / src.width) * sampleCanvas.width))+ );+ const sy = Math.min(+ sampleCanvas.height - 1,+ Math.max(0, Math.floor((pxCoord.y / src.height) * sampleCanvas.height))+ );+ const hex = samplePixelHexFromCanvas(sampleCanvas, sx, sy);+ if (!hex) return null;+ setSampledHex(hex);+ toolStoreActions.setPrimaryColor(hex, commit, colorMode);+ return hex;+ }++ // PureRef Board mode: hit-test topmost card under pointer+ const hit = hitTestBoardCards(localX,localY,- rect.width || stageSizeRef.current.width,- rect.height || stageSizeRef.current.height,- src.width,- src.height,- liveTransformRef.current+ getEffectiveCards(),+ sw,+ sh,+ liveBoardTransformRef.current);- if (!pxCoord) return null;- const hex = samplePixelHexFromCanvas(src, pxCoord.x, pxCoord.y);+ if (!hit) return null;+ const srcEntry = sourceCanvasMapRef.current.get(hit.card.id);+ if (!srcEntry) return null;+ const src = srcEntry.canvas;+ const sampleCanvas = useFiltered+ ? getDrawableCanvasForItem(hit.card, filter) ?? src+ : src;+ const sx = Math.min(+ sampleCanvas.width - 1,+ Math.max(0, Math.floor((hit.pixel.x / Math.max(1, hit.card.width)) * sampleCanvas.width))+ );+ const sy = Math.min(+ sampleCanvas.height - 1,+ Math.max(0, Math.floor((hit.pixel.y / Math.max(1, hit.card.height)) * sampleCanvas.height))+ );+ const hex = samplePixelHexFromCanvas(sampleCanvas, sx, sy);if (!hex) return null;setSampledHex(hex);toolStoreActions.setPrimaryColor(hex, commit, colorMode);return hex;},- [colorMode]+ [colorMode, getDrawableCanvasForItem, getEffectiveCards]);- const handleFilesSelected = useCallback(async (fileList: FileList | File[]) => {- const files = Array.from(fileList).filter(isImageFile);- if (files.length === 0) return;- setLoadError(null);- const loaded: Array<{ name: string; src: string; width: number; height: number }> = [];- for (const file of files) {- try {- loaded.push(await readLocalImageFile(file));- } catch {- setLoadError(`Could not load "${file.name}"`);+ const handleFilesSelected = useCallback(+ async (fileList: FileList | File[], dropClientPos?: { x: number; y: number } | null) => {+ const files = Array.from(fileList).filter(isImageFile);+ if (files.length === 0) return;+ setLoadError(null);+ const loaded: Array<{ name: string; src: string; width: number; height: number }> = [];+ for (const file of files) {+ try {+ loaded.push(await readLocalImageFile(file));+ } catch {+ setLoadError(`Could not load "${file.name}"`);+ }}+ if (loaded.length > 0) {+ let dropBoardPoint = null;+ if (+ dropClientPos &&+ viewModeRef.current === 'board' &&+ itemsRef.current.length > 0 &&+ stageRef.current+ ) {+ const rect = stageRef.current.getBoundingClientRect();+ dropBoardPoint = stagePointToBoardPoint(+ dropClientPos.x - rect.left,+ dropClientPos.y - rect.top,+ rect.width || stageSizeRef.current.width,+ rect.height || stageSizeRef.current.height,+ liveBoardTransformRef.current+ );+ }+ subViewStoreActions.addImages(loaded, { dropBoardPoint });+ }+ },+ []+ );++ const handlePasteFromClipboard = useCallback(async () => {+ setLoadError(null);+ if (typeof navigator === 'undefined' || !navigator.clipboard?.read) {+ setLoadError('Use Ctrl+V while hovering References to paste an image');+ return;}- if (loaded.length > 0) {- subViewStoreActions.addImages(loaded);+ try {+ const clipItems = await navigator.clipboard.read();+ const files: File[] = [];+ let idx = 1;+ for (const clipItem of clipItems) {+ const imgType = clipItem.types.find((t) => t.startsWith('image/'));+ if (imgType) {+ const blob = await clipItem.getType(imgType);+ const ext = imgType.split('/')[1]?.replace(/[^a-z0-9]/gi, '') || 'png';+ files.push(new File([blob], `Clipboard ${idx++}.${ext}`, { type: imgType }));+ }+ }+ if (files.length === 0) {+ setLoadError('No image found in clipboard');+ return;+ }+ await handleFilesSelected(files);+ } catch {+ setLoadError('Clipboard image read blocked — press Ctrl+V over References');}- }, []);+ }, [handleFilesSelected]);++ // Clipboard Ctrl+V listener scoped to when the References panel is hovered or focused+ useEffect(() => {+ const onPaste = (e: ClipboardEvent) => {+ const panel = panelRef.current;+ const activeEl = document.activeElement;+ const isFocusedInside = Boolean(panel && activeEl && panel.contains(activeEl));+ if (!isHoveringStageRef.current && !isFocusedInside) return;+ const cd = e.clipboardData;+ if (!cd) return;+ const imageFiles: File[] = [];+ for (let i = 0; i < cd.items.length; i++) {+ const it = cd.items[i];+ if (it.kind === 'file' && it.type.startsWith('image/')) {+ const f = it.getAsFile();+ if (f) imageFiles.push(f);+ }+ }+ if (imageFiles.length > 0) {+ e.preventDefault();+ e.stopPropagation();+ void handleFilesSelected(imageFiles);+ }+ };+ window.addEventListener('paste', onPaste);+ return () => window.removeEventListener('paste', onPaste);+ }, [handleFilesSelected]);const handleReloadActiveFile = useCallback(async (file: File | undefined) => {const item = activeItemRef.current;@@ -433,36 +1012,324 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(}}, []);+ // Viewport control actions (board camera in Board mode, active image in Single mode)+ const handleSubZoomBy = useCallback((factor: number) => {+ if (viewModeRef.current === 'board') {+ const nextZoom = clampSubViewZoom(liveBoardTransformRef.current.zoom * factor);+ subViewStoreActions.updateBoardTransform({ zoom: nextZoom, needsInitialFit: false }, true);+ return;+ }+ const item = activeItemRef.current;+ if (!item) return;+ const nextZoom = clampSubViewZoom(liveSingleTransformRef.current.zoom * factor);+ subViewStoreActions.updateImageTransform(+ item.id,+ { zoom: nextZoom, needsInitialFit: false },+ true+ );+ }, []);++ const handleSubFit = useCallback(() => {+ const { width: sw, height: sh } = stageSizeRef.current;+ if (viewModeRef.current === 'board') {+ const cards = itemsRef.current;+ if (cards.length === 0) return;+ const fit = computeBoardFitTransform(cards, sw, sh, 18);+ liveBoardTransformRef.current = fit;+ subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);+ return;+ }+ const item = activeItemRef.current;+ if (!item) return;+ const src = sourceCanvasMapRef.current.get(item.id)?.canvas;+ const w = src?.width || item.width || 1;+ const h = src?.height || item.height || 1;+ const fitZoom = computeSubViewFitZoom(sw, sh, w, h);+ subViewStoreActions.updateImageTransform(+ item.id,+ { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },+ true+ );+ }, []);++ const handleFitSelectedCard = useCallback((cardId?: string) => {+ const targetId = cardId ?? activeItemRef.current?.id;+ if (!targetId) return;+ const card = itemsRef.current.find((i) => i.id === targetId);+ if (!card) return;+ const { width: sw, height: sh } = stageSizeRef.current;+ const fit = computeBoardFitTransform([card], sw, sh, 18);+ liveBoardTransformRef.current = fit;+ subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);+ }, []);++ const handleSubRotateBy = useCallback((deltaDeg: number) => {+ if (viewModeRef.current === 'board') {+ subViewStoreActions.updateBoardTransform(+ { rotation: liveBoardTransformRef.current.rotation + deltaDeg },+ true+ );+ return;+ }+ const item = activeItemRef.current;+ if (!item) return;+ subViewStoreActions.updateImageTransform(+ item.id,+ { rotation: liveSingleTransformRef.current.rotation + deltaDeg },+ true+ );+ }, []);++ const handleSubResetRotation = useCallback(() => {+ if (viewModeRef.current === 'board') {+ subViewStoreActions.updateBoardTransform({ rotation: 0 }, true);+ return;+ }+ const item = activeItemRef.current;+ if (!item) return;+ subViewStoreActions.updateImageTransform(item.id, { rotation: 0 }, true);+ }, []);++ const handleSubToggleFlipX = useCallback(() => {+ if (viewModeRef.current === 'board') {+ subViewStoreActions.updateBoardTransform(+ { flipX: !liveBoardTransformRef.current.flipX },+ true+ );+ return;+ }+ const item = activeItemRef.current;+ if (!item) return;+ subViewStoreActions.updateImageTransform(+ item.id,+ { flipX: !liveSingleTransformRef.current.flipX },+ true+ );+ }, []);++ // Track Space / Alt and quick local study hotkeys (G = B/W, F = Fit, H = Flip H) while hovering stage+ useEffect(() => {+ if (!isHoveringStage) {+ setIsSpaceHeld(false);+ setIsAltHeld(false);+ return;+ }+ const onKeyDown = (e: KeyboardEvent) => {+ const tag = (e.target as HTMLElement | null)?.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;+ if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(true);+ if (e.key === 'Alt') setIsAltHeld(true);+ if (!e.ctrlKey && !e.metaKey && !e.altKey) {+ const lower = e.key.toLowerCase();+ if (lower === 'g') {+ e.preventDefault();+ e.stopPropagation();+ subViewStoreActions.toggleGrayscale();+ } else if (lower === 'f') {+ e.preventDefault();+ e.stopPropagation();+ handleSubFit();+ } else if (lower === 'h') {+ e.preventDefault();+ e.stopPropagation();+ handleSubToggleFlipX();+ }+ }+ };+ const onKeyUp = (e: KeyboardEvent) => {+ if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(false);+ if (e.key === 'Alt') setIsAltHeld(false);+ };+ const onBlur = () => {+ setIsSpaceHeld(false);+ setIsAltHeld(false);+ };+ window.addEventListener('keydown', onKeyDown);+ window.addEventListener('keyup', onKeyUp, true);+ window.addEventListener('blur', onBlur);+ return () => {+ window.removeEventListener('keydown', onKeyDown);+ window.removeEventListener('keyup', onKeyUp, true);+ window.removeEventListener('blur', onBlur);+ };+ }, [isHoveringStage, handleSubFit, handleSubToggleFlipX]);+const handleStagePointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {- const item = activeItemRef.current;- if (!item || !item.src) return;+ if (itemsRef.current.length === 0) return;e.preventDefault();e.stopPropagation();+ setShowArrangeMenu(false);++ const stage = stageRef.current;+ const rect = stage?.getBoundingClientRect();+ const localX = rect ? e.clientX - rect.left : e.clientX;+ const localY = rect ? e.clientY - rect.top : e.clientY;+ const sw = rect?.width || stageSizeRef.current.width;+ const sh = rect?.height || stageSizeRef.current.height;- // Middle mouse button or Space forces panconst forcePan = e.button === 1 || isSpaceHeld;- const shouldEyedrop = !forcePan && e.button === 0 && (isEyedropperActive || e.altKey);-- if (shouldEyedrop) {- interactionRef.current = {- mode: 'eyedrop',- pointerId: e.pointerId,- startClientX: e.clientX,- startClientY: e.clientY,- startPanX: 0,- startPanY: 0,- };- sampleColorAtClientPos(e.clientX, e.clientY, true);- } else if (e.button === 0 || e.button === 1) {- interactionRef.current = {- mode: 'pan',- pointerId: e.pointerId,- startClientX: e.clientX,- startClientY: e.clientY,- startPanX: liveTransformRef.current.pan.x,- startPanY: liveTransformRef.current.pan.y,- };+ const forceEyedrop = !forcePan && e.button === 0 && e.altKey;++ if (viewModeRef.current === 'single') {+ const item = activeItemRef.current;+ if (!item || !item.src) return;+ const shouldEyedrop = forceEyedrop || (!forcePan && e.button === 0 && isEyedropperActive);++ if (shouldEyedrop) {+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'eyedrop',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ };+ setActiveInteractionKind('eyedrop');+ sampleColorAtClientPos(e.clientX, e.clientY, true);+ } else if (e.button === 0 || e.button === 1) {+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'pan',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: liveSingleTransformRef.current.pan.x,+ startPanY: liveSingleTransformRef.current.pan.y,+ };+ setActiveInteractionKind('pan');+ }+ } else {+ // PureRef Board Mode+ const bt = liveBoardTransformRef.current;+ const cards = itemsRef.current;++ if (forcePan || (e.button === 0 && !forceEyedrop && boardToolRef.current === 'pan')) {+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'pan',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: bt.pan.x,+ startPanY: bt.pan.y,+ };+ setActiveInteractionKind('pan');+ } else if (forceEyedrop || (e.button === 0 && boardToolRef.current === 'eyedrop')) {+ const hit = hitTestBoardCards(localX, localY, cards, sw, sh, bt);+ if (hit) {+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'eyedrop',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ };+ setActiveInteractionKind('eyedrop');+ sampleColorAtClientPos(e.clientX, e.clientY, true);+ } else {+ // Clicking empty space around references in Eyedropper mode pans the board smoothly+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'pan',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: bt.pan.x,+ startPanY: bt.pan.y,+ };+ setActiveInteractionKind('pan');+ }+ } else if (e.button === 0 && boardToolRef.current === 'select') {+ // 1. Check active card's resize / rotate handles first+ const active = activeItemRef.current;+ const handle = active ? hitTestCardHandle(localX, localY, active, sw, sh, bt) : null;+ if (active && handle) {+ const bp = stagePointToBoardPoint(localX, localY, sw, sh, bt);+ const dx = bp.x - active.boardX;+ const dy = bp.y - active.boardY;+ const dist = Math.max(4, Math.hypot(dx, dy));+ const angle = (Math.atan2(dy, dx) * 180) / Math.PI;+ const nextMode = handle === 'rotate' ? 'card-rotate' : 'card-resize';+ liveCardPatchRef.current = {+ id: active.id,+ boardX: active.boardX,+ boardY: active.boardY,+ boardScale: active.boardScale,+ boardRotation: active.boardRotation,+ };+ interactionRef.current = {+ mode: nextMode,+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: bt.pan.x,+ startPanY: bt.pan.y,+ cardId: active.id,+ startCardX: active.boardX,+ startCardY: active.boardY,+ startCardScale: active.boardScale,+ startCardRotation: active.boardRotation,+ startCardDist: dist,+ startCardAngle: angle,+ handleKind: handle,+ };+ setActiveInteractionKind(nextMode);+ } else {+ // 2. Hit-test board cards+ const hit = hitTestBoardCards(localX, localY, cards, sw, sh, bt);+ if (hit) {+ subViewStoreActions.selectImage(hit.card.id);+ if (!hit.card.locked) {+ subViewStoreActions.bringCardToFront(hit.card.id);+ liveCardPatchRef.current = {+ id: hit.card.id,+ boardX: hit.card.boardX,+ boardY: hit.card.boardY,+ boardScale: hit.card.boardScale,+ boardRotation: hit.card.boardRotation,+ };+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'card-move',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ cardId: hit.card.id,+ startCardX: hit.card.boardX,+ startCardY: hit.card.boardY,+ startCardScale: hit.card.boardScale,+ startCardRotation: hit.card.boardRotation,+ handleKind: null,+ };+ setActiveInteractionKind('card-move');+ } else {+ // Locked card: drag pans the board instead of moving the locked card+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'pan',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: bt.pan.x,+ startPanY: bt.pan.y,+ };+ setActiveInteractionKind('pan');+ }+ } else {+ // Empty space: pan the PureRef board+ interactionRef.current = {+ ...interactionRef.current,+ mode: 'pan',+ pointerId: e.pointerId,+ startClientX: e.clientX,+ startClientY: e.clientY,+ startPanX: bt.pan.x,+ startPanY: bt.pan.y,+ };+ setActiveInteractionKind('pan');+ }+ }+ }}try {@@ -487,58 +1354,267 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(if (state.mode === 'pan') {const dx = e.clientX - state.startClientX;const dy = e.clientY - state.startClientY;- const next: SubViewTransform = {- ...liveTransformRef.current,- pan: { x: state.startPanX + dx, y: state.startPanY + dy },+ if (viewModeRef.current === 'single') {+ const next: SubViewTransform = {+ ...liveSingleTransformRef.current,+ pan: { x: state.startPanX + dx, y: state.startPanY + dy },+ };+ liveSingleTransformRef.current = next;+ renderDisplayCanvas(next);+ } else {+ const next: SubViewTransform = {+ ...liveBoardTransformRef.current,+ pan: { x: state.startPanX + dx, y: state.startPanY + dy },+ };+ liveBoardTransformRef.current = next;+ renderDisplayCanvas(next);+ }+ return;+ }++ if (state.mode === 'card-move' && state.cardId) {+ const dx = e.clientX - state.startClientX;+ const dy = e.clientY - state.startClientY;+ const deltaBoard = stageDeltaToBoardDelta(dx, dy, liveBoardTransformRef.current);+ liveCardPatchRef.current = {+ id: state.cardId,+ boardX: state.startCardX + deltaBoard.x,+ boardY: state.startCardY + deltaBoard.y,+ boardScale: state.startCardScale,+ boardRotation: state.startCardRotation,};- liveTransformRef.current = next;- renderDisplayCanvas(next);+ renderDisplayCanvas();+ return;+ }++ if ((state.mode === 'card-resize' || state.mode === 'card-rotate') && state.cardId) {+ const stage = stageRef.current;+ if (!stage) return;+ const rect = stage.getBoundingClientRect();+ const localX = e.clientX - rect.left;+ const localY = e.clientY - rect.top;+ const bp = stagePointToBoardPoint(+ localX,+ localY,+ rect.width || stageSizeRef.current.width,+ rect.height || stageSizeRef.current.height,+ liveBoardTransformRef.current+ );+ const dx = bp.x - state.startCardX;+ const dy = bp.y - state.startCardY;++ if (state.mode === 'card-resize') {+ const dist = Math.max(4, Math.hypot(dx, dy));+ const ratio = dist / Math.max(4, state.startCardDist);+ const nextScale = clampBoardCardScale(state.startCardScale * ratio);+ liveCardPatchRef.current = {+ id: state.cardId,+ boardX: state.startCardX,+ boardY: state.startCardY,+ boardScale: nextScale,+ boardRotation: state.startCardRotation,+ };+ } else {+ const angle = (Math.atan2(dy, dx) * 180) / Math.PI;+ let nextRot = state.startCardRotation + (angle - state.startCardAngle);+ if (e.shiftKey) {+ nextRot = Math.round(nextRot / 15) * 15;+ }+ liveCardPatchRef.current = {+ id: state.cardId,+ boardX: state.startCardX,+ boardY: state.startCardY,+ boardScale: state.startCardScale,+ boardRotation: nextRot,+ };+ }+ renderDisplayCanvas();+ }+ },+ [renderDisplayCanvas, sampleColorAtClientPos]+ );++ const finishStageInteraction = useCallback(+ (e?: React.PointerEvent<HTMLDivElement>) => {+ const state = interactionRef.current;+ if (state.mode === 'none') return;+ const prevMode = state.mode;+ const pid = state.pointerId;+ interactionRef.current.mode = 'none';+ interactionRef.current.pointerId = null;+ setActiveInteractionKind('none');++ if (e && pid !== null) {+ try {+ e.currentTarget.releasePointerCapture?.(pid);+ } catch {+ // Ignore in synthetic events+ }+ }++ if (prevMode === 'pan') {+ if (viewModeRef.current === 'single') {+ const item = activeItemRef.current;+ if (item) {+ subViewStoreActions.updateImageTransform(+ item.id,+ { pan: liveSingleTransformRef.current.pan, needsInitialFit: false },+ true+ );+ }+ } else {+ subViewStoreActions.updateBoardTransform(+ { pan: liveBoardTransformRef.current.pan, needsInitialFit: false },+ true+ );+ }+ } else if (prevMode === 'eyedrop' && e) {+ sampleColorAtClientPos(e.clientX, e.clientY, true);+ } else if (+ (prevMode === 'card-move' || prevMode === 'card-resize' || prevMode === 'card-rotate') &&+ liveCardPatchRef.current+ ) {+ const patch = liveCardPatchRef.current;+ liveCardPatchRef.current = null;+ subViewStoreActions.updateCardBoardProps(+ patch.id,+ {+ boardX: patch.boardX,+ boardY: patch.boardY,+ boardScale: patch.boardScale,+ boardRotation: patch.boardRotation,+ },+ true+ );+ }+ },+ [sampleColorAtClientPos]+ );++ const handleStageDoubleClick = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (viewModeRef.current !== 'board' || itemsRef.current.length === 0) return;+ if (boardToolRef.current === 'eyedrop') return;+ const stage = stageRef.current;+ if (!stage) return;+ const rect = stage.getBoundingClientRect();+ const localX = e.clientX - rect.left;+ const localY = e.clientY - rect.top;+ const hit = hitTestBoardCards(+ localX,+ localY,+ itemsRef.current,+ rect.width || stageSizeRef.current.width,+ rect.height || stageSizeRef.current.height,+ liveBoardTransformRef.current+ );+ if (hit) {+ subViewStoreActions.selectImage(hit.card.id);+ handleFitSelectedCard(hit.card.id);+ } else {+ handleSubFit();+ }+ },+ [handleFitSelectedCard, handleSubFit]+ );++ // Split Color | B/W Curtain Handle Dragging+ 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 = clampNavigatorSplitRatio(+ (e.clientX - rect.left) / Math.max(1, rect.width || stageSizeRef.current.width)+ );+ splitDragRef.current = { active: true, pointerId: e.pointerId, latestRatio: nextRatio };+ setIsDraggingSplit(true);+ renderDisplayCanvas(undefined, nextRatio);+ subViewStoreActions.updateStudyFilter({ splitRatio: nextRatio }, false);+ try {+ e.currentTarget.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore in synthetic events}},- [renderDisplayCanvas, sampleColorAtClientPos]+ [renderDisplayCanvas]);- const finishStageInteraction = useCallback(- (e?: React.PointerEvent<HTMLDivElement>) => {- const state = interactionRef.current;- if (state.mode === 'none') return;- const prevMode = state.mode;- const pid = state.pointerId;- interactionRef.current.mode = 'none';- interactionRef.current.pointerId = null;-- if (e && pid !== null) {- try {- e.currentTarget.releasePointerCapture?.(pid);- } catch {- // Ignore in synthetic events- }- }-- const item = activeItemRef.current;- if (prevMode === 'pan' && item) {- subViewStoreActions.updateImageTransform(- item.id,- { pan: liveTransformRef.current.pan, needsInitialFit: false },- true- );- } else if (prevMode === 'eyedrop' && e) {- sampleColorAtClientPos(e.clientX, e.clientY, true);- }+ 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 = clampNavigatorSplitRatio(+ (e.clientX - rect.left) / Math.max(1, rect.width || stageSizeRef.current.width)+ );+ splitDragRef.current.latestRatio = nextRatio;+ renderDisplayCanvas(undefined, nextRatio);+ subViewStoreActions.updateStudyFilter({ splitRatio: nextRatio }, false);},- [sampleColorAtClientPos]+ [renderDisplayCanvas]);- // Independent mouse wheel zoom strictly inside Sub View+ 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 events+ }+ }+ subViewStoreActions.updateStudyFilter({ splitRatio: finalRatio }, true);+ }, []);++ // Independent mouse wheel zoom (and Shift+Wheel smooth rotation!) strictly inside References stageuseEffect(() => {const el = stageRef.current;if (!el) return;const handleWheel = (e: WheelEvent) => {- const item = activeItemRef.current;- if (!item || !item.src) return;+ if (itemsRef.current.length === 0) return;+ if (viewModeRef.current === 'single' && !activeItemRef.current?.src) return;e.preventDefault();e.stopPropagation();+ // Shift + Wheel rotates smoothly by 5° steps+ if (e.shiftKey) {+ const deltaDeg = e.deltaY > 0 ? 5 : -5;+ if (viewModeRef.current === 'board') {+ const next: SubViewTransform = {+ ...liveBoardTransformRef.current,+ rotation: liveBoardTransformRef.current.rotation + deltaDeg,+ };+ liveBoardTransformRef.current = next;+ renderDisplayCanvas(next);+ subViewStoreActions.updateBoardTransform({ rotation: next.rotation }, true);+ } else if (activeItemRef.current) {+ const next: SubViewTransform = {+ ...liveSingleTransformRef.current,+ rotation: liveSingleTransformRef.current.rotation + deltaDeg,+ };+ liveSingleTransformRef.current = next;+ renderDisplayCanvas(next);+ subViewStoreActions.updateImageTransform(+ activeItemRef.current.id,+ { rotation: next.rotation },+ true+ );+ }+ return;+ }+const rect = el.getBoundingClientRect();const localX = e.clientX - rect.left;const localY = e.clientY - rect.top;@@ -546,7 +1622,10 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(const cy = (rect.height || stageSizeRef.current.height) / 2;const factor = Math.exp(-e.deltaY * 0.002);- const cur = liveTransformRef.current;+ const cur =+ viewModeRef.current === 'board'+ ? liveBoardTransformRef.current+ : liveSingleTransformRef.current;const nextZoom = Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, cur.zoom * factor));const ratio = nextZoom / cur.zoom;@@ -558,72 +1637,29 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(zoom: nextZoom,pan: { x: nextPanX, y: nextPanY },};- liveTransformRef.current = next;- renderDisplayCanvas(next);- subViewStoreActions.updateImageTransform(- item.id,- { zoom: nextZoom, pan: next.pan, needsInitialFit: false },- true- );++ if (viewModeRef.current === 'board') {+ liveBoardTransformRef.current = next;+ renderDisplayCanvas(next);+ subViewStoreActions.updateBoardTransform(+ { zoom: nextZoom, pan: next.pan, needsInitialFit: false },+ true+ );+ } else if (activeItemRef.current) {+ liveSingleTransformRef.current = next;+ renderDisplayCanvas(next);+ subViewStoreActions.updateImageTransform(+ activeItemRef.current.id,+ { zoom: nextZoom, pan: next.pan, needsInitialFit: false },+ true+ );+ }};el.addEventListener('wheel', handleWheel, { passive: false });return () => el.removeEventListener('wheel', handleWheel);}, [renderDisplayCanvas]);- // Independent Sub View control actions (strictly local to active Sub View image)- const handleSubZoomBy = useCallback((factor: number) => {- const item = activeItemRef.current;- if (!item) return;- const nextZoom = Math.max(- SUB_VIEW_MIN_ZOOM,- Math.min(SUB_VIEW_MAX_ZOOM, liveTransformRef.current.zoom * factor)- );- subViewStoreActions.updateImageTransform(item.id, { zoom: nextZoom, needsInitialFit: false }, true);- }, []);-- const handleSubFit = useCallback(() => {- const item = activeItemRef.current;- if (!item) return;- const src = sourceCanvasRef.current;- const w = src?.width || item.width || 1;- const h = src?.height || item.height || 1;- const { width: sw, height: sh } = stageSizeRef.current;- const fitZoom = computeSubViewFitZoom(sw, sh, w, h);- subViewStoreActions.updateImageTransform(- item.id,- { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },- true- );- }, []);-- const handleSubRotateBy = useCallback((deltaDeg: number) => {- const item = activeItemRef.current;- if (!item) return;- subViewStoreActions.updateImageTransform(- item.id,- { rotation: liveTransformRef.current.rotation + deltaDeg },- true- );- }, []);-- const handleSubResetRotation = useCallback(() => {- const item = activeItemRef.current;- if (!item) return;- subViewStoreActions.updateImageTransform(item.id, { rotation: 0 }, true);- }, []);-- const handleSubToggleFlipX = useCallback(() => {- const item = activeItemRef.current;- if (!item) return;- subViewStoreActions.updateImageTransform(- item.id,- { flipX: !liveTransformRef.current.flipX },- true- );- }, []);-const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {- // Ignore internal dock tab drag operationsif (e.dataTransfer.types.includes(DND_PANEL_MIME)) return;e.preventDefault();e.stopPropagation();@@ -641,32 +1677,67 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(e.stopPropagation();setIsDragOverFiles(false);if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {- void handleFilesSelected(e.dataTransfer.files);+ void handleFilesSelected(e.dataTransfer.files, { x: e.clientX, y: e.clientY });}};+ const handleArrangeBoard = (layout: SubViewBoardLayoutMode) => {+ subViewStoreActions.arrangeBoard(layout);+ setShowArrangeMenu(false);+ };+const btnBase ='h-5 px-1 rounded-ui-xs text-[10px] flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover disabled:opacity-35 disabled:pointer-events-none transition-colors cursor-pointer';const btnActive ='bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border';- const stageCursorClass = !activeItem?.src- ? 'cursor-default'- : isEyedropperActive- ? 'cursor-crosshair'- : interactionRef.current.mode === 'pan'- ? 'cursor-grabbing'- : 'cursor-grab';+ const stageCursorClass =+ items.length === 0+ ? 'cursor-default'+ : isDraggingSplit+ ? 'cursor-ew-resize'+ : isEyedropperActive+ ? 'cursor-crosshair'+ : activeInteractionKind === 'pan' || activeInteractionKind === 'card-move'+ ? 'cursor-grabbing'+ : viewMode === 'board' && boardTool === 'select'+ ? 'cursor-default'+ : 'cursor-grab';++ const activeTransform =+ viewMode === 'board'+ ? boardTransform+ : activeItem+ ? {+ zoom: activeItem.zoom,+ pan: activeItem.pan,+ rotation: activeItem.rotation,+ flipX: activeItem.flipX,+ }+ : null;++ const hasToneAdjust =+ studyFilter.brightness !== 0 ||+ studyFilter.contrast !== 0 ||+ studyFilter.valueSteps > 0 ||+ sampleDisplayTone;++ const sampledValuePct = sampledHex ? hexToPerceptualValuePercent(sampledHex) : null;+ const isBwActive = studyFilter.grayscale || studyFilter.valueSteps > 0;+ const splitLineLeft = stageSize.width * clampNavigatorSplitRatio(studyFilter.splitRatio);return (<div+ ref={panelRef}+ tabIndex={-1}data-testid="sub-view-panel"+ data-view-mode={viewMode}data-theme-preset={themePreset}onDragOver={handleDragOver}onDragLeave={handleDragLeave}onDrop={handleDrop}- className="flex flex-col h-full min-h-0 select-none relative bg-ui-panel text-ui-primary"+ className="flex flex-col h-full min-h-0 select-none relative bg-ui-panel text-ui-primary focus:outline-none">{/* Hidden Local Image Inputs */}<input@@ -694,7 +1765,7 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(}}/>- {/* Top Bar: Reference Management (+, < >, index, list toggle, delete) */}+ {/* Top Bar: Reference Import / Paste / Cycling + PureRef Board vs Single Switcher + Palette / List / Delete */}<div className="h-6 px-1 flex items-center justify-between gap-1 shrink-0 border-b bg-ui-header border-ui-subtle"><div className="flex items-center gap-0.5 min-w-0"><button@@ -706,13 +1777,22 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(><Plus className="w-3 h-3" /></button>+ <button+ type="button"+ data-testid="subview-paste-btn"+ onClick={() => void handlePasteFromClipboard()}+ title="Paste Reference from Clipboard (Ctrl+V while hovering)"+ className={`${btnBase} w-5 shrink-0`}+ >+ <ClipboardPaste className="w-3 h-3" />+ </button><buttontype="button"data-testid="subview-prev-btn"disabled={items.length <= 1}onClick={() => subViewStoreActions.stepActive(-1)}title="Previous Reference"- className={`${btnBase} w-5 shrink-0`}+ className={`${btnBase} w-4 shrink-0`}><ChevronLeft className="w-3 h-3" /></button>@@ -728,21 +1808,62 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(disabled={items.length <= 1}onClick={() => subViewStoreActions.stepActive(1)}title="Next Reference"- className={`${btnBase} w-5 shrink-0`}+ className={`${btnBase} w-4 shrink-0`}><ChevronRight className="w-3 h-3" /></button></div>- <span- data-testid="subview-active-name"- title={activeItem?.name || ''}- className="text-[10px] text-ui-secondary truncate flex-1 text-center px-1"+ {/* PureRef Board vs Single Focus Mode Toggle */}+ <div+ role="group"+ aria-label="Reference View Mode"+ className="flex items-center rounded-ui-xs bg-ui-input border border-ui-subtle p-[1px] shrink-0">- {activeItem?.name || 'No reference'}- </span>+ <button+ type="button"+ data-testid="subview-mode-board"+ aria-pressed={viewMode === 'board'}+ onClick={() => subViewStoreActions.setViewMode('board')}+ title="PureRef Board Mode (multiple simultaneous references in one zoomable & rotatable area)"+ className={`h-4 px-1 rounded-[2px] text-[9px] flex items-center gap-0.5 transition-colors cursor-pointer ${+ viewMode === 'board'+ ? 'bg-ui-accent-subtle text-ui-accent font-medium'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <LayoutGrid className="w-2.5 h-2.5" />+ <span>Board</span>+ </button>+ <button+ type="button"+ data-testid="subview-mode-single"+ aria-pressed={viewMode === 'single'}+ onClick={() => subViewStoreActions.setViewMode('single')}+ title="Single Focus Mode (cycle one reference at a time)"+ className={`h-4 px-1 rounded-[2px] text-[9px] flex items-center gap-0.5 transition-colors cursor-pointer ${+ viewMode === 'single'+ ? 'bg-ui-accent-subtle text-ui-accent font-medium'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Square className="w-2.5 h-2.5" />+ <span>1×</span>+ </button>+ </div><div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ data-testid="subview-palette-toggle"+ disabled={!activeItem}+ onClick={() => subViewStoreActions.toggleShowPalette()}+ aria-pressed={showPalette}+ title="Extract Dominant Color Palette"+ className={`${btnBase} w-5 ${showPalette && activeItem ? btnActive : ''}`}+ >+ <Palette className="w-3 h-3" />+ </button><buttontype="button"data-testid="subview-list-toggle"@@ -771,7 +1892,7 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo({showList && items.length > 0 && (<divdata-testid="subview-list-drawer"- className="max-h-24 overflow-y-auto shrink-0 border-b px-1 py-0.5 flex flex-col gap-0.5 bg-ui-input border-ui-subtle"+ className="max-h-28 overflow-y-auto shrink-0 border-b px-1 py-0.5 flex flex-col gap-0.5 bg-ui-input border-ui-subtle">{items.map((item, idx) => {const isSelected = item.id === activeItem?.id;@@ -780,7 +1901,11 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(key={item.id}data-testid={`subview-list-item-${item.id}`}onClick={() => subViewStoreActions.selectImage(item.id)}- className={`flex items-center gap-1.5 px-1 py-0.5 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${+ onDoubleClick={() => {+ subViewStoreActions.selectImage(item.id);+ if (viewMode === 'board') handleFitSelectedCard(item.id);+ }}+ className={`flex items-center gap-1 px-1 py-0.5 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${isSelected? 'bg-ui-control-active text-ui-primary': 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'@@ -790,6 +1915,7 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<imgsrc={item.src}alt=""+ style={{ filter: item.grayscale ? 'grayscale(100%)' : undefined }}className="w-4 h-4 object-cover rounded-ui-xs shrink-0 bg-ui-void"/>) : (@@ -797,13 +1923,100 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo({idx + 1}</div>)}- <span className="truncate flex-1">{item.name}</span>- <span className="text-[9px] text-ui-muted font-ui-mono tabular-nums shrink-0">- {item.width}x{item.height}+ <span className="truncate flex-1" title={item.name}>+ {item.name}+ </span>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ subViewStoreActions.updateCardBoardProps(item.id, {+ grayscale: !item.grayscale,+ });+ }}+ title={item.grayscale ? 'Disable Card B/W' : 'Per-Card B/W'}+ className={`px-1 h-4 rounded-ui-xs text-[8.5px] font-ui-mono cursor-pointer ${+ item.grayscale+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ BW+ </button>+ {viewMode === 'board' && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ subViewStoreActions.updateCardBoardProps(item.id, {+ locked: !item.locked,+ });+ }}+ title={item.locked ? 'Unlock Card' : 'Lock Card Position'}+ className={`w-4 h-4 flex items-center justify-center rounded-ui-xs cursor-pointer ${+ item.locked+ ? 'text-ui-warning'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {item.locked ? (+ <Lock className="w-2.5 h-2.5" />+ ) : (+ <Unlock className="w-2.5 h-2.5" />+ )}+ </button>+ )}+ <span className="text-[8.5px] text-ui-muted font-ui-mono tabular-nums shrink-0">+ {item.width}×{item.height}</span></div>);})}+ {items.length > 1 && (+ <div className="flex items-center justify-between pt-0.5 mt-0.5 border-t border-ui-subtle px-0.5">+ <span className="text-[9px] text-ui-muted" data-testid="subview-active-name">+ {activeItem?.name || 'No reference'}+ </span>+ <button+ type="button"+ data-testid="subview-clear-all-btn"+ onClick={() => subViewStoreActions.clearAll()}+ className="text-[9px] text-ui-muted hover:text-ui-danger transition-colors cursor-pointer"+ >+ Clear All+ </button>+ </div>+ )}+ </div>+ )}++ {/* Dominant Color Palette Extractor Strip */}+ {showPalette && activeItem && (+ <div+ data-testid="subview-palette-strip"+ className="shrink-0 px-1.5 py-1 border-b border-ui-subtle bg-ui-input flex items-center gap-1"+ >+ <span className="text-[9px] text-ui-muted shrink-0">Key</span>+ <div className="flex items-center gap-1 flex-1 min-w-0">+ {extractedSwatches.length > 0 ? (+ extractedSwatches.map((sw) => (+ <button+ key={sw.hex}+ type="button"+ data-testid={`subview-palette-swatch-${sw.hex}`}+ onClick={() => {+ setSampledHex(sw.hex);+ toolStoreActions.setPrimaryColor(sw.hex, true, colorMode);+ }}+ title={`${sw.hex.toUpperCase()} · Value ${sw.luminance}% (Click to pick)`}+ style={{ backgroundColor: sw.hex }}+ className="flex-1 h-4 min-w-[14px] rounded-ui-xs border border-ui-strong/60 hover:scale-110 transition-transform cursor-pointer"+ />+ ))+ ) : (+ <span className="text-[9px] text-ui-muted italic">No swatches</span>+ )}+ </div></div>)}@@ -820,7 +2033,8 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(onPointerMove={handleStagePointerMove}onPointerUp={finishStageInteraction}onPointerCancel={finishStageInteraction}- className={`relative flex-1 min-h-[76px] overflow-hidden flex items-center justify-center ${stageCursorClass} ${+ onDoubleClick={handleStageDoubleClick}+ className={`relative flex-1 min-h-[96px] overflow-hidden flex items-center justify-center ${stageCursorClass} ${isDragOverFiles? 'ring-2 ring-inset ring-ui-accent bg-ui-accent-subtle': 'bg-ui-void'@@ -832,21 +2046,444 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(className="absolute inset-0 w-full h-full pointer-events-none"/>- {/* Empty State / Drop Target */}- {!activeItem && (- <button- type="button"- data-testid="subview-empty-dropzone"- onClick={() => fileInputRef.current?.click()}- className="z-10 flex flex-col items-center gap-1 px-3 py-2 rounded-ui-sm border border-dashed border-ui-default hover:border-ui-accent text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"+ {/* Floating Study Bar RIGHT ON TOP OF THE REFERENCE (B/W, Split B/W, Value Notan, Squint, Grid, Tone) */}+ {items.length > 0 && (+ <div+ data-testid="subview-study-overlay"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ onDoubleClick={(e) => e.stopPropagation()}+ className="absolute top-1.5 left-1.5 z-20 flex flex-col items-start gap-1 max-w-[calc(100%-12px)]">- <ImagePlus className="w-4 h-4 opacity-75" />- <span className="text-[10px]">Drop images or click +</span>- </button>+ <div className="flex items-center gap-0.5 px-1 py-0.5 rounded-ui-sm bg-ui-floating/95 backdrop-blur-sm border border-ui-default shadow-ui-floating flex-wrap">+ {/* Primary B/W Perceptual Value Toggle */}+ <button+ type="button"+ data-testid="subview-bw-toggle"+ aria-pressed={isBwActive}+ onClick={() => subViewStoreActions.toggleGrayscale()}+ title="Toggle Perceptual Black & White Value Study (Shortcut: G)"+ className={`h-4 px-1.5 rounded-ui-xs text-[9.5px] font-medium flex items-center gap-1 transition-colors cursor-pointer ${+ isBwActive+ ? 'bg-ui-accent text-ui-accent-contrast'+ : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Contrast className="w-2.5 h-2.5" />+ <span>B/W</span>+ </button>++ {/* Split Color | B/W Curtain Toggle */}+ <button+ type="button"+ data-testid="subview-split-bw-toggle"+ aria-pressed={studyFilter.splitBw}+ onClick={() => subViewStoreActions.toggleSplitBw()}+ title="Split Compare: Color | Perceptual B/W"+ className={`h-4 px-1 rounded-ui-xs text-[9px] flex items-center justify-center transition-colors cursor-pointer ${+ studyFilter.splitBw+ ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Columns2 className="w-2.5 h-2.5" />+ </button>++ {/* Notan / Value Posterize Grouping (Off -> 2V Notan -> 3V -> 5V) */}+ <button+ type="button"+ data-testid="subview-value-steps"+ aria-pressed={studyFilter.valueSteps > 0}+ onClick={() => subViewStoreActions.cycleValueSteps()}+ title="Light & Shape Study Value Grouping (Off → 2-Value Notan → 3-Value → 5-Value)"+ className={`h-4 px-1 rounded-ui-xs text-[9px] font-ui-mono tabular-nums flex items-center justify-center transition-colors cursor-pointer ${+ studyFilter.valueSteps > 0+ ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ {VALUE_STEP_LABELS[studyFilter.valueSteps]}+ </button>++ {/* Squint Blur Toggle */}+ <button+ type="button"+ data-testid="subview-squint-toggle"+ aria-pressed={studyFilter.squintBlur}+ onClick={() => subViewStoreActions.toggleSquintBlur()}+ title="Squint Blur (Simplify fine details to read big shapes & masses)"+ className={`h-4 px-1 rounded-ui-xs text-[9px] flex items-center justify-center transition-colors cursor-pointer ${+ studyFilter.squintBlur+ ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Sparkles className="w-2.5 h-2.5" />+ </button>++ {/* Proportional Measuring Grid Overlay */}+ <button+ type="button"+ data-testid="subview-grid-toggle"+ aria-pressed={studyFilter.gridMode !== 'none'}+ onClick={() => subViewStoreActions.cycleGridMode()}+ title={`Proportional Grid Overlay: ${GRID_MODE_LABELS[studyFilter.gridMode]} (Click to cycle)`}+ className={`h-4 px-1 rounded-ui-xs text-[9px] font-ui-mono flex items-center gap-0.5 transition-colors cursor-pointer ${+ studyFilter.gridMode !== 'none'+ ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Grid3x3 className="w-2.5 h-2.5" />+ {studyFilter.gridMode !== 'none' && (+ <span>{GRID_MODE_LABELS[studyFilter.gridMode]}</span>+ )}+ </button>++ {/* Light / Tone Fine-Tuning Popover Toggle */}+ <button+ type="button"+ data-testid="subview-tone-toggle"+ aria-pressed={showTonePopover || hasToneAdjust}+ onClick={() => setShowTonePopover((p) => !p)}+ title="Light & Shape Study Settings (Notan Threshold, Brightness, Contrast)"+ className={`h-4 w-4 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${+ showTonePopover || hasToneAdjust+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <SlidersHorizontal className="w-2.5 h-2.5" />+ </button>+ </div>++ {/* Light & Shape Study Popover */}+ {showTonePopover && (+ <div+ data-testid="subview-tone-popover"+ className="w-44 p-2 rounded-ui-md bg-ui-elevated/95 backdrop-blur-sm border border-ui-default shadow-ui-popover space-y-1.5 text-[10px]"+ >+ <div className="flex items-center justify-between">+ <span className="text-[9.5px] font-medium text-ui-primary">Light & Shape Study</span>+ <button+ type="button"+ onClick={() => setShowTonePopover(false)}+ className="text-ui-muted hover:text-ui-primary cursor-pointer"+ >+ <X className="w-3 h-3" />+ </button>+ </div>++ {/* Quick Value Step Pills */}+ <div className="flex items-center gap-1">+ {([0, 2, 3, 5] as const).map((steps) => (+ <button+ key={steps}+ type="button"+ onClick={() => subViewStoreActions.setValueSteps(steps)}+ className={`flex-1 h-4 rounded-ui-xs text-[9px] font-ui-mono cursor-pointer transition-colors ${+ studyFilter.valueSteps === steps+ ? 'bg-ui-accent text-ui-accent-contrast font-medium'+ : 'bg-ui-input text-ui-secondary hover:text-ui-primary border border-ui-subtle'+ }`}+ >+ {steps === 0 ? 'Full' : `${steps}V`}+ </button>+ ))}+ </div>++ {studyFilter.valueSteps > 0 && (+ <label className="block space-y-0.5">+ <div className="flex justify-between text-[9px] text-ui-muted">+ <span>Notan Pivot</span>+ <span className="font-ui-mono tabular-nums">{studyFilter.notanThreshold}</span>+ </div>+ <input+ type="range"+ data-testid="subview-notan-slider"+ min={16}+ max={240}+ value={studyFilter.notanThreshold}+ onChange={(e) =>+ subViewStoreActions.updateStudyFilter({+ notanThreshold: Number(e.target.value),+ })+ }+ className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"+ />+ </label>+ )}++ <label className="block space-y-0.5">+ <div className="flex justify-between text-[9px] text-ui-muted">+ <span>Brightness</span>+ <span className="font-ui-mono tabular-nums">+ {studyFilter.brightness > 0+ ? `+${studyFilter.brightness}`+ : studyFilter.brightness}+ </span>+ </div>+ <input+ type="range"+ data-testid="subview-brightness-slider"+ min={-100}+ max={100}+ value={studyFilter.brightness}+ onChange={(e) =>+ subViewStoreActions.updateStudyFilter({+ brightness: Number(e.target.value),+ })+ }+ className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"+ />+ </label>++ <label className="block space-y-0.5">+ <div className="flex justify-between text-[9px] text-ui-muted">+ <span>Contrast</span>+ <span className="font-ui-mono tabular-nums">+ {studyFilter.contrast > 0+ ? `+${studyFilter.contrast}`+ : studyFilter.contrast}+ </span>+ </div>+ <input+ type="range"+ data-testid="subview-contrast-slider"+ min={-100}+ max={100}+ value={studyFilter.contrast}+ onChange={(e) =>+ subViewStoreActions.updateStudyFilter({+ contrast: Number(e.target.value),+ })+ }+ className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"+ />+ </label>++ <div className="flex items-center justify-between pt-0.5 border-t border-ui-subtle">+ <button+ type="button"+ data-testid="subview-sample-tone-toggle"+ onClick={() => subViewStoreActions.toggleSampleDisplayTone()}+ title="When enabled, eyedropper picks the filtered B/W or Notan tone instead of the original color"+ className={`text-[9px] px-1.5 py-0.5 rounded-ui-xs cursor-pointer transition-colors ${+ sampleDisplayTone+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {sampleDisplayTone ? 'Pick: Study Tone' : 'Pick: Original'}+ </button>+ <button+ type="button"+ data-testid="subview-reset-study-btn"+ onClick={() => subViewStoreActions.resetStudyFilter()}+ className="text-[9px] text-ui-muted hover:text-ui-primary cursor-pointer"+ >+ Reset+ </button>+ </div>+ </div>+ )}+ </div>+ )}++ {/* Split Color | B/W Draggable Divider Handle */}+ {items.length > 0 && studyFilter.splitBw && (+ <>+ <span className="pointer-events-none absolute bottom-1.5 left-1.5 z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase text-ui-primary">+ CLR+ </span>+ <span className="pointer-events-none absolute bottom-1.5 right-1.5 z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase text-ui-primary">+ B/W+ </span>+ <div+ role="slider"+ tabIndex={0}+ data-testid="subview-split-handle"+ aria-label="Reference Color and B/W Split Position"+ aria-valuemin={5}+ aria-valuemax={95}+ aria-valuenow={Math.round(studyFilter.splitRatio * 100)}+ onPointerDown={handleSplitPointerDown}+ onPointerMove={handleSplitPointerMove}+ onPointerUp={finishSplitDrag}+ onPointerCancel={finishSplitDrag}+ onDoubleClick={(e) => {+ e.stopPropagation();+ subViewStoreActions.updateStudyFilter({ splitRatio: 0.5 }, true);+ }}+ style={{ left: `${splitLineLeft}px` }}+ title="Drag to compare Color | B/W (Double-click to center)"+ className="absolute top-0 bottom-0 z-20 w-3 -ml-1.5 flex items-center justify-center cursor-ew-resize group"+ >+ <div className="w-[1.5px] h-full bg-white/85 shadow-[0_0_2px_rgba(0,0,0,0.85)] group-hover:bg-ui-accent transition-colors" />+ <div className="absolute w-3.5 h-3.5 rounded-full bg-ui-floating border border-ui-strong shadow-ui-floating flex items-center justify-center">+ <Columns2 className="w-2 h-2 text-ui-primary" />+ </div>+ </div>+ </>+ )}++ {/* PureRef Selected Card Quick Floating Micro-Toolbar */}+ {viewMode === 'board' && activeItem && !studyFilter.splitBw && (+ <div+ data-testid="subview-card-toolbar"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ onDoubleClick={(e) => e.stopPropagation()}+ className="absolute bottom-1.5 left-1.5 z-20 flex items-center gap-0.5 px-1 py-0.5 rounded-ui-sm bg-ui-floating/90 backdrop-blur-sm border border-ui-default shadow-ui-floating max-w-[calc(100%-12px)]"+ >+ <button+ type="button"+ data-testid="subview-card-bw-toggle"+ aria-pressed={activeItem.grayscale}+ onClick={() =>+ subViewStoreActions.updateCardBoardProps(activeItem.id, {+ grayscale: !activeItem.grayscale,+ })+ }+ title="Toggle Per-Card B/W (independent of other references)"+ className={`h-4 px-1 rounded-ui-xs text-[8.5px] font-ui-mono cursor-pointer transition-colors ${+ activeItem.grayscale+ ? 'bg-ui-accent text-ui-accent-contrast font-medium'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ BW+ </button>+ <button+ type="button"+ data-testid="subview-card-flip-h"+ aria-pressed={activeItem.boardFlipX}+ onClick={() =>+ subViewStoreActions.updateCardBoardProps(activeItem.id, {+ boardFlipX: !activeItem.boardFlipX,+ })+ }+ title="Flip Selected Reference Horizontally"+ className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ activeItem.boardFlipX+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <FlipHorizontal className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid="subview-card-flip-v"+ aria-pressed={activeItem.boardFlipY}+ onClick={() =>+ subViewStoreActions.updateCardBoardProps(activeItem.id, {+ boardFlipY: !activeItem.boardFlipY,+ })+ }+ title="Flip Selected Reference Vertically"+ className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ activeItem.boardFlipY+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <FlipVertical className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid="subview-card-opacity"+ onClick={() => {+ const nextOp =+ activeItem.opacity > 0.85 ? 0.65 : activeItem.opacity > 0.45 ? 0.35 : 1;+ subViewStoreActions.updateCardBoardProps(activeItem.id, { opacity: nextOp });+ }}+ title={`Card Opacity: ${Math.round(activeItem.opacity * 100)}% (Click to cycle)`}+ className="h-4 px-1 rounded-ui-xs text-[8.5px] font-ui-mono tabular-nums text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ {`${Math.round(activeItem.opacity * 100)}%`}+ </button>+ <button+ type="button"+ data-testid="subview-card-front"+ onClick={() => subViewStoreActions.bringCardToFront(activeItem.id)}+ title="Bring Card to Front"+ className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ <BringToFront className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid="subview-card-back"+ onClick={() => subViewStoreActions.sendCardToBack(activeItem.id)}+ title="Send Card to Back"+ className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ <SendToBack className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid="subview-card-duplicate"+ onClick={() => subViewStoreActions.duplicateCard(activeItem.id)}+ title="Duplicate Reference Card"+ className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ <Copy className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ data-testid="subview-card-lock"+ aria-pressed={activeItem.locked}+ onClick={() =>+ subViewStoreActions.updateCardBoardProps(activeItem.id, {+ locked: !activeItem.locked,+ })+ }+ title={activeItem.locked ? 'Unlock Card' : 'Lock Card'}+ className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ activeItem.locked+ ? 'text-ui-warning bg-ui-warning/15'+ : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ {activeItem.locked ? (+ <Lock className="w-2.5 h-2.5" />+ ) : (+ <Unlock className="w-2.5 h-2.5" />+ )}+ </button>+ <button+ type="button"+ data-testid="subview-card-focus"+ onClick={() => handleFitSelectedCard(activeItem.id)}+ title="Focus / Fit Selected Card"+ className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ <Focus className="w-2.5 h-2.5" />+ </button>+ </div>+ )}++ {/* Empty State / Drop Target */}+ {items.length === 0 && (+ <div className="z-10 flex flex-col items-center gap-1.5 px-3 text-center">+ <button+ type="button"+ data-testid="subview-empty-dropzone"+ onClick={() => fileInputRef.current?.click()}+ className="flex flex-col items-center gap-1 px-3 py-2 rounded-ui-sm border border-dashed border-ui-default hover:border-ui-accent text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"+ >+ <ImagePlus className="w-4 h-4 opacity-75" />+ <span className="text-[10px]">Drop images, click +, or Ctrl+V</span>+ </button>+ <span className="text-[9px] text-ui-muted/80">+ PureRef Board · Multi-ref · B/W & Notan Study+ </span>+ </div>)}- {/* Persisted Metadata-Only Slot (image exceeded localStorage budget) */}- {activeItem && !activeItem.src && (+ {/* Persisted Metadata-Only Slot (Single mode) */}+ {viewMode === 'single' && activeItem && !activeItem.src && (<div className="z-10 flex flex-col items-center gap-1 px-2 text-center"><span className="text-[10px] text-ui-secondary">{activeItem.name} (reload file)@@ -864,36 +2501,50 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo({/* Error Pill */}{loadError && (- <div className="absolute bottom-1 left-1 right-1 z-20 px-1.5 py-0.5 rounded-ui-xs bg-ui-elevated border border-ui-danger/50 text-[9px] text-ui-danger truncate">- {loadError}+ <div className="absolute bottom-7 left-1.5 right-1.5 z-30 px-1.5 py-0.5 rounded-ui-xs bg-ui-elevated border border-ui-danger/50 text-[9px] text-ui-danger flex items-center justify-between gap-1">+ <span className="truncate">{loadError}</span>+ <button+ type="button"+ onClick={() => setLoadError(null)}+ className="shrink-0 hover:text-ui-primary cursor-pointer"+ >+ <X className="w-2.5 h-2.5" />+ </button></div>)}- {/* Live Sampled Color Swatch Pill */}+ {/* Live Sampled Color Swatch Pill (with Perceptual Value %) */}{sampledHex && (<divdata-testid="subview-sampled-pill"- className="absolute top-1 right-1 z-20 px-1.5 py-0.5 rounded-ui-sm bg-ui-floating border border-ui-default flex items-center gap-1 pointer-events-none shadow-ui-floating"+ className="absolute top-1.5 right-1.5 z-20 px-1.5 py-0.5 rounded-ui-sm bg-ui-floating border border-ui-default flex items-center gap-1 pointer-events-none shadow-ui-floating"><spanclassName="w-2.5 h-2.5 rounded-ui-xs border border-ui-strong shrink-0"style={{ backgroundColor: sampledHex }}/>- <span className="text-[9px] font-ui-mono tabular-nums text-ui-primary uppercase">{sampledHex}</span>+ <span className="text-[9px] font-ui-mono tabular-nums text-ui-primary uppercase">+ {sampledHex}+ </span>+ {sampledValuePct !== null && (+ <span className="text-[8.5px] font-ui-mono tabular-nums text-ui-muted">+ V{sampledValuePct}+ </span>+ )}</div>)}</div>- {/* Bottom Compact Control Bar (Strictly Local Sub View Transforms + Eyedropper Mode) */}- <div className="shrink-0 px-1.5 py-1 flex items-center justify-between gap-0.5 flex-wrap border-t bg-ui-header border-ui-subtle">- {/* Zoom + Fit */}+ {/* Bottom Compact Control Bar (Strictly Local Viewport Transforms + Auto-Arrange + Tools) */}+ <div className="shrink-0 px-1.5 py-1 flex items-center justify-between gap-0.5 flex-wrap border-t bg-ui-header border-ui-subtle relative">+ {/* Zoom + Fit + Auto-Arrange (Board mode) */}<div className="flex items-center gap-0.5"><buttontype="button"data-testid="subview-zoom-out"- disabled={!activeItem}+ disabled={items.length === 0}onClick={() => handleSubZoomBy(1 / 1.25)}- title="Sub View Zoom Out"+ title="References Zoom Out"className={`${btnBase} w-5`}><ZoomOut className="w-3 h-3" />@@ -901,9 +2552,9 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<buttontype="button"data-testid="subview-zoom-in"- disabled={!activeItem}+ disabled={items.length === 0}onClick={() => handleSubZoomBy(1.25)}- title="Sub View Zoom In"+ title="References Zoom In"className={`${btnBase} w-5`}><ZoomIn className="w-3 h-3" />@@ -911,13 +2562,66 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<buttontype="button"data-testid="subview-fit"- disabled={!activeItem}+ disabled={items.length === 0}onClick={handleSubFit}- title="Reset Sub View (Fit, 0°, Unflip)"+ title={+ viewMode === 'board'+ ? 'Fit All References & Reset Board View (Shortcut: F)'+ : 'Reset Reference View (Fit, 0°, Unflip)'+ }className={`${btnBase} w-5`}><Maximize className="w-3 h-3" /></button>++ {viewMode === 'board' && (+ <div className="relative">+ <button+ type="button"+ data-testid="subview-arrange-btn"+ disabled={items.length === 0}+ onClick={() => setShowArrangeMenu((p) => !p)}+ title="Auto-Arrange PureRef Board (Pack Grid, Row, Column)"+ className={`${btnBase} w-5 ${showArrangeMenu ? btnActive : ''}`}+ >+ <LayoutGrid className="w-3 h-3" />+ </button>+ {showArrangeMenu && (+ <div+ data-testid="subview-arrange-menu"+ className="absolute bottom-6 left-0 z-30 min-w-28 p-1 rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover flex flex-col gap-0.5 text-[10px]"+ >+ <button+ type="button"+ data-testid="subview-arrange-grid"+ onClick={() => handleArrangeBoard('grid')}+ className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"+ >+ <LayoutGrid className="w-3 h-3 text-ui-icon-muted" />+ <span>Pack Grid</span>+ </button>+ <button+ type="button"+ data-testid="subview-arrange-row"+ onClick={() => handleArrangeBoard('row')}+ className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"+ >+ <Columns3 className="w-3 h-3 text-ui-icon-muted" />+ <span>Horizontal Strip</span>+ </button>+ <button+ type="button"+ data-testid="subview-arrange-column"+ onClick={() => handleArrangeBoard('column')}+ className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"+ >+ <Rows3 className="w-3 h-3 text-ui-icon-muted" />+ <span>Vertical Stack</span>+ </button>+ </div>+ )}+ </div>+ )}</div>{/* Rotate + Flip H */}@@ -925,9 +2629,9 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<buttontype="button"data-testid="subview-rotate-left"- disabled={!activeItem}+ disabled={items.length === 0}onClick={() => handleSubRotateBy(-15)}- title="Sub View Rotate Left (-15°)"+ title="Rotate Left (-15°, or Shift+Wheel)"className={`${btnBase} w-5`}><RotateCcw className="w-3 h-3" />@@ -935,19 +2639,19 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<buttontype="button"data-testid="subview-reset-rotation"- disabled={!activeItem}+ disabled={items.length === 0}onClick={handleSubResetRotation}- title="Reset Sub View Rotation (0°)"+ title="Reset Rotation (0°)"className={`${btnBase} px-1 font-ui-mono tabular-nums`}>- {`${Math.round(activeItem?.rotation ?? 0)}°`}+ {`${Math.round(activeTransform?.rotation ?? 0)}°`}</button><buttontype="button"data-testid="subview-rotate-right"- disabled={!activeItem}+ disabled={items.length === 0}onClick={() => handleSubRotateBy(15)}- title="Sub View Rotate Right (+15°)"+ title="Rotate Right (+15°, or Shift+Wheel)"className={`${btnBase} w-5`}><RotateCw className="w-3 h-3" />@@ -955,40 +2659,88 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(<buttontype="button"data-testid="subview-flip-h"- disabled={!activeItem}- aria-pressed={Boolean(activeItem?.flipX)}+ disabled={items.length === 0}+ aria-pressed={Boolean(activeTransform?.flipX)}onClick={handleSubToggleFlipX}- title="Sub View Flip Horizontal"- className={`${btnBase} w-5 ${activeItem?.flipX ? btnActive : ''}`}+ title="Flip View Horizontally (Shortcut: H)"+ className={`${btnBase} w-5 ${activeTransform?.flipX ? btnActive : ''}`}><FlipHorizontal className="w-3 h-3" /></button></div>- {/* Eyedropper / Pan Mode Controls */}+ {/* Tool Controls: Board (Arrange / Pan / Eyedropper) vs Single (Auto Eyedropper / Pan) */}<div className="flex items-center gap-0.5">- <button- type="button"- data-testid="subview-auto-eyedropper"- aria-pressed={autoEyedropper}- onClick={() => subViewStoreActions.toggleAutoEyedropper()}- title="Switch to Eyedropper Automatically on Hover/Click (CSP mode)"- className={`${btnBase} gap-0.5 px-1 ${autoEyedropper ? btnActive : ''}`}- >- <Pipette className="w-3 h-3" />- <span>Auto</span>- </button>- {!autoEyedropper && (- <button- type="button"- data-testid="subview-mode-toggle"- aria-pressed={manualEyedropper}- onClick={() => subViewStoreActions.setManualEyedropper(!manualEyedropper)}- title={manualEyedropper ? 'Eyedropper Active (click for Pan)' : 'Pan Active (click for Eyedropper)'}- className={`${btnBase} w-5 ${manualEyedropper ? btnActive : ''}`}- >- {manualEyedropper ? <Pipette className="w-3 h-3" /> : <Hand className="w-3 h-3" />}- </button>+ {viewMode === 'board' ? (+ <>+ <button+ type="button"+ data-testid="subview-tool-select"+ aria-pressed={boardTool === 'select'}+ onClick={() => subViewStoreActions.setBoardTool('select')}+ title="Arrange Cards (Drag cards to move, drag corners to resize, top handle to rotate; drag empty space to pan)"+ className={`${btnBase} w-5 ${boardTool === 'select' ? btnActive : ''}`}+ >+ <MousePointer2 className="w-3 h-3" />+ </button>+ <button+ type="button"+ data-testid="subview-tool-pan"+ aria-pressed={boardTool === 'pan'}+ onClick={() => subViewStoreActions.setBoardTool('pan')}+ title="Pan Board (or hold Space / Middle-click anywhere)"+ className={`${btnBase} w-5 ${boardTool === 'pan' ? btnActive : ''}`}+ >+ <Hand className="w-3 h-3" />+ </button>+ <button+ type="button"+ data-testid="subview-auto-eyedropper"+ aria-pressed={boardTool === 'eyedrop'}+ onClick={() =>+ subViewStoreActions.setBoardTool(boardTool === 'eyedrop' ? 'select' : 'eyedrop')+ }+ title="Eyedropper Mode (Click any reference to pick color; Alt+Click works from any tool)"+ className={`${btnBase} gap-0.5 px-1 ${boardTool === 'eyedrop' ? btnActive : ''}`}+ >+ <Pipette className="w-3 h-3" />+ <span>Pick</span>+ </button>+ </>+ ) : (+ <>+ <button+ type="button"+ data-testid="subview-auto-eyedropper"+ aria-pressed={autoEyedropper}+ onClick={() => subViewStoreActions.toggleAutoEyedropper()}+ title="Switch to Eyedropper Automatically on Hover/Click (CSP mode)"+ className={`${btnBase} gap-0.5 px-1 ${autoEyedropper ? btnActive : ''}`}+ >+ <Pipette className="w-3 h-3" />+ <span>Auto</span>+ </button>+ {!autoEyedropper && (+ <button+ type="button"+ data-testid="subview-mode-toggle"+ aria-pressed={manualEyedropper}+ onClick={() => subViewStoreActions.setManualEyedropper(!manualEyedropper)}+ title={+ manualEyedropper+ ? 'Eyedropper Active (click for Pan)'+ : 'Pan Active (click for Eyedropper)'+ }+ className={`${btnBase} w-5 ${manualEyedropper ? btnActive : ''}`}+ >+ {manualEyedropper ? (+ <Pipette className="w-3 h-3" />+ ) : (+ <Hand className="w-3 h-3" />+ )}+ </button>+ )}+ </>)}</div></div>diff --git a/src/components/TextEditorOverlay.tsx b/src/components/TextEditorOverlay.tsxindex 19d0b1a..109893c 100644--- a/src/components/TextEditorOverlay.tsx+++ b/src/components/TextEditorOverlay.tsx@@ -1,17 +1,38 @@-import React, { useRef, useState } from 'react';-import { TextSettings } from '../types/editor';+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {- Bold,- Italic,- AlignLeft,AlignCenter,+ AlignLeft,AlignRight,+ Bold,+ Check,+ GripVertical,+ Italic,+ Minus,+ Move,+ Pipette,+ Plus,+ RotateCcw,+ SlidersHorizontal,+ Trash2,+ Underline,+ X,} from 'lucide-react';+import { TextSettings } from '../types/editor';+import { computeMangaTextLayout, renderMangaTextToCanvas } from '../utils/mangaTextEngine';+import {+ DEFAULT_TEXT_SETTINGS,+ getTextFontOptions,+ queryInstalledSystemFonts,+ TEXT_FONT_PRESETS,+ TEXT_QUICK_COLORS,+} from '../utils/textSettings';interface TextEditorOverlayProps {x: number;y: number;settings: TextSettings;+ editingLayerId?: string | null;+ primaryColor?: string;zoom: number;rotation?: number;flipX?: boolean;@@ -20,22 +41,17 @@ interface TextEditorOverlayProps {onMove: (newX: number, newY: number) => void;onConfirm: () => void;onCancel: () => void;+ onDelete?: () => void;}-export const MANGA_FONTS = [- { id: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif", label: 'Manga / Anime (RU/EN)' },- { id: "'Anime Ace', 'Comic Sans MS', sans-serif", label: 'Anime Ace (Comic)' },- { id: "'Comic Sans MS', cursive, sans-serif", label: 'Comic Sans MS' },- { id: 'Arial, sans-serif', label: 'Arial' },- { id: 'Impact, sans-serif', label: 'Impact' },- { id: "'Times New Roman', serif", label: 'Times New Roman' },- { id: 'Georgia, serif', label: 'Georgia' },-];+export const MANGA_FONTS = TEXT_FONT_PRESETS.map((f) => ({ id: f.value, label: f.label }));export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({x,y,settings,+ editingLayerId = null,+ primaryColor,zoom,rotation = 0,flipX = false,@@ -44,54 +60,366 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({onMove,onConfirm,onCancel,+ onDelete,}) => {- const isDraggingRef = useRef(false);- const dragStartRef = useRef<{ clientX: number; clientY: number; initX: number; initY: number }>({+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);+ const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);++ const [showMoreStyle, setShowMoreStyle] = useState(false);+ const [showColorPopover, setShowColorPopover] = useState(false);+ const [systemFonts, setSystemFonts] = useState<string[]>([]);+ const [fontSizeInput, setFontSizeInput] = useState<string>(String(settings.fontSize));++ const isVertical = settings.writingMode === 'vertical-rl';+ const safeZoom = zoom > 0.05 ? zoom : 1;+ const invScaleX = (flipX ? -1 : 1) / safeZoom;+ const invScaleY = (flipY ? -1 : 1) / safeZoom;++ useEffect(() => {+ setFontSizeInput(String(settings.fontSize));+ }, [settings.fontSize]);++ // Focus textarea when opening or switching writing modes+ useEffect(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.focus();+ const len = el.value.length;+ try {+ el.setSelectionRange(len, len);+ } catch {+ // ignore in non-browser test environments+ }+ }, [editingLayerId, isVertical]);++ const handleLoadSystemFonts = useCallback(() => {+ if (systemFonts.length > 0) return;+ void queryInstalledSystemFonts().then((fonts) => {+ if (fonts.length > 0) setSystemFonts(fonts);+ });+ }, [systemFonts.length]);++ const fontOptions = useMemo(+ () => getTextFontOptions(settings.fontFamily, systemFonts),+ [settings.fontFamily, systemFonts]+ );++ // Compute exact layout matching committed canvas output 1:1+ const layout = useMemo(() => {+ const sampleText = settings.text || ' ';+ return computeMangaTextLayout(sampleText, {+ fontSize: settings.fontSize,+ fontFamily: settings.fontFamily,+ writingMode: settings.writingMode || 'horizontal-tb',+ bold: settings.bold,+ italic: settings.italic,+ underline: settings.underline,+ align: settings.align,+ lineHeightRatio: settings.lineSpacing,+ letterSpacing: settings.letterSpacing,+ maxWidth: settings.maxWidth,+ anchorTopLeft: true,+ });+ }, [+ settings.text,+ settings.fontSize,+ settings.fontFamily,+ settings.writingMode,+ settings.bold,+ settings.italic,+ settings.underline,+ settings.align,+ settings.lineSpacing,+ settings.letterSpacing,+ settings.maxWidth,+ ]);++ const boxWidth = Math.max(+ settings.maxWidth ?? 0,+ Math.ceil(layout.width),+ Math.ceil(settings.fontSize * 3.5),+ 72+ );+ const boxHeight = Math.max(Math.ceil(layout.height), Math.ceil(settings.fontSize * 1.25), 28);++ const canvasPad = useMemo(() => {+ const outlinePad = settings.outline ? (settings.outlineWidth || 3) * 3 : 0;+ return Math.ceil(Math.max(16, outlinePad + settings.fontSize * 0.45));+ }, [settings.outline, settings.outlineWidth, settings.fontSize]);++ // Render live pixel-exact canvas preview using the exact same renderer as committed text layers+ useEffect(() => {+ const canvas = previewCanvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;++ const cssW = boxWidth + canvasPad * 2;+ const cssH = boxHeight + canvasPad * 2;+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;+ const renderScale = Math.max(1, Math.min(3, dpr * Math.min(2, safeZoom)));+ const pixelW = Math.max(1, Math.round(cssW * renderScale));+ const pixelH = Math.max(1, Math.round(cssH * renderScale));++ if (canvas.width !== pixelW || canvas.height !== pixelH) {+ canvas.width = pixelW;+ canvas.height = pixelH;+ }++ ctx.save();+ ctx.setTransform(renderScale, 0, 0, renderScale, 0, 0);+ ctx.clearRect(0, 0, cssW, cssH);++ if (settings.text && settings.text.trim()) {+ renderMangaTextToCanvas(ctx, settings.text, canvasPad, canvasPad, {+ fontSize: settings.fontSize,+ fontFamily: settings.fontFamily,+ writingMode: settings.writingMode || 'horizontal-tb',+ bold: settings.bold,+ italic: settings.italic,+ underline: settings.underline,+ align: settings.align,+ color: settings.color,+ outline: settings.outline,+ outlineColor: settings.outlineColor,+ outlineWidth: settings.outlineWidth,+ lineHeightRatio: settings.lineSpacing,+ letterSpacing: settings.letterSpacing,+ opacity: settings.opacity,+ maxWidth: settings.maxWidth ?? boxWidth,+ anchorTopLeft: true,+ });+ }+ ctx.restore();+ }, [+ boxWidth,+ boxHeight,+ canvasPad,+ safeZoom,+ settings.text,+ settings.fontSize,+ settings.fontFamily,+ settings.writingMode,+ settings.bold,+ settings.italic,+ settings.underline,+ settings.align,+ settings.color,+ settings.outline,+ settings.outlineColor,+ settings.outlineWidth,+ settings.lineSpacing,+ settings.letterSpacing,+ settings.opacity,+ settings.maxWidth,+ ]);++ // Convert screen pointer delta to canvas delta accounting for zoom, rotation, flipX/Y+ const screenDeltaToCanvas = useCallback(+ (dxScreen: number, dyScreen: number) => {+ const rad = (-rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ return {+ dx: ((dxScreen * cos - dyScreen * sin) * (flipX ? -1 : 1)) / safeZoom,+ dy: ((dxScreen * sin + dyScreen * cos) * (flipY ? -1 : 1)) / safeZoom,+ };+ },+ [rotation, flipX, flipY, safeZoom]+ );++ // Move drag state+ const dragModeRef = useRef<'none' | 'move' | 'resize-width' | 'scale-font'>('none');+ const dragStartRef = useRef({clientX: 0,clientY: 0,initX: x,initY: y,+ initWidth: boxWidth,+ initFontSize: settings.fontSize,});- const [activeTab, setActiveTab] = useState<'text' | 'style'>('text');-- const handleDragDown = (e: React.PointerEvent) => {- e.stopPropagation();- (e.target as HTMLElement).setPointerCapture(e.pointerId);- isDraggingRef.current = true;- dragStartRef.current = {- clientX: e.clientX,- clientY: e.clientY,- initX: x,- initY: y,- };- };-- const handleDragMove = (e: React.PointerEvent) => {- if (!isDraggingRef.current) return;- const dxScreen = e.clientX - dragStartRef.current.clientX;- const dyScreen = e.clientY - dragStartRef.current.clientY;- const rad = (-rotation * Math.PI) / 180;- const cos = Math.cos(rad);- const sin = Math.sin(rad);- const dx = ((dxScreen * cos - dyScreen * sin) * (flipX ? -1 : 1)) / zoom;- const dy = ((dxScreen * sin + dyScreen * cos) * (flipY ? -1 : 1)) / zoom;- onMove(Math.round(dragStartRef.current.initX + dx), Math.round(dragStartRef.current.initY + dy));- };-- const handleDragUp = (e: React.PointerEvent) => {- if (isDraggingRef.current) {+ const startDrag = useCallback(+ (mode: 'move' | 'resize-width' | 'scale-font', e: React.PointerEvent) => {+ e.stopPropagation();+ e.preventDefault();try {- (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);} catch {- // ignore+ // ignore synthetic events+ }+ dragModeRef.current = mode;+ dragStartRef.current = {+ clientX: e.clientX,+ clientY: e.clientY,+ initX: x,+ initY: y,+ initWidth: settings.maxWidth ?? boxWidth,+ initFontSize: settings.fontSize,+ };+ },+ [x, y, settings.maxWidth, boxWidth, settings.fontSize]+ );++ const handleDragMove = useCallback(+ (e: React.PointerEvent) => {+ const mode = dragModeRef.current;+ if (mode === 'none') return;+ e.stopPropagation();+ const { dx, dy } = screenDeltaToCanvas(+ e.clientX - dragStartRef.current.clientX,+ e.clientY - dragStartRef.current.clientY+ );++ if (mode === 'move') {+ onMove(+ Math.round(dragStartRef.current.initX + dx),+ Math.round(dragStartRef.current.initY + dy)+ );+ } else if (mode === 'resize-width') {+ const nextW = Math.max(48, Math.round(dragStartRef.current.initWidth + dx));+ onUpdateSettings((prev) => ({ ...prev, maxWidth: nextW }));+ } else if (mode === 'scale-font') {+ const delta = Math.abs(dy) > Math.abs(dx) ? dy : dx;+ const scaleFactor = Math.max(0.25, 1 + delta / Math.max(60, dragStartRef.current.initFontSize * 2));+ const nextSize = Math.max(+ 6,+ Math.min(400, Math.round(dragStartRef.current.initFontSize * scaleFactor))+ );+ onUpdateSettings((prev) => ({ ...prev, fontSize: nextSize }));+ }+ },+ [screenDeltaToCanvas, onMove, onUpdateSettings]+ );++ const handleDragUp = useCallback((e: React.PointerEvent) => {+ if (dragModeRef.current === 'none') return;+ e.stopPropagation();+ try {+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);+ } catch {+ // ignore+ }+ dragModeRef.current = 'none';+ }, []);++ const stepFontSize = useCallback(+ (delta: number) => {+ onUpdateSettings((prev) => ({+ ...prev,+ fontSize: Math.max(6, Math.min(400, Math.round((prev.fontSize || 36) + delta))),+ }));+ },+ [onUpdateSettings]+ );++ const handleEditorKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ // Stop propagation so global canvas shortcuts never fire while typing+ e.stopPropagation();++ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {+ e.preventDefault();+ onConfirm();+ return;}- isDraggingRef.current = false;+ if (e.key === 'Escape') {+ e.preventDefault();+ onCancel();+ return;+ }++ // Rich formatting shortcuts+ if (e.ctrlKey || e.metaKey) {+ const k = e.key.toLowerCase();+ if (k === 'b') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }));+ return;+ }+ if (k === 'i') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }));+ return;+ }+ if (k === 'u') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, underline: !prev.underline }));+ return;+ }+ if (e.key === ']' || (e.shiftKey && e.key === '>')) {+ e.preventDefault();+ stepFontSize(e.shiftKey ? 4 : 2);+ return;+ }+ if (e.key === '[' || (e.shiftKey && e.key === '<')) {+ e.preventDefault();+ stepFontSize(e.shiftKey ? -4 : -2);+ return;+ }+ if (e.shiftKey && k === 'l') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, align: 'left' }));+ return;+ }+ if (e.shiftKey && k === 'e') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, align: 'center' }));+ return;+ }+ if (e.shiftKey && k === 'r') {+ e.preventDefault();+ onUpdateSettings((prev) => ({ ...prev, align: 'right' }));+ return;+ }+ }++ // Alt + Arrow key nudging+ if (e.altKey && !e.ctrlKey && !e.metaKey) {+ const step = e.shiftKey ? 10 : 1;+ if (e.key === 'ArrowLeft') {+ e.preventDefault();+ onMove(x - step, y);+ } else if (e.key === 'ArrowRight') {+ e.preventDefault();+ onMove(x + step, y);+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ onMove(x, y - step);+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ onMove(x, y + step);+ }+ }+ },+ [onConfirm, onCancel, onUpdateSettings, stepFontSize, onMove, x, y]+ );++ const commitFontSizeInput = useCallback(() => {+ const parsed = parseInt(fontSizeInput, 10);+ if (Number.isFinite(parsed)) {+ const clamped = Math.max(6, Math.min(400, parsed));+ onUpdateSettings((prev) => ({ ...prev, fontSize: clamped }));+ setFontSizeInput(String(clamped));+ } else {+ setFontSizeInput(String(settings.fontSize));}- };+ }, [fontSizeInput, onUpdateSettings, settings.fontSize]);++ const handleResetToStandard = useCallback(() => {+ onUpdateSettings((prev) => ({+ ...DEFAULT_TEXT_SETTINGS,+ text: prev.text,+ maxWidth: prev.maxWidth ?? null,+ }));+ }, [onUpdateSettings]);++ const borderPx = Math.max(1, 1.25 / safeZoom);+ const handleSize = Math.max(7, 9 / safeZoom);return (<div+ data-testid="text-editor-overlay"className="absolute z-40 pointer-events-auto select-none"style={{left: `${x}px`,@@ -99,303 +427,640 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({}}onPointerDown={(e) => e.stopPropagation()}>- {/* Live Text Preview on Canvas */}+ {/* Direct On-Canvas WYSIWYG Text Bounding Box */}<div- className="pointer-events-none mb-2 border border-dashed border-cyan-400/60 p-1.5 min-w-[120px] bg-black/10 rounded"+ className="relative"style={{- fontFamily: settings.fontFamily,- fontSize: `${settings.fontSize}px`,- fontWeight: settings.bold ? 'bold' : 'normal',- fontStyle: settings.italic ? 'italic' : 'normal',- textAlign: settings.align,- color: settings.color,- lineHeight: settings.lineSpacing ?? 1.25,- writingMode: settings.writingMode === 'vertical-rl' ? 'vertical-rl' : 'horizontal-tb',- textOrientation: 'mixed',- textShadow: settings.outline- ? `- -${settings.outlineWidth}px -${settings.outlineWidth}px 0 ${settings.outlineColor},- ${settings.outlineWidth}px -${settings.outlineWidth}px 0 ${settings.outlineColor},- -${settings.outlineWidth}px ${settings.outlineWidth}px 0 ${settings.outlineColor},- ${settings.outlineWidth}px ${settings.outlineWidth}px 0 ${settings.outlineColor}- `- : 'none',- whiteSpace: 'pre-wrap',+ width: `${boxWidth}px`,+ height: `${boxHeight}px`,}}>- {settings.text || <span className="opacity-40 italic">Type manga text here...</span>}+ {/* Pixel-exact Canvas Renderer (1:1 parity with committed layer) */}+ <canvas+ ref={previewCanvasRef}+ data-testid="text-live-preview-canvas"+ className="pointer-events-none absolute"+ style={{+ left: `${-canvasPad}px`,+ top: `${-canvasPad}px`,+ width: `${boxWidth + canvasPad * 2}px`,+ height: `${boxHeight + canvasPad * 2}px`,+ }}+ />++ {/* Crisp Zoom-Compensated Dashed Bounding Frame */}+ <div+ className="pointer-events-none absolute inset-0 rounded-[2px]"+ style={{+ outline: `${borderPx}px dashed rgba(56, 189, 248, 0.85)`,+ outlineOffset: `${Math.max(2, 3 / safeZoom)}px`,+ boxShadow: `0 0 0 ${borderPx}px rgba(0, 0, 0, 0.35)`,+ }}+ />++ {/* Subtle Placeholder when Empty */}+ {!settings.text && (+ <div+ className="pointer-events-none absolute inset-0 overflow-hidden"+ style={{+ fontFamily: settings.fontFamily,+ fontSize: `${settings.fontSize}px`,+ fontWeight: settings.bold ? 700 : 400,+ fontStyle: settings.italic ? 'italic' : 'normal',+ lineHeight: `${layout.lineHeight}px`,+ letterSpacing: settings.letterSpacing ? `${settings.letterSpacing}px` : undefined,+ textAlign: settings.align,+ color: settings.color || '#ffffff',+ opacity: 0.42,+ whiteSpace: 'nowrap',+ }}+ >+ Type text...+ </div>+ )}++ {/* Direct Transparent On-Canvas Input for Horizontal Mode (Alt+Drag moves box) */}+ {!isVertical && (+ <textarea+ ref={textareaRef}+ data-testid="text-editor-textarea"+ aria-label="Canvas text input"+ value={settings.text}+ onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}+ onKeyDown={handleEditorKeyDown}+ onPointerDown={(e) => {+ e.stopPropagation();+ if (e.altKey) {+ startDrag('move', e);+ }+ }}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ spellCheck={false}+ className="absolute inset-0 w-full h-full bg-transparent outline-none border-0 p-0 m-0 resize-none overflow-hidden select-text selection:bg-sky-400/35"+ style={{+ fontFamily: settings.fontFamily,+ fontSize: `${settings.fontSize}px`,+ fontWeight: settings.bold ? 700 : 400,+ fontStyle: settings.italic ? 'italic' : 'normal',+ lineHeight: `${layout.lineHeight}px`,+ letterSpacing: settings.letterSpacing ? `${settings.letterSpacing}px` : undefined,+ textAlign: settings.align,+ color: 'transparent',+ caretColor: '#38bdf8',+ whiteSpace: settings.maxWidth ? 'pre-wrap' : 'pre',+ overflowWrap: 'break-word',+ cursor: 'text',+ }}+ />+ )}++ {/* Direct Drag Surface for Vertical Mode */}+ {isVertical && (+ <div+ onPointerDown={(e) => startDrag('move', e)}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ className="absolute inset-0 cursor-move"+ title="Drag to reposition vertical text"+ />+ )}++ {/* Top-Left Move Grip Pill (always easy to grab & reposition text) */}+ <div+ data-testid="text-move-handle"+ onPointerDown={(e) => startDrag('move', e)}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ title="Drag to move text (or Alt+Drag / Alt+Arrow keys)"+ className="absolute flex items-center justify-center rounded-full bg-sky-500 text-white shadow cursor-move hover:bg-sky-400 transition-colors"+ style={{+ left: `${-handleSize * 1.1}px`,+ top: `${-handleSize * 1.1}px`,+ width: `${handleSize * 2.1}px`,+ height: `${handleSize * 2.1}px`,+ }}+ >+ <Move style={{ width: `${handleSize * 1.2}px`, height: `${handleSize * 1.2}px` }} />+ </div>++ {/* Right-Edge Wrap Width Handle (horizontal mode) */}+ {!isVertical && (+ <div+ data-testid="text-width-handle"+ onPointerDown={(e) => startDrag('resize-width', e)}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ onDoubleClick={(e) => {+ e.stopPropagation();+ onUpdateSettings((prev) => ({ ...prev, maxWidth: null }));+ }}+ title={+ settings.maxWidth+ ? `Wrap width: ${settings.maxWidth}px (drag to resize, double-click for auto width)`+ : 'Drag to set word-wrap box width'+ }+ className="absolute top-1/2 -translate-y-1/2 rounded-full bg-white border border-sky-500 shadow cursor-ew-resize hover:bg-sky-100"+ style={{+ right: `${-handleSize * 0.75}px`,+ width: `${handleSize * 0.85}px`,+ height: `${Math.max(handleSize * 2.2, Math.min(boxHeight * 0.5, handleSize * 3.5))}px`,+ }}+ />+ )}++ {/* Bottom-Right Corner Font Scale Handle */}+ <div+ data-testid="text-scale-handle"+ onPointerDown={(e) => startDrag('scale-font', e)}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ title="Drag diagonally to scale font size"+ className="absolute rounded-[2px] bg-white border border-sky-500 shadow cursor-nwse-resize hover:bg-sky-100"+ style={{+ right: `${-handleSize * 0.75}px`,+ bottom: `${-handleSize * 0.75}px`,+ width: `${handleSize * 1.25}px`,+ height: `${handleSize * 1.25}px`,+ }}+ /></div>- {/* Floating Tool Panel */}+ {/* Compact Zoom-Compensated Floating Quick Bar */}<div- className="w-80 bg-ui-floating border border-ui-default rounded-ui-lg shadow-ui-popover overflow-hidden flex flex-col text-ui-primary"+ className="mt-2"style={{- transform: `scale(${(flipX ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)}, ${(flipY ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)})`,+ transform: `scale(${invScaleX}, ${invScaleY})`,transformOrigin: 'top left',}}>- {/* Header Draggable Bar */}- <div- onPointerDown={handleDragDown}- onPointerMove={handleDragMove}- onPointerUp={handleDragUp}- className="bg-ui-header px-3 py-1.5 border-b border-ui-subtle flex items-center justify-between cursor-move text-xs text-ui-muted"- >- <span className="font-medium text-ui-primary">Text Tool</span>-- <div className="flex items-center space-x-1">- <button- type="button"- onClick={() => setActiveTab('text')}- className={`px-2 py-0.5 rounded-ui-xs text-[11px] font-medium transition-colors cursor-pointer ${- activeTab === 'text' ? 'bg-ui-control-active text-ui-primary' : 'text-ui-muted hover:text-ui-primary'- }`}+ <div className="w-max max-w-[560px] bg-ui-floating/95 backdrop-blur-md border border-ui-default rounded-ui-lg shadow-ui-popover text-ui-primary overflow-visible">+ {/* Primary Compact Toolbar Row */}+ <div className="px-2 py-1.5 flex items-center gap-1.5 flex-wrap">+ {/* Drag Handle */}+ <div+ onPointerDown={(e) => startDrag('move', e)}+ onPointerMove={handleDragMove}+ onPointerUp={handleDragUp}+ title="Drag to move text"+ className="p-0.5 text-ui-muted hover:text-ui-primary cursor-move shrink-0">- Content- </button>- <button- type="button"- onClick={() => setActiveTab('style')}- className={`px-2 py-0.5 rounded-ui-xs text-[11px] font-medium transition-colors cursor-pointer ${- activeTab === 'style' ? 'bg-ui-control-active text-ui-primary' : 'text-ui-muted hover:text-ui-primary'- }`}+ <GripVertical className="w-3.5 h-3.5" />+ </div>++ {/* Font Family */}+ <select+ aria-label="Font Family"+ value={settings.fontFamily}+ onFocus={handleLoadSystemFonts}+ onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontFamily: e.target.value }))}+ className="h-6 max-w-[140px] bg-ui-input text-ui-primary text-[11px] border border-ui-subtle rounded-ui-xs px-1.5 focus:border-ui-focus focus:outline-none cursor-pointer"+ style={{ fontFamily: settings.fontFamily }}>- Style- </button>- </div>- </div>+ {fontOptions.map((f) => (+ <option+ key={f.value}+ value={f.value}+ className="bg-ui-elevated text-ui-primary"+ style={{ fontFamily: f.value }}+ >+ {f.label}+ </option>+ ))}+ </select>- {/* Tab 1: Text Content */}- {activeTab === 'text' && (- <div className="p-3 space-y-2.5">- <textarea- autoFocus- value={settings.text}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}- placeholder="Enter text (multiline supported)..."- rows={3}- className="w-full bg-ui-input text-ui-primary placeholder:text-ui-muted text-xs border border-ui-default rounded-ui-sm p-2 focus:border-ui-focus focus:outline-none resize-none font-ui-mono"- onKeyDown={(e) => {- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {- e.preventDefault();- onConfirm();- } else if (e.key === 'Escape') {- e.preventDefault();- onCancel();- }- }}- />-- <div className="flex items-center space-x-2">- <label className="text-[11px] text-ui-muted w-16 shrink-0">Font:</label>- <select- value={settings.fontFamily}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontFamily: e.target.value }))}- className="flex-1 bg-ui-input text-ui-primary text-xs border border-ui-default rounded-ui-sm px-2 py-1 focus:border-ui-focus focus:outline-none"+ {/* Font Size Stepper + Input */}+ <div className="inline-flex items-center bg-ui-input border border-ui-subtle rounded-ui-xs h-6 overflow-hidden shrink-0">+ <button+ type="button"+ onClick={() => stepFontSize(-2)}+ title="Decrease font size (Ctrl+[)"+ className="w-5 h-full flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer">- {MANGA_FONTS.map((f) => (- <option key={f.id} value={f.id} className="bg-ui-elevated text-ui-primary">- {f.label}- </option>- ))}- </select>- </div>-- <div className="flex items-center space-x-2">- <label className="text-[11px] text-ui-muted tabular-nums w-16 shrink-0">Size: {settings.fontSize}px</label>+ <Minus className="w-2.5 h-2.5" />+ </button><input- type="range"- min={10}- max={160}- value={settings.fontSize}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontSize: Number(e.target.value) }))}- className="flex-1"+ type="text"+ inputMode="numeric"+ aria-label="Font Size"+ value={fontSizeInput}+ onChange={(e) => setFontSizeInput(e.target.value.replace(/[^0-9]/g, ''))}+ onBlur={commitFontSizeInput}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === 'Enter') {+ commitFontSizeInput();+ textareaRef.current?.focus();+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ stepFontSize(e.shiftKey ? 10 : 1);+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ stepFontSize(e.shiftKey ? -10 : -1);+ }+ }}+ className="w-9 h-full bg-transparent text-center text-[11px] font-ui-mono tabular-nums text-ui-primary focus:outline-none"/>+ <button+ type="button"+ onClick={() => stepFontSize(2)}+ title="Increase font size (Ctrl+])"+ className="w-5 h-full flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"+ >+ <Plus className="w-2.5 h-2.5" />+ </button></div>- <div className="flex items-center space-x-2">- <label className="text-[11px] text-ui-muted tabular-nums w-16 shrink-0">- Line: {(settings.lineSpacing ?? 1.25).toFixed(2)}- </label>- <input- type="range"- min={0.8}- max={2.5}- step={0.05}- value={settings.lineSpacing ?? 1.25}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, lineSpacing: Number(e.target.value) }))}- className="flex-1"- />+ {/* Text Color Swatch + Quick Popover */}+ <div className="relative shrink-0">+ <button+ type="button"+ data-testid="text-color-trigger"+ onClick={() => setShowColorPopover((v) => !v)}+ title={`Text Color (${settings.color || '#ffffff'})`}+ className="w-6 h-6 rounded-ui-xs border border-ui-default hover:border-ui-strong flex items-center justify-center bg-ui-input cursor-pointer"+ >+ <span+ className="w-4 h-4 rounded-[2px] border border-black/30"+ style={{ backgroundColor: settings.color || '#ffffff' }}+ />+ </button>++ {showColorPopover && (+ <div className="absolute left-0 top-7 z-50 p-2 bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-popover flex flex-col gap-2 w-44">+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Text Color</span>+ <span className="font-ui-mono uppercase">{settings.color || '#ffffff'}</span>+ </div>+ <div className="flex items-center gap-1.5 flex-wrap">+ {TEXT_QUICK_COLORS.map((swatch) => (+ <button+ key={swatch.hex}+ type="button"+ title={swatch.label}+ onClick={() => {+ onUpdateSettings((prev) => ({ ...prev, color: swatch.hex }));+ setShowColorPopover(false);+ }}+ className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${+ (settings.color || '#ffffff').toLowerCase() === swatch.hex+ ? 'border-ui-accent ring-1 ring-ui-accent-border'+ : 'border-ui-default hover:border-ui-strong'+ }`}+ style={{ backgroundColor: swatch.hex }}+ />+ ))}+ </div>+ <div className="flex items-center justify-between gap-1.5 pt-1 border-t border-ui-subtle">+ <label className="inline-flex items-center gap-1.5 text-[10px] text-ui-secondary cursor-pointer">+ <input+ type="color"+ value={settings.color || '#ffffff'}+ onChange={(e) =>+ onUpdateSettings((prev) => ({ ...prev, color: e.target.value }))+ }+ className="w-5 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"+ />+ <span>Custom</span>+ </label>+ {primaryColor && (+ <button+ type="button"+ onClick={() => {+ onUpdateSettings((prev) => ({ ...prev, color: primaryColor }));+ setShowColorPopover(false);+ }}+ title={`Use current brush color (${primaryColor})`}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer"+ >+ <Pipette className="w-2.5 h-2.5" />+ <span>Brush</span>+ </button>+ )}+ </div>+ </div>+ )}</div>- <div className="flex items-center justify-between">- <span className="text-[11px] text-ui-muted">Text Color:</span>- <input- type="color"- value={settings.color || '#000000'}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, color: e.target.value }))}- className="w-6 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"- />+ <span className="h-4 w-px bg-ui-subtle shrink-0" />++ {/* Bold / Italic / Underline */}+ <div className="inline-flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ aria-pressed={settings.bold}+ onClick={() => onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }))}+ title="Bold (Ctrl+B)"+ className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${+ settings.bold+ ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'+ : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Bold className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ aria-pressed={settings.italic}+ onClick={() => onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }))}+ title="Italic (Ctrl+I)"+ className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${+ settings.italic+ ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'+ : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Italic className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ aria-pressed={Boolean(settings.underline)}+ onClick={() =>+ onUpdateSettings((prev) => ({ ...prev, underline: !prev.underline }))+ }+ title="Underline (Ctrl+U)"+ className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${+ settings.underline+ ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'+ : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <Underline className="w-3.5 h-3.5" />+ </button></div>- </div>- )}- {/* Tab 2: Style & Manga Bubble Outline */}- {activeTab === 'style' && (- <div className="p-3 space-y-3">- {/* Formatting toggles */}- <div className="flex items-center justify-between">- <div className="flex items-center space-x-1">+ {/* Alignment */}+ <div className="inline-flex items-center gap-0.5 bg-ui-input p-0.5 rounded-ui-xs border border-ui-subtle shrink-0">+ {(+ [+ { id: 'left', icon: <AlignLeft className="w-3 h-3" />, label: 'Align Left (Ctrl+Shift+L)' },+ { id: 'center', icon: <AlignCenter className="w-3 h-3" />, label: 'Align Center (Ctrl+Shift+E)' },+ { id: 'right', icon: <AlignRight className="w-3 h-3" />, label: 'Align Right (Ctrl+Shift+R)' },+ ] as const+ ).map((a) => (<button+ key={a.id}type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }))}- title="Bold"- className={`p-1.5 rounded-ui-xs border transition-colors cursor-pointer ${- settings.bold- ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'- : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'+ title={a.label}+ onClick={() => onUpdateSettings((prev) => ({ ...prev, align: a.id }))}+ className={`w-5 h-5 rounded-[2px] flex items-center justify-center cursor-pointer transition-colors ${+ settings.align === a.id+ ? 'bg-ui-control-active text-ui-accent'+ : 'text-ui-icon-muted hover:text-ui-primary'}`}>- <Bold className="w-3.5 h-3.5" />+ {a.icon}</button>- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }))}- title="Italic"- className={`p-1.5 rounded-ui-xs border transition-colors cursor-pointer ${- settings.italic- ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'- : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'- }`}- >- <Italic className="w-3.5 h-3.5" />- </button>- </div>+ ))}+ </div>- {/* Writing Direction (Horizontal vs Vertical Manga Tate-gaki) */}- <div className="flex items-center space-x-1 bg-ui-input p-0.5 rounded-ui-sm border border-ui-subtle">- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'horizontal-tb' }))}- title="Horizontal Layout (Left-to-Right)"- className={`px-1.5 py-0.5 rounded-ui-xs text-[10px] font-medium transition-colors cursor-pointer ${- settings.writingMode !== 'vertical-rl'- ? 'bg-ui-control-active text-ui-primary'- : 'text-ui-muted hover:text-ui-primary'- }`}- >- Horiz- </button>- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'vertical-rl' }))}- title="Vertical Layout (Manga Tate-gaki: Right-to-Left columns)"- className={`px-1.5 py-0.5 rounded-ui-xs text-[10px] font-medium transition-colors cursor-pointer ${- settings.writingMode === 'vertical-rl'- ? 'bg-ui-accent-subtle text-ui-accent border border-ui-accent-border'- : 'text-ui-muted hover:text-ui-primary'- }`}- >- Vert- </button>- </div>+ {/* Horizontal / Vertical Toggle */}+ <div className="inline-flex items-center gap-0.5 bg-ui-input p-0.5 rounded-ui-xs border border-ui-subtle shrink-0">+ <button+ type="button"+ onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'horizontal-tb' }))}+ title="Horizontal Text"+ className={`px-1.5 h-5 rounded-[2px] text-[10px] font-medium cursor-pointer transition-colors ${+ !isVertical+ ? 'bg-ui-control-active text-ui-primary'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ H+ </button>+ <button+ type="button"+ onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'vertical-rl' }))}+ title="Vertical Text (Tate-gaki)"+ className={`px-1.5 h-5 rounded-[2px] text-[10px] font-medium cursor-pointer transition-colors ${+ isVertical+ ? 'bg-ui-accent-subtle text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ V+ </button>+ </div>- {/* Alignments */}- <div className="flex items-center space-x-1 bg-ui-input p-0.5 rounded-ui-sm border border-ui-subtle">- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'left' }))}- title="Align Left"- className={`p-1 rounded-ui-xs cursor-pointer transition-colors ${settings.align === 'left' ? 'bg-ui-control-active text-ui-primary' : 'text-ui-icon-muted hover:text-ui-primary'}`}- >- <AlignLeft className="w-3 h-3" />- </button>- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'center' }))}- title="Align Center"- className={`p-1 rounded-ui-xs cursor-pointer transition-colors ${settings.align === 'center' ? 'bg-ui-control-active text-ui-primary' : 'text-ui-icon-muted hover:text-ui-primary'}`}- >- <AlignCenter className="w-3 h-3" />- </button>- <button- type="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'right' }))}- title="Align Right"- className={`p-1 rounded-ui-xs cursor-pointer transition-colors ${settings.align === 'right' ? 'bg-ui-control-active text-ui-primary' : 'text-ui-icon-muted hover:text-ui-primary'}`}- >- <AlignRight className="w-3 h-3" />- </button>- </div>+ {/* Expand Typography / Outline Settings */}+ <button+ type="button"+ data-testid="text-more-style-btn"+ aria-expanded={showMoreStyle}+ onClick={() => setShowMoreStyle((v) => !v)}+ title="Spacing, opacity, and outline options"+ className={`h-6 px-1.5 rounded-ui-xs border text-[10.5px] inline-flex items-center gap-1 cursor-pointer transition-colors shrink-0 ${+ showMoreStyle || settings.outline+ ? 'bg-ui-control-active border-ui-accent-border text-ui-primary'+ : 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ <SlidersHorizontal className="w-3 h-3" />+ <span>Style</span>+ </button>++ <span className="h-4 w-px bg-ui-subtle shrink-0" />++ {/* Delete / Cancel / Apply */}+ {editingLayerId && onDelete && (+ <button+ type="button"+ data-testid="text-delete-btn"+ onClick={onDelete}+ title="Delete text layer"+ className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-danger hover:bg-ui-danger/15 transition-colors cursor-pointer shrink-0"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ )}+ <button+ type="button"+ data-testid="text-cancel-btn"+ onClick={onCancel}+ title="Cancel (Esc)"+ className="w-6 h-6 rounded-ui-xs flex items-center justify-center bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer shrink-0"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ data-testid="text-confirm-btn"+ onClick={onConfirm}+ title="Apply text (Ctrl+Enter or click outside)"+ className="h-6 px-2 rounded-ui-xs inline-flex items-center gap-1 bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer shrink-0"+ >+ <Check className="w-3.5 h-3.5" />+ <span>Done</span>+ </button>+ </div>++ {/* Dedicated Text Input Box for Vertical Mode */}+ {isVertical && (+ <div className="px-2.5 pb-2 pt-1 border-t border-ui-subtle">+ <textarea+ ref={textareaRef}+ data-testid="text-editor-textarea"+ aria-label="Vertical text input"+ value={settings.text}+ onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}+ onKeyDown={handleEditorKeyDown}+ placeholder="Type vertical text (Enter starts next column)..."+ rows={2}+ className="w-full bg-ui-input text-ui-primary placeholder:text-ui-muted text-xs border border-ui-subtle rounded-ui-sm p-1.5 focus:border-ui-focus focus:outline-none resize-none"+ /></div>+ )}- {/* Manga Outline Option */}- <div className="space-y-1.5 border-t border-ui-subtle pt-2">- <div className="flex items-center justify-between">- <span className="text-[11px] text-ui-primary font-medium">Manga Speech Bubble Outline</span>- <input- type="checkbox"- checked={settings.outline}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, outline: e.target.checked }))}- className="cursor-pointer"- />+ {/* Expandable Advanced Typography & Optional Outline Drawer */}+ {showMoreStyle && (+ <div className="px-3 py-2.5 border-t border-ui-subtle bg-ui-header/70 space-y-2 text-[11px]">+ <div className="grid grid-cols-2 gap-x-4 gap-y-2">+ <label className="flex items-center gap-2">+ <span className="text-ui-muted w-16 shrink-0 tabular-nums">+ Line {(settings.lineSpacing ?? 1.25).toFixed(2)}+ </span>+ <input+ type="range"+ min={0.8}+ max={2.5}+ step={0.05}+ value={settings.lineSpacing ?? 1.25}+ onChange={(e) =>+ onUpdateSettings((prev) => ({ ...prev, lineSpacing: Number(e.target.value) }))+ }+ className="flex-1 min-w-0"+ />+ </label>++ <label className="flex items-center gap-2">+ <span className="text-ui-muted w-16 shrink-0 tabular-nums">+ Track {(settings.letterSpacing ?? 0).toFixed(0)}px+ </span>+ <input+ type="range"+ min={-6}+ max={30}+ step={0.5}+ value={settings.letterSpacing ?? 0}+ onChange={(e) =>+ onUpdateSettings((prev) => ({+ ...prev,+ letterSpacing: Number(e.target.value),+ }))+ }+ className="flex-1 min-w-0"+ />+ </label>++ <label className="flex items-center gap-2">+ <span className="text-ui-muted w-16 shrink-0 tabular-nums">+ Opacity {Math.round((settings.opacity ?? 1) * 100)}%+ </span>+ <input+ type="range"+ min={0.1}+ max={1}+ step={0.05}+ value={settings.opacity ?? 1}+ onChange={(e) =>+ onUpdateSettings((prev) => ({ ...prev, opacity: Number(e.target.value) }))+ }+ className="flex-1 min-w-0"+ />+ </label>++ <div className="flex items-center justify-between gap-2">+ <label className="inline-flex items-center gap-1.5 cursor-pointer text-ui-primary">+ <input+ type="checkbox"+ checked={Boolean(settings.outline)}+ onChange={(e) =>+ onUpdateSettings((prev) => ({ ...prev, outline: e.target.checked }))+ }+ className="cursor-pointer"+ />+ <span>Outline</span>+ </label>+ <button+ type="button"+ onClick={handleResetToStandard}+ title="Reset to plain white text without outline"+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer"+ >+ <RotateCcw className="w-2.5 h-2.5" />+ <span>Plain White</span>+ </button>+ </div></div>{settings.outline && (- <div className="space-y-2 pt-1">- <div className="flex items-center justify-between text-xs">- <span className="text-[11px] text-ui-muted tabular-nums">Outline Width: {settings.outlineWidth}px</span>+ <div className="flex items-center gap-3 pt-1.5 border-t border-ui-subtle">+ <label className="flex items-center gap-2 flex-1">+ <span className="text-ui-muted tabular-nums shrink-0">+ Width {settings.outlineWidth}px+ </span><inputtype="range"min={1}- max={12}+ max={16}value={settings.outlineWidth}- onChange={(e) => onUpdateSettings((prev) => ({ ...prev, outlineWidth: Number(e.target.value) }))}- className="w-32"+ onChange={(e) =>+ onUpdateSettings((prev) => ({+ ...prev,+ outlineWidth: Number(e.target.value),+ }))+ }+ className="flex-1 min-w-0"/>- </div>- <div className="flex items-center space-x-2">- <span className="text-[11px] text-ui-muted">Outline Color:</span>+ </label>++ <div className="flex items-center gap-1 shrink-0">+ <span className="text-ui-muted">Color:</span><buttontype="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, outlineColor: '#ffffff' }))}- className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${settings.outlineColor === '#ffffff' ? 'border-ui-accent ring-1 ring-ui-accent-border' : 'border-ui-default hover:border-ui-strong'}`}- style={{ backgroundColor: '#ffffff' }}- title="White outline"+ onClick={() =>+ onUpdateSettings((prev) => ({ ...prev, outlineColor: '#000000' }))+ }+ className={`w-4 h-4 rounded-ui-xs border cursor-pointer ${+ settings.outlineColor === '#000000'+ ? 'border-ui-accent ring-1 ring-ui-accent-border'+ : 'border-ui-default'+ }`}+ style={{ backgroundColor: '#000000' }}+ title="Black outline"/><buttontype="button"- onClick={() => onUpdateSettings((prev) => ({ ...prev, outlineColor: '#000000' }))}- className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${settings.outlineColor === '#000000' ? 'border-ui-accent ring-1 ring-ui-accent-border' : 'border-ui-default hover:border-ui-strong'}`}- style={{ backgroundColor: '#000000' }}- title="Black outline"+ onClick={() =>+ onUpdateSettings((prev) => ({ ...prev, outlineColor: '#ffffff' }))+ }+ className={`w-4 h-4 rounded-ui-xs border cursor-pointer ${+ settings.outlineColor === '#ffffff'+ ? 'border-ui-accent ring-1 ring-ui-accent-border'+ : 'border-ui-default'+ }`}+ style={{ backgroundColor: '#ffffff' }}+ title="White outline"+ />+ <input+ type="color"+ aria-label="Outline Color"+ value={settings.outlineColor || '#000000'}+ onChange={(e) =>+ onUpdateSettings((prev) => ({ ...prev, outlineColor: e.target.value }))+ }+ className="w-5 h-4 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"/></div></div>)}- </div>- </div>- )}- {/* Footer Confirm / Cancel */}- <div className="px-3 py-2 bg-ui-header border-t border-ui-subtle flex items-center justify-between">- <span className="text-[10px] text-ui-muted">Ctrl+Enter to Apply</span>- <div className="flex items-center gap-2">- <button- type="button"- onClick={onCancel}- className="px-2.5 py-1 bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary rounded-ui-sm text-xs font-medium transition-colors cursor-pointer"- >- Cancel- </button>- <button- type="button"- onClick={onConfirm}- className="px-3 py-1 bg-ui-accent text-ui-accent-contrast hover:opacity-90 rounded-ui-sm text-xs font-medium transition-opacity cursor-pointer"- >- Apply- </button>- </div>+ <div className="flex items-center justify-between text-[10px] text-ui-muted pt-1 border-t border-ui-subtle">+ <span>Click outside or Ctrl+Enter to apply</span>+ <span>Alt+Arrows to nudge • Drag edge to wrap</span>+ </div>+ </div>+ )}</div></div></div>diff --git a/src/components/TimelapseExportModal.tsx b/src/components/TimelapseExportModal.tsxindex c482915..8b05ad9 100644--- a/src/components/TimelapseExportModal.tsx+++ b/src/components/TimelapseExportModal.tsx@@ -1,23 +1,57 @@-import React, { useEffect, useRef, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import {- X,- Film,+ Camera,+ Check,+ ChevronDown,+ ChevronLeft,+ ChevronRight,Circle,- Square,Download,- Trash2,- Play,- Pause,+ Film,+ FolderClock,+ HardDrive,Loader2,+ Maximize2,+ Pause,+ Play,+ RefreshCw,+ Repeat,+ SkipBack,+ SlidersHorizontal,+ Square,+ Stamp,+ Trash2,+ X,} from 'lucide-react';import {+ formatTimelapseBytes,globalTimelapseManager,+ StoredRecordingSummary,TimelapseAspectRatio,+ TimelapseBackgroundMode,+ TimelapseCaptureArea,+ TimelapseCaptureResolution,TimelapseDurationPreset,+ TimelapseFps,+ TimelapseQualityPreset,TimelapseResolution,+ TimelapseWatermarkConfig,} from '../utils/timelapseEngine';-import { downloadFile } from '../utils/saveManager';-import { documentStoreActions } from '../stores';+import {+ loadSavedWatermarkConfig,+ saveWatermarkConfig,+} from '../utils/timelapseWatermark';+import { saveFileWithDialog } from '../utils/fileSaveDialog';+import { sanitizeDocumentStem } from '../utils/saveManager/fileNameUtils';+import { documentStoreActions, useUiStore } from '../stores';+import { ToggleSwitch } from './ui';+import {+ formatTimecode,+ TimelapsePlaybackSpeed,+ useTimelapsePreviewPlayer,+} from './timelapse/useTimelapsePreviewPlayer';+import { TimelapseFullscreenViewer } from './timelapse/TimelapseFullscreenViewer';+import { TimelapseWatermarkControls } from './timelapse/TimelapseWatermarkControls';interface TimelapseExportModalProps {isOpen: boolean;@@ -28,6 +62,86 @@ interface TimelapseExportModalProps {showToast?: (msg: string) => void;}+type InspectorTab = 'export' | 'watermark' | 'library';++const CAPTURE_AREA_OPTIONS: Array<{+ value: TimelapseCaptureArea;+ label: string;+ description: string;+}> = [+ {+ value: 'artwork',+ label: 'Artwork only',+ description: 'Clean upright canvas without UI or zoom wobble',+ },+ {+ value: 'canvas-view',+ label: 'Canvas view',+ description: 'Live viewport with pan, zoom, rotation & view flip',+ },+ {+ value: 'app-window',+ label: 'App window',+ description: 'Entire Ink Studio window including panels & canvas',+ },+];++const CAPTURE_RES_OPTIONS: Array<{ value: TimelapseCaptureResolution; label: string }> = [+ { value: '720p', label: '720p' },+ { value: '1080p', label: '1080p' },+ { value: '2k', label: '2K' },+ { value: '4k', label: '4K' },+];++const DURATION_OPTIONS: Array<{ value: TimelapseDurationPreset; label: string }> = [+ { value: '15s', label: '15s' },+ { value: '30s', label: '30s' },+ { value: '60s', label: '60s' },+ { value: '120s', label: '2m' },+ { value: 'full', label: 'Full' },+ { value: 'custom', label: 'Custom' },+];++const FPS_OPTIONS: TimelapseFps[] = [24, 30, 60];++const QUALITY_OPTIONS: Array<{ value: TimelapseQualityPreset; label: string }> = [+ { value: 'standard', label: 'Std' },+ { value: 'high', label: 'High' },+ { value: 'ultra', label: 'Ultra' },+ { value: 'lossless', label: 'Max' },+];++const EXPORT_RES_OPTIONS: Array<{ value: TimelapseResolution; label: string }> = [+ { value: '720p', label: '720p' },+ { value: '1080p', label: '1080p' },+ { value: '2k', label: '2K' },+ { value: '4k', label: '4K' },+];++const ASPECT_RATIO_OPTIONS: Array<{ value: TimelapseAspectRatio; label: string }> = [+ { value: 'original', label: 'Orig' },+ { value: '16:9', label: '16:9' },+ { value: '9:16', label: '9:16' },+ { value: '1:1', label: '1:1' },+ { value: '4:5', label: '4:5' },+];++const SPEED_CYCLE: TimelapsePlaybackSpeed[] = [0.5, 1, 2];++function formatRelativeDate(ts: number): string {+ if (!ts) return 'Unknown date';+ try {+ return new Date(ts).toLocaleString(undefined, {+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ });+ } catch {+ return 'Saved locally';+ }+}+export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({isOpen,onClose,@@ -36,31 +150,82 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({onCaptureNow,showToast,}) => {+ const userName = useUiStore((s) => s.appSettings.userName);++ // Export & Preview Settingsconst [duration, setDuration] = useState<TimelapseDurationPreset>('30s');+ const [customDurationSec, setCustomDurationSec] = useState<number>(45);+ const [fps, setFps] = useState<TimelapseFps>(30);+ const [quality, setQuality] = useState<TimelapseQualityPreset>('high');const [aspectRatio, setAspectRatio] = useState<TimelapseAspectRatio>('original');const [resolution, setResolution] = useState<TimelapseResolution>('1080p');- const [backgroundColor, setBackgroundColor] = useState<'#ffffff' | '#141414'>('#ffffff');+ const [backgroundMode, setBackgroundMode] = useState<TimelapseBackgroundMode>('white');+ const [customBgColor, setCustomBgColor] = useState<string>('#202024');const [preferFfmpeg, setPreferFfmpeg] = useState(false);const [ffmpegAvailable, setFfmpegAvailable] = useState(false);+ // Watermark State (persisted across sessions)+ const [watermark, setWatermark] = useState<TimelapseWatermarkConfig>(() =>+ loadSavedWatermarkConfig(userName ? `@${userName}` : 'Ink Studio')+ );++ // UI / Playback / Dropdown / Library State+ const [activeTab, setActiveTab] = useState<InspectorTab>('export');+ const [isFullscreen, setIsFullscreen] = useState(false);+ const [playbackSpeed, setPlaybackSpeed] = useState<TimelapsePlaybackSpeed>(1);+ const [loop, setLoop] = useState(true);+ const [openDropdown, setOpenDropdown] = useState<'capture' | 'max-size' | null>(null);+ const [storedRecordings, setStoredRecordings] = useState<StoredRecordingSummary[]>([]);+ const [loadingRecordings, setLoadingRecordings] = useState(false);+const [stats, setStats] = useState(() => globalTimelapseManager.getStats(documentId));- const [previewIdx, setPreviewIdx] = useState(0);- const [previewUrl, setPreviewUrl] = useState<string | null>(null);- const [isPlayingPreview, setIsPlayingPreview] = useState(false);const [isExporting, setIsExporting] = useState(false);const [exportProgress, setExportProgress] = useState(0);const [errorMsg, setErrorMsg] = useState<string | null>(null);- const previewUrlRef = useRef<string | null>(null);+ const dropdownBarRef = useRef<HTMLDivElement | null>(null);- // Reset scrubber state when switching active documents- useEffect(() => {- setPreviewIdx(0);- setIsPlayingPreview(false);- }, [documentId]);+ const effectiveBgColor =+ backgroundMode === 'dark'+ ? '#141414'+ : backgroundMode === 'custom'+ ? customBgColor+ : '#ffffff';++ const player = useTimelapsePreviewPlayer({+ isOpen,+ documentId,+ frameCount: stats.frameCount,+ duration,+ customDurationSec,+ fps,+ aspectRatio,+ resolution,+ backgroundMode,+ backgroundColor: effectiveBgColor,+ watermark,+ playbackSpeed,+ loop,+ isFullscreen,+ });++ const refreshStoredRecordings = useCallback(async () => {+ setLoadingRecordings(true);+ try {+ const list = await globalTimelapseManager.listStoredRecordings();+ setStoredRecordings(list);+ } finally {+ setLoadingRecordings(false);+ }+ }, []);+ // Subscribe to session stats & check FFmpeg on modal openuseEffect(() => {- if (!isOpen) return;+ if (!isOpen) {+ setIsFullscreen(false);+ setOpenDropdown(null);+ return;+ }setStats(globalTimelapseManager.getStats(documentId));globalTimelapseManager.checkFfmpegAvailable().then((ok) => {setFfmpegAvailable(ok);@@ -71,92 +236,156 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({});return () => {unsub();- setIsPlayingPreview(false);};}, [isOpen, documentId]);- // Load current preview frame blobuseEffect(() => {- if (!isOpen || !documentId) return;- const frames = globalTimelapseManager.getFrames(documentId);- if (frames.length === 0) {- if (previewUrlRef.current) {- URL.revokeObjectURL(previewUrlRef.current);- previewUrlRef.current = null;- }- setPreviewUrl(null);- return;+ if (isOpen && activeTab === 'library') {+ void refreshStoredRecordings();}+ }, [isOpen, activeTab, refreshStoredRecordings]);- const clampedIdx = Math.max(0, Math.min(frames.length - 1, previewIdx));- let cancelled = false;- globalTimelapseManager.loadFrameBlob(documentId, frames[clampedIdx]).then((blob) => {- if (cancelled || !blob) return;- const nextUrl = URL.createObjectURL(blob);- if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);- previewUrlRef.current = nextUrl;- setPreviewUrl(nextUrl);- });-- return () => {- cancelled = true;- };- }, [isOpen, documentId, previewIdx, stats.frameCount]);-- // Cleanup preview object URL on unmount+ // Close capture/resolution popover when clicking outsideuseEffect(() => {- return () => {- if (previewUrlRef.current) {- URL.revokeObjectURL(previewUrlRef.current);- previewUrlRef.current = null;+ if (!openDropdown) return;+ const handlePointerDown = (e: MouseEvent) => {+ if (+ dropdownBarRef.current &&+ e.target instanceof Node &&+ !dropdownBarRef.current.contains(e.target)+ ) {+ setOpenDropdown(null);}};- }, []);+ window.addEventListener('mousedown', handlePointerDown);+ return () => window.removeEventListener('mousedown', handlePointerDown);+ }, [openDropdown]);- // Playback preview timer- useEffect(() => {- if (!isPlayingPreview || stats.frameCount <= 1) return;- const timer = window.setInterval(() => {- setPreviewIdx((prev) => (prev + 1) % stats.frameCount);- }, 100);- return () => window.clearInterval(timer);- }, [isPlayingPreview, stats.frameCount]);-- // Escape key closes modal when not exporting+ // Keyboard shortcuts: Esc, F (fullscreen), Space (play/pause), Left/Right arrows (step)useEffect(() => {if (!isOpen) return;const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === 'Escape' && !isExporting) {+ const target = e.target as HTMLElement | null;+ const isTextInput =+ target &&+ (target.tagName === 'INPUT' ||+ target.tagName === 'TEXTAREA' ||+ target.isContentEditable);++ if (e.key === 'Escape') {e.preventDefault();e.stopPropagation();- onClose();+ if (openDropdown) {+ setOpenDropdown(null);+ } else if (isFullscreen) {+ setIsFullscreen(false);+ } else if (!isExporting) {+ onClose();+ }+ return;+ }++ if (isTextInput || isExporting) return;++ if (e.key === 'f' || e.key === 'F') {+ if (stats.frameCount > 0) {+ e.preventDefault();+ setIsFullscreen((prev) => !prev);+ }+ } else if (e.key === ' ') {+ if (stats.frameCount > 1 && target?.tagName !== 'BUTTON') {+ e.preventDefault();+ player.togglePlay();+ }+ } else if (e.key === 'ArrowLeft' && stats.frameCount > 0) {+ e.preventDefault();+ player.stepBy(-1);+ } else if (e.key === 'ArrowRight' && stats.frameCount > 0) {+ e.preventDefault();+ player.stepBy(1);}};window.addEventListener('keydown', handleKeyDown, true);return () => window.removeEventListener('keydown', handleKeyDown, true);- }, [isOpen, isExporting, onClose]);+ }, [isOpen, isExporting, isFullscreen, openDropdown, stats.frameCount, onClose, player]);++ const handleWatermarkChange = useCallback((next: TimelapseWatermarkConfig) => {+ setWatermark(next);+ saveWatermarkConfig(next);+ }, []);if (!isOpen) return null;+ const cleanDocName = (documentName || 'Untitled').replace(/\*+$/, '').trim() || 'Untitled';+ const activeAreaMeta =+ CAPTURE_AREA_OPTIONS.find((o) => o.value === stats.captureArea) ?? CAPTURE_AREA_OPTIONS[0];+ const activeCapResMeta =+ CAPTURE_RES_OPTIONS.find((o) => o.value === stats.captureResolution) ?? CAPTURE_RES_OPTIONS[1];+const handleToggleRecording = () => {if (!documentId) return;- const next = globalTimelapseManager.toggleRecording(documentId);+ const next = globalTimelapseManager.toggleRecording(documentId, cleanDocName);documentStoreActions.markDocumentDirty(documentId, true);if (next) {onCaptureNow?.();- showToast?.('Time-lapse recording enabled');+ showToast?.('Time-lapse recording enabled (saved locally)');} else {showToast?.('Time-lapse recording paused');}};+ const handleSelectCaptureArea = (area: TimelapseCaptureArea) => {+ if (!documentId) return;+ globalTimelapseManager.setCaptureArea(documentId, area);+ documentStoreActions.markDocumentDirty(documentId, true);+ setOpenDropdown(null);+ const label = CAPTURE_AREA_OPTIONS.find((o) => o.value === area)?.label ?? area;+ showToast?.(`Capture area set to ${label}`);+ };++ const handleSelectCaptureResolution = (res: TimelapseCaptureResolution) => {+ if (!documentId) return;+ globalTimelapseManager.setCaptureResolution(documentId, res);+ documentStoreActions.markDocumentDirty(documentId, true);+ setOpenDropdown(null);+ };+const handleClear = async () => {if (!documentId) return;- setIsPlayingPreview(false);+ player.setIsPlaying(false);+ setIsFullscreen(false);await globalTimelapseManager.clearSession(documentId);documentStoreActions.markDocumentDirty(documentId, true);- setPreviewIdx(0);- showToast?.('Time-lapse frames cleared');+ showToast?.('Time-lapse recording cleared');+ if (activeTab === 'library') {+ void refreshStoredRecordings();+ }+ };++ const handleAttachRecording = async (rec: StoredRecordingSummary) => {+ if (!documentId) return;+ player.setIsPlaying(false);+ const res = await globalTimelapseManager.attachExistingRecording(+ documentId,+ rec.recordingId,+ cleanDocName+ );+ documentStoreActions.markDocumentDirty(documentId, true);+ showToast?.(`Attached "${rec.documentName}" (${res.frameCount} frames)`);+ setActiveTab('export');+ };++ const handleDeleteStoredRecording = async (rec: StoredRecordingSummary) => {+ await globalTimelapseManager.deleteStoredRecording(rec.recordingId);+ showToast?.(`Deleted local recording "${rec.documentName}"`);+ void refreshStoredRecordings();+ };++ const handleCycleSpeed = () => {+ setPlaybackSpeed((prev) => {+ const idx = SPEED_CYCLE.indexOf(prev);+ return SPEED_CYCLE[(idx + 1) % SPEED_CYCLE.length];+ });};const handleExport = async () => {@@ -164,28 +393,42 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({setIsExporting(true);setExportProgress(0);setErrorMsg(null);- setIsPlayingPreview(false);+ player.setIsPlaying(false);try {const result = await globalTimelapseManager.exportVideo(documentId,{duration,+ customDurationSec,aspectRatio,resolution,- fps: 30,- backgroundColor,+ fps,+ quality,+ backgroundMode,+ backgroundColor: effectiveBgColor,+ watermark,preferFfmpeg,},(p) => setExportProgress(p));- const safeName =- (documentName || 'timelapse').replace(/[^a-zA-Z0-9_\- ]/g, '_').trim() || 'timelapse';- downloadFile(- result.blob,- `${safeName}_timelapse_${duration}${result.extension}`,- result.mimeType+ const safeName = sanitizeDocumentStem(cleanDocName, 'timelapse');+ const durTag = duration === 'custom' ? `${Math.round(customDurationSec)}s` : duration;+ const suggestedName = `${safeName}_timelapse_${durTag}_${fps}fps${result.extension}`;+ const saveRes = await saveFileWithDialog({+ data: result.blob,+ suggestedName,+ mimeType: result.mimeType,+ description: result.extension === '.mp4' ? 'MP4 Video' : 'WebM Video',+ extensions: [result.extension],+ category: 'timelapse',+ title: 'Save Time-lapse Video As',+ });+ if (saveRes.canceled) {+ return;+ }+ showToast?.(+ `Exported ${result.durationSec.toFixed(1)}s time-lapse (${fps} FPS, ${result.extension})`);- showToast?.(`Exported ${result.durationSec.toFixed(1)}s time-lapse (${result.extension})`);} catch (err) {setErrorMsg(err instanceof Error ? err.message : 'Time-lapse export failed');} finally {@@ -193,241 +436,801 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({}};- const memMb = (stats.memoryBytes / (1024 * 1024)).toFixed(2);+ const storageLabel =+ stats.storageBackend === 'disk'+ ? 'Local app storage'+ : stats.storageBackend === 'indexeddb'+ ? 'Browser storage'+ : 'Session RAM';++ const progressPct =+ player.totalTimelineFrames > 1+ ? (player.timelineIndex / (player.totalTimelineFrames - 1)) * 100+ : 0;return (- <div- role="dialog"- aria-modal="true"- aria-labelledby="timelapse-modal-title"- className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"- onClick={() => {- if (!isExporting) onClose();- }}- >+ <><div- onClick={(e) => e.stopPropagation()}- className="w-[540px] max-w-[95vw] bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover overflow-hidden text-xs text-ui-primary"+ role="dialog"+ aria-modal="true"+ aria-labelledby="timelapse-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-3 sm:p-4 select-none"+ onClick={() => {+ if (!isExporting && !isFullscreen) onClose();+ }}>- {/* Header */}- <div className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between">- <div className="flex items-center gap-2 font-medium text-ui-primary">- <Film className="w-3.5 h-3.5 text-ui-accent" />- <span id="timelapse-modal-title">Time-lapse Recording & Export</span>+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-[840px] max-w-[96vw] max-h-[92vh] bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover overflow-hidden text-xs text-ui-primary flex flex-col"+ >+ {/* Header */}+ <div className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between shrink-0">+ <div className="flex items-center gap-2 font-medium text-ui-primary">+ <Film className="w-3.5 h-3.5 text-ui-accent" />+ <span id="timelapse-modal-title">Time-lapse Studio</span>+ </div>+ <button+ type="button"+ onClick={onClose}+ disabled={isExporting}+ aria-label="Close"+ title="Close (Esc)"+ className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer disabled:opacity-40"+ >+ <X className="w-3.5 h-3.5" />+ </button></div>- <button- type="button"- onClick={onClose}- disabled={isExporting}- aria-label="Close"- title="Cancel (Esc)"- className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer disabled:opacity-40"++ {/* Top Recording & Capture Area Strip */}+ <div+ ref={dropdownBarRef}+ className="px-4 py-2.5 bg-ui-header/70 border-b border-ui-subtle space-y-2 shrink-0">- <X className="w-3.5 h-3.5" />- </button>- </div>+ <div className="flex flex-wrap items-end justify-between gap-3">+ {/* Capture Area + Max Size Dropdowns */}+ <div className="flex items-end gap-2.5">+ {/* Capture Area Dropdown */}+ <div className="relative">+ <span className="block text-[10px] text-ui-muted mb-1">Capture</span>+ <button+ type="button"+ disabled={!documentId || isExporting}+ aria-haspopup="listbox"+ aria-expanded={openDropdown === 'capture'}+ onClick={() =>+ setOpenDropdown((prev) => (prev === 'capture' ? null : 'capture'))+ }+ className={`h-7 min-w-[138px] px-2.5 rounded-ui-sm bg-ui-input border text-xs font-medium text-ui-primary flex items-center justify-between gap-2 cursor-pointer transition-colors disabled:opacity-40 ${+ openDropdown === 'capture'+ ? 'border-ui-focus bg-ui-control'+ : 'border-ui-default hover:border-ui-strong'+ }`}+ >+ <span>{activeAreaMeta.label}</span>+ <ChevronDown+ className={`w-3 h-3 text-ui-muted transition-transform ${+ openDropdown === 'capture' ? 'rotate-180' : ''+ }`}+ />+ </button>++ {openDropdown === 'capture' && (+ <div+ role="listbox"+ aria-label="Capture area"+ className="absolute left-0 top-full mt-1 w-64 z-30 bg-ui-floating border border-ui-strong rounded-ui-md shadow-ui-popover p-1 space-y-0.5"+ >+ {CAPTURE_AREA_OPTIONS.map((opt) => {+ const selected = stats.captureArea === opt.value;+ return (+ <button+ key={opt.value}+ type="button"+ role="option"+ aria-selected={selected}+ onClick={() => handleSelectCaptureArea(opt.value)}+ className={`w-full text-left px-2 py-1.5 rounded-ui-sm flex items-start gap-2 cursor-pointer transition-colors ${+ selected+ ? 'bg-ui-control-active text-ui-primary'+ : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ <span className="w-3.5 h-3.5 mt-0.5 flex items-center justify-center shrink-0">+ {selected && <Check className="w-3.5 h-3.5 text-ui-accent" />}+ </span>+ <span className="min-w-0">+ <span className="block text-xs font-medium leading-tight">+ {opt.label}+ </span>+ <span className="block text-[10px] text-ui-muted leading-snug mt-0.5">+ {opt.description}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>++ {/* Maximum Capture Resolution Dropdown */}+ <div className="relative">+ <span className="block text-[10px] text-ui-muted mb-1">Maximum</span>+ <button+ type="button"+ disabled={!documentId || isExporting}+ aria-haspopup="listbox"+ aria-expanded={openDropdown === 'max-size'}+ onClick={() =>+ setOpenDropdown((prev) => (prev === 'max-size' ? null : 'max-size'))+ }+ className={`h-7 min-w-[78px] px-2.5 rounded-ui-sm bg-ui-input border text-xs font-ui-mono font-medium text-ui-primary flex items-center justify-between gap-2 cursor-pointer transition-colors disabled:opacity-40 ${+ openDropdown === 'max-size'+ ? 'border-ui-focus bg-ui-control'+ : 'border-ui-default hover:border-ui-strong'+ }`}+ >+ <span>{activeCapResMeta.label}</span>+ <ChevronDown+ className={`w-3 h-3 text-ui-muted transition-transform ${+ openDropdown === 'max-size' ? 'rotate-180' : ''+ }`}+ />+ </button>- <div className="p-4 space-y-4">- {/* Status & Record Toggle */}- <div className="flex items-center justify-between bg-ui-header rounded-ui-md px-3 py-2.5 border border-ui-subtle">- <div className="space-y-0.5">- <div className="flex items-center gap-2 font-medium text-ui-primary">+ {openDropdown === 'max-size' && (+ <div+ role="listbox"+ aria-label="Maximum capture resolution"+ className="absolute left-0 top-full mt-1 w-32 z-30 bg-ui-floating border border-ui-strong rounded-ui-md shadow-ui-popover p-1 space-y-0.5"+ >+ {CAPTURE_RES_OPTIONS.map((opt) => {+ const selected = stats.captureResolution === opt.value;+ return (+ <button+ key={opt.value}+ type="button"+ role="option"+ aria-selected={selected}+ onClick={() => handleSelectCaptureResolution(opt.value)}+ className={`w-full text-left px-2 py-1.5 rounded-ui-sm flex items-center gap-2 font-ui-mono text-xs cursor-pointer transition-colors ${+ selected+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'+ }`}+ >+ <span className="w-3.5 h-3.5 flex items-center justify-center">+ {selected && <Check className="w-3.5 h-3.5 text-ui-accent" />}+ </span>+ <span>{opt.label}</span>+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>++ {/* Record / Snapshot / Clear Action Controls */}+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ disabled={!documentId || isExporting}+ onClick={handleToggleRecording}+ className={`h-7 px-3 rounded-ui-sm text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 border ${+ stats.enabled+ ? 'bg-ui-danger/20 hover:bg-ui-danger/30 text-ui-danger border-ui-danger/45'+ : 'bg-ui-control hover:bg-ui-control-hover text-ui-primary border-ui-default'+ }`}+ >+ {stats.enabled ? (+ <>+ <Square className="w-3 h-3 fill-current" />+ <span>Pause Recording</span>+ </>+ ) : (+ <>+ <Circle className="w-3 h-3 text-ui-danger fill-ui-danger" />+ <span>{stats.frameCount > 0 ? 'Continue Recording' : 'Record'}</span>+ </>+ )}+ </button>++ <button+ type="button"+ disabled={!documentId || !stats.enabled || isExporting}+ onClick={() => onCaptureNow?.()}+ title="Capture keyframe now"+ className="h-7 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer disabled:opacity-35"+ >+ <Camera className="w-3.5 h-3.5" />+ </button>++ <button+ type="button"+ disabled={!documentId || stats.frameCount === 0 || isExporting}+ onClick={handleClear}+ title="Clear recorded keyframes"+ className="h-7 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle hover:border-ui-danger/40 text-ui-muted hover:text-ui-danger transition-colors cursor-pointer disabled:opacity-35"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ </div>+ </div>++ {/* Compact Session Telemetry Line */}+ <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-ui-muted">+ <div className="flex items-center gap-2 min-w-0"><span- className={`w-2 h-2 rounded-full ${+ className={`w-2 h-2 rounded-full shrink-0 ${stats.enabled ? 'bg-ui-danger animate-pulse' : 'bg-ui-disabled'}`}/>- <span>{stats.enabled ? 'Recording Keyframes' : 'Recording Paused'}</span>+ <span className="text-ui-secondary font-medium truncate max-w-[180px]">+ {cleanDocName}+ </span>+ <span className="font-ui-mono tabular-nums">+ · {stats.frameCount} frame{stats.frameCount === 1 ? '' : 's'} ·{' '}+ {formatTimelapseBytes(stats.storageBytes)}+ </span></div>- <div className="text-[10px] text-ui-muted font-ui-mono tabular-nums">- {stats.frameCount} keyframes · {memMb} MB RAM- {stats.diskFrames > 0 ? ` · ${stats.diskFrames} offloaded to scratch disk` : ''}+ <div className="flex items-center gap-1.5 text-[10px] text-ui-muted">+ <HardDrive className="w-3 h-3 text-ui-accent" />+ <span>{storageLabel} · resumes automatically after restart</span></div></div>+ </div>- <div className="flex items-center gap-1.5">- <button- type="button"- disabled={!documentId || isExporting}- onClick={handleToggleRecording}- className={`px-2.5 py-1.5 rounded-ui-sm text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 border ${- stats.enabled- ? 'bg-ui-danger/20 hover:bg-ui-danger/30 text-ui-danger border-ui-danger/45'- : 'bg-ui-control hover:bg-ui-control-hover text-ui-primary border-ui-default'- }`}- >- {stats.enabled ? (+ {/* Two-Column Body: Live Preview Left + Inspector Tabs Right */}+ <div className="flex-1 min-h-0 grid grid-cols-1 md:grid-cols-12 overflow-y-auto md:overflow-hidden">+ {/* LEFT: WYSIWYG Preview Player */}+ <div className="md:col-span-7 p-4 flex flex-col gap-2.5 border-b md:border-b-0 md:border-r border-ui-subtle bg-ui-panel">+ {/* Preview Canvas Viewport */}+ <div className="relative flex-1 min-h-[250px] max-h-[380px] flex items-center justify-center overflow-hidden rounded-ui-md bg-ui-void border border-ui-subtle group">+ {stats.frameCount > 0 ? (<>- <Square className="w-3 h-3 fill-current" />- <span>Pause</span>+ <canvas+ ref={player.modalCanvasRef}+ onClick={player.togglePlay}+ onDoubleClick={() => setIsFullscreen(true)}+ title="Click to Play/Pause · Double-click for Full-Screen"+ className="max-h-full max-w-full object-contain cursor-pointer"+ />+ {/* Top-left info badge */}+ <div className="absolute top-2 left-2 px-2 py-0.5 rounded-ui-xs bg-black/65 text-white/90 text-[10px] font-ui-mono tabular-nums pointer-events-none">+ {player.outputDims.width}×{player.outputDims.height} · {fps} FPS+ {watermark.enabled ? ' · WM' : ''}+ </div>+ {/* Top-right Full-Screen Trigger */}+ <button+ type="button"+ onClick={() => setIsFullscreen(true)}+ aria-label="View in full-screen"+ title="Full-Screen Preview (F)"+ className="absolute top-2 right-2 px-2 py-1 rounded-ui-sm bg-black/65 hover:bg-black/85 text-white text-[10px] flex items-center gap-1 cursor-pointer transition-colors"+ >+ <Maximize2 className="w-3 h-3" />+ <span>Full-screen</span>+ </button></>) : (- <>- <Circle className="w-3 h-3 text-ui-danger fill-ui-danger" />- <span>Record</span>- </>+ <div className="text-[11px] text-ui-muted text-center px-6 space-y-1.5">+ <Film className="w-6 h-6 mx-auto text-ui-disabled" />+ <div className="text-ui-secondary font-medium">No time-lapse frames yet</div>+ <div>+ Click <span className="text-ui-primary font-medium">Record</span> and draw+ strokes to capture keyframes automatically in external storage.+ </div>+ </div>)}- </button>-- <button- type="button"- disabled={!documentId || stats.frameCount === 0 || isExporting}- onClick={handleClear}- title="Clear recorded keyframes"- className="p-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle hover:border-ui-danger/40 text-ui-muted hover:text-ui-danger transition-colors cursor-pointer disabled:opacity-35"- >- <Trash2 className="w-3.5 h-3.5" />- </button>- </div>- </div>-- {/* Preview Player */}- <div className="bg-ui-header rounded-ui-md border border-ui-subtle p-2 space-y-2">- <div className="h-44 flex items-center justify-center overflow-hidden rounded-ui-sm bg-ui-void border border-ui-subtle">- {previewUrl ? (- <img- src={previewUrl}- alt="Time-lapse keyframe preview"- className="max-h-full max-w-full object-contain"- />- ) : (- <div className="text-[11px] text-ui-muted text-center px-4">- Enable Record and draw strokes to capture time-lapse keyframes automatically.- </div>- )}- </div>+ </div>- {stats.frameCount > 0 && (- <div className="flex items-center gap-2">- <button- type="button"- onClick={() => setIsPlayingPreview((p) => !p)}- className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary cursor-pointer transition-colors"- >- {isPlayingPreview ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}- </button>- <input- type="range"- min={0}- max={Math.max(0, stats.frameCount - 1)}- value={Math.min(previewIdx, Math.max(0, stats.frameCount - 1))}- onChange={(e) => setPreviewIdx(Number(e.target.value))}- className="flex-1"- />- <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted w-14 text-right">- {Math.min(previewIdx + 1, stats.frameCount)} / {stats.frameCount}+ {/* Direct In-App Preview Interval Switcher (15s / 30s / 60s / 2m / Full / Custom) */}+ <div className="flex flex-wrap items-center justify-between gap-2 bg-ui-header rounded-ui-md border border-ui-subtle px-2.5 py-1.5">+ <span className="text-[10px] uppercase tracking-wider text-ui-muted">+ Preview clip</span>+ <div className="flex items-center gap-1 flex-wrap">+ {DURATION_OPTIONS.map((opt) => (+ <button+ key={opt.value}+ type="button"+ disabled={isExporting}+ onClick={() => setDuration(opt.value)}+ className={`px-2 py-0.5 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${+ duration === opt.value+ ? 'bg-ui-accent text-ui-accent-contrast font-semibold'+ : 'bg-ui-control text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'+ }`}+ >+ {opt.label}+ </button>+ ))}+ {duration === 'custom' && (+ <div className="flex items-center gap-1 ml-1">+ <input+ type="number"+ min={2}+ max={600}+ value={customDurationSec}+ disabled={isExporting}+ onChange={(e) =>+ setCustomDurationSec(+ Math.max(2, Math.min(600, Number(e.target.value) || 30))+ )+ }+ aria-label="Custom duration seconds"+ className="w-12 h-5 px-1 rounded-ui-xs bg-ui-input border border-ui-default text-[10px] font-ui-mono text-ui-primary text-right"+ />+ <span className="text-[10px] text-ui-muted">s</span>+ </div>+ )}+ </div></div>- )}- </div>- {/* Export Settings Grid */}- <div className="grid grid-cols-2 gap-3">- <div className="space-y-1">- <label className="text-[11px] text-ui-muted block">Length</label>- <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">- {(['15s', '30s', '60s', 'full'] as const).map((d) => (- <button- key={d}- type="button"- onClick={() => setDuration(d)}- className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] uppercase cursor-pointer transition-colors ${- duration === d- ? 'bg-ui-control-active text-ui-primary font-semibold'- : 'text-ui-muted hover:text-ui-primary'- }`}- >- {d}- </button>- ))}- </div>- </div>+ {/* Timeline Scrubber & Transport Controls */}+ <div className="bg-ui-header rounded-ui-md border border-ui-subtle p-2 space-y-2">+ <div className="flex items-center gap-2">+ <span className="text-[10px] font-ui-mono tabular-nums text-ui-primary w-11">+ {formatTimecode(player.currentTimeSec)}+ </span>+ <input+ type="range"+ aria-label="Time-lapse preview timeline"+ disabled={stats.frameCount === 0}+ min={0}+ max={Math.max(0, player.totalTimelineFrames - 1)}+ value={Math.min(+ player.timelineIndex,+ Math.max(0, player.totalTimelineFrames - 1)+ )}+ onChange={(e) => player.seekTo(Number(e.target.value))}+ className="flex-1 cursor-pointer disabled:opacity-40"+ style={{+ background: `linear-gradient(to right, var(--ui-accent) ${progressPct}%, var(--ui-bg-input) ${progressPct}%)`,+ }}+ />+ <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted w-11 text-right">+ {formatTimecode(player.totalDurationSec)}+ </span>+ </div>- <div className="space-y-1">- <label className="text-[11px] text-ui-muted block">Aspect Ratio</label>- <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">- {(['original', '16:9', '9:16', '1:1'] as const).map((ar) => (- <button- key={ar}- type="button"- onClick={() => setAspectRatio(ar)}- className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${- aspectRatio === ar- ? 'bg-ui-control-active text-ui-primary font-semibold'- : 'text-ui-muted hover:text-ui-primary'- }`}- >- {ar === 'original' ? 'Orig' : ar}- </button>- ))}- </div>- </div>+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1">+ <button+ type="button"+ disabled={stats.frameCount === 0}+ onClick={player.restart}+ title="Jump to start"+ className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"+ >+ <SkipBack className="w-3 h-3" />+ </button>+ <button+ type="button"+ disabled={stats.frameCount === 0}+ onClick={() => player.stepBy(-1)}+ title="Previous frame (Left Arrow)"+ className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"+ >+ <ChevronLeft className="w-3 h-3" />+ </button>+ <button+ type="button"+ disabled={stats.frameCount <= 1}+ onClick={player.togglePlay}+ title="Play / Pause (Space)"+ className="px-2.5 py-1 rounded-ui-sm bg-ui-control-active hover:bg-ui-control-hover border border-ui-default text-ui-primary flex items-center gap-1 text-[11px] font-medium cursor-pointer disabled:opacity-35"+ >+ {player.isPlaying ? (+ <>+ <Pause className="w-3 h-3" />+ <span>Pause</span>+ </>+ ) : (+ <>+ <Play className="w-3 h-3" />+ <span>Play</span>+ </>+ )}+ </button>+ <button+ type="button"+ disabled={stats.frameCount === 0}+ onClick={() => player.stepBy(1)}+ title="Next frame (Right Arrow)"+ className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"+ >+ <ChevronRight className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => setLoop((l) => !l)}+ title={loop ? 'Loop playback on' : 'Loop playback off'}+ className={`p-1 rounded-ui-sm border cursor-pointer transition-colors ${+ loop+ ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-accent'+ : 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Repeat className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={handleCycleSpeed}+ title="Preview playback speed"+ className="px-1.5 py-0.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] font-ui-mono tabular-nums text-ui-secondary cursor-pointer"+ >+ {playbackSpeed}×+ </button>+ </div>- <div className="space-y-1">- <label className="text-[11px] text-ui-muted block">Resolution</label>- <div className="grid grid-cols-2 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">- {(['720p', '1080p'] as const).map((res) => (- <button- key={res}- type="button"- onClick={() => setResolution(res)}- className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${- resolution === res- ? 'bg-ui-control-active text-ui-primary font-semibold'- : 'text-ui-muted hover:text-ui-primary'- }`}- >- {res}- </button>- ))}+ <div className="flex items-center gap-2">+ <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">+ {stats.frameCount > 0+ ? `Key ${Math.min(player.currentSourceFrameIndex + 1, stats.frameCount)}/${stats.frameCount}`+ : '0/0'}+ </span>+ <button+ type="button"+ disabled={stats.frameCount === 0}+ onClick={() => setIsFullscreen(true)}+ title="Full-Screen Preview (F)"+ className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary cursor-pointer disabled:opacity-35"+ >+ <Maximize2 className="w-3 h-3" />+ </button>+ </div>+ </div></div></div>- <div className="space-y-1">- <label className="text-[11px] text-ui-muted block">Letterbox Background</label>- <div className="grid grid-cols-2 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {/* RIGHT: Tabbed Export, Watermark & Saved Recordings Controls */}+ <div className="md:col-span-5 flex flex-col min-h-0 bg-ui-panel">+ {/* Inspector Tabs */}+ <div className="grid grid-cols-3 border-b border-ui-subtle bg-ui-header shrink-0">+ <button+ type="button"+ onClick={() => setActiveTab('export')}+ className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${+ activeTab === 'export'+ ? 'border-ui-accent text-ui-primary bg-ui-panel'+ : 'border-transparent text-ui-muted hover:text-ui-primary'+ }`}+ >+ <SlidersHorizontal className="w-3 h-3" />+ <span>Export</span>+ </button><buttontype="button"- onClick={() => setBackgroundColor('#ffffff')}- className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${- backgroundColor === '#ffffff'- ? 'bg-ui-control-active text-ui-primary font-semibold'- : 'text-ui-muted hover:text-ui-primary'+ onClick={() => setActiveTab('watermark')}+ className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${+ activeTab === 'watermark'+ ? 'border-ui-accent text-ui-primary bg-ui-panel'+ : 'border-transparent text-ui-muted hover:text-ui-primary'}`}>- White+ <Stamp className="w-3 h-3" />+ <span>Watermark</span>+ {watermark.enabled && (+ <span className="w-1.5 h-1.5 rounded-full bg-ui-accent" />+ )}</button><buttontype="button"- onClick={() => setBackgroundColor('#141414')}- className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${- backgroundColor === '#141414'- ? 'bg-ui-control-active text-ui-primary font-semibold'- : 'text-ui-muted hover:text-ui-primary'+ onClick={() => setActiveTab('library')}+ className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${+ activeTab === 'library'+ ? 'border-ui-accent text-ui-primary bg-ui-panel'+ : 'border-transparent text-ui-muted hover:text-ui-primary'}`}>- Dark+ <FolderClock className="w-3 h-3" />+ <span>Library</span></button></div>++ <div className="flex-1 overflow-y-auto p-3.5 space-y-3">+ {activeTab === 'export' && (+ <>+ {/* FPS & Quality */}+ <div className="grid grid-cols-2 gap-2.5">+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ FPS+ </label>+ <div className="grid grid-cols-3 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {FPS_OPTIONS.map((f) => (+ <button+ key={f}+ type="button"+ disabled={isExporting}+ onClick={() => setFps(f)}+ className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${+ fps === f+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {f}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Quality+ </label>+ <div className="grid grid-cols-4 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {QUALITY_OPTIONS.map((q) => (+ <button+ key={q.value}+ type="button"+ disabled={isExporting}+ onClick={() => setQuality(q.value)}+ className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${+ quality === q.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {q.label}+ </button>+ ))}+ </div>+ </div>+ </div>++ {/* Export Resolution */}+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Export Resolution+ </label>+ <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {EXPORT_RES_OPTIONS.map((res) => (+ <button+ key={res.value}+ type="button"+ disabled={isExporting}+ onClick={() => setResolution(res.value)}+ className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${+ resolution === res.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {res.label}+ </button>+ ))}+ </div>+ </div>++ {/* Aspect Ratio */}+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Aspect Ratio+ </label>+ <div className="grid grid-cols-5 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {ASPECT_RATIO_OPTIONS.map((ar) => (+ <button+ key={ar.value}+ type="button"+ disabled={isExporting}+ onClick={() => setAspectRatio(ar.value)}+ className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${+ aspectRatio === ar.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {ar.label}+ </button>+ ))}+ </div>+ </div>++ {/* Letterbox Backdrop */}+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Letterbox Backdrop+ </label>+ <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {(+ [+ { value: 'white', label: 'White' },+ { value: 'dark', label: 'Dark' },+ { value: 'blur', label: 'Blur' },+ { value: 'custom', label: 'Custom' },+ ] as const+ ).map((bg) => (+ <button+ key={bg.value}+ type="button"+ disabled={isExporting}+ onClick={() => setBackgroundMode(bg.value)}+ className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${+ backgroundMode === bg.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {bg.label}+ </button>+ ))}+ </div>+ {backgroundMode === 'custom' && (+ <div className="flex items-center justify-between bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-1 mt-1">+ <span className="text-[10px] text-ui-muted">Background color</span>+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] font-ui-mono text-ui-secondary uppercase">+ {customBgColor}+ </span>+ <input+ type="color"+ value={customBgColor}+ disabled={isExporting}+ onChange={(e) => setCustomBgColor(e.target.value)}+ className="w-5 h-5 bg-transparent border-0 cursor-pointer"+ />+ </div>+ </div>+ )}+ </div>++ {/* FFmpeg Hardware-Friendly MP4 Toggle */}+ {ffmpegAvailable && (+ <div className="flex items-center justify-between bg-ui-header border border-ui-subtle px-2.5 py-2 rounded-ui-sm">+ <div>+ <div className="text-[11px] text-ui-primary font-medium">+ Native FFmpeg (.mp4)+ </div>+ <div className="text-[10px] text-ui-muted">+ Fast H.264 encode with watermark & CRF quality+ </div>+ </div>+ <ToggleSwitch+ checked={preferFfmpeg}+ onChange={setPreferFfmpeg}+ disabled={isExporting}+ aria-label="Use native FFmpeg encoder"+ />+ </div>+ )}++ {/* Quick Watermark Summary Link */}+ <button+ type="button"+ onClick={() => setActiveTab('watermark')}+ className="w-full flex items-center justify-between bg-ui-header hover:bg-ui-control border border-ui-subtle px-2.5 py-2 rounded-ui-sm text-left cursor-pointer transition-colors"+ >+ <div className="flex items-center gap-2 min-w-0">+ <Stamp className="w-3.5 h-3.5 text-ui-accent shrink-0" />+ <div className="min-w-0">+ <div className="text-[11px] text-ui-primary font-medium">Watermark</div>+ <div className="text-[10px] text-ui-muted truncate">+ {watermark.enabled+ ? watermark.mode === 'image'+ ? 'Custom logo enabled'+ : `"${watermark.text || 'Text'}" · ${watermark.position}`+ : 'Off — click to add text or logo'}+ </div>+ </div>+ </div>+ <ChevronRight className="w-3.5 h-3.5 text-ui-muted shrink-0" />+ </button>+ </>+ )}++ {activeTab === 'watermark' && (+ <TimelapseWatermarkControls+ config={watermark}+ onChange={handleWatermarkChange}+ disabled={isExporting}+ onError={(msg) => setErrorMsg(msg)}+ />+ )}++ {activeTab === 'library' && (+ <div className="space-y-2.5">+ <div className="flex items-center justify-between">+ <div className="text-[10px] text-ui-muted leading-snug">+ Saved locally outside your <span className="font-ui-mono">.ink</span>{' '}+ files so projects stay fast & lightweight.+ </div>+ <button+ type="button"+ onClick={() => void refreshStoredRecordings()}+ title="Refresh local recordings"+ className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-muted hover:text-ui-primary cursor-pointer shrink-0"+ >+ <RefreshCw+ className={`w-3 h-3 ${loadingRecordings ? 'animate-spin' : ''}`}+ />+ </button>+ </div>++ {storedRecordings.length === 0 ? (+ <div className="py-8 text-center text-[11px] text-ui-muted bg-ui-header/50 rounded-ui-md border border-ui-subtle">+ No locally stored recordings found yet.+ </div>+ ) : (+ <div className="space-y-1.5">+ {storedRecordings.map((rec) => {+ const isCurrent = rec.recordingId === stats.recordingId;+ return (+ <div+ key={rec.recordingId}+ className={`p-2 rounded-ui-md border flex items-center justify-between gap-2 ${+ isCurrent+ ? 'bg-ui-accent-subtle/50 border-ui-accent-border'+ : 'bg-ui-header border-ui-subtle'+ }`}+ >+ <div className="min-w-0">+ <div className="flex items-center gap-1.5">+ <span className="text-[11px] font-medium text-ui-primary truncate">+ {rec.documentName}+ </span>+ {isCurrent && (+ <span className="px-1 py-0.2 rounded-ui-xs bg-ui-accent text-ui-accent-contrast text-[9px] font-semibold">+ Active+ </span>+ )}+ </div>+ <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">+ {rec.frameCount} frames · {formatTimelapseBytes(rec.totalBytes)} ·{' '}+ {formatRelativeDate(rec.updatedAt)}+ </div>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ {!isCurrent && documentId && (+ <button+ type="button"+ disabled={isExporting}+ onClick={() => void handleAttachRecording(rec)}+ className="px-2 py-1 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary cursor-pointer"+ >+ Load+ </button>+ )}+ <button+ type="button"+ disabled={isExporting}+ onClick={() => void handleDeleteStoredRecording(rec)}+ title="Delete recording from local storage"+ className="p-1 rounded-ui-xs bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle text-ui-muted hover:text-ui-danger cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ )}++ {errorMsg && (+ <div className="text-[11px] text-ui-danger bg-ui-danger/15 border border-ui-danger/40 rounded-ui-sm px-2.5 py-2">+ {errorMsg}+ </div>+ )}+ </div></div></div>- {ffmpegAvailable && (- <label className="flex items-center justify-between bg-ui-header border border-ui-subtle px-3 py-2 rounded-ui-sm text-[11px] text-ui-primary cursor-pointer">- <span>Use native FFmpeg encoder (.mp4)</span>- <input- type="checkbox"- checked={preferFfmpeg}- onChange={(e) => setPreferFfmpeg(e.target.checked)}- />- </label>- )}-+ {/* Export Progress Bar */}{isExporting && (- <div className="space-y-1">+ <div className="px-4 py-2 bg-ui-header border-t border-ui-subtle space-y-1 shrink-0"><div className="flex items-center justify-between text-[10px] text-ui-muted">- <span>Rendering video frames...</span>- <span className="font-ui-mono tabular-nums">{Math.round(exportProgress * 100)}%</span>+ <span>+ Encoding {player.outputDims.width}×{player.outputDims.height} @ {fps} FPS...+ </span>+ <span className="font-ui-mono tabular-nums">+ {Math.round(exportProgress * 100)}%+ </span></div><div className="w-full h-1.5 bg-ui-input border border-ui-subtle rounded-full overflow-hidden"><div@@ -438,43 +1241,72 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({</div>)}- {errorMsg && (- <div className="text-[11px] text-ui-danger bg-ui-danger/15 border border-ui-danger/40 rounded-ui-sm px-3 py-2">- {errorMsg}+ {/* Footer */}+ <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex flex-wrap items-center justify-between gap-2 shrink-0">+ <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">+ Output: {player.outputDims.width}×{player.outputDims.height} · {fps} FPS ·{' '}+ {player.totalDurationSec.toFixed(1)}s · {quality}+ {ffmpegAvailable && preferFfmpeg ? ' · MP4' : ' · WebM'}</div>- )}- </div>- {/* Footer */}- <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-end gap-2">- <button- type="button"- onClick={onClose}- disabled={isExporting}- className="px-3.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary font-medium transition-colors cursor-pointer disabled:opacity-40"- >- Close- </button>- <button- type="button"- disabled={!documentId || stats.frameCount === 0 || isExporting}- onClick={handleExport}- className="px-4 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium flex items-center gap-1.5 transition-opacity cursor-pointer disabled:opacity-40"- >- {isExporting ? (- <>- <Loader2 className="w-3.5 h-3.5 animate-spin" />- <span>Exporting...</span>- </>- ) : (- <>- <Download className="w-3.5 h-3.5" />- <span>Export Video</span>- </>- )}- </button>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onClose}+ disabled={isExporting}+ className="px-3.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary font-medium transition-colors cursor-pointer disabled:opacity-40"+ >+ Close+ </button>+ <button+ type="button"+ disabled={!documentId || stats.frameCount === 0 || isExporting}+ onClick={handleExport}+ className="px-4 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium flex items-center gap-1.5 transition-opacity cursor-pointer disabled:opacity-40"+ >+ {isExporting ? (+ <>+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ <span>Exporting...</span>+ </>+ ) : (+ <>+ <Download className="w-3.5 h-3.5" />+ <span>Export Video</span>+ </>+ )}+ </button>+ </div>+ </div></div></div>- </div>++ {/* Full-Screen Immersive Playback Viewer */}+ <TimelapseFullscreenViewer+ isOpen={isFullscreen}+ onExit={() => setIsFullscreen(false)}+ documentName={cleanDocName}+ canvasRef={player.fullscreenCanvasRef}+ isPlaying={player.isPlaying}+ onTogglePlay={player.togglePlay}+ onStepBy={player.stepBy}+ onRestart={player.restart}+ timelineIndex={player.timelineIndex}+ totalTimelineFrames={player.totalTimelineFrames}+ onSeek={player.seekTo}+ currentTimeSec={player.currentTimeSec}+ totalDurationSec={player.totalDurationSec}+ currentSourceFrameIndex={player.currentSourceFrameIndex}+ totalCapturedFrames={stats.frameCount}+ duration={duration}+ onChangeDuration={setDuration}+ fps={fps}+ outputDims={player.outputDims}+ playbackSpeed={playbackSpeed}+ onCycleSpeed={handleCycleSpeed}+ loop={loop}+ onToggleLoop={() => setLoop((l) => !l)}+ />+ </>);};diff --git a/src/components/ToolOptionsBar.tsx b/src/components/ToolOptionsBar.tsxindex cdc59f0..4540a9b 100644--- a/src/components/ToolOptionsBar.tsx+++ b/src/components/ToolOptionsBar.tsx@@ -26,6 +26,7 @@ import {Spline,SquareDashed,Type,+ Underline,Waves,X,} from 'lucide-react';@@ -58,6 +59,7 @@ import {loadCustomBrushes,} from '../utils/brushStorage';import { activateQuickBrush, resolveQuickBrush } from '../utils/quickBrushUtils';+import { getTextFontOptions, queryInstalledSystemFonts } from '../utils/textSettings';import { Gizmo3DMode, Shading3DMode, Tool3DMode } from '../utils/tool3DRules';import {store3DActions,@@ -146,14 +148,6 @@ const RETOUCH_MODE_OPTIONS: ReadonlyArray<{ value: RetouchMode; label: string }>{ value: 'clone-stamp', label: 'Clone Stamp' },];-const FONT_FAMILY_OPTIONS: ReadonlyArray<{ value: string; label: string }> = [- { value: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif", label: 'Manga Dialogue' },- { value: "Inter, 'Segoe UI', system-ui, sans-serif", label: 'Sans Clean' },- { value: "Georgia, 'Times New Roman', serif", label: 'Editorial Serif' },- { value: "'Impact', 'Arial Black', sans-serif", label: 'SFX Bold' },- { value: "'JetBrains Mono', Consolas, monospace", label: 'Mono' },-];-const BRUSH_FILTER_TABS: ReadonlyArray<{ id: 'all' | BrushCategory | 'custom'; label: string }> = [{ id: 'all', label: 'All' },{ id: 'pen', label: 'Pen' },@@ -161,6 +155,7 @@ const BRUSH_FILTER_TABS: ReadonlyArray<{ id: 'all' | BrushCategory | 'custom'; l{ id: 'brush', label: 'Brush' },{ id: 'blend', label: 'Blend' },{ id: 'natural-paint', label: 'Paint' },+ { id: 'texture-fx', label: 'FX' },{ id: 'custom', label: 'Custom' },];@@ -1005,6 +1000,18 @@ TransformOptionsSegment.displayName = 'TransformOptionsSegment';const TextOptionsSegment: React.FC = React.memo(() => {const ts = useToolStore((s) => s.textSettings);+ const [systemFonts, setSystemFonts] = useState<string[]>([]);+ const fontOptions = useMemo(+ () => getTextFontOptions(ts.fontFamily, systemFonts),+ [ts.fontFamily, systemFonts]+ );++ const handleLoadSystemFonts = useCallback(() => {+ if (systemFonts.length > 0) return;+ void queryInstalledSystemFonts().then((fonts) => {+ if (fonts.length > 0) setSystemFonts(fonts);+ });+ }, [systemFonts.length]);return (<>@@ -1012,11 +1019,13 @@ const TextOptionsSegment: React.FC = React.memo(() => {<selectaria-label="Font Family"value={ts.fontFamily}+ onFocus={handleLoadSystemFonts}onChange={(e) => toolStoreActions.updateTextSettings({ fontFamily: e.target.value })}- className={`${compactSelectClass} max-w-[132px]`}+ className={`${compactSelectClass} max-w-[144px]`}+ style={{ fontFamily: ts.fontFamily }}>- {FONT_FAMILY_OPTIONS.map((f) => (- <option key={f.label} value={f.value}>+ {fontOptions.map((f) => (+ <option key={f.value} value={f.value} style={{ fontFamily: f.value }}>{f.label}</option>))}@@ -1026,22 +1035,35 @@ const TextOptionsSegment: React.FC = React.memo(() => {<ScrubSliderlabel="Size"size="xs"- min={8}- max={180}+ min={6}+ max={400}step={1}- defaultValue={28}+ defaultValue={36}unit="px"value={ts.fontSize}onChange={(v) => toolStoreActions.updateTextSettings({ fontSize: v })}/></div>- <div className="w-[96px] shrink-0">+ <label+ title={`Text Color (${ts.color || '#ffffff'})`}+ className="w-[22px] h-[22px] rounded-ui-xs border border-ui-subtle hover:border-ui-strong bg-ui-input flex items-center justify-center cursor-pointer shrink-0 overflow-hidden"+ >+ <input+ type="color"+ aria-label="Text Color"+ value={ts.color || '#ffffff'}+ onChange={(e) => toolStoreActions.updateTextSettings({ color: e.target.value })}+ className="w-6 h-6 p-0 border-0 bg-transparent cursor-pointer"+ />+ </label>++ <div className="w-[92px] shrink-0"><ScrubSliderlabel="Lead"size="xs"- min={0.8}- max={2.5}+ min={0.7}+ max={3.0}step={0.05}defaultValue={1.25}value={ts.lineSpacing ?? 1.25}@@ -1049,22 +1071,43 @@ const TextOptionsSegment: React.FC = React.memo(() => {/></div>+ <div className="w-[92px] shrink-0">+ <ScrubSlider+ label="Track"+ size="xs"+ min={-10}+ max={40}+ step={0.5}+ defaultValue={0}+ unit="px"+ value={ts.letterSpacing ?? 0}+ onChange={(v) => toolStoreActions.updateTextSettings({ letterSpacing: v })}+ />+ </div>+<BarDivider /><ToggleChipactive={ts.bold}label=""- title="Bold"+ title="Bold (Ctrl+B)"icon={<Bold className="w-3 h-3" />}onClick={() => toolStoreActions.updateTextSettings({ bold: !ts.bold })}/><ToggleChipactive={ts.italic}label=""- title="Italic"+ title="Italic (Ctrl+I)"icon={<Italic className="w-3 h-3" />}onClick={() => toolStoreActions.updateTextSettings({ italic: !ts.italic })}/>+ <ToggleChip+ active={Boolean(ts.underline)}+ label=""+ title="Underline (Ctrl+U)"+ icon={<Underline className="w-3 h-3" />}+ onClick={() => toolStoreActions.updateTextSettings({ underline: !ts.underline })}+ /><div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">{(@@ -1090,6 +1133,17 @@ const TextOptionsSegment: React.FC = React.memo(() => {))}</div>+ <ToggleChip+ active={ts.writingMode === 'vertical-rl'}+ label={ts.writingMode === 'vertical-rl' ? 'Vert' : 'Horiz'}+ title="Toggle Horizontal / Vertical Writing Mode"+ onClick={() =>+ toolStoreActions.updateTextSettings({+ writingMode: ts.writingMode === 'vertical-rl' ? 'horizontal-tb' : 'vertical-rl',+ })+ }+ />+<BarDivider /><ToggleChip@@ -1098,20 +1152,41 @@ const TextOptionsSegment: React.FC = React.memo(() => {onClick={() => toolStoreActions.updateTextSettings({ outline: !ts.outline })}/>{ts.outline && (- <div className="w-[88px] shrink-0">- <ScrubSlider- label="Width"- size="xs"- min={1}- max={16}- step={1}- defaultValue={3}- unit="px"- value={ts.outlineWidth}- onChange={(v) => toolStoreActions.updateTextSettings({ outlineWidth: v })}- />- </div>+ <>+ <div className="w-[88px] shrink-0">+ <ScrubSlider+ label="Width"+ size="xs"+ min={1}+ max={24}+ step={1}+ defaultValue={3}+ unit="px"+ value={ts.outlineWidth}+ onChange={(v) => toolStoreActions.updateTextSettings({ outlineWidth: v })}+ />+ </div>+ <label+ title={`Outline Color (${ts.outlineColor || '#000000'})`}+ className="w-[22px] h-[22px] rounded-ui-xs border border-ui-subtle hover:border-ui-strong bg-ui-input flex items-center justify-center cursor-pointer shrink-0 overflow-hidden"+ >+ <input+ type="color"+ aria-label="Outline Color"+ value={ts.outlineColor || '#000000'}+ onChange={(e) => toolStoreActions.updateTextSettings({ outlineColor: e.target.value })}+ className="w-6 h-6 p-0 border-0 bg-transparent cursor-pointer"+ />+ </label>+ </>)}++ <ActionChip+ label="Reset"+ title="Reset to plain white text without outline"+ icon={<RotateCcw className="w-3 h-3" />}+ onClick={() => toolStoreActions.resetTextSettings()}+ /></>);});diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsxindex 625cde0..fa7f7ba 100644--- a/src/components/ToolPropertyInspector.tsx+++ b/src/components/ToolPropertyInspector.tsx@@ -15,6 +15,13 @@ import {Trash2,Crop,AlertTriangle,+ Bold,+ Italic,+ Underline,+ AlignLeft,+ AlignCenter,+ AlignRight,+ Pipette,} from 'lucide-react';import {BrushSettings,@@ -44,6 +51,11 @@ import {isPaintTool,} from '../types/editor';import { isOpenShape } from '../utils/shapeEngine';+import {+ getTextFontOptions,+ queryInstalledSystemFonts,+ TEXT_QUICK_COLORS,+} from '../utils/textSettings';import {GRADIENT_PRESETS,getSelectedMeshNodeIndices,@@ -2015,22 +2027,44 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React}if (currentTool === 'text') {+ const fontOptions = getTextFontOptions(textSettings.fontFamily);return (<div className="p-2.5 space-y-3 overflow-y-auto flex-1">- <div className="text-[11px] font-medium text-ui-primary">Text</div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[11px] font-medium text-ui-primary">Text</span>+ <button+ type="button"+ onClick={() => toolStoreActions.resetTextSettings()}+ title="Reset to plain white text without outline"+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors"+ >+ <RotateCcw className="w-2.5 h-2.5" />+ <span>Plain White</span>+ </button>+ </div>+<select+ aria-label="Font Family"value={textSettings.fontFamily}+ onFocus={() => {+ void queryInstalledSystemFonts();+ }}onChange={(e) => toolStoreActions.updateTextSettings({ fontFamily: e.target.value })}- className="w-full px-2 py-1 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm"+ className="w-full px-2 py-1 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"+ style={{ fontFamily: textSettings.fontFamily }}>- <option value="'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif">- Manga / Anime- </option>- <option value="'Anime Ace', 'Comic Sans MS', sans-serif">Anime Ace</option>- <option value="Arial, sans-serif">Arial</option>- <option value="Impact, sans-serif">Impact</option>- <option value="Georgia, serif">Georgia</option>+ {fontOptions.map((f) => (+ <option+ key={f.value}+ value={f.value}+ className="bg-ui-elevated text-ui-primary"+ style={{ fontFamily: f.value }}+ >+ {f.label}+ </option>+ ))}</select>+<SegmentedControlsize="xs"fullWidth@@ -2038,18 +2072,204 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactvalue={textSettings.writingMode === 'vertical-rl' ? 'vertical-rl' : 'horizontal-tb'}onChange={(mode) => toolStoreActions.updateTextSettings({ writingMode: mode })}options={[- { value: 'horizontal-tb', label: 'Horiz' },- { value: 'vertical-rl', label: 'Vert' },+ { value: 'horizontal-tb', label: 'Horizontal' },+ { value: 'vertical-rl', label: 'Vertical' },]}/>++ {/* Formatting & Alignment */}+ <div className="flex items-center justify-between gap-1.5">+ <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ <button+ type="button"+ title="Bold (Ctrl+B)"+ onClick={() => toolStoreActions.updateTextSettings({ bold: !textSettings.bold })}+ className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ textSettings.bold+ ? 'bg-ui-control-active text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Bold className="w-3 h-3" />+ </button>+ <button+ type="button"+ title="Italic (Ctrl+I)"+ onClick={() =>+ toolStoreActions.updateTextSettings({ italic: !textSettings.italic })+ }+ className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ textSettings.italic+ ? 'bg-ui-control-active text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Italic className="w-3 h-3" />+ </button>+ <button+ type="button"+ title="Underline (Ctrl+U)"+ onClick={() =>+ toolStoreActions.updateTextSettings({ underline: !textSettings.underline })+ }+ className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ textSettings.underline+ ? 'bg-ui-control-active text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Underline className="w-3 h-3" />+ </button>+ </div>++ <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {(+ [+ { id: 'left', icon: <AlignLeft className="w-3 h-3" /> },+ { id: 'center', icon: <AlignCenter className="w-3 h-3" /> },+ { id: 'right', icon: <AlignRight className="w-3 h-3" /> },+ ] as const+ ).map((a) => (+ <button+ key={a.id}+ type="button"+ title={`Align ${a.id}`}+ onClick={() => toolStoreActions.updateTextSettings({ align: a.id })}+ className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${+ textSettings.align === a.id+ ? 'bg-ui-control-active text-ui-accent'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {a.icon}+ </button>+ ))}+ </div>+ </div>+<CompactSliderlabel="Font Size"- valueLabel={`${textSettings.fontSize ?? 28}px`}- min={12}- max={160}- value={textSettings.fontSize ?? 28}+ valueLabel={`${textSettings.fontSize ?? 36}px`}+ min={6}+ max={400}+ value={textSettings.fontSize ?? 36}onChange={(v) => toolStoreActions.updateTextSettings({ fontSize: v })}/>+ <CompactSlider+ label="Line Height"+ valueLabel={`${(textSettings.lineSpacing ?? 1.25).toFixed(2)}×`}+ min={0.7}+ max={3.0}+ step={0.05}+ value={textSettings.lineSpacing ?? 1.25}+ onChange={(v) => toolStoreActions.updateTextSettings({ lineSpacing: v })}+ />+ <CompactSlider+ label="Letter Spacing"+ valueLabel={`${(textSettings.letterSpacing ?? 0).toFixed(1)}px`}+ min={-10}+ max={40}+ step={0.5}+ value={textSettings.letterSpacing ?? 0}+ onChange={(v) => toolStoreActions.updateTextSettings({ letterSpacing: v })}+ />+ <CompactSlider+ label="Opacity"+ valueLabel={`${Math.round((textSettings.opacity ?? 1) * 100)}%`}+ min={5}+ max={100}+ step={1}+ value={Math.round((textSettings.opacity ?? 1) * 100)}+ onChange={(v) => toolStoreActions.updateTextSettings({ opacity: v / 100 })}+ />++ {/* Text Color */}+ <div className="space-y-1.5 pt-2 border-t border-ui-subtle">+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Text Color</span>+ <button+ type="button"+ onClick={() =>+ toolStoreActions.updateTextSettings({+ color: useToolStore.getState().primaryColor || '#ffffff',+ })+ }+ title="Copy current brush color"+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer"+ >+ <Pipette className="w-2.5 h-2.5" />+ <span>Brush</span>+ </button>+ </div>+ <div className="flex items-center gap-1.5 flex-wrap">+ {TEXT_QUICK_COLORS.map((swatch) => (+ <button+ key={swatch.hex}+ type="button"+ title={swatch.label}+ onClick={() => toolStoreActions.updateTextSettings({ color: swatch.hex })}+ className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${+ (textSettings.color || '#ffffff').toLowerCase() === swatch.hex+ ? 'border-ui-accent ring-1 ring-ui-accent-border'+ : 'border-ui-default hover:border-ui-strong'+ }`}+ style={{ backgroundColor: swatch.hex }}+ />+ ))}+ <input+ type="color"+ aria-label="Custom Text Color"+ value={textSettings.color || '#ffffff'}+ onChange={(e) => toolStoreActions.updateTextSettings({ color: e.target.value })}+ className="w-6 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"+ />+ </div>+ </div>++ {/* Optional Outline (off by default) */}+ <div className="space-y-2 pt-2 border-t border-ui-subtle">+ <label className="flex items-center justify-between text-[11px] text-ui-primary cursor-pointer">+ <span>Outline</span>+ <input+ type="checkbox"+ checked={Boolean(textSettings.outline)}+ onChange={(e) =>+ toolStoreActions.updateTextSettings({ outline: e.target.checked })+ }+ className="cursor-pointer"+ />+ </label>+ {textSettings.outline && (+ <div className="space-y-2">+ <CompactSlider+ label="Outline Width"+ valueLabel={`${textSettings.outlineWidth ?? 3}px`}+ min={1}+ max={24}+ value={textSettings.outlineWidth ?? 3}+ onChange={(v) => toolStoreActions.updateTextSettings({ outlineWidth: v })}+ />+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Outline Color</span>+ <input+ type="color"+ aria-label="Outline Color"+ value={textSettings.outlineColor || '#000000'}+ onChange={(e) =>+ toolStoreActions.updateTextSettings({ outlineColor: e.target.value })+ }+ className="w-6 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"+ />+ </div>+ </div>+ )}+ </div>++ <div className="text-[10px] text-ui-muted leading-relaxed pt-2 border-t border-ui-subtle space-y-0.5">+ <div>• Click canvas to type, or drag to create a wrapped text box</div>+ <div>• Click existing text to re-edit non-destructively</div>+ <div>• Latest typography settings save automatically</div>+ </div></div>);}diff --git a/src/components/WebtoonExportModal.tsx b/src/components/WebtoonExportModal.tsxindex f25d8c2..5106c5a 100644--- a/src/components/WebtoonExportModal.tsx+++ b/src/components/WebtoonExportModal.tsx@@ -4,7 +4,7 @@ import { uiStoreActions } from '../stores';import {exportWebtoonChapterZip,exportWebtoonChapterZipFromRenderer,- downloadWebtoonZip,+ saveWebtoonZipWithDialog,WebtoonRegionRenderer,} from '../utils/webtoonExporter';@@ -93,9 +93,12 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({}const zipName = `${documentTitle.replace(/\s+/g, '_')}_slices.zip`;- downloadWebtoonZip(zipBytes, zipName);+ const saveRes = await saveWebtoonZipWithDialog(zipBytes, zipName);setIsExporting(false);setProgress(null);+ if (saveRes.canceled) {+ return;+ }onClose();} catch (err) {console.error('Webtoon export error:', err);diff --git a/src/components/WelcomeScreen.tsx b/src/components/WelcomeScreen.tsxindex e3f3e75..d50539b 100644--- a/src/components/WelcomeScreen.tsx+++ b/src/components/WelcomeScreen.tsx@@ -336,10 +336,6 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({<span className="text-[10px] font-ui-mono uppercase tracking-[0.14em] text-ui-muted leading-none">Ink Studio</span>- <span className="w-1 h-1 rounded-full bg-ui-strong" aria-hidden="true" />- <span className="text-[10px] font-ui-mono text-ui-muted leading-none">- Atelier- </span></div><h1 className="text-[14px] font-medium tracking-[-0.01em] text-ui-primary truncate mt-0.5 leading-tight">{trimmedName ? `Welcome back, ${trimmedName}` : 'Studio Workspace'}diff --git a/src/components/WorkspaceAndBarsTab.tsx b/src/components/WorkspaceAndBarsTab.tsxindex fafd53e..23883b5 100644--- a/src/components/WorkspaceAndBarsTab.tsx+++ b/src/components/WorkspaceAndBarsTab.tsx@@ -27,6 +27,7 @@ import {workspaceStoreActions,} from '../stores';import { IconButton, ToggleSwitch } from './ui';+import { saveFileWithDialog } from '../utils/fileSaveDialog';export interface WorkspaceAndBarsTabProps {onNotify: (message: string) => void;@@ -60,21 +61,16 @@ function slugifyWorkspaceName(name: string): string {return slug || 'ink-studio-workspace';}-function triggerJsonFileDownload(fileName: string, json: string): boolean {- try {- const blob = new Blob([json], { type: 'application/json;charset=utf-8' });- const url = URL.createObjectURL(blob);- const anchor = document.createElement('a');- anchor.href = url;- anchor.download = fileName;- document.body.appendChild(anchor);- anchor.click();- document.body.removeChild(anchor);- setTimeout(() => URL.revokeObjectURL(url), 1000);- return true;- } catch {- return false;- }+async function saveWorkspaceBundleFile(fileName: string, json: string) {+ return saveFileWithDialog({+ data: json,+ suggestedName: fileName,+ mimeType: 'application/json',+ description: 'Ink Studio Workspace',+ extensions: ['.inkworkspace', '.json'],+ category: 'workspace',+ title: 'Save Workspace As',+ });}export const WorkspaceAndBarsTab: React.FC<WorkspaceAndBarsTabProps> = React.memo(@@ -128,7 +124,7 @@ export const WorkspaceAndBarsTab: React.FC<WorkspaceAndBarsTabProps> = React.mem);const handleExportCurrentBundle = useCallback(- (profileId?: string, profileName?: string) => {+ async (profileId?: string, profileName?: string) => {const activeSaved = activeSavedWorkspaceId? savedWorkspaces.find((ws) => ws.id === activeSavedWorkspaceId): undefined;@@ -145,9 +141,15 @@ export const WorkspaceAndBarsTab: React.FC<WorkspaceAndBarsTabProps> = React.memauthor: userName?.trim() || undefined,});const fileName = `${slugifyWorkspaceName(resolvedName)}.inkworkspace`;- if (triggerJsonFileDownload(fileName, json)) {- onNotify(`Exported ${fileName}`);- } else {+ try {+ const res = await saveWorkspaceBundleFile(fileName, json);+ if (res.canceled) return;+ if (res.saved) {+ onNotify(`Exported ${res.fileName}`);+ } else {+ onNotify('Unable to export .inkworkspace file');+ }+ } catch {onNotify('Unable to export .inkworkspace file');}},diff --git a/src/components/__tests__/colorPalettes.test.tsx b/src/components/__tests__/colorPalettes.test.tsxindex 7e644f5..135e753 100644--- a/src/components/__tests__/colorPalettes.test.tsx+++ b/src/components/__tests__/colorPalettes.test.tsx@@ -1,5 +1,6 @@import { Profiler, act } from 'react';import { createRoot, Root } from 'react-dom/client';+import { zlibSync } from 'fflate';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ColorSetsPanel } from '../ColorSetsPanel';import { ColorHistoryPanel } from '../ColorHistoryPanel';@@ -846,4 +847,115 @@ describe('Color Palette Ecosystem Upgrade', () => {expect(setsRenders).toBe(1);expect(historyRenders).toBe(1);});++ it('ColorSetsPanel imports Clip Studio .cls and .png color set files via file picker and drag-and-drop', async () => {+ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(<ColorSetsPanel colorMode="color" containerWidth={224} />);+ });++ const fileInput = dom.container.findByAttr('data-testid', 'color-sets-import-input');+ expect(fileInput).not.toBeNull();+ const acceptAttr = fileInput!.getAttribute('accept') ?? '';+ expect(acceptAttr).toContain('.cls');+ expect(acceptAttr).toContain('.png');+ expect(acceptAttr).toContain('.json');++ // Construct a minimal valid Clip Studio .cls file ("Studio Ink" with 2 swatches)+ const nameBytes = new TextEncoder().encode('Studio Ink');+ const headerLen = 2 + nameBytes.length + 4 + 2 + nameBytes.length;+ const clsBytes = new Uint8Array(10 + headerLen + 12 + 24);+ const dv = new DataView(clsBytes.buffer);+ clsBytes.set([0x53, 0x4c, 0x43, 0x43], 0); // SLCC+ dv.setUint16(4, 256, true);+ dv.setUint32(6, headerLen, true);+ let p = 10;+ dv.setUint16(p, nameBytes.length, true);+ p += 2;+ clsBytes.set(nameBytes, p);+ p += nameBytes.length + 4;+ dv.setUint16(p, nameBytes.length, true);+ p += 2;+ clsBytes.set(nameBytes, p);+ p += nameBytes.length;+ dv.setUint32(p, 4, true);+ dv.setUint32(p + 4, 2, true);+ dv.setUint32(p + 8, 24, true);+ p += 12;+ // Swatch 1: #ff3264+ dv.setUint32(p, 8, true);+ clsBytes.set([0xff, 0x32, 0x64, 0xff], p + 4);+ p += 12;+ // Swatch 2: #37aa87+ dv.setUint32(p, 8, true);+ clsBytes.set([0x37, 0xaa, 0x87, 0xff], p + 4);++ const clsFile = new File([clsBytes], 'Studio Ink.cls', { type: 'application/octet-stream' });++ const inputProps = getReactProps(fileInput!);+ expect(inputProps?.onChange).toBeTypeOf('function');+ await act(async () => {+ await inputProps!.onChange({+ target: { files: [clsFile], value: 'Studio Ink.cls' },+ currentTarget: { files: [clsFile], value: 'Studio Ink.cls' },+ });+ });++ const importedClsSet = useColorSetsStore.getState().sets.find((s) => s.name === 'Studio Ink');+ expect(importedClsSet).toBeDefined();+ expect(importedClsSet!.swatches.map((s) => s.hex)).toEqual(['#ff3264', '#37aa87']);+ expect(useColorSetsStore.getState().activeSetId).toBe(importedClsSet!.id);++ // Construct a minimal 2x1 RGBA PNG palette ("Pastel Duo.png") and drop it onto ColorSetsPanel+ const makeChunk = (type: string, data: Uint8Array) => {+ const c = new Uint8Array(12 + data.length);+ const cdv = new DataView(c.buffer);+ cdv.setUint32(0, data.length, false);+ for (let i = 0; i < 4; i++) c[4 + i] = type.charCodeAt(i);+ c.set(data, 8);+ return c;+ };+ const ihdr = new Uint8Array(13);+ const idv = new DataView(ihdr.buffer);+ idv.setUint32(0, 2, false);+ idv.setUint32(4, 1, false);+ ihdr[8] = 8;+ ihdr[9] = 6;+ const scanline = new Uint8Array([0, 0xfe, 0xd7, 0xaa, 0xff, 0xbf, 0xdb, 0xfe, 0xff]);+ const chunks = [+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ makeChunk('IHDR', ihdr),+ makeChunk('IDAT', zlibSync(scanline)),+ makeChunk('IEND', new Uint8Array(0)),+ ];+ const pngBytes = new Uint8Array(chunks.reduce((s, c) => s + c.length, 0));+ let off = 0;+ for (const c of chunks) {+ pngBytes.set(c, off);+ off += c.length;+ }++ const pngFile = new File([pngBytes], 'Pastel Duo.png', { type: 'image/png' });+ const panelEl = dom.container.findByAttr('data-testid', 'color-sets-panel');+ const panelProps = getReactProps(panelEl!);+ expect(panelProps?.onDrop).toBeTypeOf('function');++ await act(async () => {+ panelProps!.onDrop({+ preventDefault: () => {},+ stopPropagation: () => {},+ dataTransfer: {+ types: ['Files'],+ files: [pngFile],+ },+ });+ await Promise.resolve();+ await Promise.resolve();+ });++ const importedPngSet = useColorSetsStore.getState().sets.find((s) => s.name === 'Pastel Duo');+ expect(importedPngSet).toBeDefined();+ expect(importedPngSet!.swatches.map((s) => s.hex)).toEqual(['#fed7aa', '#bfdbfe']);+ expect(useColorSetsStore.getState().activeSetId).toBe(importedPngSet!.id);+ });});diff --git a/src/components/brushStudio/BrushStudioTabsSecondary.tsx b/src/components/brushStudio/BrushStudioTabsSecondary.tsxindex 0b70bd6..04d2beb 100644--- a/src/components/brushStudio/BrushStudioTabsSecondary.tsx+++ b/src/components/brushStudio/BrushStudioTabsSecondary.tsx@@ -669,6 +669,7 @@ export const AboutPresetsTab: React.FC<AboutPresetsTabProps> = ({<option value="brush">Brush</option><option value="blend">Blend</option><option value="natural-paint">Natural Paint</option>+ <option value="texture-fx">Texture & FX</option><option value="custom">Custom</option></select></div>diff --git a/src/components/canvasArea/CanvasArtboardOverlays.tsx b/src/components/canvasArea/CanvasArtboardOverlays.tsxindex cd44f7b..1bfd7cc 100644--- a/src/components/canvasArea/CanvasArtboardOverlays.tsx+++ b/src/components/canvasArea/CanvasArtboardOverlays.tsx@@ -8,6 +8,7 @@ import { Local3DContainer } from '../Local3DContainer';import { GradientOverlay } from '../GradientOverlay';import { PenPathOverlay } from '../PenPathOverlay';import { QuickShapeOverlay } from '../QuickShapeOverlay';+import { CanvasResizeOverlay } from '../CanvasResizeOverlay';import { RemotePeerCursorsOverlay } from './RemotePeerCursorsOverlay';import { CanvasAreaProps, formatArtboardTransform } from './types';@@ -60,6 +61,8 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onMoveTextSession,onConfirmText,onCancelText,+ onDeleteText,+ textDragPreview = null,activeBalloon = null,onUpdateBalloon,onConfirmBalloon,@@ -200,12 +203,14 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({/>)}- {/* Manga Text Editor Overlay */}+ {/* Direct WYSIWYG Text Editor Overlay */}{textSession && (<TextEditorOverlayx={textSession.x}y={textSession.y}settings={textSession.settings}+ editingLayerId={textSession.editingLayerId}+ primaryColor={canvasProps.primaryColor}zoom={liveZoom}rotation={liveRotation}flipX={liveFlipX}@@ -214,9 +219,30 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onMove={onMoveTextSession || (() => {})}onConfirm={onConfirmText || (() => {})}onCancel={onCancelText || (() => {})}+ onDelete={onDeleteText}/>)}+ {/* Click-Drag Wrapped Text Box Preview */}+ {textDragPreview && (+ <svg+ data-testid="text-drag-preview-svg"+ className="absolute inset-0 w-full h-full overflow-visible pointer-events-none z-35"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ <rect+ x={Math.min(textDragPreview.start.x, textDragPreview.end.x)}+ y={Math.min(textDragPreview.start.y, textDragPreview.end.y)}+ width={Math.abs(textDragPreview.end.x - textDragPreview.start.x)}+ height={Math.abs(textDragPreview.end.y - textDragPreview.start.y)}+ fill="rgba(56, 189, 248, 0.08)"+ stroke="#38bdf8"+ strokeWidth={1.5 / liveZoom}+ strokeDasharray={`${5 / liveZoom},${3 / liveZoom}`}+ />+ </svg>+ )}+{/* Parametric Speech Balloon Overlay */}{activeBalloon && (<SpeechBalloonOverlay@@ -648,6 +674,29 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onUpdatePerspectiveRuler={onUpdatePerspectiveRuler}/>)}++ {/* Interactive Resize Canvas / Manual Crop Overlay */}+ <CanvasResizeOverlay+ dimensions={dimensions}+ viewportRef={canvasProps.viewportRef}+ navigation={canvasProps.navigation}+ pan={livePan}+ zoom={liveZoom}+ rotation={liveRotation}+ flipX={liveFlipX}+ flipY={liveFlipY}+ isNavigationActive={+ canvasProps.isSpaceDown ||+ canvasProps.isPanning ||+ canvasProps.isRotating ||+ Boolean(canvasProps.isZoomDragging) ||+ canvasProps.isRotateModifier ||+ canvasProps.heldModifierAction === 'pan' ||+ canvasProps.heldModifierAction === 'rotate' ||+ canvasProps.heldModifierAction === 'zoom-drag'+ }+ onApply={canvasProps.onApplyResizeCanvas}+ /></div>);};diff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.tsindex 9fbbd69..45dccd7 100644--- a/src/components/canvasArea/types.ts+++ b/src/components/canvasArea/types.ts@@ -29,7 +29,7 @@ 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 { ModifierAction, ResizeCanvasOptions } from '../../types/settings';import { ExternalFileDropPayloadKind } from '../../utils/fileDropImport';import { isNaturalPaintBrush } from '../../engine/NaturalPaintRenderer';@@ -101,11 +101,18 @@ export interface CanvasAreaProps {onUpdateTransformSession?: (updater: (prev: TransformSession) => TransformSession) => void;onApplyTransform?: () => void;onCancelTransform?: () => void;- textSession?: { x: number; y: number; settings: TextSettings } | null;+ textSession?: {+ x: number;+ y: number;+ settings: TextSettings;+ editingLayerId?: string | null;+ } | null;onUpdateTextSettings?: (updater: (prev: TextSettings) => TextSettings) => void;onMoveTextSession?: (x: number, y: number) => void;onConfirmText?: () => void;onCancelText?: () => void;+ onDeleteText?: () => void;+ textDragPreview?: { start: { x: number; y: number }; end: { x: number; y: number } } | null;perspectiveRuler?: PerspectiveRuler | null;onUpdatePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;straightRuler?: StraightRuler | null;@@ -166,6 +173,7 @@ export interface CanvasAreaProps {tileGrid?: SparseTileGrid;isExternalFileDropActive?: boolean;externalFileDropKind?: ExternalFileDropPayloadKind;+ onApplyResizeCanvas?: (options: ResizeCanvasOptions) => void;}export type CursorRotationSource = 'none' | 'direction' | 'tilt' | 'twist';@@ -352,6 +360,7 @@ export interface CursorStyleParams {isRotateModifier: boolean;isPanning: boolean;isSpaceDown: boolean;+ isResizeCanvasOpen?: boolean;tool: ToolType;fillMethod?: FillMethod;}@@ -433,6 +442,7 @@ export function getCursorStyle({isRotateModifier,isPanning,isSpaceDown,+ isResizeCanvasOpen = false,tool,fillMethod,}: CursorStyleParams): React.CSSProperties {@@ -451,6 +461,9 @@ export function getCursorStyle({if (isSpaceDown || heldModifierAction === 'pan') {return { cursor: 'grab' };}+ if (isResizeCanvasOpen) {+ return { cursor: 'default' };+ }if (tool === 'pipette' || heldModifierAction === 'eyedropper') {return { cursor: PIPETTE_CURSOR_CSS };}diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.tsindex ba26661..29b3062 100644--- a/src/components/canvasArea/useCanvasEffects.ts+++ b/src/components/canvasArea/useCanvasEffects.ts@@ -6,6 +6,7 @@ import { computeTipStampDimensions } from '../../engine/BrushEngine';import { preloadTipImage } from '../../utils/brushStorage';import { shouldSuppressDomPointerEvent, subscribeNativeTablet } from '../../utils/nativeTabletInput';import { isNaturalPaintBrush } from '../../engine/NaturalPaintRenderer';+import { useUiStore } from '../../stores';import {computeEffectiveCursorAngleDeg,computeNextDynamicCursorAngleDeg,@@ -266,7 +267,10 @@ export function useCanvasEffects({brushSettings.preset,]);+ const isResizeCanvasModalOpen = useUiStore((s) => s.isResizeCanvasModalOpen);+const shouldHideCursorRing =+ isResizeCanvasModalOpen ||isSpaceDown ||isPanning ||isRotating ||diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex 950b116..6cef439 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -270,8 +270,20 @@ export function useCanvasPointerHandlers({},modSettings);- if (resolved && dispatchModifierAction(resolved.action, e, false)) {- return;+ if (resolved) {+ if (useUiStore.getState().isResizeCanvasModalOpen) {+ if (+ resolved.action === 'pan' ||+ resolved.action === 'rotate' ||+ resolved.action === 'zoom-drag'+ ) {+ dispatchModifierAction(resolved.action, e, false);+ }+ return;+ }+ if (dispatchModifierAction(resolved.action, e, false)) {+ return;+ }}};@@ -297,11 +309,27 @@ export function useCanvasPointerHandlers({);if (resolved) {+ if (useUiStore.getState().isResizeCanvasModalOpen) {+ if (+ resolved.action === 'pan' ||+ resolved.action === 'rotate' ||+ resolved.action === 'zoom-drag'+ ) {+ if (dispatchModifierAction(resolved.action, e, false)) {+ return;+ }+ }+ return;+ }if (dispatchModifierAction(resolved.action, e, true)) {return;}}+ if (useUiStore.getState().isResizeCanvasModalOpen) {+ return;+ }+if (e.button === 0) {e.preventDefault();e.stopPropagation();@@ -337,7 +365,7 @@ export function useCanvasPointerHandlers({};const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {- if (isWorkspaceInteractionActive()) return;+ if (isWorkspaceInteractionActive() || useUiStore.getState().isResizeCanvasModalOpen) return;if ((tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)diff --git a/src/components/timelapse/TimelapseFullscreenViewer.tsx b/src/components/timelapse/TimelapseFullscreenViewer.tsxnew file mode 100644index 0000000..12ee28a--- /dev/null+++ b/src/components/timelapse/TimelapseFullscreenViewer.tsx@@ -0,0 +1,327 @@+import React, { useEffect, useRef, useState } from 'react';+import {+ ChevronLeft,+ ChevronRight,+ Minimize2,+ Pause,+ Play,+ Repeat,+ SkipBack,+ X,+} from 'lucide-react';+import { TimelapseDurationPreset } from '../../utils/timelapseEngine';+import { formatTimecode, TimelapsePlaybackSpeed } from './useTimelapsePreviewPlayer';++const QUICK_INTERVALS: Array<{ value: TimelapseDurationPreset; label: string }> = [+ { value: '15s', label: '15s' },+ { value: '30s', label: '30s' },+ { value: '60s', label: '60s' },+ { value: '120s', label: '2m' },+ { value: 'full', label: 'Full' },+];++export interface TimelapseFullscreenViewerProps {+ isOpen: boolean;+ onExit: () => void;+ documentName: string;+ canvasRef: React.RefObject<HTMLCanvasElement | null>;+ isPlaying: boolean;+ onTogglePlay: () => void;+ onStepBy: (delta: number) => void;+ onRestart: () => void;+ timelineIndex: number;+ totalTimelineFrames: number;+ onSeek: (idx: number) => void;+ currentTimeSec: number;+ totalDurationSec: number;+ currentSourceFrameIndex: number;+ totalCapturedFrames: number;+ duration: TimelapseDurationPreset;+ onChangeDuration: (d: TimelapseDurationPreset) => void;+ fps: number;+ outputDims: { width: number; height: number };+ playbackSpeed: TimelapsePlaybackSpeed;+ onCycleSpeed: () => void;+ loop: boolean;+ onToggleLoop: () => void;+}++export const TimelapseFullscreenViewer: React.FC<TimelapseFullscreenViewerProps> = ({+ isOpen,+ onExit,+ documentName,+ canvasRef,+ isPlaying,+ onTogglePlay,+ onStepBy,+ onRestart,+ timelineIndex,+ totalTimelineFrames,+ onSeek,+ currentTimeSec,+ totalDurationSec,+ currentSourceFrameIndex,+ totalCapturedFrames,+ duration,+ onChangeDuration,+ fps,+ outputDims,+ playbackSpeed,+ onCycleSpeed,+ loop,+ onToggleLoop,+}) => {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const [hudVisible, setHudVisible] = useState(true);+ const hideTimerRef = useRef<number | null>(null);++ // Request native browser/WebView fullscreen gracefully; stay working in full-viewport overlay if declined+ useEffect(() => {+ if (!isOpen) return;+ const el = containerRef.current;+ let enteredNative = false;+ if (el && typeof el.requestFullscreen === 'function') {+ el.requestFullscreen()+ .then(() => {+ enteredNative = true;+ })+ .catch(() => {+ enteredNative = false;+ });+ }++ const handleFullscreenChange = () => {+ if (enteredNative && typeof document !== 'undefined' && !document.fullscreenElement) {+ onExit();+ }+ };+ if (typeof document !== 'undefined') {+ document.addEventListener('fullscreenchange', handleFullscreenChange);+ }++ return () => {+ if (typeof document !== 'undefined') {+ document.removeEventListener('fullscreenchange', handleFullscreenChange);+ if (document.fullscreenElement === el && typeof document.exitFullscreen === 'function') {+ document.exitFullscreen().catch(() => {});+ }+ }+ };+ }, [isOpen, onExit]);++ // Auto-hide HUD while playing & cursor is idle+ useEffect(() => {+ if (!isOpen) return;+ if (!isPlaying) {+ setHudVisible(true);+ if (hideTimerRef.current !== null) {+ window.clearTimeout(hideTimerRef.current);+ hideTimerRef.current = null;+ }+ return;+ }+ const scheduleHide = () => {+ if (hideTimerRef.current !== null) window.clearTimeout(hideTimerRef.current);+ hideTimerRef.current = window.setTimeout(() => {+ setHudVisible(false);+ }, 2400);+ };+ scheduleHide();+ return () => {+ if (hideTimerRef.current !== null) {+ window.clearTimeout(hideTimerRef.current);+ hideTimerRef.current = null;+ }+ };+ }, [isOpen, isPlaying]);++ const bumpHud = () => {+ setHudVisible(true);+ if (isPlaying) {+ if (hideTimerRef.current !== null) window.clearTimeout(hideTimerRef.current);+ hideTimerRef.current = window.setTimeout(() => setHudVisible(false), 2400);+ }+ };++ if (!isOpen) return null;++ const progressPct =+ totalTimelineFrames > 1 ? (timelineIndex / (totalTimelineFrames - 1)) * 100 : 0;++ return (+ <div+ ref={containerRef}+ role="dialog"+ aria-modal="true"+ aria-label="Time-lapse Full-screen Preview"+ onMouseMove={bumpHud}+ onClick={(e) => e.stopPropagation()}+ className="fixed inset-0 z-[100] bg-black flex flex-col items-center justify-center select-none overflow-hidden"+ >+ {/* Top Overlay Bar */}+ <div+ className={`absolute top-0 inset-x-0 z-20 px-5 py-3 bg-gradient-to-b from-black/80 via-black/45 to-transparent flex items-center justify-between transition-opacity duration-200 ${+ hudVisible ? 'opacity-100' : 'opacity-0 pointer-events-none'+ }`}+ >+ <div className="flex items-center gap-3 min-w-0">+ <span className="text-sm font-medium text-white truncate">+ {documentName.replace(/\*+$/, '') || 'Untitled'}+ </span>+ <span className="text-[11px] font-ui-mono tabular-nums text-white/70 bg-white/10 px-2 py-0.5 rounded-ui-sm">+ {outputDims.width}×{outputDims.height} · {fps} FPS · {totalCapturedFrames} frames+ </span>+ </div>++ <button+ type="button"+ onClick={onExit}+ aria-label="Exit full-screen"+ title="Exit Full-screen (Esc / F)"+ className="px-2.5 py-1.5 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white text-xs flex items-center gap-1.5 transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ <span>Exit</span>+ </button>+ </div>++ {/* Center Canvas Stage */}+ <div+ onClick={onTogglePlay}+ onDoubleClick={onExit}+ className="w-full h-full flex items-center justify-center p-4 sm:p-10 cursor-pointer"+ >+ <canvas+ ref={canvasRef}+ className="max-w-full max-h-full object-contain shadow-2xl rounded-ui-sm"+ />+ </div>++ {/* Bottom Floating Transport HUD */}+ <div+ onMouseEnter={() => setHudVisible(true)}+ className={`absolute bottom-0 inset-x-0 z-20 px-6 pb-5 pt-10 bg-gradient-to-t from-black/90 via-black/60 to-transparent transition-opacity duration-200 ${+ hudVisible ? 'opacity-100' : 'opacity-0 pointer-events-none'+ }`}+ >+ <div className="max-w-4xl mx-auto space-y-2.5">+ {/* Timeline Scrubber */}+ <div className="flex items-center gap-3">+ <span className="text-[11px] font-ui-mono tabular-nums text-white/90 w-12">+ {formatTimecode(currentTimeSec)}+ </span>+ <div className="relative flex-1 flex items-center">+ <input+ type="range"+ aria-label="Full-screen timeline scrubber"+ min={0}+ max={Math.max(0, totalTimelineFrames - 1)}+ value={Math.min(timelineIndex, Math.max(0, totalTimelineFrames - 1))}+ onChange={(e) => onSeek(Number(e.target.value))}+ className="w-full accent-white cursor-pointer"+ style={{+ background: `linear-gradient(to right, rgba(255,255,255,0.92) ${progressPct}%, rgba(255,255,255,0.22) ${progressPct}%)`,+ }}+ />+ </div>+ <span className="text-[11px] font-ui-mono tabular-nums text-white/70 w-12 text-right">+ {formatTimecode(totalDurationSec)}+ </span>+ </div>++ {/* Transport + Interval Switcher Row */}+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={onRestart}+ title="Jump to start"+ className="p-1.5 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white transition-colors cursor-pointer"+ >+ <SkipBack className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={() => onStepBy(-1)}+ title="Previous frame (Left arrow)"+ className="p-1.5 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white transition-colors cursor-pointer"+ >+ <ChevronLeft className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onTogglePlay}+ title="Play / Pause (Space)"+ className="px-3 py-1.5 rounded-ui-sm bg-white text-black hover:bg-white/90 font-medium text-xs flex items-center gap-1.5 transition-colors cursor-pointer"+ >+ {isPlaying ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}+ <span>{isPlaying ? 'Pause' : 'Play'}</span>+ </button>+ <button+ type="button"+ onClick={() => onStepBy(1)}+ title="Next frame (Right arrow)"+ className="p-1.5 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white transition-colors cursor-pointer"+ >+ <ChevronRight className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onToggleLoop}+ title={loop ? 'Loop enabled' : 'Loop disabled'}+ className={`p-1.5 rounded-ui-sm transition-colors cursor-pointer ${+ loop+ ? 'bg-white/25 text-white'+ : 'bg-white/10 text-white/55 hover:text-white hover:bg-white/15'+ }`}+ >+ <Repeat className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onCycleSpeed}+ title="Playback speed"+ className="px-2 py-1 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white text-[11px] font-ui-mono tabular-nums cursor-pointer"+ >+ {playbackSpeed}×+ </button>+ </div>++ {/* Quick Interval Switcher directly inside Full-Screen */}+ <div className="flex items-center gap-1 bg-white/10 p-0.5 rounded-ui-sm">+ {QUICK_INTERVALS.map((opt) => (+ <button+ key={opt.value}+ type="button"+ onClick={() => onChangeDuration(opt.value)}+ className={`px-2 py-1 rounded-ui-xs text-[11px] font-ui-mono tabular-nums cursor-pointer transition-colors ${+ duration === opt.value+ ? 'bg-white text-black font-semibold'+ : 'text-white/75 hover:text-white'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>++ <div className="flex items-center gap-2.5">+ <span className="text-[10px] font-ui-mono tabular-nums text-white/65">+ Keyframe {Math.min(currentSourceFrameIndex + 1, totalCapturedFrames)} /{' '}+ {totalCapturedFrames}+ </span>+ <button+ type="button"+ onClick={onExit}+ title="Exit Full-screen (F)"+ className="p-1.5 rounded-ui-sm bg-white/10 hover:bg-white/20 text-white transition-colors cursor-pointer"+ >+ <Minimize2 className="w-3.5 h-3.5" />+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/timelapse/TimelapseWatermarkControls.tsx b/src/components/timelapse/TimelapseWatermarkControls.tsxnew file mode 100644index 0000000..5d429cc--- /dev/null+++ b/src/components/timelapse/TimelapseWatermarkControls.tsx@@ -0,0 +1,334 @@+import React, { useRef } from 'react';+import { Image as ImageIcon, Trash2, Type, Upload } from 'lucide-react';+import {+ prepareWatermarkImageDataUrl,+ TimelapseWatermarkConfig,+ TimelapseWatermarkFontStyle,+ TimelapseWatermarkPosition,+} from '../../utils/timelapseWatermark';+import { ToggleSwitch } from '../ui';++const POSITION_GRID: Array<{ value: TimelapseWatermarkPosition; label: string }> = [+ { value: 'top-left', label: 'TL' },+ { value: 'top-center', label: 'TC' },+ { value: 'top-right', label: 'TR' },+ { value: 'center', label: 'Center' },+ { value: 'bottom-left', label: 'BL' },+ { value: 'bottom-center', label: 'BC' },+ { value: 'bottom-right', label: 'BR' },+];++const FONT_STYLES: Array<{ value: TimelapseWatermarkFontStyle; label: string }> = [+ { value: 'sans', label: 'Sans' },+ { value: 'bold', label: 'Bold' },+ { value: 'mono', label: 'Mono' },+ { value: 'serif', label: 'Serif' },+];++const QUICK_COLORS = ['#ffffff', '#141414', '#f59e0b', '#38bdf8', '#f43f5e'];++export interface TimelapseWatermarkControlsProps {+ config: TimelapseWatermarkConfig;+ onChange: (next: TimelapseWatermarkConfig) => void;+ disabled?: boolean;+ onError?: (msg: string) => void;+}++export const TimelapseWatermarkControls: React.FC<TimelapseWatermarkControlsProps> = ({+ config,+ onChange,+ disabled = false,+ onError,+}) => {+ const fileInputRef = useRef<HTMLInputElement | null>(null);++ const patch = (partial: Partial<TimelapseWatermarkConfig>) => {+ onChange({ ...config, ...partial });+ };++ const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;+ try {+ const dataUrl = await prepareWatermarkImageDataUrl(file);+ patch({ mode: 'image', imageDataUrl: dataUrl, enabled: true });+ } catch (err) {+ onError?.(err instanceof Error ? err.message : 'Failed to load watermark image');+ } finally {+ if (fileInputRef.current) fileInputRef.current.value = '';+ }+ };++ return (+ <div className="space-y-3">+ {/* Master Enable Toggle */}+ <div className="flex items-center justify-between bg-ui-header border border-ui-subtle rounded-ui-md px-3 py-2">+ <div>+ <div className="text-[11px] font-medium text-ui-primary">Enable Watermark</div>+ <div className="text-[10px] text-ui-muted">+ Rendered live in preview and burned into exported videos+ </div>+ </div>+ <ToggleSwitch+ checked={config.enabled}+ onChange={(enabled) => patch({ enabled })}+ disabled={disabled}+ aria-label="Enable watermark"+ />+ </div>++ <div className={config.enabled ? 'space-y-3' : 'space-y-3 opacity-50 pointer-events-none'}>+ {/* Watermark Mode */}+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">Type</label>+ <div className="grid grid-cols-2 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ <button+ type="button"+ disabled={disabled}+ onClick={() => patch({ mode: 'text' })}+ className={`py-1.5 rounded-ui-xs text-[11px] flex items-center justify-center gap-1.5 cursor-pointer transition-colors ${+ config.mode === 'text'+ ? 'bg-ui-control-active text-ui-primary font-medium'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <Type className="w-3 h-3" />+ <span>Text</span>+ </button>+ <button+ type="button"+ disabled={disabled}+ onClick={() => patch({ mode: 'image' })}+ className={`py-1.5 rounded-ui-xs text-[11px] flex items-center justify-center gap-1.5 cursor-pointer transition-colors ${+ config.mode === 'image'+ ? 'bg-ui-control-active text-ui-primary font-medium'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ <ImageIcon className="w-3 h-3" />+ <span>Logo / Signature</span>+ </button>+ </div>+ </div>++ {/* Mode-Specific Controls */}+ {config.mode === 'text' ? (+ <div className="space-y-2.5">+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Watermark Text+ </label>+ <input+ type="text"+ maxLength={80}+ value={config.text}+ disabled={disabled}+ onChange={(e) => patch({ text: e.target.value })}+ placeholder="@yourhandle or Ink Studio"+ className="w-full h-7 px-2.5 rounded-ui-sm bg-ui-input border border-ui-default text-xs text-ui-primary focus:outline-none focus:border-ui-focus"+ />+ </div>++ <div className="grid grid-cols-2 gap-2">+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Style+ </label>+ <div className="grid grid-cols-4 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">+ {FONT_STYLES.map((st) => (+ <button+ key={st.value}+ type="button"+ disabled={disabled}+ onClick={() => patch({ fontStyle: st.value })}+ className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${+ config.fontStyle === st.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {st.label}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Color+ </label>+ <div className="flex items-center gap-1 h-7 px-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle">+ {QUICK_COLORS.map((hex) => (+ <button+ key={hex}+ type="button"+ disabled={disabled}+ onClick={() => patch({ textColor: hex })}+ title={hex}+ className={`w-4 h-4 rounded-full border cursor-pointer transition-transform ${+ config.textColor.toLowerCase() === hex.toLowerCase()+ ? 'border-ui-accent scale-110'+ : 'border-ui-default'+ }`}+ style={{ backgroundColor: hex }}+ />+ ))}+ <input+ type="color"+ aria-label="Custom watermark color"+ value={config.textColor}+ disabled={disabled}+ onChange={(e) => patch({ textColor: e.target.value })}+ className="w-5 h-5 ml-auto bg-transparent border-0 cursor-pointer"+ />+ </div>+ </div>+ </div>++ <div className="flex items-center justify-between bg-ui-header/70 border border-ui-subtle rounded-ui-sm px-2.5 py-1.5">+ <span className="text-[11px] text-ui-secondary">Subtle backdrop pill</span>+ <ToggleSwitch+ checked={config.showBackdrop}+ onChange={(showBackdrop) => patch({ showBackdrop })}+ disabled={disabled}+ aria-label="Watermark backdrop pill"+ />+ </div>+ </div>+ ) : (+ <div className="space-y-2">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/webp,image/svg+xml,image/jpeg"+ onChange={handleImageUpload}+ className="hidden"+ />+ <div className="flex items-center gap-2 bg-ui-header border border-ui-subtle rounded-ui-md p-2">+ <div className="w-12 h-12 rounded-ui-sm bg-ui-void border border-ui-subtle flex items-center justify-center overflow-hidden shrink-0">+ {config.imageDataUrl ? (+ <img+ src={config.imageDataUrl}+ alt="Watermark logo preview"+ className="max-w-full max-h-full object-contain"+ />+ ) : (+ <ImageIcon className="w-4 h-4 text-ui-muted" />+ )}+ </div>+ <div className="flex-1 min-w-0 space-y-1">+ <div className="text-[11px] text-ui-primary font-medium truncate">+ {config.imageDataUrl ? 'Custom logo / signature' : 'No image selected'}+ </div>+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ disabled={disabled}+ onClick={() => fileInputRef.current?.click()}+ className="px-2 py-1 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer"+ >+ <Upload className="w-3 h-3" />+ <span>{config.imageDataUrl ? 'Replace' : 'Upload PNG/SVG'}</span>+ </button>+ {config.imageDataUrl && (+ <button+ type="button"+ disabled={disabled}+ onClick={() => patch({ imageDataUrl: null })}+ title="Remove logo"+ className="p-1 rounded-ui-xs bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle text-ui-muted hover:text-ui-danger cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ )}+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Position Anchor Grid */}+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-ui-muted block">+ Position+ </label>+ <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-1 rounded-ui-sm">+ {POSITION_GRID.map((pos) => (+ <button+ key={pos.value}+ type="button"+ disabled={disabled}+ onClick={() => patch({ position: pos.value })}+ className={`py-1 rounded-ui-xs text-[10px] font-ui-mono cursor-pointer transition-colors ${+ pos.value === 'center' ? 'col-span-1' : ''+ } ${+ config.position === pos.value+ ? 'bg-ui-control-active text-ui-primary font-semibold'+ : 'text-ui-muted hover:text-ui-primary'+ }`}+ >+ {pos.label}+ </button>+ ))}+ </div>+ </div>++ {/* Size / Opacity / Margin Sliders */}+ <div className="grid grid-cols-3 gap-2">+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Size</span>+ <span className="font-ui-mono tabular-nums text-ui-secondary">{config.scale}%</span>+ </div>+ <input+ type="range"+ min={5}+ max={40}+ step={1}+ disabled={disabled}+ value={config.scale}+ onChange={(e) => patch({ scale: Number(e.target.value) })}+ className="w-full cursor-pointer"+ />+ </div>++ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Opacity</span>+ <span className="font-ui-mono tabular-nums text-ui-secondary">+ {Math.round(config.opacity * 100)}%+ </span>+ </div>+ <input+ type="range"+ min={10}+ max={100}+ step={5}+ disabled={disabled}+ value={Math.round(config.opacity * 100)}+ onChange={(e) => patch({ opacity: Number(e.target.value) / 100 })}+ className="w-full cursor-pointer"+ />+ </div>++ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px] text-ui-muted">+ <span>Margin</span>+ <span className="font-ui-mono tabular-nums text-ui-secondary">{config.margin}%</span>+ </div>+ <input+ type="range"+ min={0}+ max={12}+ step={1}+ disabled={disabled}+ value={config.margin}+ onChange={(e) => patch({ margin: Number(e.target.value) })}+ className="w-full cursor-pointer"+ />+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/timelapse/useTimelapsePreviewPlayer.ts b/src/components/timelapse/useTimelapsePreviewPlayer.tsnew file mode 100644index 0000000..dbb4f67--- /dev/null+++ b/src/components/timelapse/useTimelapsePreviewPlayer.ts@@ -0,0 +1,446 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import {+ computeTimelapseDimensions,+ globalTimelapseManager,+ resolveTimelapseTargetSeconds,+ sampleTimelapseFrameIndices,+ TimelapseAspectRatio,+ TimelapseBackgroundMode,+ TimelapseDurationPreset,+ TimelapseResolution,+ TimelapseWatermarkConfig,+} from '../../utils/timelapseEngine';+import {+ loadWatermarkImageElement,+ renderTimelapseOutputFrame,+} from '../../utils/timelapseWatermark';++export type TimelapsePlaybackSpeed = 0.5 | 1 | 2;++export interface UseTimelapsePreviewPlayerParams {+ isOpen: boolean;+ documentId: string | null;+ frameCount: number;+ duration: TimelapseDurationPreset;+ customDurationSec: number;+ fps: number;+ aspectRatio: TimelapseAspectRatio;+ resolution: TimelapseResolution;+ backgroundMode: TimelapseBackgroundMode;+ backgroundColor: string;+ watermark: TimelapseWatermarkConfig;+ playbackSpeed: TimelapsePlaybackSpeed;+ loop: boolean;+ isFullscreen: boolean;+}++const MAX_DECODED_CACHE = 36;+const LOOKAHEAD_UNIQUE_FRAMES = 6;++export function formatTimecode(seconds: number): string {+ const safe = Math.max(0, Number.isFinite(seconds) ? seconds : 0);+ const mins = Math.floor(safe / 60);+ const secs = safe - mins * 60;+ const wholeSecs = Math.floor(secs);+ const tenths = Math.floor((secs - wholeSecs) * 10);+ return `${String(mins).padStart(2, '0')}:${String(wholeSecs).padStart(2, '0')}.${tenths}`;+}++export function useTimelapsePreviewPlayer({+ isOpen,+ documentId,+ frameCount,+ duration,+ customDurationSec,+ fps,+ aspectRatio,+ resolution,+ backgroundMode,+ backgroundColor,+ watermark,+ playbackSpeed,+ loop,+ isFullscreen,+}: UseTimelapsePreviewPlayerParams) {+ const [isPlaying, setIsPlaying] = useState(false);+ const [timelineIndex, setTimelineIndex] = useState(0);++ const modalCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const fullscreenCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const decodedCacheRef = useRef<Map<string, ImageBitmap | HTMLImageElement>>(new Map());+ const inFlightLoadsRef = useRef<Map<string, Promise<ImageBitmap | HTMLImageElement | null>>>(+ new Map()+ );+ const watermarkImgRef = useRef<HTMLImageElement | null>(null);+ const [watermarkImgVersion, setWatermarkImgVersion] = useState(0);+ const lastRenderedSourceRef = useRef<ImageBitmap | HTMLImageElement | null>(null);+ const timelineIndexRef = useRef(0);+ timelineIndexRef.current = timelineIndex;++ // Sample exact output timeline matching the export engine+ const sampledIndices = useMemo(+ () => sampleTimelapseFrameIndices(frameCount, duration, fps, customDurationSec),+ [frameCount, duration, fps, customDurationSec]+ );++ const totalTimelineFrames = sampledIndices.length;+ const totalDurationSec = useMemo(+ () => resolveTimelapseTargetSeconds(frameCount, duration, fps, customDurationSec),+ [frameCount, duration, fps, customDurationSec]+ );++ // Compute target export dimensions (and preview canvas resolution)+ const outputDims = useMemo(() => {+ if (!documentId || frameCount <= 0) {+ return computeTimelapseDimensions(1920, 1080, aspectRatio, resolution);+ }+ const frames = globalTimelapseManager.getFrames(documentId);+ const refFrame = frames[frames.length - 1] ?? frames[0];+ return computeTimelapseDimensions(+ refFrame?.width || 1920,+ refFrame?.height || 1080,+ aspectRatio,+ resolution+ );+ }, [documentId, frameCount, aspectRatio, resolution]);++ const previewCanvasDims = useMemo(() => {+ const maxEdge = isFullscreen ? 1920 : 960;+ const scale = Math.min(1, maxEdge / Math.max(outputDims.width, outputDims.height));+ return {+ width: Math.max(2, Math.round((outputDims.width * scale) / 2) * 2),+ height: Math.max(2, Math.round((outputDims.height * scale) / 2) * 2),+ };+ }, [outputDims.width, outputDims.height, isFullscreen]);++ // Preserve proportional playback position whenever duration preset or FPS changes+ const prevTotalRef = useRef(totalTimelineFrames);+ useEffect(() => {+ const prevTotal = prevTotalRef.current;+ prevTotalRef.current = totalTimelineFrames;+ if (totalTimelineFrames <= 0) {+ setTimelineIndex(0);+ setIsPlaying(false);+ return;+ }+ if (prevTotal > 1 && prevTotal !== totalTimelineFrames) {+ const ratio = Math.min(1, Math.max(0, timelineIndexRef.current / (prevTotal - 1)));+ const nextIdx = Math.round(ratio * (totalTimelineFrames - 1));+ setTimelineIndex(nextIdx);+ } else if (timelineIndexRef.current >= totalTimelineFrames) {+ setTimelineIndex(Math.max(0, totalTimelineFrames - 1));+ }+ }, [totalTimelineFrames]);++ const clearDecodedCache = useCallback(() => {+ for (const item of decodedCacheRef.current.values()) {+ if ('close' in item && typeof item.close === 'function') {+ try {+ item.close();+ } catch {+ // ignore+ }+ }+ }+ decodedCacheRef.current.clear();+ inFlightLoadsRef.current.clear();+ lastRenderedSourceRef.current = null;+ }, []);++ // Reset cache when switching documents or closing modal+ useEffect(() => {+ setTimelineIndex(0);+ setIsPlaying(false);+ clearDecodedCache();+ }, [documentId, clearDecodedCache]);++ useEffect(() => {+ if (!isOpen) {+ setIsPlaying(false);+ clearDecodedCache();+ }+ }, [isOpen, clearDecodedCache]);++ useEffect(() => {+ return () => {+ clearDecodedCache();+ };+ }, [clearDecodedCache]);++ // Load watermark logo image when configured+ useEffect(() => {+ let cancelled = false;+ if (watermark.enabled && watermark.mode === 'image' && watermark.imageDataUrl) {+ loadWatermarkImageElement(watermark.imageDataUrl).then((img) => {+ if (cancelled) return;+ watermarkImgRef.current = img;+ setWatermarkImgVersion((v) => v + 1);+ });+ } else {+ watermarkImgRef.current = null;+ setWatermarkImgVersion((v) => v + 1);+ }+ return () => {+ cancelled = true;+ };+ }, [watermark.enabled, watermark.mode, watermark.imageDataUrl]);++ const decodeFrameAtSourceIndex = useCallback(+ async (srcIdx: number): Promise<ImageBitmap | HTMLImageElement | null> => {+ if (!documentId) return null;+ const frames = globalTimelapseManager.getFrames(documentId);+ const entry = frames[srcIdx];+ if (!entry) return null;++ const cacheKey = entry.id;+ const cached = decodedCacheRef.current.get(cacheKey);+ if (cached) {+ // Refresh LRU position+ decodedCacheRef.current.delete(cacheKey);+ decodedCacheRef.current.set(cacheKey, cached);+ return cached;+ }++ const existingPromise = inFlightLoadsRef.current.get(cacheKey);+ if (existingPromise) return existingPromise;++ const promise = (async (): Promise<ImageBitmap | HTMLImageElement | null> => {+ try {+ const blob = await globalTimelapseManager.loadFrameBlob(documentId, entry);+ if (!blob) return null;+ let decoded: ImageBitmap | HTMLImageElement | null = null;+ if (typeof createImageBitmap === 'function') {+ try {+ decoded = await createImageBitmap(blob);+ } catch {+ decoded = null;+ }+ }+ if (!decoded && typeof Image !== 'undefined') {+ const url = URL.createObjectURL(blob);+ decoded = await new Promise<HTMLImageElement | null>((resolve) => {+ const el = new Image();+ el.onload = () => {+ URL.revokeObjectURL(url);+ resolve(el);+ };+ el.onerror = () => {+ URL.revokeObjectURL(url);+ resolve(null);+ };+ el.src = url;+ });+ }+ if (decoded) {+ if (decodedCacheRef.current.size >= MAX_DECODED_CACHE) {+ const oldestKey = decodedCacheRef.current.keys().next().value;+ if (oldestKey !== undefined) {+ const oldest = decodedCacheRef.current.get(oldestKey);+ if (+ oldest &&+ oldest !== lastRenderedSourceRef.current &&+ 'close' in oldest &&+ typeof oldest.close === 'function'+ ) {+ try {+ oldest.close();+ } catch {+ // ignore+ }+ }+ decodedCacheRef.current.delete(oldestKey);+ }+ }+ decodedCacheRef.current.set(cacheKey, decoded);+ }+ return decoded;+ } finally {+ inFlightLoadsRef.current.delete(cacheKey);+ }+ })();++ inFlightLoadsRef.current.set(cacheKey, promise);+ return promise;+ },+ [documentId]+ );++ const paintCanvas = useCallback(+ (source: ImageBitmap | HTMLImageElement | null) => {+ const target = isFullscreen ? fullscreenCanvasRef.current : modalCanvasRef.current;+ if (!target) return;+ if (target.width !== previewCanvasDims.width) target.width = previewCanvasDims.width;+ if (target.height !== previewCanvasDims.height) target.height = previewCanvasDims.height;+ const ctx = target.getContext('2d');+ if (!ctx) return;+ renderTimelapseOutputFrame(ctx, source, target.width, target.height, {+ backgroundMode,+ backgroundColor,+ watermark,+ watermarkImage: watermarkImgRef.current,+ });+ },+ [+ isFullscreen,+ previewCanvasDims.width,+ previewCanvasDims.height,+ backgroundMode,+ backgroundColor,+ watermark,+ ]+ );++ // Render active frame & prefetch upcoming unique frames+ useEffect(() => {+ if (!isOpen || !documentId || totalTimelineFrames === 0) return;++ const clamped = Math.max(0, Math.min(totalTimelineFrames - 1, timelineIndex));+ const srcIdx = sampledIndices[clamped] ?? 0;+ const frames = globalTimelapseManager.getFrames(documentId);+ const entry = frames[srcIdx];+ let cancelled = false;++ const cached = entry ? decodedCacheRef.current.get(entry.id) : undefined;+ if (cached) {+ lastRenderedSourceRef.current = cached;+ paintCanvas(cached);+ } else {+ // Keep previous frame visible while async decode finishes (zero flicker!)+ if (lastRenderedSourceRef.current) {+ paintCanvas(lastRenderedSourceRef.current);+ }+ void decodeFrameAtSourceIndex(srcIdx).then((decoded) => {+ if (cancelled || !decoded) return;+ lastRenderedSourceRef.current = decoded;+ paintCanvas(decoded);+ });+ }++ // Lookahead prefetcher: pre-decode the next N unique source frames along the sampled timeline+ const seen = new Set<number>([srcIdx]);+ let prefetched = 0;+ for (+ let offset = 1;+ offset < totalTimelineFrames && prefetched < LOOKAHEAD_UNIQUE_FRAMES;+ offset+++ ) {+ const nextPos = (clamped + offset) % totalTimelineFrames;+ const nextSrc = sampledIndices[nextPos];+ if (nextSrc !== undefined && !seen.has(nextSrc)) {+ seen.add(nextSrc);+ prefetched++;+ void decodeFrameAtSourceIndex(nextSrc);+ }+ }++ return () => {+ cancelled = true;+ };+ }, [+ isOpen,+ documentId,+ totalTimelineFrames,+ timelineIndex,+ sampledIndices,+ paintCanvas,+ decodeFrameAtSourceIndex,+ watermarkImgVersion,+ isFullscreen,+ frameCount,+ ]);++ // Real-time rAF playback loop synchronized strictly to (fps * playbackSpeed)+ useEffect(() => {+ if (!isOpen || !isPlaying || totalTimelineFrames <= 1) return;++ let rafId = 0;+ let lastTs = performance.now();+ let floatPos = timelineIndexRef.current;++ const tick = (now: number) => {+ const dtSec = Math.min(0.15, Math.max(0, (now - lastTs) / 1000));+ lastTs = now;+ floatPos += dtSec * fps * playbackSpeed;++ if (floatPos >= totalTimelineFrames) {+ if (loop) {+ floatPos = floatPos % totalTimelineFrames;+ } else {+ setTimelineIndex(totalTimelineFrames - 1);+ setIsPlaying(false);+ return;+ }+ }++ const nextDiscrete = Math.floor(floatPos);+ if (nextDiscrete !== timelineIndexRef.current) {+ timelineIndexRef.current = nextDiscrete;+ setTimelineIndex(nextDiscrete);+ }+ rafId = requestAnimationFrame(tick);+ };++ rafId = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(rafId);+ }, [isOpen, isPlaying, totalTimelineFrames, fps, playbackSpeed, loop]);++ const togglePlay = useCallback(() => {+ if (totalTimelineFrames <= 1) return;+ setIsPlaying((prev) => {+ if (!prev && timelineIndexRef.current >= totalTimelineFrames - 1) {+ setTimelineIndex(0);+ }+ return !prev;+ });+ }, [totalTimelineFrames]);++ const seekTo = useCallback(+ (idx: number) => {+ const clamped = Math.max(0, Math.min(Math.max(0, totalTimelineFrames - 1), idx));+ setTimelineIndex(clamped);+ },+ [totalTimelineFrames]+ );++ const stepBy = useCallback(+ (delta: number) => {+ setIsPlaying(false);+ if (totalTimelineFrames <= 0) return;+ setTimelineIndex((prev) => {+ const next = prev + delta;+ if (next < 0) return loop ? totalTimelineFrames - 1 : 0;+ if (next >= totalTimelineFrames) return loop ? 0 : totalTimelineFrames - 1;+ return next;+ });+ },+ [totalTimelineFrames, loop]+ );++ const restart = useCallback(() => {+ setTimelineIndex(0);+ }, []);++ const currentSourceFrameIndex =+ totalTimelineFrames > 0+ ? (sampledIndices[Math.min(timelineIndex, totalTimelineFrames - 1)] ?? 0)+ : 0;+ const currentTimeSec = fps > 0 ? timelineIndex / fps : 0;++ return {+ modalCanvasRef,+ fullscreenCanvasRef,+ isPlaying,+ setIsPlaying,+ togglePlay,+ timelineIndex,+ totalTimelineFrames,+ currentSourceFrameIndex,+ currentTimeSec,+ totalDurationSec,+ outputDims,+ previewCanvasDims,+ seekTo,+ stepBy,+ restart,+ };+}diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.tsindex bd2a86c..24b68a2 100644--- a/src/hooks/drawing/useShapeAndFillTools.ts+++ b/src/hooks/drawing/useShapeAndFillTools.ts@@ -44,6 +44,7 @@ import {Point2D,} from '../../utils/frameEngine';import { hitTestEditableVectorLayer } from '../../utils/vectorLayerRenderer';+import { extractPersistableTextStyle, normalizeTextSettings } from '../../utils/textSettings';import { useToolStore, toolStoreActions } from '../../stores';import { PushHistoryStepFn } from './types';@@ -54,6 +55,11 @@ export interface TextPlacementSession {editingLayerId?: string | null;}+export interface TextDragPreview {+ start: Point2D;+ end: Point2D;+}+export interface FrameDragPreview {mode: 'create' | 'divide';start: Point2D;@@ -106,6 +112,7 @@ export interface UseShapeAndFillToolsParams {export interface UseShapeAndFillToolsResult {textSession: TextPlacementSession | null;setTextSession: React.Dispatch<React.SetStateAction<TextPlacementSession | null>>;+ textDragPreview: TextDragPreview | null;activeBalloon: SpeechBalloon | null;setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;frameDragPreview: FrameDragPreview | null;@@ -116,6 +123,7 @@ export interface UseShapeAndFillToolsResult {handleSampleColor: (pt: { x: number; y: number }, commit?: boolean) => void;handleConfirmText: () => void;handleCancelText: () => void;+ handleDeleteText: () => void;handleConfirmBalloon: () => void;handleDeleteBalloon: () => void;handleShapeFillPointerDown: (@@ -180,12 +188,19 @@ export function useShapeAndFillTools({showToast,}: UseShapeAndFillToolsParams): UseShapeAndFillToolsResult {const [textSession, setTextSession] = useState<TextPlacementSession | null>(null);+ const [textDragPreview, setTextDragPreview] = useState<TextDragPreview | null>(null);const [activeBalloon, setActiveBalloon] = useState<SpeechBalloon | null>(null);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 textSessionRef = useRef<TextPlacementSession | null>(null);+ textSessionRef.current = textSession;+ const upsertTextLayerRef = useRef(upsertTextLayer);+ upsertTextLayerRef.current = upsertTextLayer;+ const textDragRef = useRef<{ start: { x: number; y: number }; end: { x: number; y: number } } | null>(null);+const isPipetteSamplingRef = useRef<boolean>(false);const liquifyPersistentRef = useRef<PersistentLiquifyWarpSession | null>(null);const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);@@ -310,24 +325,13 @@ export function useShapeAndFillTools({setActiveBalloon(null);setEditingBalloonLayerId(null);const td = layer.textData;+ const normalized = normalizeTextSettings(td);+ toolStoreActions.updateTextSettings(extractPersistableTextStyle(normalized));setTextSession({x: td.x,y: td.y,editingLayerId: layer.id,- settings: {- text: td.text,- fontFamily: td.fontFamily,- fontSize: td.fontSize,- lineSpacing: td.lineSpacing ?? 1.25,- bold: td.bold,- italic: td.italic,- align: td.align,- outline: td.outline,- outlineColor: td.outlineColor,- outlineWidth: td.outlineWidth,- color: td.color,- writingMode: td.writingMode || 'horizontal-tb',- },+ settings: normalized,});return true;}@@ -353,6 +357,22 @@ export function useShapeAndFillTools({} | null>(null);const liquifySelectionMaskRef = useRef<Uint8Array | null>(null);+ const commitTextSession = useCallback((session: TextPlacementSession | null) => {+ if (!session) return;+ const persistable = extractPersistableTextStyle(session.settings);+ toolStoreActions.updateTextSettings(persistable);+ if (!session.settings.text.trim()) {+ return;+ }+ const normalized = normalizeTextSettings(session.settings);+ const textData: TextLayerData = {+ ...normalized,+ x: Math.round(session.x),+ y: Math.round(session.y),+ };+ upsertTextLayerRef.current(textData, session.editingLayerId);+ }, []);+useEffect(() => {const clearPersistent = () => {if (liquifyPersistentRef.current) {@@ -362,18 +382,57 @@ export function useShapeAndFillTools({}};let prevTool = useToolStore.getState().tool;+ let prevTextSettings = useToolStore.getState().textSettings;const unsub = useToolStore.subscribe(() => {- const curTool = useToolStore.getState().tool;+ const state = useToolStore.getState();+ const curTool = state.tool;if (prevTool === 'liquify' && curTool !== 'liquify') {clearPersistent();}+ if (prevTool !== curTool && curTool !== 'text' && curTool !== 'object') {+ if (textDragRef.current) {+ textDragRef.current = null;+ setTextDragPreview(null);+ }+ if (textSessionRef.current) {+ commitTextSession(textSessionRef.current);+ setTextSession(null);+ }+ }prevTool = curTool;++ // Live-sync Tool Options Bar / Property Inspector changes into an open textSession+ if (state.textSettings !== prevTextSettings) {+ prevTextSettings = state.textSettings;+ if (textSessionRef.current) {+ const syncedStyle = extractPersistableTextStyle(state.textSettings);+ setTextSession((prev) => {+ if (!prev) return null;+ const cur = prev.settings;+ let changed = false;+ for (const key of Object.keys(syncedStyle) as Array<keyof TextSettings>) {+ if (cur[key] !== syncedStyle[key]) {+ changed = true;+ break;+ }+ }+ if (!changed) return prev;+ return {+ ...prev,+ settings: {+ ...cur,+ ...syncedStyle,+ },+ };+ });+ }+ }});return () => {unsub();clearPersistent();};- }, []);+ }, [commitTextSession]);const handleSampleColor = useCallback((pt: { x: number; y: number }, commit = true) => {@@ -404,24 +463,22 @@ export function useShapeAndFillTools({);const handleConfirmText = useCallback(() => {- if (!textSession || !textSession.settings.text.trim()) {- setTextSession(null);- return;- }- const textData: TextLayerData = {- ...textSession.settings,- lineSpacing: textSession.settings.lineSpacing ?? 1.25,- x: textSession.x,- y: textSession.y,- };- upsertTextLayer(textData, textSession.editingLayerId);+ commitTextSession(textSessionRef.current);setTextSession(null);- }, [textSession, upsertTextLayer]);+ }, [commitTextSession]);const handleCancelText = useCallback(() => {setTextSession(null);}, []);+ const handleDeleteText = useCallback(() => {+ const editingId = textSessionRef.current?.editingLayerId;+ if (editingId && deleteLayer) {+ deleteLayer(editingId);+ }+ setTextSession(null);+ }, [deleteLayer]);+const handleConfirmBalloon = useCallback(() => {if (!activeBalloon) return;upsertBalloonLayer(activeBalloon, editingBalloonLayerId);@@ -497,7 +554,6 @@ export function useShapeAndFillTools({tool,primaryColor,fillSettings,- textSettings,balloonSettings,liquifySettings,shapeSettings,@@ -842,18 +898,33 @@ export function useShapeAndFillTools({if (tool === 'text') {e.preventDefault();+ const existingSession = textSessionRef.current;const hitText = hitTestEditableVectorLayer(layers, pt, isLayerEffectivelyVisible, 'text');- if (hitText && openLayerForEditing(hitText)) {++ if (existingSession) {+ const hadText = Boolean(existingSession.settings.text.trim());+ commitTextSession(existingSession);+ setTextSession(null);+ if (hitText && hitText.id !== existingSession.editingLayerId && openLayerForEditing(hitText)) {+ return true;+ }+ // Clicking outside commits non-empty text cleanly; if it was empty, allow placing at new point+ if (hadText) {+ return true;+ }+ } else if (hitText && openLayerForEditing(hitText)) {return true;}+setActiveBalloon(null);setEditingBalloonLayerId(null);- setTextSession({- x: Math.round(pt.x),- y: Math.round(pt.y),- editingLayerId: null,- settings: { ...textSettings, color: primaryColor || textSettings.color },- });+ try {+ (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore capture errors in synthetic events+ }+ textDragRef.current = { start: pt, end: pt };+ setTextDragPreview(null);return true;}@@ -903,6 +974,7 @@ export function useShapeAndFillTools({updateLayerThumbnail,pushHistoryStep,openLayerForEditing,+ commitTextSession,showToast,]);@@ -1012,6 +1084,16 @@ export function useShapeAndFillTools({return true;}+ if (tool === 'text' && textDragRef.current) {+ const pt = getCanvasCoords(e);+ textDragRef.current.end = pt;+ const dist = Math.hypot(pt.x - textDragRef.current.start.x, pt.y - textDragRef.current.start.y);+ if (dist >= 12) {+ setTextDragPreview({ start: { ...textDragRef.current.start }, end: { ...pt } });+ }+ return true;+ }+if (tool === 'fill' &&(fillSettings.method === 'lasso' ||@@ -1448,6 +1530,39 @@ export function useShapeAndFillTools({return true;}+ if (tool === 'text' && textDragRef.current) {+ try {+ if ((e.currentTarget as HTMLElement)?.hasPointerCapture?.(e.pointerId)) {+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);+ }+ } catch {+ // Ignore release errors+ }+ const drag = textDragRef.current;+ textDragRef.current = null;+ setTextDragPreview(null);++ const latestTextSettings = useToolStore.getState().textSettings;+ const dragW = Math.abs(pt.x - drag.start.x);+ const dragH = Math.abs(pt.y - drag.start.y);+ const isBoxDrag = dragW >= 36 && Math.hypot(dragW, dragH) >= 36;+ const originX = isBoxDrag ? Math.min(drag.start.x, pt.x) : drag.start.x;+ const originY = isBoxDrag ? Math.min(drag.start.y, pt.y) : drag.start.y;+ const maxWidth = isBoxDrag ? Math.round(dragW) : null;++ setTextSession({+ x: Math.round(originX),+ y: Math.round(originY),+ editingLayerId: null,+ settings: normalizeTextSettings({+ ...latestTextSettings,+ text: '',+ maxWidth,+ }),+ });+ return true;+ }+return false;},[@@ -1471,6 +1586,7 @@ export function useShapeAndFillTools({return {textSession,setTextSession,+ textDragPreview,activeBalloon,setActiveBalloon,frameDragPreview,@@ -1481,6 +1597,7 @@ export function useShapeAndFillTools({handleSampleColor,handleConfirmText,handleCancelText,+ handleDeleteText,handleConfirmBalloon,handleDeleteBalloon,handleShapeFillPointerDown,diff --git a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts b/src/hooks/layerManager/useLayerPropertiesAndMasks.tsindex eb3b607..d6f4f3c 100644--- a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts+++ b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts@@ -2,12 +2,14 @@ import { useCallback } from 'react';import {AdjustmentLayerData,BlendMode,+ LayerColorLabel,LayerItem,LayerStyles,TileDelta,isFolderLikeLayer,} from '../../types/editor';import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';+import { computeBatchColorLabel } from '../../utils/layerOrganization';import { multiplayerService } from '../../services/multiplayerService';import {computeBatchLock,@@ -151,6 +153,22 @@ export function useLayerPropertiesAndMasks();}, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);+ // Assign organizational color label tag (batch applies if part of multi-selection)+ const setLayerColorLabel = useCallback((id: string, colorLabel: LayerColorLabel) => {+ const prev = layersRef.current;+ const next = computeBatchColorLabel(prev, selectedLayerIdsRef.current, id, colorLabel);+ if (next === prev) return;+ layersRef.current = next;+ setLayers(next);+ recordLayerHistory(+ 'Set Layer Color Label',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);+// Add a non-destructive grayscale Layer Maskconst addLayerMask = useCallback((layerId: string) => {const prev = layersRef.current;@@ -466,6 +484,7 @@ export function useLayerPropertiesAndMasks(toggleCollapse,toggleClipping,toggleAlphaLock,+ setLayerColorLabel,addLayerMask,removeLayerMask,toggleLayerMask,diff --git a/src/hooks/layerManager/useLayerResize.ts b/src/hooks/layerManager/useLayerResize.tsindex c270d00..9aba940 100644--- a/src/hooks/layerManager/useLayerResize.ts+++ b/src/hooks/layerManager/useLayerResize.ts@@ -1,11 +1,184 @@import { useCallback } from 'react';-import { CanvasDimensions, hasTileBackedLayer } from '../../types/editor';+import {+ CanvasDimensions,+ ComicFrame,+ SpeechBalloon,+ TextLayerData,+ VectorStroke,+ hasTileBackedLayer,+} from '../../types/editor';import { ResizeCanvasOptions } from '../../types/settings';import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';import { releaseTemporaryCanvas } from '../../utils/tileEngine';import { isBackgroundLayerId } from './layerTreeOps';import { LayerManagerContext } from './types';+function transformPoint(+ x: number,+ y: number,+ scaleContent: boolean,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+): { x: number; y: number } {+ if (scaleContent) {+ return { x: x * scaleX, y: y * scaleY };+ }+ return { x: x + offsetX, y: y + offsetY };+}++function transformComicFramesForResize(+ frames: ComicFrame[],+ scaleContent: boolean,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+): ComicFrame[] {+ const avgScale = (scaleX + scaleY) * 0.5;+ return frames.map((frame) => ({+ ...frame,+ polygon: frame.polygon.map((pt) =>+ transformPoint(pt.x, pt.y, scaleContent, offsetX, offsetY, scaleX, scaleY)+ ),+ borderWidth: scaleContent ? Math.max(0.5, frame.borderWidth * avgScale) : frame.borderWidth,+ }));+}++function transformVectorStrokesForResize(+ strokes: VectorStroke[],+ scaleContent: boolean,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+): VectorStroke[] {+ const avgScale = (scaleX + scaleY) * 0.5;+ return strokes.map((stroke) => {+ const nextKnots = stroke.knots.map((k) => {+ const p = transformPoint(k.x, k.y, scaleContent, offsetX, offsetY, scaleX, scaleY);+ const handleIn = k.handleIn+ ? transformPoint(k.handleIn.x, k.handleIn.y, scaleContent, offsetX, offsetY, scaleX, scaleY)+ : k.handleIn;+ const handleOut = k.handleOut+ ? transformPoint(+ k.handleOut.x,+ k.handleOut.y,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ )+ : k.handleOut;+ return {+ ...k,+ x: p.x,+ y: p.y,+ width: scaleContent ? Math.max(0.25, k.width * avgScale) : k.width,+ handleIn,+ handleOut,+ };+ });+ const minP = transformPoint(+ stroke.bounds.minX,+ stroke.bounds.minY,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ );+ const maxP = transformPoint(+ stroke.bounds.maxX,+ stroke.bounds.maxY,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ );+ return {+ ...stroke,+ knots: nextKnots,+ baseWidth: scaleContent ? Math.max(0.25, stroke.baseWidth * avgScale) : stroke.baseWidth,+ bounds: {+ minX: minP.x,+ minY: minP.y,+ maxX: maxP.x,+ maxY: maxP.y,+ },+ };+ });+}++function transformTextDataForResize(+ textData: TextLayerData,+ scaleContent: boolean,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+): TextLayerData {+ const p = transformPoint(textData.x, textData.y, scaleContent, offsetX, offsetY, scaleX, scaleY);+ if (!scaleContent) {+ return { ...textData, x: p.x, y: p.y };+ }+ const avgScale = (scaleX + scaleY) * 0.5;+ return {+ ...textData,+ x: p.x,+ y: p.y,+ fontSize: Math.max(4, Math.round(textData.fontSize * avgScale)),+ maxWidth:+ typeof textData.maxWidth === 'number'+ ? Math.max(10, Math.round(textData.maxWidth * scaleX))+ : textData.maxWidth,+ };+}++function transformBalloonForResize(+ balloon: SpeechBalloon,+ scaleContent: boolean,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+): SpeechBalloon {+ const avgScale = (scaleX + scaleY) * 0.5;+ const bPos = transformPoint(+ balloon.bounds.x,+ balloon.bounds.y,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ );+ const mapTailPt = (pt: SpeechBalloon['tail']['start']) => {+ const mapped = transformPoint(pt.x, pt.y, scaleContent, offsetX, offsetY, scaleX, scaleY);+ return { ...pt, x: mapped.x, y: mapped.y };+ };+ return {+ ...balloon,+ bounds: {+ x: bPos.x,+ y: bPos.y,+ width: scaleContent ? Math.max(4, balloon.bounds.width * scaleX) : balloon.bounds.width,+ height: scaleContent ? Math.max(4, balloon.bounds.height * scaleY) : balloon.bounds.height,+ },+ tail: {+ start: mapTailPt(balloon.tail.start),+ control1: mapTailPt(balloon.tail.control1),+ control2: mapTailPt(balloon.tail.control2),+ tip: mapTailPt(balloon.tail.tip),+ },+ strokeWidth: scaleContent ? Math.max(0.5, balloon.strokeWidth * avgScale) : balloon.strokeWidth,+ fontSize: scaleContent ? Math.max(4, Math.round(balloon.fontSize * avgScale)) : balloon.fontSize,+ };+}+export function useLayerResize(ctx: LayerManagerContext) {const {dimensions,@@ -30,12 +203,16 @@ export function useLayerResize(ctx: LayerManagerContext) {const currentH = dimensions.height;const newW = newDims.width;const newH = newDims.height;+ const scaleX = newW / Math.max(1, currentW);+ const scaleY = newH / Math.max(1, currentH);let offsetX = 0;let offsetY = 0;if (!scaleContent) {- if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {+ if (typeof options.offsetX === 'number' && Number.isFinite(options.offsetX)) {+ offsetX = Math.round(options.offsetX);+ } else if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {offsetX = 0;} else if (anchor === 'top-right' || anchor === 'right' || anchor === 'bottom-right') {offsetX = newW - currentW;@@ -43,7 +220,9 @@ export function useLayerResize(ctx: LayerManagerContext) {offsetX = Math.round((newW - currentW) / 2);}- if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {+ if (typeof options.offsetY === 'number' && Number.isFinite(options.offsetY)) {+ offsetY = Math.round(options.offsetY);+ } else if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {offsetY = 0;} else if (anchor === 'bottom-left' || anchor === 'bottom' || anchor === 'bottom-right') {offsetY = newH - currentH;@@ -120,11 +299,25 @@ export function useLayerResize(ctx: LayerManagerContext) {grid.notifyChange(true);+ const geometryChanged =+ scaleContent+ ? Math.abs(scaleX - 1) > 1e-6 || Math.abs(scaleY - 1) > 1e-6+ : offsetX !== 0 || offsetY !== 0;+setLayers((prev) =>prev.map((l) => {const newThumb = updatedThumbnails.get(l.id);const maskInfo = updatedMasks.get(l.id);- if (!newThumb && !maskInfo) return l;+ const hasCoordMeta =+ geometryChanged &&+ Boolean(+ l.comicFrames?.length ||+ l.vectorStrokes?.length ||+ l.textData ||+ l.balloonData ||+ l.balloons?.length+ );+ if (!newThumb && !maskInfo && !hasCoordMeta) return l;return {...l,...(newThumb ? { thumbnailUrl: newThumb } : {}),@@ -135,6 +328,61 @@ export function useLayerResize(ctx: LayerManagerContext) {maskVersion: (l.maskVersion || 0) + 1,}: {}),+ ...(geometryChanged && l.comicFrames?.length+ ? {+ comicFrames: transformComicFramesForResize(+ l.comicFrames,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ ),+ }+ : {}),+ ...(geometryChanged && l.vectorStrokes?.length+ ? {+ vectorStrokes: transformVectorStrokesForResize(+ l.vectorStrokes,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ ),+ }+ : {}),+ ...(geometryChanged && l.textData+ ? {+ textData: transformTextDataForResize(+ l.textData,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ ),+ }+ : {}),+ ...(geometryChanged && l.balloonData+ ? {+ balloonData: transformBalloonForResize(+ l.balloonData,+ scaleContent,+ offsetX,+ offsetY,+ scaleX,+ scaleY+ ),+ }+ : {}),+ ...(geometryChanged && l.balloons?.length+ ? {+ balloons: l.balloons.map((b) =>+ transformBalloonForResize(b, scaleContent, offsetX, offsetY, scaleX, scaleY)+ ),+ }+ : {}),};}));diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsxindex 8cd352d..fb59ffc 100644--- a/src/hooks/useAppMenuSections.tsx+++ b/src/hooks/useAppMenuSections.tsx@@ -336,7 +336,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio},{id: 'file-timelapse-export',- label: 'Export Time-lapse...',+ label: 'Preview & Export Time-lapse...',onClick: () => uiStoreActions.setTimelapseExportModalOpen(true),},],diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.tsindex 2d978a3..877fe19 100644--- a/src/hooks/useCanvasNavigation.ts+++ b/src/hooks/useCanvasNavigation.ts@@ -1271,7 +1271,10 @@ export function useCanvasNavigation({) {return;}- if (document.querySelector('[role="dialog"]') || useUiStore.getState().isSettingsModalOpen) {+ if (+ document.querySelector('[role="dialog"]:not([data-allow-canvas-nav="true"])') ||+ useUiStore.getState().isSettingsModalOpen+ ) {return;}diff --git a/src/hooks/useExternalFileDrop.ts b/src/hooks/useExternalFileDrop.tsindex 5d08e59..f4845ed 100644--- a/src/hooks/useExternalFileDrop.ts+++ b/src/hooks/useExternalFileDrop.ts@@ -298,7 +298,10 @@ export function useExternalFileDrop({const handleDragOver = (e: DragEvent) => {if (!isExternalFileDrag(e.dataTransfer)) return;const targetEl = e.target instanceof Element ? e.target : null;- if (targetEl?.closest('[data-testid="sub-view-panel"]')) {+ if (+ targetEl?.closest('[data-testid="sub-view-panel"]') ||+ targetEl?.closest('[data-testid="color-sets-panel"]')+ ) {updateDropTarget(null);return;}@@ -329,7 +332,10 @@ export function useExternalFileDrop({const handleDrop = (e: DragEvent) => {if (!isExternalFileDrag(e.dataTransfer)) return;const targetEl = e.target instanceof Element ? e.target : null;- if (targetEl?.closest('[data-testid="sub-view-panel"]')) {+ if (+ targetEl?.closest('[data-testid="sub-view-panel"]') ||+ targetEl?.closest('[data-testid="color-sets-panel"]')+ ) {updateDropTarget(null);return;}diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex dd2262f..50ca98e 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -4,6 +4,11 @@ import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';import { documentStore } from '../utils/documentStore';import { recoveryService } from '../services/recoveryService';import { documentStoreActions } from '../stores';+import {+ SoloLayerState,+ computeRestoreSolo,+ computeSoloToggle,+} from '../utils/layerOrganization';import { computeLayerSelection } from './layerManager/layerTreeOps';import { LayerManagerContext, UseLayerManagerProps } from './layerManager/types';import { useLayerCanvasRegistry } from './layerManager/useLayerCanvasRegistry';@@ -71,6 +76,8 @@ export function useLayerManager({const [layers, setLayers] = useState<LayerItem[]>([]);const [activeLayerId, setActiveLayerIdState] = useState<string>('');const [selectedLayerIds, setSelectedLayerIdsState] = useState<string[]>([]);+ const [soloLayerId, setSoloLayerId] = useState<string | null>(null);+ const soloStatesBySessionRef = useRef<Map<string, SoloLayerState>>(new Map());const activeLayerIdRef = useRef<string>(activeLayerId);activeLayerIdRef.current = activeLayerId;const selectedLayerIdsRef = useRef<string[]>(selectedLayerIds);@@ -96,7 +103,7 @@ export function useLayerManager({const structSig = layers.map((l) =>- `${l.id}:${l.name}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.locked ? 1 : 0}:${l.clipped ? 1 : 0}:${l.alphaLocked ? 1 : 0}:${l.parentId || ''}:${l.expressionColor || ''}:${l.toneEnabled ? 1 : 0}:${l.maskCanvas ? 1 : 0}:${l.maskEnabled === false ? 0 : 1}:${l.maskLinked === false ? 0 : 1}`+ `${l.id}:${l.name}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.locked ? 1 : 0}:${l.clipped ? 1 : 0}:${l.alphaLocked ? 1 : 0}:${l.colorLabel || ''}:${l.parentId || ''}:${l.expressionColor || ''}:${l.toneEnabled ? 1 : 0}:${l.maskCanvas ? 1 : 0}:${l.maskEnabled === false ? 0 : 1}:${l.maskLinked === false ? 0 : 1}`).join(';');@@ -225,6 +232,52 @@ export function useLayerManager({const clipboard = useLayerClipboard(ctx);const specialLayers = useLayerSpecialLayers(ctx, crud.addLayer, canvasRegistry.updateLayerThumbnail);+ // Sync per-document solo indicator when switching document tabs or when the soloed layer is removed+ useEffect(() => {+ const key = activeSessionId || '__default__';+ const currentSolo = soloStatesBySessionRef.current.get(key) ?? null;+ if (currentSolo && !layers.some((l) => l.id === currentSolo.layerId)) {+ soloStatesBySessionRef.current.delete(key);+ setSoloLayerId(null);+ } else {+ setSoloLayerId(currentSolo?.layerId ?? null);+ }+ }, [activeSessionId, layers]);++ const toggleSoloLayer = useCallback(+ (id: string) => {+ const key = activeSessionIdRef.current || '__default__';+ const currentSolo = soloStatesBySessionRef.current.get(key) ?? null;+ const result = computeSoloToggle(layersRef.current, id, currentSolo);+ if (result.action === 'noop') return;++ if (result.nextSolo) {+ soloStatesBySessionRef.current.set(key, result.nextSolo);+ } else {+ soloStatesBySessionRef.current.delete(key);+ }+ setSoloLayerId(result.nextSolo?.layerId ?? null);+ layersRef.current = result.nextLayers;+ setLayers(result.nextLayers);+ activeTileGridRef.current.notifyChange(true);+ },+ [activeSessionIdRef, activeTileGridRef, layersRef, setLayers]+ );++ const exitSoloLayer = useCallback(() => {+ const key = activeSessionIdRef.current || '__default__';+ const currentSolo = soloStatesBySessionRef.current.get(key) ?? null;+ if (!currentSolo) return;+ const result = computeRestoreSolo(layersRef.current, currentSolo);+ soloStatesBySessionRef.current.delete(key);+ setSoloLayerId(null);+ if (result.nextLayers !== layersRef.current) {+ layersRef.current = result.nextLayers;+ setLayers(result.nextLayers);+ activeTileGridRef.current.notifyChange(true);+ }+ }, [activeSessionIdRef, activeTileGridRef, layersRef, setLayers]);+// Get active layer objectconst activeLayer = layers.find((l) => l.id === activeLayerId) || layers[0];@@ -275,6 +328,10 @@ export function useLayerManager({pasteLayerFromFile: clipboard.pasteLayerFromFile,resizeCanvas: resize.resizeCanvas,toggleVisibility: propertiesAndMasks.toggleVisibility,+ soloLayerId,+ toggleSoloLayer,+ exitSoloLayer,+ setLayerColorLabel: propertiesAndMasks.setLayerColorLabel,setOpacity: propertiesAndMasks.setOpacity,setBlendMode: propertiesAndMasks.setBlendMode,toggleLock: propertiesAndMasks.toggleLock,diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.tsindex 32b1f27..7d0d928 100644--- a/src/services/recoveryService.ts+++ b/src/services/recoveryService.ts@@ -787,13 +787,52 @@ class RecoveryService {public async discardCrashedSession(sessionId: string): Promise<void> {if (!isTauriEnvironment()) return;try {- const { invoke } = await import('@tauri-apps/api/core');+ const invoke = await this.getInvoke();await invoke('recovery_close_session', { sessionId });} catch (err) {console.warn('[RecoveryService] Failed to discard crashed session:', err);}}+ /**+ * Discards multiple unrecovered crashed session directories.+ * Returns which session IDs succeeded and which (if any) failed.+ */+ public async discardAllCrashedSessions(+ sessionIds: readonly string[]+ ): Promise<{ discardedIds: string[]; failedIds: string[] }> {+ const uniqueIds = Array.from(new Set(sessionIds.filter(Boolean)));+ if (uniqueIds.length === 0) {+ return { discardedIds: [], failedIds: [] };+ }+ if (!isTauriEnvironment()) {+ return { discardedIds: uniqueIds, failedIds: [] };+ }++ const discardedIds: string[] = [];+ const failedIds: string[] = [];++ let invoke: typeof import('@tauri-apps/api/core').invoke;+ try {+ invoke = await this.getInvoke();+ } catch (err) {+ console.warn('[RecoveryService] Failed to load Tauri invoke for discard all:', err);+ return { discardedIds: [], failedIds: uniqueIds };+ }++ for (const sessionId of uniqueIds) {+ try {+ await invoke('recovery_close_session', { sessionId });+ discardedIds.push(sessionId);+ } catch (err) {+ console.warn(`[RecoveryService] Failed to discard crashed session "${sessionId}":`, err);+ failedIds.push(sessionId);+ }+ }++ return { discardedIds, failedIds };+ }+/*** Loads raw snapshot and parsed WAL entries for replaying a crashed session.*/diff --git a/src/stores/index.ts b/src/stores/index.tsindex e9f6f6b..78cf178 100644--- a/src/stores/index.ts+++ b/src/stores/index.ts@@ -71,6 +71,7 @@ export {createDefaultColorSets,serializeColorSetJson,parseColorSetJson,+ parseColorSetBytes,} from './useColorSetsStore';export type {ColorSwatch,diff --git a/src/stores/useColorSetsStore.ts b/src/stores/useColorSetsStore.tsindex a6d9fb4..c0dc123 100644--- a/src/stores/useColorSetsStore.ts+++ b/src/stores/useColorSetsStore.ts@@ -1,6 +1,13 @@import { createStore } from './createStore';import { safeLocalStorageGetItem, safeLocalStorageSetItem } from '../utils/safeStorage';import { isValidHex } from '../utils/colorUtils';+import {+ deriveColorSetNameFromFilename,+ hasPngSignature,+ hasSlccMagic,+ parseClipStudioColorSet,+ parsePngColorSet,+} from '../utils/colorSetImport';export const COLOR_SETS_STORAGE_KEY = 'ink_studio_color_sets_v1';export const COLOR_SET_EXPORT_FORMAT = 'ink-studio-color-set' as const;@@ -392,6 +399,88 @@ export function parseColorSetJson(rawJson: string): { ok: true; name: string; swreturn { ok: true, name, swatches };}+export function parseColorSetBytes(+ data: Uint8Array | ArrayBuffer,+ filename?: string+): { ok: true; name: string; swatches: ColorSwatch[] } | { ok: false; error: string } {+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);+ if (bytes.byteLength === 0) {+ return { ok: false, error: 'Color set file is empty.' };+ }++ const lower = (filename ?? '').trim().toLowerCase();++ if (hasSlccMagic(bytes) || lower.endsWith('.cls')) {+ const parsed = parseClipStudioColorSet(bytes, filename, MAX_SWATCHES_PER_SET);+ if (!parsed.ok) return parsed;+ const swatches = sanitizeSwatches(parsed.swatches);+ if (swatches.length === 0) {+ return { ok: false, error: 'No valid colors found in Clip Studio color set.' };+ }+ return { ok: true, name: parsed.name, swatches };+ }++ if (hasPngSignature(bytes) || lower.endsWith('.png')) {+ const parsed = parsePngColorSet(bytes, filename, MAX_SWATCHES_PER_SET);+ if (!parsed.ok) return parsed;+ const swatches = sanitizeSwatches(parsed.swatches);+ if (swatches.length === 0) {+ return { ok: false, error: 'No valid colors found in PNG color palette.' };+ }+ return { ok: true, name: parsed.name, swatches };+ }++ if (lower && !lower.endsWith('.json')) {+ return {+ ok: false,+ error: 'Unsupported color set format. Use .json, Clip Studio .cls, or .png palette files.',+ };+ }++ const text = new TextDecoder('utf-8').decode(bytes);+ const jsonRes = parseColorSetJson(text);+ if (!jsonRes.ok) return jsonRes;++ const resolvedName =+ jsonRes.name === 'Imported Set' && filename+ ? deriveColorSetNameFromFilename(filename, 'Imported Set')+ : jsonRes.name;++ return { ok: true, name: resolvedName, swatches: jsonRes.swatches };+}++function commitImportedColorSet(name: string, swatches: ColorSwatch[]): ImportColorSetResult {+ const state = useColorSetsStore.getState();+ if (state.sets.length >= MAX_COLOR_SETS) {+ return {+ ok: false,+ error: `Maximum of ${MAX_COLOR_SETS} color sets reached. Delete a set before importing.`,+ };+ }++ let uniqueName = name.trim().slice(0, 48) || 'Imported Set';+ const existingLower = new Set(state.sets.map((s) => s.name.trim().toLowerCase()));+ if (existingLower.has(uniqueName.toLowerCase())) {+ let n = 2;+ while (existingLower.has(`${uniqueName} (${n})`.toLowerCase()) && n < 100) {+ n += 1;+ }+ uniqueName = `${uniqueName.slice(0, 42)} (${n})`;+ }++ const imported: ColorSet = {+ id: makeId('set'),+ name: uniqueName,+ swatches,+ };+ useColorSetsStore.setState((prev) => ({+ sets: [...prev.sets, imported].slice(0, MAX_COLOR_SETS),+ activeSetId: imported.id,+ }));+ persist();+ return { ok: true, set: imported };+}+export const colorSetsStoreActions = {selectSet(setId: string): void {const state = useColorSetsStore.getState();@@ -602,26 +691,21 @@ export const colorSetsStoreActions = {importSetJson(rawJson: string): ImportColorSetResult {const parsed = parseColorSetJson(rawJson);if (!parsed.ok) return parsed;- const state = useColorSetsStore.getState();- let uniqueName = parsed.name;- const existingLower = new Set(state.sets.map((s) => s.name.trim().toLowerCase()));- if (existingLower.has(uniqueName.toLowerCase())) {- let n = 2;- while (existingLower.has(`${uniqueName} (${n})`.toLowerCase()) && n < 100) {- n += 1;- }- uniqueName = `${uniqueName.slice(0, 42)} (${n})`;+ return commitImportedColorSet(parsed.name, parsed.swatches);+ },++ importSetBytes(data: Uint8Array | ArrayBuffer, filename?: string): ImportColorSetResult {+ const parsed = parseColorSetBytes(data, filename);+ if (!parsed.ok) return parsed;+ return commitImportedColorSet(parsed.name, parsed.swatches);+ },++ async importSetFile(file: File): Promise<ImportColorSetResult> {+ try {+ const buffer = await file.arrayBuffer();+ return this.importSetBytes(new Uint8Array(buffer), file.name);+ } catch {+ return { ok: false, error: 'Failed to read color set file.' };}- const imported: ColorSet = {- id: makeId('set'),- name: uniqueName,- swatches: parsed.swatches,- };- useColorSetsStore.setState((prev) => ({- sets: [...prev.sets, imported].slice(0, MAX_COLOR_SETS),- activeSetId: imported.id,- }));- persist();- return { ok: true, set: imported };},};diff --git a/src/stores/useSubViewStore.ts b/src/stores/useSubViewStore.tsindex a6f980e..40f45b3 100644--- a/src/stores/useSubViewStore.ts+++ b/src/stores/useSubViewStore.ts@@ -4,57 +4,119 @@ import {safeLocalStorageGetItem,safeLocalStorageSetItem,} from '../utils/safeStorage';+import {+ BoardPoint,+ DEFAULT_SUB_VIEW_STUDY_FILTER,+ DEFAULT_SUB_VIEW_TRANSFORM,+ SUB_VIEW_MAX_ZOOM,+ SUB_VIEW_MIN_ZOOM,+ SubViewBoardLayoutMode,+ SubViewBoardTool,+ SubViewGridMode,+ SubViewMode,+ SubViewStudyFilter,+ SubViewTransform,+ SubViewValueSteps,+ clampBoardCardScale,+ clampSubViewZoom,+ computeBoardAutoLayout,+ computeNormalizedBoardScale,+ computePlacementForNewBoardItems,+ sanitizeStudyFilter,+} from '../utils/subViewEngine';++export { SUB_VIEW_MIN_ZOOM, SUB_VIEW_MAX_ZOOM };+export type {+ SubViewTransform,+ SubViewMode,+ SubViewBoardTool,+ SubViewStudyFilter,+ SubViewValueSteps,+ SubViewGridMode,+ SubViewBoardLayoutMode,+};export const SUB_VIEW_STORAGE_KEY = 'ink_studio_subview_v1';const SUB_VIEW_DB_NAME = 'InkStudioSubViewDB';const SUB_VIEW_DB_VERSION = 1;const SUB_VIEW_IMAGE_STORE = 'subview_images';-export interface SubViewTransform {- zoom: number;- pan: { x: number; y: number };- rotation: number; // degrees- flipX: boolean;-}-export interface SubViewImageItem {id: string;name: string;src: string; // data: URL stored in IndexedDB (empty until hydrated or if evicted)width: number;height: number;+ // Single-mode per-image transformzoom: number;pan: { x: number; y: number };rotation: number;flipX: boolean;- /** True until first fit-to-container calculation is performed for this item */+ /** True until first fit-to-container calculation is performed for this item (Single mode) */needsInitialFit?: boolean;+ // PureRef Board-mode per-card transform & study properties+ boardX: number;+ boardY: number;+ boardScale: number;+ boardRotation: number;+ boardFlipX: boolean;+ boardFlipY: boolean;+ zIndex: number;+ opacity: number; // 0.1..1.0+ locked: boolean;+ grayscale: boolean; // Per-card B/W override}export interface SubViewStoreState {items: SubViewImageItem[];activeId: string | null;+ viewMode: SubViewMode;+ boardTool: SubViewBoardTool;+ boardTransform: SubViewTransform;+ boardNeedsInitialFit: boolean;+ studyFilter: SubViewStudyFilter;+ sampleDisplayTone: boolean;autoEyedropper: boolean;manualEyedropper: boolean;showList: boolean;+ showPalette: boolean;+}++interface PersistedSubViewItem {+ id: string;+ name: string;+ width: number;+ height: number;+ zoom?: number;+ pan?: { x: number; y: number };+ rotation?: number;+ flipX?: boolean;+ needsInitialFit?: boolean;+ boardX?: number;+ boardY?: number;+ boardScale?: number;+ boardRotation?: number;+ boardFlipX?: boolean;+ boardFlipY?: boolean;+ zIndex?: number;+ opacity?: number;+ locked?: boolean;+ grayscale?: boolean;}interface PersistedSubViewPayload {- version: 1;+ version: 2;activeId: string | null;- autoEyedropper: boolean;- showList: boolean;- items: Array<{- id: string;- name: string;- width: number;- height: number;- zoom: number;- pan: { x: number; y: number };- rotation: number;- flipX: boolean;- needsInitialFit?: boolean;- }>;+ viewMode?: SubViewMode;+ boardTool?: SubViewBoardTool;+ boardTransform?: SubViewTransform;+ boardNeedsInitialFit?: boolean;+ studyFilter?: Partial<SubViewStudyFilter>;+ sampleDisplayTone?: boolean;+ autoEyedropper?: boolean;+ showList?: boolean;+ showPalette?: boolean;+ items: PersistedSubViewItem[];}interface SubViewImageRecord {@@ -62,12 +124,9 @@ interface SubViewImageRecord {src: string;}-export const SUB_VIEW_MIN_ZOOM = 0.05;-export const SUB_VIEW_MAX_ZOOM = 16.0;--function clampZoom(z: number): number {- if (!Number.isFinite(z)) return 1;- return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, z));+function clampOpacity(val: number): number {+ if (!Number.isFinite(val)) return 1;+ return Math.max(0.1, Math.min(1, val));}function isSafeImageSrc(src: unknown): src is string {@@ -113,7 +172,7 @@ export async function saveSubViewImageToIdb(id: string, src: string): Promise<votx.onerror = () => reject(tx.error);});} catch (err) {- handleIndexedDbError(err, 'Sub View reference image');+ handleIndexedDbError(err, 'References image');}}@@ -167,14 +226,41 @@ export async function loadSubViewImagesFromIdb(): Promise<Map<string, string>> {return map;}-export function loadSubViewState(): SubViewStoreState {- const fallback: SubViewStoreState = {+function createFallbackState(): SubViewStoreState {+ return {items: [],activeId: null,+ viewMode: 'board',+ boardTool: 'select',+ boardTransform: { ...DEFAULT_SUB_VIEW_TRANSFORM, pan: { x: 0, y: 0 } },+ boardNeedsInitialFit: true,+ studyFilter: { ...DEFAULT_SUB_VIEW_STUDY_FILTER },+ sampleDisplayTone: false,autoEyedropper: true,manualEyedropper: false,showList: false,+ showPalette: false,+ };+}++function sanitizeTransform(raw: unknown): SubViewTransform {+ if (!raw || typeof raw !== 'object') {+ return { ...DEFAULT_SUB_VIEW_TRANSFORM, pan: { x: 0, y: 0 } };+ }+ const r = raw as Record<string, unknown>;+ const panRec = r.pan && typeof r.pan === 'object' ? (r.pan as Record<string, unknown>) : null;+ const panX = panRec && typeof panRec.x === 'number' && Number.isFinite(panRec.x) ? panRec.x : 0;+ const panY = panRec && typeof panRec.y === 'number' && Number.isFinite(panRec.y) ? panRec.y : 0;+ return {+ zoom: clampSubViewZoom(typeof r.zoom === 'number' ? r.zoom : 1),+ pan: { x: panX, y: panY },+ rotation: typeof r.rotation === 'number' && Number.isFinite(r.rotation) ? r.rotation : 0,+ flipX: Boolean(r.flipX),};+}++export function loadSubViewState(): SubViewStoreState {+ const fallback = createFallbackState();try {const raw = safeLocalStorageGetItem(SUB_VIEW_STORAGE_KEY);@@ -186,8 +272,10 @@ export function loadSubViewState(): SubViewStoreState {const items: SubViewImageItem[] = [];const legacyInlineImages: Array<{ id: string; src: string }> = [];const seen = new Set<string>();+ let hasAnyBoardCoords = false;- for (const entry of rawItems) {+ for (let idx = 0; idx < rawItems.length; idx++) {+ const entry = rawItems[idx];if (!entry || typeof entry !== 'object') continue;const r = entry as Record<string, unknown>;const id = typeof r.id === 'string' && r.id.trim() ? r.id : '';@@ -199,15 +287,33 @@ export function loadSubViewState(): SubViewStoreState {if (legacySrc) {legacyInlineImages.push({ id, src: legacySrc });}- const width = typeof r.width === 'number' && Number.isFinite(r.width) && r.width > 0 ? Math.round(r.width) : 0;- const height = typeof r.height === 'number' && Number.isFinite(r.height) && r.height > 0 ? Math.round(r.height) : 0;- const zoom = clampZoom(typeof r.zoom === 'number' ? r.zoom : 1);+ const width =+ typeof r.width === 'number' && Number.isFinite(r.width) && r.width > 0+ ? Math.round(r.width)+ : 0;+ const height =+ typeof r.height === 'number' && Number.isFinite(r.height) && r.height > 0+ ? Math.round(r.height)+ : 0;+ const zoom = clampSubViewZoom(typeof r.zoom === 'number' ? r.zoom : 1);const panRec = r.pan && typeof r.pan === 'object' ? (r.pan as Record<string, unknown>) : null;const panX = panRec && typeof panRec.x === 'number' && Number.isFinite(panRec.x) ? panRec.x : 0;const panY = panRec && typeof panRec.y === 'number' && Number.isFinite(panRec.y) ? panRec.y : 0;const rotation = typeof r.rotation === 'number' && Number.isFinite(r.rotation) ? r.rotation : 0;const flipX = Boolean(r.flipX);+ const hasBoardPos =+ typeof r.boardX === 'number' &&+ Number.isFinite(r.boardX) &&+ typeof r.boardY === 'number' &&+ Number.isFinite(r.boardY);+ if (hasBoardPos) hasAnyBoardCoords = true;++ const boardScale =+ typeof r.boardScale === 'number' && Number.isFinite(r.boardScale)+ ? clampBoardCardScale(r.boardScale)+ : computeNormalizedBoardScale(width || 100, height || 100);+items.push({id,name,@@ -218,21 +324,72 @@ export function loadSubViewState(): SubViewStoreState {pan: { x: panX, y: panY },rotation,flipX,- needsInitialFit: typeof r.needsInitialFit === 'boolean' ? r.needsInitialFit : !panX && !panY && zoom === 1,+ needsInitialFit:+ typeof r.needsInitialFit === 'boolean' ? r.needsInitialFit : !panX && !panY && zoom === 1,+ boardX: hasBoardPos ? (r.boardX as number) : 0,+ boardY: hasBoardPos ? (r.boardY as number) : 0,+ boardScale,+ boardRotation:+ typeof r.boardRotation === 'number' && Number.isFinite(r.boardRotation)+ ? r.boardRotation+ : 0,+ boardFlipX: Boolean(r.boardFlipX),+ boardFlipY: Boolean(r.boardFlipY),+ zIndex:+ typeof r.zIndex === 'number' && Number.isFinite(r.zIndex) ? Math.round(r.zIndex) : idx + 1,+ opacity: clampOpacity(typeof r.opacity === 'number' ? r.opacity : 1),+ locked: Boolean(r.locked),+ grayscale: Boolean(r.grayscale),});}+ // If migrating v1 items that had no PureRef board coordinates, auto-pack them neatly+ const isV2 = parsed.version === 2;+ if (!isV2 && items.length > 0 && !hasAnyBoardCoords) {+ const autoLayout = computeBoardAutoLayout(+ items.map((it) => ({ id: it.id, width: it.width || 100, height: it.height || 100 })),+ 'grid'+ );+ for (const it of items) {+ const p = autoLayout.get(it.id);+ if (p) {+ it.boardX = p.boardX;+ it.boardY = p.boardY;+ it.boardScale = p.boardScale;+ }+ }+ }+const activeId =typeof parsed.activeId === 'string' && items.some((i) => i.id === parsed.activeId)? parsed.activeId: items[0]?.id ?? null;+ const viewMode: SubViewMode =+ parsed.viewMode === 'single' || parsed.viewMode === 'board' ? parsed.viewMode : 'board';+ const boardTool: SubViewBoardTool =+ parsed.boardTool === 'eyedrop' || parsed.boardTool === 'select' || parsed.boardTool === 'pan'+ ? parsed.boardTool+ : 'select';+const state: SubViewStoreState = {items,activeId,+ viewMode,+ boardTool,+ boardTransform: sanitizeTransform(parsed.boardTransform),+ boardNeedsInitialFit:+ typeof parsed.boardNeedsInitialFit === 'boolean'+ ? parsed.boardNeedsInitialFit+ : isV2+ ? true+ : !hasAnyBoardCoords,+ studyFilter: sanitizeStudyFilter(parsed.studyFilter as Partial<SubViewStudyFilter>),+ sampleDisplayTone: Boolean(parsed.sampleDisplayTone),autoEyedropper: typeof parsed.autoEyedropper === 'boolean' ? parsed.autoEyedropper : true,manualEyedropper: false,showList: typeof parsed.showList === 'boolean' ? parsed.showList : false,+ showPalette: Boolean(parsed.showPalette),};// Migrate any legacy inline data URLs out of localStorage into IndexedDB immediately@@ -250,29 +407,71 @@ export function loadSubViewState(): SubViewStoreState {}/**- * Persists only lightweight Sub View metadata and IDs to localStorage.+ * Persists only lightweight Sub View metadata and IDs to localStorage,+ * omitting default fields to keep storage footprint tiny.* Image data URLs live exclusively in IndexedDB.*/export function saveSubViewState(state: SubViewStoreState): void {+ const sf = state.studyFilter;+ const compactFilter: Partial<SubViewStudyFilter> = {};+ if (sf.grayscale) compactFilter.grayscale = true;+ if (sf.valueSteps !== 0) compactFilter.valueSteps = sf.valueSteps;+ if (sf.notanThreshold !== 128) compactFilter.notanThreshold = sf.notanThreshold;+ if (sf.squintBlur) compactFilter.squintBlur = true;+ if (sf.brightness !== 0) compactFilter.brightness = sf.brightness;+ if (sf.contrast !== 0) compactFilter.contrast = sf.contrast;+ if (sf.gridMode !== 'none') compactFilter.gridMode = sf.gridMode;+ if (sf.splitBw) compactFilter.splitBw = true;+ if (sf.splitRatio !== 0.5) compactFilter.splitRatio = sf.splitRatio;++ const bt = state.boardTransform;+ const hasCustomBoardTransform =+ bt.zoom !== 1 || bt.pan.x !== 0 || bt.pan.y !== 0 || bt.rotation !== 0 || bt.flipX;+const payload: PersistedSubViewPayload = {- version: 1,+ version: 2,activeId: state.activeId,- autoEyedropper: state.autoEyedropper,- showList: state.showList,- items: state.items.map((item) => ({- id: item.id,- name: item.name,- width: item.width,- height: item.height,- zoom: item.zoom,- pan: item.pan,- rotation: item.rotation,- flipX: item.flipX,- needsInitialFit: item.needsInitialFit,- })),+ ...(state.viewMode !== 'board' ? { viewMode: state.viewMode } : {}),+ ...(state.boardTool !== 'select' ? { boardTool: state.boardTool } : {}),+ ...(hasCustomBoardTransform ? { boardTransform: bt } : {}),+ ...(state.boardNeedsInitialFit === false ? { boardNeedsInitialFit: false } : {}),+ ...(Object.keys(compactFilter).length > 0 ? { studyFilter: compactFilter } : {}),+ ...(state.sampleDisplayTone ? { sampleDisplayTone: true } : {}),+ ...(state.autoEyedropper === false ? { autoEyedropper: false } : {}),+ ...(state.showList ? { showList: true } : {}),+ ...(state.showPalette ? { showPalette: true } : {}),+ items: state.items.map((item) => {+ const entry: PersistedSubViewItem = {+ id: item.id,+ name: item.name,+ width: item.width,+ height: item.height,+ };+ if (item.zoom !== 1) entry.zoom = item.zoom;+ if (item.pan.x !== 0 || item.pan.y !== 0) entry.pan = item.pan;+ if (item.rotation !== 0) entry.rotation = item.rotation;+ if (item.flipX) entry.flipX = true;+ if (item.needsInitialFit === false) entry.needsInitialFit = false;+ if (item.boardX !== 0 || item.boardY !== 0) {+ entry.boardX = Math.round(item.boardX * 100) / 100;+ entry.boardY = Math.round(item.boardY * 100) / 100;+ }+ const defaultScale = computeNormalizedBoardScale(item.width || 100, item.height || 100);+ if (Math.abs(item.boardScale - defaultScale) > 1e-4) {+ entry.boardScale = Math.round(item.boardScale * 10000) / 10000;+ }+ if (item.boardRotation !== 0) entry.boardRotation = item.boardRotation;+ if (item.boardFlipX) entry.boardFlipX = true;+ if (item.boardFlipY) entry.boardFlipY = true;+ if (item.zIndex !== 1) entry.zIndex = item.zIndex;+ if (item.opacity !== 1) entry.opacity = item.opacity;+ if (item.locked) entry.locked = true;+ if (item.grayscale) entry.grayscale = true;+ return entry;+ }),};- safeLocalStorageSetItem(SUB_VIEW_STORAGE_KEY, JSON.stringify(payload), 'Sub View layout');+ safeLocalStorageSetItem(SUB_VIEW_STORAGE_KEY, JSON.stringify(payload), 'References layout');}export const useSubViewStore = createStore<SubViewStoreState>(loadSubViewState);@@ -310,25 +509,68 @@ function persist(): void {saveSubViewState(useSubViewStore.getState());}+function getNextZIndex(items: readonly SubViewImageItem[]): number {+ let maxZ = 0;+ for (const it of items) {+ if (it.zIndex > maxZ) maxZ = it.zIndex;+ }+ return maxZ + 1;+}+export const subViewStoreActions = {- addImages(newItems: Array<{ name: string; src: string; width: number; height: number; id?: string }>): void {+ addImages(+ newItems: Array<{ name: string; src: string; width: number; height: number; id?: string }>,+ options?: { dropBoardPoint?: BoardPoint | null }+ ): void {if (newItems.length === 0) return;- const prepared: SubViewImageItem[] = newItems.map((item) => ({- id: item.id || createSubViewItemId(),- name: item.name.slice(0, 120) || 'Reference',- src: item.src,- width: Math.max(1, Math.round(item.width)),- height: Math.max(1, Math.round(item.height)),- zoom: 1,- pan: { x: 0, y: 0 },- rotation: 0,- flipX: false,- needsInitialFit: true,- }));+ const prevState = useSubViewStore.getState();+ const wasEmpty = prevState.items.length === 0;+ const placements = computePlacementForNewBoardItems(+ prevState.items,+ newItems.map((it) => ({+ width: Math.max(1, Math.round(it.width)),+ height: Math.max(1, Math.round(it.height)),+ })),+ options?.dropBoardPoint ?? null+ );+ let nextZ = getNextZIndex(prevState.items);++ const prepared: SubViewImageItem[] = newItems.map((item, idx) => {+ const w = Math.max(1, Math.round(item.width));+ const h = Math.max(1, Math.round(item.height));+ const pos = placements[idx] ?? {+ boardX: 0,+ boardY: 0,+ boardScale: computeNormalizedBoardScale(w, h),+ };+ return {+ id: item.id || createSubViewItemId(),+ name: item.name.slice(0, 120) || 'Reference',+ src: item.src,+ width: w,+ height: h,+ zoom: 1,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+ needsInitialFit: true,+ boardX: pos.boardX,+ boardY: pos.boardY,+ boardScale: pos.boardScale,+ boardRotation: 0,+ boardFlipX: false,+ boardFlipY: false,+ zIndex: nextZ++,+ opacity: 1,+ locked: false,+ grayscale: false,+ };+ });useSubViewStore.setState((prev) => ({items: [...prev.items, ...prepared],activeId: prepared[prepared.length - 1].id,+ boardNeedsInitialFit: wasEmpty || (!options?.dropBoardPoint && prev.boardNeedsInitialFit),}));persist();for (const item of prepared) {@@ -346,14 +588,23 @@ export const subViewStoreActions = {const fallbackIdx = Math.min(idx, nextItems.length - 1);nextActive = fallbackIdx >= 0 ? nextItems[fallbackIdx].id : null;}- return { items: nextItems, activeId: nextActive };+ return {+ items: nextItems,+ activeId: nextActive,+ boardNeedsInitialFit: nextItems.length === 0 ? true : prev.boardNeedsInitialFit,+ };});persist();void deleteSubViewImageFromIdb(id);},clearAll(): void {- useSubViewStore.setState({ items: [], activeId: null });+ useSubViewStore.setState({+ items: [],+ activeId: null,+ boardTransform: { ...DEFAULT_SUB_VIEW_TRANSFORM, pan: { x: 0, y: 0 } },+ boardNeedsInitialFit: true,+ });persist();void clearSubViewImagesFromIdb();},@@ -377,6 +628,50 @@ export const subViewStoreActions = {persist();},+ setViewMode(viewMode: SubViewMode): void {+ useSubViewStore.setState((prev) => {+ if (prev.viewMode === viewMode) return prev;+ return { viewMode };+ });+ persist();+ },++ toggleViewMode(): void {+ useSubViewStore.setState((prev) => ({+ viewMode: prev.viewMode === 'board' ? 'single' : 'board',+ }));+ persist();+ },++ setBoardTool(boardTool: SubViewBoardTool): void {+ useSubViewStore.setState({+ boardTool,+ autoEyedropper: boardTool === 'eyedrop',+ manualEyedropper: boardTool === 'eyedrop',+ });+ persist();+ },++ updateBoardTransform(+ patch: Partial<SubViewTransform> & { needsInitialFit?: boolean },+ shouldPersist = true+ ): void {+ useSubViewStore.setState((prev) => ({+ boardTransform: {+ zoom: patch.zoom !== undefined ? clampSubViewZoom(patch.zoom) : prev.boardTransform.zoom,+ pan: patch.pan !== undefined ? { x: patch.pan.x, y: patch.pan.y } : prev.boardTransform.pan,+ rotation:+ patch.rotation !== undefined && Number.isFinite(patch.rotation)+ ? patch.rotation+ : prev.boardTransform.rotation,+ flipX: patch.flipX !== undefined ? patch.flipX : prev.boardTransform.flipX,+ },+ boardNeedsInitialFit:+ patch.needsInitialFit !== undefined ? patch.needsInitialFit : prev.boardNeedsInitialFit,+ }));+ if (shouldPersist) persist();+ },+updateImageTransform(id: string,patch: Partial<SubViewTransform> & { needsInitialFit?: boolean },@@ -387,17 +682,153 @@ export const subViewStoreActions = {if (item.id !== id) return item;return {...item,- zoom: patch.zoom !== undefined ? clampZoom(patch.zoom) : item.zoom,+ zoom: patch.zoom !== undefined ? clampSubViewZoom(patch.zoom) : item.zoom,pan: patch.pan !== undefined ? { x: patch.pan.x, y: patch.pan.y } : item.pan,- rotation: patch.rotation !== undefined && Number.isFinite(patch.rotation) ? patch.rotation : item.rotation,+ rotation:+ patch.rotation !== undefined && Number.isFinite(patch.rotation)+ ? patch.rotation+ : item.rotation,flipX: patch.flipX !== undefined ? patch.flipX : item.flipX,- needsInitialFit: patch.needsInitialFit !== undefined ? patch.needsInitialFit : item.needsInitialFit,+ needsInitialFit:+ patch.needsInitialFit !== undefined ? patch.needsInitialFit : item.needsInitialFit,};}),}));if (shouldPersist) persist();},+ updateCardBoardProps(+ id: string,+ patch: Partial<+ Pick<+ SubViewImageItem,+ | 'boardX'+ | 'boardY'+ | 'boardScale'+ | 'boardRotation'+ | 'boardFlipX'+ | 'boardFlipY'+ | 'zIndex'+ | 'opacity'+ | 'locked'+ | 'grayscale'+ >+ >,+ shouldPersist = true+ ): void {+ useSubViewStore.setState((prev) => ({+ items: prev.items.map((item) => {+ if (item.id !== id) return item;+ return {+ ...item,+ boardX:+ patch.boardX !== undefined && Number.isFinite(patch.boardX)+ ? patch.boardX+ : item.boardX,+ boardY:+ patch.boardY !== undefined && Number.isFinite(patch.boardY)+ ? patch.boardY+ : item.boardY,+ boardScale:+ patch.boardScale !== undefined+ ? clampBoardCardScale(patch.boardScale)+ : item.boardScale,+ boardRotation:+ patch.boardRotation !== undefined && Number.isFinite(patch.boardRotation)+ ? patch.boardRotation+ : item.boardRotation,+ boardFlipX: patch.boardFlipX !== undefined ? patch.boardFlipX : item.boardFlipX,+ boardFlipY: patch.boardFlipY !== undefined ? patch.boardFlipY : item.boardFlipY,+ zIndex:+ patch.zIndex !== undefined && Number.isFinite(patch.zIndex)+ ? Math.round(patch.zIndex)+ : item.zIndex,+ opacity: patch.opacity !== undefined ? clampOpacity(patch.opacity) : item.opacity,+ locked: patch.locked !== undefined ? patch.locked : item.locked,+ grayscale: patch.grayscale !== undefined ? patch.grayscale : item.grayscale,+ };+ }),+ }));+ if (shouldPersist) persist();+ },++ bringCardToFront(id: string): void {+ useSubViewStore.setState((prev) => {+ const target = prev.items.find((i) => i.id === id);+ if (!target) return prev;+ const maxZ = prev.items.reduce((m, i) => Math.max(m, i.zIndex), 0);+ if (target.zIndex === maxZ && prev.items.filter((i) => i.zIndex === maxZ).length === 1) {+ return prev;+ }+ return {+ items: prev.items.map((i) => (i.id === id ? { ...i, zIndex: maxZ + 1 } : i)),+ };+ });+ persist();+ },++ sendCardToBack(id: string): void {+ useSubViewStore.setState((prev) => {+ const target = prev.items.find((i) => i.id === id);+ if (!target) return prev;+ const minZ = prev.items.reduce((m, i) => Math.min(m, i.zIndex), 1);+ return {+ items: prev.items.map((i) => (i.id === id ? { ...i, zIndex: minZ - 1 } : i)),+ };+ });+ persist();+ },++ duplicateCard(id: string): void {+ const state = useSubViewStore.getState();+ const src = state.items.find((i) => i.id === id);+ if (!src) return;+ const cloneId = createSubViewItemId();+ const nextZ = getNextZIndex(state.items);+ const clone: SubViewImageItem = {+ ...src,+ id: cloneId,+ name: `${src.name} copy`.slice(0, 120),+ boardX: src.boardX + 24,+ boardY: src.boardY + 24,+ zIndex: nextZ,+ locked: false,+ };+ useSubViewStore.setState((prev) => ({+ items: [...prev.items, clone],+ activeId: cloneId,+ }));+ persist();+ if (clone.src) {+ void saveSubViewImageToIdb(cloneId, clone.src);+ }+ },++ arrangeBoard(mode: SubViewBoardLayoutMode): void {+ useSubViewStore.setState((prev) => {+ if (prev.items.length === 0) return prev;+ const layout = computeBoardAutoLayout(+ prev.items.map((i) => ({ id: i.id, width: i.width || 100, height: i.height || 100 })),+ mode+ );+ return {+ items: prev.items.map((item) => {+ const p = layout.get(item.id);+ if (!p) return item;+ return {+ ...item,+ boardX: p.boardX,+ boardY: p.boardY,+ boardScale: p.boardScale,+ boardRotation: p.boardRotation,+ };+ }),+ boardNeedsInitialFit: true,+ };+ });+ persist();+ },+replaceImageSrc(id: string, src: string, width: number, height: number): void {useSubViewStore.setState((prev) => ({items: prev.items.map((item) =>@@ -408,6 +839,7 @@ export const subViewStoreActions = {width: Math.max(1, Math.round(width)),height: Math.max(1, Math.round(height)),needsInitialFit: true,+ boardScale: computeNormalizedBoardScale(width, height),}: item),@@ -416,22 +848,132 @@ export const subViewStoreActions = {void saveSubViewImageToIdb(id, src);},+ updateStudyFilter(patch: Partial<SubViewStudyFilter>, shouldPersist = true): void {+ useSubViewStore.setState((prev) => ({+ studyFilter: sanitizeStudyFilter({ ...prev.studyFilter, ...patch }),+ }));+ if (shouldPersist) persist();+ },++ toggleGrayscale(): void {+ useSubViewStore.setState((prev) => {+ const nextGray = !prev.studyFilter.grayscale;+ return {+ studyFilter: {+ ...prev.studyFilter,+ grayscale: nextGray,+ // Turning off B/W also exits value posterize / split-BW smoothly+ valueSteps: nextGray ? prev.studyFilter.valueSteps : 0,+ splitBw: nextGray ? false : prev.studyFilter.splitBw,+ },+ };+ });+ persist();+ },++ setValueSteps(steps: SubViewValueSteps): void {+ useSubViewStore.setState((prev) => ({+ studyFilter: {+ ...prev.studyFilter,+ valueSteps: steps,+ grayscale: steps > 0 ? true : prev.studyFilter.grayscale,+ splitBw: steps > 0 ? false : prev.studyFilter.splitBw,+ },+ }));+ persist();+ },++ cycleValueSteps(): void {+ const cur = useSubViewStore.getState().studyFilter.valueSteps;+ const next: SubViewValueSteps = cur === 0 ? 2 : cur === 2 ? 3 : cur === 3 ? 5 : 0;+ subViewStoreActions.setValueSteps(next);+ },++ toggleSquintBlur(): void {+ useSubViewStore.setState((prev) => ({+ studyFilter: {+ ...prev.studyFilter,+ squintBlur: !prev.studyFilter.squintBlur,+ },+ }));+ persist();+ },++ toggleSplitBw(): void {+ useSubViewStore.setState((prev) => {+ const nextSplit = !prev.studyFilter.splitBw;+ return {+ studyFilter: {+ ...prev.studyFilter,+ splitBw: nextSplit,+ grayscale: nextSplit ? false : prev.studyFilter.grayscale,+ valueSteps: nextSplit ? 0 : prev.studyFilter.valueSteps,+ },+ };+ });+ persist();+ },++ cycleGridMode(): void {+ const order: SubViewGridMode[] = ['none', 'thirds', 'grid4', 'grid8', 'golden', 'crosshair'];+ useSubViewStore.setState((prev) => {+ const idx = order.indexOf(prev.studyFilter.gridMode);+ const next = order[(idx + 1) % order.length];+ return {+ studyFilter: {+ ...prev.studyFilter,+ gridMode: next,+ },+ };+ });+ persist();+ },++ resetStudyFilter(): void {+ useSubViewStore.setState({+ studyFilter: { ...DEFAULT_SUB_VIEW_STUDY_FILTER },+ });+ persist();+ },++ toggleSampleDisplayTone(): void {+ useSubViewStore.setState((prev) => ({ sampleDisplayTone: !prev.sampleDisplayTone }));+ persist();+ },+setAutoEyedropper(enabled: boolean): void {- useSubViewStore.setState({ autoEyedropper: enabled });+ useSubViewStore.setState((prev) => ({+ autoEyedropper: enabled,+ boardTool: enabled ? 'eyedrop' : prev.boardTool === 'eyedrop' ? 'select' : prev.boardTool,+ }));persist();},toggleAutoEyedropper(): void {- useSubViewStore.setState((prev) => ({ autoEyedropper: !prev.autoEyedropper }));+ useSubViewStore.setState((prev) => {+ const next = !prev.autoEyedropper;+ return {+ autoEyedropper: next,+ boardTool: next ? 'eyedrop' : prev.boardTool === 'eyedrop' ? 'select' : prev.boardTool,+ };+ });persist();},setManualEyedropper(enabled: boolean): void {- useSubViewStore.setState({ manualEyedropper: enabled });+ useSubViewStore.setState((prev) => ({+ manualEyedropper: enabled,+ boardTool: enabled ? 'eyedrop' : prev.boardTool === 'eyedrop' ? 'pan' : prev.boardTool,+ }));},toggleShowList(): void {useSubViewStore.setState((prev) => ({ showList: !prev.showList }));persist();},++ toggleShowPalette(): void {+ useSubViewStore.setState((prev) => ({ showPalette: !prev.showPalette }));+ persist();+ },};diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.tsindex 158adef..f01909d 100644--- a/src/stores/useToolStore.ts+++ b/src/stores/useToolStore.ts@@ -29,6 +29,12 @@ import {updateGradientMeshNodes,} from '../utils/gradientEngine';import { DEFAULT_RETOUCH_SETTINGS } from '../utils/retouchEngine';+import {+ DEFAULT_TEXT_SETTINGS,+ extractPersistableTextStyle,+ loadInitialTextSettings,+ saveTextSettings,+} from '../utils/textSettings';import {saveBrushSettingsDebounced,getEffectiveBrushSettings,@@ -307,19 +313,7 @@ const createInitialToolState = (): ToolStoreState => {smartAreaScale: 1,brushSize: 24,},- textSettings: {- text: '',- fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",- fontSize: 28,- lineSpacing: 1.25,- bold: false,- italic: false,- align: 'center',- outline: true,- outlineColor: '#ffffff',- outlineWidth: 3,- color: '#000000',- },+ textSettings: loadInitialTextSettings(),frameSettings: {mode: 'create',divideMode: 'same-folder',@@ -886,9 +880,22 @@ export const toolStoreActions = {},updateTextSettings(patch: Partial<TextSettings>): void {- useToolStore.setState((prev) => ({- textSettings: { ...prev.textSettings, ...patch },- }));+ useToolStore.setState((prev) => {+ const sanitizedStyle = extractPersistableTextStyle(patch);+ const next: TextSettings = {+ ...prev.textSettings,+ ...sanitizedStyle,+ text: patch.text !== undefined ? patch.text : prev.textSettings.text,+ };+ saveTextSettings(next);+ return { textSettings: next };+ });+ },++ resetTextSettings(): void {+ const next: TextSettings = { ...DEFAULT_TEXT_SETTINGS };+ saveTextSettings(next);+ useToolStore.setState({ textSettings: next });},updateFrameSettings(patch: Partial<FrameSettings>): void {diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.tsindex d8996db..ff61353 100644--- a/src/stores/useUiStore.ts+++ b/src/stores/useUiStore.ts@@ -10,7 +10,7 @@ import {AppearanceConfig,sanitizeAppearanceConfig,} from '../types/appearance';-import { FilterType } from '../types/editor';+import { CanvasDimensions, FilterType } from '../types/editor';import { CrashedSessionInfo } from '../services/recoveryService';import { TonalCorrectionType, ProcessingBounds, TileHistogramMap } from '../utils/tonalEngine';import type { TileSnapshotEntry } from '../utils/tileEngine';@@ -18,7 +18,12 @@ import { performanceManager } from '../utils/performanceManager';import { applyInterfaceScale, clampInterfaceScale } from '../utils/interfaceScale';import { applyAppearanceToDocument } from '../utils/themeEngine';import { safeLocalStorageSetItem, setStorageQuotaNotifier } from '../utils/safeStorage';+import {+ CanvasResizeDraft,+ createInitialCanvasResizeDraft,+} from '../utils/canvasResizeCrop';import { createStore } from './createStore';+import { useDocumentStore } from './useDocumentStore';import { useUpdaterStore } from './useUpdaterStore';const PIGMENT_TO_LEGACY_ACCENT: Record<AccentPigmentId, ModernAccentColor> = {@@ -134,6 +139,8 @@ export interface UiStoreState {// Modals & Live DrawersisNewCanvasModalOpen: boolean;isResizeCanvasModalOpen: boolean;+ canvasResizeDraft: CanvasResizeDraft | null;+ isResizeInspectorCollapsed: boolean;isSettingsModalOpen: boolean;isAppearanceStudioOpen: boolean;isAboutModalOpen: boolean;@@ -204,6 +211,8 @@ const createInitialUiState = (): UiStoreState => {isNewCanvasModalOpen: false,isResizeCanvasModalOpen: false,+ canvasResizeDraft: null,+ isResizeInspectorCollapsed: false,isSettingsModalOpen: false,isAppearanceStudioOpen: false,isAboutModalOpen: false,@@ -377,8 +386,37 @@ export const uiStoreActions = {useUiStore.setState({ isNewCanvasModalOpen: open });},- setResizeCanvasModalOpen(open: boolean): void {- useUiStore.setState({ isResizeCanvasModalOpen: open });+ setResizeCanvasModalOpen(open: boolean, initialDimensions?: CanvasDimensions): void {+ if (open) {+ const dims = initialDimensions ?? useDocumentStore.getState().dimensions;+ useUiStore.setState({+ isResizeCanvasModalOpen: true,+ canvasResizeDraft: createInitialCanvasResizeDraft(dims),+ isResizeInspectorCollapsed: false,+ });+ } else {+ useUiStore.setState({+ isResizeCanvasModalOpen: false,+ canvasResizeDraft: null,+ isResizeInspectorCollapsed: false,+ });+ }+ },++ updateCanvasResizeDraft(+ updater: CanvasResizeDraft | ((prev: CanvasResizeDraft) => CanvasResizeDraft)+ ): void {+ useUiStore.setState((prev) => {+ if (typeof updater === 'function') {+ if (!prev.canvasResizeDraft) return prev;+ return { canvasResizeDraft: updater(prev.canvasResizeDraft) };+ }+ return { canvasResizeDraft: updater };+ });+ },++ setResizeInspectorCollapsed(collapsed: boolean): void {+ useUiStore.setState({ isResizeInspectorCollapsed: collapsed });},setSettingsModalOpen(open: boolean): void {diff --git a/src/types/editor.ts b/src/types/editor.tsindex c407631..5d86bb9 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -77,6 +77,7 @@ export type BrushCategory =| 'brush'| 'blend'| 'natural-paint'+ | 'texture-fx'| DecorationCategory;export type BrushRenderMode = 'stamp' | 'bristle-ribbon' | 'bristle-hybrid';@@ -186,12 +187,20 @@ export type BrushPresetId =| 'rough-pen'| 'dot-pen'| 'calligraphy'+ | 'tapered-ink-liner'+ | 'sumi-fude-brush'+ | 'silk-embroidery-ribbon'+ | 'fine-hair-wisp'// Sketch section| 'mechanical-pencil'| 'pencil-hb-2b'| 'pencil-6b-8b'| 'charcoal-pencil'| 'standard-chalk'+ | 'vine-charcoal-wash'+ | 'compressed-charcoal-block'+ | 'conte-sanguine-crayon'+ | 'col-erase-sketch-pencil'// Brush section (Painterly Coloring & Illustration)| 'oil-flat-alla-prima'| 'thick-oil-impasto'@@ -202,6 +211,16 @@ export type BrushPresetId =| 'soft-glaze-airbrush'| 'atmospheric-grain-shader'| 'fine-detail-filbert'+ | 'sculptural-hard-square'+ | 'opaque-gouache-flat'+ | 'tapered-painterly-oval'+ | 'silky-hair-locks'+ | 'dry-hair-sheen'+ | 'rough-concept-bristle'+ | 'wedge-chisel-gouache'+ | 'translucent-watercolor-wash'+ | 'pastel-blush-airbrush'+ | 'metallic-specular-glint'// Blend section (Dedicated Pure Blenders)| 'blend-velvet-soft'| 'blend-oil-bristle'@@ -209,6 +228,10 @@ export type BrushPresetId =| 'blend-rake-hair'| 'blend-canvas-scumble'| 'blend-fingertip'+ | 'blend-charcoal-stump'+ | 'blend-gouache-softener'+ | 'blend-smoke-wisps'+ | 'blend-palette-knife-smear'// Natural Paint section| 'impasto-bristle-oil'| 'wet-mixing-filbert'@@ -219,6 +242,21 @@ export type BrushPresetId =| 'granulating-watercolor'| 'oil-bristle-blender'| 'pastel-stick-canvas'+ | 'wide-hog-flat-oil'+ | 'splayed-fan-foliage'+ | 'sumi-ink-wash-natural'+ | 'matte-casein-tempera'+ // Texture & FX section+ | 'painterly-foliage-leaves'+ | 'bokeh-foreground-leaves'+ | 'skin-freckles-pores'+ | 'ethereal-smoke-mist'+ | 'craggy-rock-bone'+ | 'ember-ash-spatter'+ | 'painterly-clouds'+ | 'woven-brocade-fabric'+ | 'luminous-rim-glow'+ | 'stipple-halftone-grain'| string;export interface CspEffectorCurvePoint {@@ -700,9 +738,11 @@ export interface DocumentTab {isDirty?: boolean;dimensions: CanvasDimensions;colorMode: CanvasColorMode;+ sourcePath?: string | null;savedFileInfo?: {name: string;handle?: any;+ path?: string;extension: string;} | null;layers: LayerItem[];@@ -797,14 +837,18 @@ export interface TextSettings {fontFamily: string;fontSize: number;lineSpacing?: number; // lineHeightRatio, default 1.25 (horizontal) / 1.4 (vertical)+ letterSpacing?: number; // extra tracking in px, default 0bold: boolean;italic: boolean;+ underline?: boolean;align: 'left' | 'center' | 'right';outline: boolean;outlineColor: string;outlineWidth: number;color: string;writingMode?: 'horizontal-tb' | 'vertical-rl';+ opacity?: number; // 0.05..1, default 1+ maxWidth?: number | null; // optional word-wrap box width in canvas px}export interface TextLayerData extends TextSettings {@@ -1265,6 +1309,17 @@ export interface LayerStyles {outerGlow?: LayerStyleOuterGlow;}+export type LayerColorLabel =+ | 'none'+ | 'red'+ | 'orange'+ | 'yellow'+ | 'green'+ | 'cyan'+ | 'blue'+ | 'purple'+ | 'gray';+export type LayerType =| 'raster'| 'folder'@@ -1289,6 +1344,8 @@ export interface LayerItem {parentId: string | null; // null for root, or folder idthumbnailUrl?: string; // live layer thumbnail data URLisReference?: boolean; // Clip Studio Paint Reference Layer toggle+ /** Organizational color tag label displayed in the Layers panel (distinct from layerColor tint effect). */+ colorLabel?: LayerColorLabel;// Screentone (CSP Tone Effect)isToneLayer?: boolean; // True for dedicated screentone fill layers with flat editable density; false/undefined for regular layers whose tone adapts to image tonestoneEnabled?: boolean;@@ -1427,6 +1484,12 @@ export interface NewCanvasOptions {defaultFrequency?: number;}+export type TimelapseCaptureArea = 'artwork' | 'canvas-view' | 'app-window';+export type TimelapseCaptureResolution = '720p' | '1080p' | '2k' | '4k';+export type TimelapseExportResolution = '720p' | '1080p' | '2k' | '4k';+export type TimelapseExportAspectRatio = 'original' | '16:9' | '9:16' | '1:1' | '4:5';+export type TimelapseQualityPreset = 'standard' | 'high' | 'ultra' | 'lossless';+export interface InkTimelapseFrameMetadata {index: number;path: string;@@ -1435,6 +1498,7 @@ export interface InkTimelapseFrameMetadata {height: number;mimeType: 'image/webp' | 'image/jpeg';bytes: number;+ captureArea?: TimelapseCaptureArea;}export interface InkTimelapseFrameData {@@ -1444,15 +1508,24 @@ export interface InkTimelapseFrameData {height: number;mimeType: 'image/webp' | 'image/jpeg';bytes: Uint8Array;+ captureArea?: TimelapseCaptureArea;}export interface InkTimelapseMetadata {+ /** Stable local recording ID linking this document to external persistent time-lapse storage (not stored in .ink). */+ recordingId?: string;+ /** 'external' = stored outside .ink in app local storage; 'embedded' = legacy archive frames. */+ storageMode?: 'external' | 'embedded';enabled: boolean;frameCount: number;nextIndex?: number;+ captureArea?: TimelapseCaptureArea;+ captureResolution?: TimelapseCaptureResolution;fps?: number;- resolution?: '720p' | '1080p';- aspectRatio?: 'original' | '16:9' | '9:16' | '1:1';+ resolution?: TimelapseExportResolution;+ aspectRatio?: TimelapseExportAspectRatio;+ quality?: TimelapseQualityPreset;+ /** Legacy embedded frame descriptors (only present in older .ink archives). */frames?: InkTimelapseFrameMetadata[];}diff --git a/src/types/multiplayer.ts b/src/types/multiplayer.tsindex fad9ea3..6aff46a 100644--- a/src/types/multiplayer.ts+++ b/src/types/multiplayer.ts@@ -171,6 +171,7 @@ export type LayerClearableField =| 'alphaLocked'| 'clipped'| 'isReference'+ | 'colorLabel'| 'isToneLayer'| 'toneEnabled'| 'toneFrequency'diff --git a/src/types/settings.ts b/src/types/settings.tsindex a077b6f..83fb8b0 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -33,6 +33,10 @@ export interface ResizeCanvasOptions {dpi?: number;scaleContent?: boolean;anchor?: AnchorPosition;+ /** Optional explicit pixel offset of the old canvas origin inside the new canvas (i.e. -cropX). Overrides `anchor` when finite. */+ offsetX?: number;+ /** Optional explicit pixel offset of the old canvas origin inside the new canvas (i.e. -cropY). Overrides `anchor` when finite. */+ offsetY?: number;backgroundColor?: string;}diff --git a/src/types/workspace.ts b/src/types/workspace.tsindex 964bd2c..9699c72 100644--- a/src/types/workspace.ts+++ b/src/types/workspace.ts@@ -406,14 +406,14 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {},'sub-view': {id: 'sub-view',- title: 'Sub View',- shortTitle: 'SubView',+ title: 'References',+ shortTitle: 'Refs',defaultSide: 'right',defaultWidth: 224,minWidth: 176,- maxWidth: 400,- defaultFloatWidth: 320,- defaultFloatHeight: 340,+ maxWidth: 440,+ defaultFloatWidth: 360,+ defaultFloatHeight: 380,minFloatHeight: 180,},info: {diff --git a/src/utils/__tests__/builtinBrushes.test.ts b/src/utils/__tests__/builtinBrushes.test.tsindex f208015..dbaeaac 100644--- a/src/utils/__tests__/builtinBrushes.test.ts+++ b/src/utils/__tests__/builtinBrushes.test.ts@@ -180,13 +180,14 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P};});- it('registers all 35 built-in brushes cleanly across Pen (6), Sketch (5), Brush (9), Blend (6), and Natural Paint (9)', () => {+ it('registers all 71 built-in brushes cleanly across Pen (10), Sketch (9), Brush (19), Blend (10), Natural Paint (13), and Texture & FX (10)', () => {expect(BUILTIN_BRUSH_SECTIONS.map((s) => s.id)).toEqual(['pen','sketch','brush','blend','natural-paint',+ 'texture-fx',]);const penIds = BUILTIN_BRUSHES.filter((b) => b.category === 'pen').map((b) => b.id);@@ -194,6 +195,7 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending Pconst brushIds = BUILTIN_BRUSHES.filter((b) => b.category === 'brush').map((b) => b.id);const blendIds = BUILTIN_BRUSHES.filter((b) => b.category === 'blend').map((b) => b.id);const naturalIds = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint').map((b) => b.id);+ const textureFxIds = BUILTIN_BRUSHES.filter((b) => b.category === 'texture-fx').map((b) => b.id);expect(penIds).toEqual(['g-pen',@@ -202,6 +204,10 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P'rough-pen','dot-pen','calligraphy',+ 'tapered-ink-liner',+ 'sumi-fude-brush',+ 'silk-embroidery-ribbon',+ 'fine-hair-wisp',]);expect(sketchIds).toEqual(['mechanical-pencil',@@ -209,6 +215,10 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P'pencil-6b-8b','charcoal-pencil','standard-chalk',+ 'vine-charcoal-wash',+ 'compressed-charcoal-block',+ 'conte-sanguine-crayon',+ 'col-erase-sketch-pencil',]);expect(brushIds).toEqual(['oil-flat-alla-prima',@@ -220,6 +230,16 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P'soft-glaze-airbrush','atmospheric-grain-shader','fine-detail-filbert',+ 'sculptural-hard-square',+ 'opaque-gouache-flat',+ 'tapered-painterly-oval',+ 'silky-hair-locks',+ 'dry-hair-sheen',+ 'rough-concept-bristle',+ 'wedge-chisel-gouache',+ 'translucent-watercolor-wash',+ 'pastel-blush-airbrush',+ 'metallic-specular-glint',]);expect(blendIds).toEqual(['blend-velvet-soft',@@ -228,6 +248,10 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P'blend-rake-hair','blend-canvas-scumble','blend-fingertip',+ 'blend-charcoal-stump',+ 'blend-gouache-softener',+ 'blend-smoke-wisps',+ 'blend-palette-knife-smear',]);expect(naturalIds).toEqual(['impasto-bristle-oil',@@ -239,11 +263,28 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending P'granulating-watercolor','oil-bristle-blender','pastel-stick-canvas',+ 'wide-hog-flat-oil',+ 'splayed-fan-foliage',+ 'sumi-ink-wash-natural',+ 'matte-casein-tempera',]);- expect(BUILTIN_BRUSHES).toHaveLength(35);+ expect(textureFxIds).toEqual([+ 'painterly-foliage-leaves',+ 'bokeh-foreground-leaves',+ 'skin-freckles-pores',+ 'ethereal-smoke-mist',+ 'craggy-rock-bone',+ 'ember-ash-spatter',+ 'painterly-clouds',+ 'woven-brocade-fabric',+ 'luminous-rim-glow',+ 'stipple-halftone-grain',+ ]);+ expect(BUILTIN_BRUSHES).toHaveLength(71);+ expect(new Set(BUILTIN_BRUSHES.map((b) => b.id)).size).toBe(71);});- it('generates deterministic non-empty PNG assets for tips, sub-tips, dual tips, and paper textures across all 35 presets', () => {+ it('generates deterministic non-empty PNG assets for tips, sub-tips, dual tips, and paper textures across all 71 presets', () => {prewarmBuiltinBrushAssets();for (const def of BUILTIN_BRUSHES) {const cfg = getBuiltinBrushConfig(def.id);@@ -575,9 +616,9 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending Pexpect(fineDetail.amountOfPaint!).toBeGreaterThanOrEqual(0.9);});- it('enforces pure-smear invariants across all 6 Blend brushes (zero blank deposition, zero first-contact foreground contamination)', () => {+ it('enforces pure-smear invariants across all 10 Blend brushes (zero blank deposition, zero first-contact foreground contamination)', () => {const blendDefs = BUILTIN_BRUSHES.filter((b) => b.category === 'blend');- expect(blendDefs).toHaveLength(6);+ expect(blendDefs).toHaveLength(10);const blankCanvas = createMockCanvas(64, 64);const blankSampler = new LayerPixelSampler(blankCanvas);@@ -661,6 +702,55 @@ describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending Pexpect(getBuiltinBrushConfig('blend-fingertip')!.useBlur).toBe(false);expect(getBuiltinBrushConfig('blend-matte-chalk')!.paperTextureMode).toBe('compare');expect(getBuiltinBrushConfig('blend-canvas-scumble')!.surfaceTextureId).toBe('linen-canvas');+ expect(getBuiltinBrushConfig('blend-charcoal-stump')!.useBlur).toBe(true);+ expect(getBuiltinBrushConfig('blend-charcoal-stump')!.paperTextureMode).toBe('compare');+ expect(getBuiltinBrushConfig('blend-gouache-softener')!.surfaceTextureId).toBe('gesso-board');+ expect(getBuiltinBrushConfig('blend-smoke-wisps')!.useBlur).toBe(true);+ expect(getBuiltinBrushConfig('blend-palette-knife-smear')!.useBlur).toBe(false);+ });++ it('calibrates the 36 pro brush additions (Ribbon embroidery, Dual Brush smoke/rock/sheen, multi-tip foliage/freckles, wet-edge gouache, and Add-Glow bloom)', () => {+ // Silk Thread Multi-Line Ribbon+ const silk = getBuiltinBrushConfig('silk-embroidery-ribbon')!;+ expect(silk.isRibbon).toBe(true);+ expect(silk.subTips?.length).toBe(3);+ expect(silk.subTips?.[0].width).toBe(64);+ expect(silk.subTips?.[0].height).toBe(512);+ expect(silk.taper?.useIn).toBe(true);+ expect(silk.taper?.useOut).toBe(true);++ // Dual Brush pro additions resolve cleanly with valid secondary tips+ for (const id of ['dry-hair-sheen', 'rough-concept-bristle', 'ethereal-smoke-mist', 'craggy-rock-bone']) {+ const cfg = getBuiltinBrushConfig(id)!;+ expect(cfg.dualBrush, `${id} dualBrush`).toBe(true);+ expect(cfg.dualBrushConfig?.tipDataUrl).toMatch(/^data:image\/png;base64,/);+ expect(cfg.dualBrushConfig?.tipImage).toBeDefined();+ expect(resolveDualBrushConfig(cfg as BrushSettings)).not.toBeNull();+ }++ // Painterly Gouache Flat & Soft Watercolor Wash feature authentic wet-edge pooling+ expect(getBuiltinBrushConfig('opaque-gouache-flat')!.wetEdge!).toBeGreaterThan(0.15);+ expect(getBuiltinBrushConfig('translucent-watercolor-wash')!.wetEdge!).toBeGreaterThan(0.35);++ // Multi-tip organic scatter & color dynamics for foliage, freckles, clouds, embers, stipple+ const leaves = getBuiltinBrushConfig('painterly-foliage-leaves')!;+ expect(leaves.subTips?.length).toBe(4);+ expect(leaves.dynamics?.colorJitterEnabled).toBe(true);+ expect(leaves.dynamics?.scatter!).toBeGreaterThan(0.5);++ const freckles = getBuiltinBrushConfig('skin-freckles-pores')!;+ expect(freckles.subTips?.length).toBe(4);+ expect(freckles.dynamics?.scatter!).toBeGreaterThan(0.4);++ // Optical Luminous Magic & Rim Glow uses add-glow blend mode and renders cleanly on transparent & opaque surfaces+ const glow = getBuiltinBrushConfig('luminous-rim-glow')!;+ expect(glow.brushCombineMode).toBe('add-glow');+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];+ compositeBrushPixelInto(0, 0, 0, 0, 200, 120, 255, 160, 'source-over', 'add-glow', pxOut);+ expect(pxOut[3]).toBe(160);+ compositeBrushPixelInto(40, 30, 80, 255, 180, 100, 220, 128, 'source-over', 'add-glow', pxOut);+ expect(pxOut[0]).toBeGreaterThan(40);+ expect(pxOut[2]).toBeGreaterThan(80);});it('produces measurably smoother transitions across a hard color seam in SpatialTipMixer when useBlur is enabled', () => {diff --git a/src/utils/__tests__/canvasResizeCrop.test.tsx b/src/utils/__tests__/canvasResizeCrop.test.tsxnew file mode 100644index 0000000..a76323a--- /dev/null+++ b/src/utils/__tests__/canvasResizeCrop.test.tsx@@ -0,0 +1,1208 @@+import React, { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ CanvasResizeDraft,+ applyAnchorToDraft,+ applyCropXToDraft,+ applyCropYToDraft,+ applyFitBoundsToDraft,+ applyHeightToDraft,+ applyLockRatioToggleToDraft,+ applyRatioPresetToDraft,+ applyResetCropToDraft,+ applyScaleContentToggleToDraft,+ applySwapDimensionsToDraft,+ applyWidthToDraft,+ computeCropOriginForAnchor,+ createCropRectFromDrag,+ createInitialCanvasResizeDraft,+ cycleCropGridMode,+ draftToResizeCanvasOptions,+ getRotatedResizeCursor,+ isCropModified,+ moveCropRect,+ nudgeCropDraft,+ resizeCropRectByHandle,+} from '../canvasResizeCrop';+import { sanitizeCanvasResize } from '../collabSyncUtils';+import { SparseTileGrid } from '../tileEngine';+import { useLayerResize } from '../../hooks/layerManager/useLayerResize';+import { CanvasDimensions, LayerItem } from '../../types/editor';+import { ResizeCanvasOptions } from '../../types/settings';+import { uiStoreActions, useUiStore } from '../../stores';+import { ResizeCanvasModal } from '../../components/ResizeCanvasModal';+import {+ CanvasResizeMarqueeBackdrop,+ CanvasResizeOverlay,+} from '../../components/CanvasResizeOverlay';++// ---------------------------------------------------------------------------+// Minimal DOM shim matching the repo's node-environment React test setup+// ---------------------------------------------------------------------------++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 MiniStyle {+ private map = new Map<string, string>();+ [key: string]: unknown;+ setProperty(k: string, v: string) {+ this.map.set(k, String(v));+ this[k] = String(v);+ }+ getPropertyValue(k: string): string {+ return this.map.get(k) ?? (typeof this[k] === 'string' ? (this[k] as string) : '');+ }+ removeProperty(k: string) {+ this.map.delete(k);+ delete this[k];+ }+}++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 = new MiniStyle();+ className = '';+ disabled = false;+ type = '';+ clientWidth = 1000;+ clientHeight = 800;+ attrs = new Map<string, string>();+ private _value = '';++ constructor(+ tag: string,+ public ownerDocument: MiniDoc,+ namespaceURI = 'http://www.w3.org/1999/xhtml'+ ) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ this.namespaceURI = namespaceURI;+ }++ get value(): string {+ return this._value;+ }+ set value(v: string) {+ this._value = String(v);+ }+ 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() {}+ hasPointerCapture() {+ return false;+ }+ releasePointerCapture() {}+ getContext() {+ return null;+ }++ focus() {+ this.ownerDocument.activeElement = this;+ this.dispatchEvent(new Event('focus', { bubbles: false }));+ this.dispatchEvent(new Event('focusin', { bubbles: true }));+ }++ blur() {+ if (this.ownerDocument.activeElement === this) {+ this.ownerDocument.activeElement = this.ownerDocument.body;+ }+ this.dispatchEvent(new Event('blur', { bubbles: false }));+ this.dispatchEvent(new Event('focusout', { bubbles: true }));+ }++ matchesSimpleSelector(sel: string): boolean {+ const trimmed = sel.trim();+ if (!trimmed) return false;+ if (trimmed.startsWith('[')) {+ const m = trimmed.match(/^\[([^=\]]+)(?:=["']?([^"'\]]*)["']?)?\]$/);+ if (!m) return false;+ const attrVal = this.getAttribute(m[1]);+ if (m[2] === undefined) return attrVal !== null;+ return attrVal === m[2];+ }+ return this.tagName === trimmed.toUpperCase();+ }++ closest(selectorList: string): MiniEl | null {+ const selectors = selectorList.split(',').map((s) => s.trim());+ let cur: MiniEl | null = this;+ while (cur) {+ if (selectors.some((sel) => cur!.matchesSimpleSelector(sel))) {+ return cur;+ }+ cur = cur.parentNode;+ }+ 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));+ if (k === 'type') this.type = String(v);+ if (k === 'value') this._value = String(v);+ if (k === 'disabled') this.disabled = true;+ }++ getAttribute(k: string): string | null {+ return this.attrs.get(k) ?? null;+ }++ removeAttribute(k: string) {+ this.attrs.delete(k);+ if (k === 'disabled') this.disabled = false;+ }++ 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;+ }++ override dispatchEvent(event: Event): boolean {+ if (!event.target) {+ Object.defineProperty(event, 'target', { value: this, configurable: true });+ }+ let cur: MiniEl | null = this;+ while (cur) {+ Object.defineProperty(event, 'currentTarget', { value: cur, configurable: true });+ EventTarget.prototype.dispatchEvent.call(cur, event);+ if (!event.bubbles || event.cancelBubble) break;+ cur = cur.parentNode;+ }+ return !event.defaultPrevented;+ }++ findAll(pred: (el: MiniEl) => boolean): MiniEl[] {+ const out: MiniEl[] = [];+ const walk = (node: MiniEl | MiniText | MiniComment) => {+ if (node instanceof MiniEl) {+ if (pred(node)) out.push(node);+ for (const child of node.childNodes) walk(child);+ }+ };+ walk(this);+ return out;+ }++ findByTestId(id: string): MiniEl | null {+ return this.findAll((el) => el.getAttribute('data-testid') === id)[0] ?? 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 docTarget = new EventTarget();+ const winTarget = new EventTarget();++ const doc = {+ 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) {+ return new MiniEl(tag, doc);+ },+ createElementNS(ns: string, tag: string) {+ return new MiniEl(tag, doc, ns);+ },+ createTextNode(text: string) {+ return new MiniText(text, doc);+ },+ createComment(text: string) {+ return new MiniComment(text, doc);+ },+ addEventListener: docTarget.addEventListener.bind(docTarget),+ removeEventListener: docTarget.removeEventListener.bind(docTarget),+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),+ } as unknown as MiniDoc;++ doc.documentElement = new MiniEl('html', doc);+ doc.body = new MiniEl('body', doc);+ doc.documentElement.appendChild(doc.body);+ doc.activeElement = doc.body;++ class MockIFrame extends MiniEl {}+ const win: Record<string, unknown> = {+ document: doc,+ Node: MiniEl,+ Element: MiniEl,+ HTMLElement: MiniEl,+ HTMLInputElement: MiniEl,+ HTMLIFrameElement: MockIFrame,+ SVGElement: MiniEl,+ Event,+ CustomEvent,+ KeyboardEvent: Event,+ MouseEvent: Event,+ PointerEvent: Event,+ getSelection: () => ({+ anchorNode: null,+ anchorOffset: 0,+ focusNode: null,+ focusOffset: 0,+ }),+ addEventListener: winTarget.addEventListener.bind(winTarget),+ removeEventListener: winTarget.removeEventListener.bind(winTarget),+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),+ getComputedStyle: () => ({ zoom: '1', getPropertyValue: () => '' }),+ innerWidth: 1280,+ innerHeight: 800,+ requestAnimationFrame: (cb: FrameRequestCallback) => {+ cb(0);+ return 1;+ },+ cancelAnimationFrame: () => {},+ };+ doc.defaultView = win;++ const prevWindow = (globalThis as Record<string, unknown>).window;+ const prevDocument = (globalThis as Record<string, unknown>).document;+ const prevHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const prevHTMLInputElement = (globalThis as Record<string, unknown>).HTMLInputElement;+ const prevHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const prevNode = (globalThis as Record<string, unknown>).Node;+ const prevElement = (globalThis as Record<string, unknown>).Element;+ const prevDOMRect = (globalThis as Record<string, unknown>).DOMRect;+ const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ (globalThis as Record<string, unknown>).window = win;+ (globalThis as Record<string, unknown>).document = doc;+ (globalThis as Record<string, unknown>).HTMLElement = MiniEl;+ (globalThis as Record<string, unknown>).HTMLInputElement = MiniEl;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = MockIFrame;+ (globalThis as Record<string, unknown>).Node = MiniEl;+ (globalThis as Record<string, unknown>).Element = MiniEl;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ if (typeof DOMRect === 'undefined') {+ (globalThis as Record<string, unknown>).DOMRect = class {+ constructor(+ public x = 0,+ public y = 0,+ public width = 0,+ public height = 0+ ) {}+ get left() {+ return this.x;+ }+ get top() {+ return this.y;+ }+ get right() {+ return this.x + this.width;+ }+ get bottom() {+ return this.y + this.height;+ }+ };+ }++ return {+ doc,+ win,+ cleanup() {+ (globalThis as Record<string, unknown>).window = prevWindow;+ (globalThis as Record<string, unknown>).document = prevDocument;+ (globalThis as Record<string, unknown>).HTMLElement = prevHTMLElement;+ (globalThis as Record<string, unknown>).HTMLInputElement = prevHTMLInputElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = prevHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Node = prevNode;+ (globalThis as Record<string, unknown>).Element = prevElement;+ (globalThis as Record<string, unknown>).DOMRect = prevDOMRect;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;+ },+ };+}++function makePointerEvent(+ type: string,+ props: {+ clientX?: number;+ clientY?: number;+ button?: number;+ shiftKey?: boolean;+ altKey?: boolean;+ ctrlKey?: boolean;+ metaKey?: boolean;+ pointerType?: string;+ pointerId?: number;+ } = {}+): Event {+ const ev = new Event(type, { bubbles: true, cancelable: true });+ Object.assign(ev, {+ clientX: props.clientX ?? 0,+ clientY: props.clientY ?? 0,+ button: props.button ?? 0,+ shiftKey: props.shiftKey ?? false,+ altKey: props.altKey ?? false,+ ctrlKey: props.ctrlKey ?? false,+ metaKey: props.metaKey ?? false,+ pointerType: props.pointerType ?? 'mouse',+ pointerId: props.pointerId ?? 1,+ });+ return ev;+}++function makeKeyEvent(+ type: string,+ props: {+ key: string;+ shiftKey?: boolean;+ ctrlKey?: boolean;+ metaKey?: boolean;+ altKey?: boolean;+ }+): Event {+ const ev = new Event(type, { bubbles: true, cancelable: true });+ Object.assign(ev, {+ key: props.key,+ shiftKey: props.shiftKey ?? false,+ ctrlKey: props.ctrlKey ?? false,+ metaKey: props.metaKey ?? false,+ altKey: props.altKey ?? false,+ });+ return ev;+}++// ---------------------------------------------------------------------------+// 1. Pure Crop Geometry & Draft State Tests+// ---------------------------------------------------------------------------++describe('canvasResizeCrop geometry & draft engine', () => {+ it('computes exact anchor crop origins matching offsetX = -cropX, offsetY = -cropY', () => {+ expect(computeCropOriginForAnchor(1000, 800, 600, 400, 'top-left')).toEqual({+ cropX: 0,+ cropY: 0,+ });+ expect(computeCropOriginForAnchor(1000, 800, 600, 400, 'center')).toEqual({+ cropX: 200,+ cropY: 200,+ });+ expect(computeCropOriginForAnchor(1000, 800, 600, 400, 'bottom-right')).toEqual({+ cropX: 400,+ cropY: 400,+ });+ // Expansion produces negative cropX/cropY so offsetX/offsetY are positive+ expect(computeCropOriginForAnchor(1000, 800, 1400, 1000, 'center')).toEqual({+ cropX: -200,+ cropY: -100,+ });+ expect(computeCropOriginForAnchor(1000, 800, 1400, 1000, 'bottom-right')).toEqual({+ cropX: -400,+ cropY: -200,+ });+ });++ it('resizes all 8 handles freely with pinned opposite edges and supports outward expansion', () => {+ const start = { x: 100, y: 100, width: 400, height: 300 };++ expect(resizeCropRectByHandle(start, 'e', 50, 99).rect).toEqual({+ x: 100,+ y: 100,+ width: 450,+ height: 300,+ });+ expect(resizeCropRectByHandle(start, 'w', -150, 0).rect).toEqual({+ x: -50,+ y: 100,+ width: 550,+ height: 300,+ });+ expect(resizeCropRectByHandle(start, 'n', 0, 80).rect).toEqual({+ x: 100,+ y: 180,+ width: 400,+ height: 220,+ });+ expect(resizeCropRectByHandle(start, 's', 0, -50).rect).toEqual({+ x: 100,+ y: 100,+ width: 400,+ height: 250,+ });+ expect(resizeCropRectByHandle(start, 'nw', 40, 30).rect).toEqual({+ x: 140,+ y: 130,+ width: 360,+ height: 270,+ });+ expect(resizeCropRectByHandle(start, 'ne', 60, -20).rect).toEqual({+ x: 100,+ y: 80,+ width: 460,+ height: 320,+ });+ expect(resizeCropRectByHandle(start, 'sw', -25, 75).rect).toEqual({+ x: 75,+ y: 100,+ width: 425,+ height: 375,+ });+ expect(resizeCropRectByHandle(start, 'se', -100, -50).rect).toEqual({+ x: 100,+ y: 100,+ width: 300,+ height: 250,+ });+ });++ it('maintains aspect ratio on corners and edges when lockAspect is enabled', () => {+ const start = { x: 0, y: 0, width: 800, height: 400 }; // 2:1+ const se = resizeCropRectByHandle(start, 'se', -200, -100, {+ lockAspect: true,+ aspectRatio: 2,+ }).rect;+ expect(se.width).toBe(600);+ expect(se.height).toBe(300);+ expect(se.x).toBe(0);+ expect(se.y).toBe(0);++ // Dragging east edge with locked 2:1 aspect scales height symmetrically around vertical center+ const east = resizeCropRectByHandle(start, 'e', -200, 0, {+ lockAspect: true,+ aspectRatio: 2,+ }).rect;+ expect(east.width).toBe(600);+ expect(east.height).toBe(300);+ expect(east.x).toBe(0);+ expect(east.y).toBe(50);++ // Dragging NW corner with locked aspect pins SE corner at (800, 400)+ const nw = resizeCropRectByHandle(start, 'nw', 200, 100, {+ lockAspect: true,+ aspectRatio: 2,+ }).rect;+ expect(nw.x + nw.width).toBe(800);+ expect(nw.y + nw.height).toBe(400);+ expect(nw.width).toBe(600);+ expect(nw.height).toBe(300);+ });++ it('supports Alt symmetric from-center resizing and magnetic edge snapping', () => {+ const start = { x: 100, y: 100, width: 200, height: 200 };+ const centered = resizeCropRectByHandle(start, 'se', 50, 25, {+ fromCenter: true,+ }).rect;+ expect(centered).toEqual({ x: 50, y: 75, width: 300, height: 250 });++ // Magnetic snap to original edge x=0 when within threshold+ const snapped = resizeCropRectByHandle(start, 'w', -97, 0, {+ snapTargets: { x: [0, 500, 1000], y: [0, 400, 800], threshold: 6 },+ });+ expect(snapped.rect.x).toBe(0);+ expect(snapped.rect.width).toBe(300);+ expect(snapped.snapGuides.x).toBe(0);+ });++ it('moves crop rectangle with optional Shift axis locking and center/edge snapping', () => {+ const start = { x: 100, y: 100, width: 300, height: 200 };+ const axisLocked = moveCropRect(start, 80, 15, { constrainAxis: true }).rect;+ expect(axisLocked).toEqual({ x: 180, y: 100, width: 300, height: 200 });++ const snapped = moveCropRect(start, -96, 10, {+ snapTargets: { x: [0, 500, 1000], y: [0, 400, 800], threshold: 6 },+ });+ expect(snapped.rect.x).toBe(0);+ expect(snapped.snapGuides.x).toBe(0);+ });++ it('draws a brand-new crop marquee in any direction with Shift aspect lock & Alt from-center', () => {+ const nwDrag = createCropRectFromDrag({ x: 400, y: 300 }, { x: 150, y: 100 }).rect;+ expect(nwDrag).toEqual({ x: 150, y: 100, width: 250, height: 200 });++ const squareDrag = createCropRectFromDrag(+ { x: 100, y: 100 },+ { x: 260, y: 180 },+ { lockAspect: true, aspectRatio: 1 }+ ).rect;+ expect(squareDrag).toEqual({ x: 100, y: 100, width: 160, height: 160 });++ const centerDrag = createCropRectFromDrag(+ { x: 200, y: 200 },+ { x: 250, y: 230 },+ { fromCenter: true }+ ).rect;+ expect(centerDrag).toEqual({ x: 150, y: 170, width: 100, height: 60 });+ });++ it('computes accurate rotated and flipped resize cursors', () => {+ expect(getRotatedResizeCursor('move', 45, true, false)).toBe('move');+ expect(getRotatedResizeCursor('e', 0, false, false)).toBe('ew-resize');+ expect(getRotatedResizeCursor('e', 90, false, false)).toBe('ns-resize');+ expect(getRotatedResizeCursor('se', 0, false, false)).toBe('nwse-resize');+ expect(getRotatedResizeCursor('se', 0, true, false)).toBe('nesw-resize');+ expect(getRotatedResizeCursor('n', 45, false, false)).toBe('nesw-resize');+ });++ it('synchronizes draft helpers (width, height, anchor, ratio preset, swap, reset, selection, nudge)', () => {+ let draft: CanvasResizeDraft = createInitialCanvasResizeDraft({+ width: 1000,+ height: 800,+ dpi: 300,+ });+ expect(isCropModified(draft)).toBe(false);+ expect(draft.lockRatio).toBe(false);++ draft = applyWidthToDraft(draft, 600);+ expect(draft.width).toBe(600);+ expect(draft.cropX).toBe(200); // center anchor+ expect(isCropModified(draft)).toBe(true);++ draft = applyHeightToDraft(draft, 500);+ expect(draft.height).toBe(500);+ expect(draft.cropY).toBe(150); // center anchor+ draft = applyHeightToDraft(draft, 800);+ expect(draft.cropY).toBe(0);++ draft = applyAnchorToDraft(draft, 'top-left');+ expect(draft.cropX).toBe(0);+ expect(draft.cropY).toBe(0);++ draft = applyCropXToDraft(draft, 125);+ draft = applyCropYToDraft(draft, 75);+ expect(draft.anchor).toBeNull();++ const opts = draftToResizeCanvasOptions(draft);+ expect(opts).toEqual({+ width: 600,+ height: 800,+ dpi: 300,+ scaleContent: false,+ anchor: 'center',+ offsetX: -125,+ offsetY: -75,+ });++ draft = applyRatioPresetToDraft(draft, 16, 9);+ expect(draft.lockRatio).toBe(true);+ expect(draft.height).toBe(Math.round((600 * 9) / 16));++ const prevW = draft.width;+ const prevH = draft.height;+ draft = applySwapDimensionsToDraft(draft);+ expect(draft.width).toBe(prevH);+ expect(draft.height).toBe(prevW);++ draft = nudgeCropDraft(draft, 10, -5);+ expect(draft.anchor).toBeNull();++ draft = applyFitBoundsToDraft(draft, { x: 50, y: 60, width: 320, height: 240 });+ expect({ x: draft.cropX, y: draft.cropY, w: draft.width, h: draft.height }).toEqual({+ x: 50,+ y: 60,+ w: 320,+ h: 240,+ });++ draft = applyScaleContentToggleToDraft(draft, true, true);+ expect(draft.scaleContent).toBe(true);+ expect(draft.lockRatio).toBe(true);+ expect(draftToResizeCanvasOptions(draft).offsetX).toBeUndefined();++ draft = applyLockRatioToggleToDraft(draft, false);+ expect(draft.lockRatio).toBe(false);++ draft = applyResetCropToDraft({ ...draft, scaleContent: false });+ expect(isCropModified(draft)).toBe(false);+ expect(cycleCropGridMode('thirds')).toBe('golden');+ expect(cycleCropGridMode('golden')).toBe('none');+ expect(cycleCropGridMode('none')).toBe('thirds');+ });+});++// ---------------------------------------------------------------------------+// 2. Layer Resize Engine & Collab Sync Tests+// ---------------------------------------------------------------------------++function readGridPixel(grid: SparseTileGrid, layerId: string, x: number, y: number): number[] {+ const tile = grid.getTile(layerId, x >> 8, y >> 8, 0);+ if (!tile) return [0, 0, 0, 0];+ const rgba = grid.getTileAsRGBA(tile);+ const off = ((y & 255) * 256 + (x & 255)) << 2;+ return [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]];+}++describe('useLayerResize custom crop offsets & non-raster layer transform', () => {+ it('crops raster tiles and shifts comic frames, vectors, text, and balloons by exact manual offset', () => {+ const dom = installMiniDom();+ try {+ const grid = new SparseTileGrid();+ const origDims: CanvasDimensions = { width: 400, height: 300, dpi: 300 };++ // Paint a bright red pixel at (150, 100) on layer-1+ grid.setLayerFormat('layer-1', 'color-32bit');+ grid.markLayerIngested('layer-1');+ grid.writeImageData(+ 'layer-1',+ { data: new Uint8ClampedArray([255, 10, 20, 255]), width: 1, height: 1 },+ 150,+ 100,+ 'color-32bit',+ true+ );+ grid.fillLayerSolidColor('layer-bg', 400, 300, '#ffffff', 'color-32bit');++ let layersState: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Art',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ {+ id: 'layer-vec',+ name: 'Ink Vector',+ type: 'vector',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ vectorStrokes: [+ {+ id: 'vs-1',+ layerId: 'layer-vec',+ tool: 'pen',+ knots: [+ {+ x: 150,+ y: 100,+ pressure: 1,+ width: 4,+ timestamp: 0,+ handleIn: { x: 140, y: 90 },+ handleOut: { x: 160, y: 110 },+ },+ ],+ color: '#000',+ baseWidth: 4,+ opacity: 1,+ bounds: { minX: 140, minY: 90, maxX: 160, maxY: 110 },+ },+ ],+ },+ {+ id: 'layer-frame',+ name: 'Panel',+ type: 'frame-folder',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ comicFrames: [+ {+ id: 'cf-1',+ layerId: 'layer-frame',+ polygon: [+ { x: 120, y: 80 },+ { x: 320, y: 80 },+ { x: 320, y: 230 },+ { x: 120, y: 230 },+ ],+ borderWidth: 3,+ gutterVertical: 10,+ gutterHorizontal: 10,+ clipChildren: true,+ },+ ],+ },+ {+ id: 'layer-text',+ name: 'Dialogue',+ type: 'text',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ textData: {+ x: 180,+ y: 120,+ text: 'Hello',+ fontFamily: 'sans-serif',+ fontSize: 24,+ bold: false,+ italic: false,+ align: 'left',+ outline: false,+ outlineColor: '#fff',+ outlineWidth: 0,+ color: '#000',+ },+ },+ {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];++ let currentDims: CanvasDimensions = origDims;+ let resizeFn!: (dims: CanvasDimensions, opts: ResizeCanvasOptions) => void;+ const Harness: React.FC = () => {+ const api = useLayerResize({+ dimensions: currentDims,+ dimensionsRef: { current: currentDims },+ activeTileGridRef: { current: grid },+ layers: layersState,+ layersRef: { current: layersState },+ activeLayerId: 'layer-1',+ activeLayerIdRef: { current: 'layer-1' },+ selectedLayerIds: ['layer-1'],+ setLayers: (updater: React.SetStateAction<LayerItem[]>) => {+ layersState = typeof updater === 'function' ? updater(layersState) : updater;+ },+ setActiveLayerId: vi.fn(),+ setSelectedLayerIds: vi.fn(),+ setSoloLayerId: vi.fn(),+ } as unknown as Parameters<typeof useLayerResize>[0]);+ resizeFn = api.resizeCanvas;+ return null;+ };++ const mount = dom.doc.createElement('div');+ dom.doc.body.appendChild(mount);+ const root = createRoot(mount as unknown as HTMLElement);+ act(() => {+ root.render(<Harness />);+ });++ // Crop to rect x=120, y=80, width=200, height=150 => offsetX=-120, offsetY=-80+ act(() => {+ resizeFn(+ { width: 200, height: 150, dpi: 300 },+ { width: 200, height: 150, scaleContent: false, offsetX: -120, offsetY: -80 }+ );+ });++ // Pixel originally at (150, 100) must now be at (30, 20)+ expect(readGridPixel(grid, 'layer-1', 30, 20)).toEqual([255, 10, 20, 255]);+ // Old location (150, 100) must be transparent+ expect(readGridPixel(grid, 'layer-1', 150, 100)[3]).toBe(0);++ // Vector stroke + handles shifted by (-120, -80)+ const vecLayer = layersState.find((l) => l.id === 'layer-vec')!;+ expect(vecLayer.vectorStrokes![0].knots[0].x).toBe(30);+ expect(vecLayer.vectorStrokes![0].knots[0].y).toBe(20);+ expect(vecLayer.vectorStrokes![0].knots[0].handleIn).toEqual({ x: 20, y: 10 });+ expect(vecLayer.vectorStrokes![0].bounds).toEqual({+ minX: 20,+ minY: 10,+ maxX: 40,+ maxY: 30,+ });++ // Comic frame shifted to (0,0)-(200,150)+ const frameLayer = layersState.find((l) => l.id === 'layer-frame')!;+ expect(frameLayer.comicFrames![0].polygon[0]).toEqual({ x: 0, y: 0 });+ expect(frameLayer.comicFrames![0].polygon[2]).toEqual({ x: 200, y: 150 });++ // Text layer shifted by (-120, -80)+ const textLayer = layersState.find((l) => l.id === 'layer-text')!;+ expect(textLayer.textData!.x).toBe(60);+ expect(textLayer.textData!.y).toBe(40);++ // Now expand canvas outward by 60px left and 40px top (cropX=-60, cropY=-40 => offsetX=60, offsetY=40)+ currentDims = { width: 200, height: 150, dpi: 300 };+ act(() => {+ root.render(<Harness />);+ });+ act(() => {+ resizeFn(+ { width: 320, height: 240, dpi: 300 },+ { width: 320, height: 240, scaleContent: false, offsetX: 60, offsetY: 40 }+ );+ });+ // Previously at (30, 20), now shifted by (+60, +40) to (90, 60)+ expect(readGridPixel(grid, 'layer-1', 90, 60)).toEqual([255, 10, 20, 255]);+ // Newly expanded background margin at (10, 10) is solid white+ expect(readGridPixel(grid, 'layer-bg', 10, 10)).toEqual([255, 255, 255, 255]);++ act(() => {+ root.unmount();+ });+ } finally {+ dom.cleanup();+ }+ });++ it('preserves and clamps custom offsetX / offsetY in sanitizeCanvasResize for collab sync', () => {+ const valid = sanitizeCanvasResize({+ dimensions: { width: 800, height: 600, dpi: 300 },+ options: {+ width: 800,+ height: 600,+ scaleContent: false,+ anchor: 'center',+ offsetX: -140.4,+ offsetY: 85.6,+ },+ });+ expect(valid).not.toBeNull();+ expect(valid!.options.offsetX).toBe(-140);+ expect(valid!.options.offsetY).toBe(86);++ const legacy = sanitizeCanvasResize({+ dimensions: { width: 800, height: 600 },+ options: { width: 800, height: 600, anchor: 'top-left' },+ });+ expect(legacy!.options.offsetX).toBeUndefined();+ expect(legacy!.options.offsetY).toBeUndefined();+ });+});++// ---------------------------------------------------------------------------+// 3. Interactive Component Integration: ResizeCanvasModal <-> CanvasResizeOverlay+// ---------------------------------------------------------------------------++describe('ResizeCanvasModal & CanvasResizeOverlay interactive crop workflow', () => {+ let dom: ReturnType<typeof installMiniDom>;+ let root: Root | null = null;+ let container: MiniEl;++ beforeEach(() => {+ dom = installMiniDom();+ container = dom.doc.createElement('div');+ dom.doc.body.appendChild(container);+ uiStoreActions.setResizeCanvasModalOpen(false);+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root!.unmount();+ });+ root = null;+ }+ uiStoreActions.setResizeCanvasModalOpen(false);+ dom.cleanup();+ });++ it('syncs on-canvas handle drags, move drags, marquee redraws, keyboard nudges, and applies exact crop options', () => {+ const dims: CanvasDimensions = { width: 1000, height: 800, dpi: 300 };+ const onResize = vi.fn();+ const viewportEl = dom.doc.createElement('div');+ viewportEl.clientWidth = 1000;+ viewportEl.clientHeight = 800;+ const viewportRef = { current: viewportEl as unknown as HTMLDivElement };++ uiStoreActions.setResizeCanvasModalOpen(true, dims);++ const Harness: React.FC = () => {+ const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);+ return (+ <div>+ <CanvasResizeMarqueeBackdrop+ dimensions={dims}+ viewportRef={viewportRef}+ pan={{ x: 500, y: 400 }}+ zoom={1}+ rotation={0}+ />+ <CanvasResizeOverlay+ dimensions={dims}+ viewportRef={viewportRef}+ pan={{ x: 500, y: 400 }}+ zoom={1}+ rotation={0}+ onApply={onResize}+ />+ <ResizeCanvasModal+ isOpen={isOpen}+ onClose={() => uiStoreActions.setResizeCanvasModalOpen(false)}+ currentDimensions={dims}+ onResize={onResize}+ selectionBounds={{ x: 100, y: 50, width: 300, height: 250 }}+ />+ </div>+ );+ };++ root = createRoot(container as unknown as HTMLElement);+ act(() => {+ root!.render(<Harness />);+ });++ // Non-blocking dialog has data-allow-canvas-nav="true" and crop overlay is rendered+ const dialog = container.findAll((el) => el.getAttribute('role') === 'dialog')[0];+ expect(dialog).toBeTruthy();+ expect(dialog.getAttribute('data-allow-canvas-nav')).toBe('true');+ expect(container.findByTestId('canvas-resize-crop-overlay')).toBeTruthy();+ expect(dom.doc.body.findByTestId('canvas-crop-action-bar')).toBeTruthy();++ // 1. Drag SE corner handle inward by (-200, -150) -> 800 x 650+ const seHandle = container.findByTestId('canvas-crop-handle-se')!;+ expect(seHandle).toBeTruthy();+ act(() => {+ seHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 1000, clientY: 800 }));+ (dom.win as unknown as EventTarget).dispatchEvent(+ makePointerEvent('pointermove', { clientX: 800, clientY: 650, ctrlKey: true })+ );+ (dom.win as unknown as EventTarget).dispatchEvent(makePointerEvent('pointerup'));+ });++ expect(useUiStore.getState().canvasResizeDraft?.width).toBe(800);+ expect(useUiStore.getState().canvasResizeDraft?.height).toBe(650);+ expect(container.findByTestId('canvas-crop-dimension-badge')?.textContent).toContain(+ '800 × 650 px'+ );++ // 2. Drag NW corner handle outward by (-50, -40) -> expands canvas to (-50, -40, 850, 690)+ const nwHandle = container.findByTestId('canvas-crop-handle-nw')!;+ act(() => {+ nwHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 0, clientY: 0 }));+ (dom.win as unknown as EventTarget).dispatchEvent(+ makePointerEvent('pointermove', { clientX: -50, clientY: -40, ctrlKey: true })+ );+ (dom.win as unknown as EventTarget).dispatchEvent(makePointerEvent('pointerup'));+ });++ expect(useUiStore.getState().canvasResizeDraft?.cropX).toBe(-50);+ expect(useUiStore.getState().canvasResizeDraft?.cropY).toBe(-40);+ expect(useUiStore.getState().canvasResizeDraft?.width).toBe(850);+ expect(useUiStore.getState().canvasResizeDraft?.height).toBe(690);+ // Expansion preview checkerboard path appears when extending past original bounds+ expect(container.findByTestId('canvas-crop-expansion-area')).toBeTruthy();++ // 3. Drag interior move area by (+120, +90) -> cropX=70, cropY=50+ const moveArea = container.findByTestId('canvas-crop-move-area')!;+ act(() => {+ moveArea.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 200 }));+ (dom.win as unknown as EventTarget).dispatchEvent(+ makePointerEvent('pointermove', { clientX: 320, clientY: 290, ctrlKey: true })+ );+ (dom.win as unknown as EventTarget).dispatchEvent(makePointerEvent('pointerup'));+ });++ expect(useUiStore.getState().canvasResizeDraft?.cropX).toBe(70);+ expect(useUiStore.getState().canvasResizeDraft?.cropY).toBe(50);++ // 4. Arrow key nudge (Shift+ArrowRight = +10px, ArrowDown = +1px)+ act(() => {+ (dom.win as unknown as EventTarget).dispatchEvent(+ makeKeyEvent('keydown', { key: 'ArrowRight', shiftKey: true })+ );+ (dom.win as unknown as EventTarget).dispatchEvent(+ makeKeyEvent('keydown', { key: 'ArrowDown' })+ );+ });+ expect(useUiStore.getState().canvasResizeDraft?.cropX).toBe(80);+ expect(useUiStore.getState().canvasResizeDraft?.cropY).toBe(51);++ // 5. Drag on outside marquee backdrop to draw a brand-new crop box (150, 120) -> (550, 420)+ const backdrop = container.findByTestId('canvas-crop-marquee-backdrop')!;+ act(() => {+ backdrop.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 120 }));+ (dom.win as unknown as EventTarget).dispatchEvent(+ makePointerEvent('pointermove', { clientX: 550, clientY: 420, ctrlKey: true })+ );+ (dom.win as unknown as EventTarget).dispatchEvent(makePointerEvent('pointerup'));+ });+ expect(useUiStore.getState().canvasResizeDraft?.cropX).toBe(150);+ expect(useUiStore.getState().canvasResizeDraft?.cropY).toBe(120);+ expect(useUiStore.getState().canvasResizeDraft?.width).toBe(400);+ expect(useUiStore.getState().canvasResizeDraft?.height).toBe(300);++ // 6. Collapse inspector panel -> modal hides while crop overlay stays interactive!+ act(() => {+ uiStoreActions.setResizeInspectorCollapsed(true);+ });+ expect(container.findAll((el) => el.getAttribute('role') === 'dialog').length).toBe(0);+ expect(container.findByTestId('canvas-resize-crop-overlay')).toBeTruthy();++ // 7. Double-click inside crop box commits with exact manual offset (-150, -120) and closes!+ const moveAreaAfterCollapse = container.findByTestId('canvas-crop-move-area')!;+ act(() => {+ moveAreaAfterCollapse.dispatchEvent(new Event('dblclick', { bubbles: true }));+ });+ expect(onResize).toHaveBeenCalledTimes(1);+ expect(onResize).toHaveBeenCalledWith({+ width: 400,+ height: 300,+ dpi: 300,+ scaleContent: false,+ anchor: 'center',+ offsetX: -150,+ offsetY: -120,+ });+ expect(useUiStore.getState().isResizeCanvasModalOpen).toBe(false);+ expect(useUiStore.getState().canvasResizeDraft).toBeNull();+ });++ it('hides crop handles in Scale Content mode and supports Crop to Selection and Escape cancel', () => {+ const dims: CanvasDimensions = { width: 1000, height: 800, dpi: 300 };+ const onResize = vi.fn();+ const viewportEl = dom.doc.createElement('div');+ const viewportRef = { current: viewportEl as unknown as HTMLDivElement };++ uiStoreActions.setResizeCanvasModalOpen(true, dims);++ const Harness: React.FC = () => {+ const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);+ return (+ <div>+ <CanvasResizeOverlay+ dimensions={dims}+ viewportRef={viewportRef}+ pan={{ x: 500, y: 400 }}+ zoom={1}+ rotation={0}+ onApply={onResize}+ />+ <ResizeCanvasModal+ isOpen={isOpen}+ onClose={() => uiStoreActions.setResizeCanvasModalOpen(false)}+ currentDimensions={dims}+ onResize={onResize}+ selectionBounds={{ x: 80, y: 90, width: 320, height: 240 }}+ />+ </div>+ );+ };++ root = createRoot(container as unknown as HTMLElement);+ act(() => {+ root!.render(<Harness />);+ });++ // Click "Selection" quick button to match selection bounds+ const selectionBtn = container.findAll(+ (el) => el.tagName === 'BUTTON' && el.textContent.includes('Selection')+ )[0];+ expect(selectionBtn).toBeTruthy();+ act(() => {+ selectionBtn.dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useUiStore.getState().canvasResizeDraft?.cropX).toBe(80);+ expect(useUiStore.getState().canvasResizeDraft?.cropY).toBe(90);+ expect(useUiStore.getState().canvasResizeDraft?.width).toBe(320);+ expect(useUiStore.getState().canvasResizeDraft?.height).toBe(240);++ // Switch to Scale Content mode -> crop handles disappear, resample preview appears+ const scaleBtn = container.findAll(+ (el) => el.tagName === 'BUTTON' && el.textContent.includes('Scale Content')+ )[0];+ expect(scaleBtn).toBeTruthy();+ act(() => {+ scaleBtn.dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(container.findByTestId('canvas-resize-crop-overlay')).toBeNull();+ expect(container.findByTestId('canvas-resize-scale-preview')).toBeTruthy();++ // Escape cancels without calling onResize+ act(() => {+ (dom.win as unknown as EventTarget).dispatchEvent(+ makeKeyEvent('keydown', { key: 'Escape' })+ );+ });+ expect(onResize).not.toHaveBeenCalled();+ expect(useUiStore.getState().isResizeCanvasModalOpen).toBe(false);+ });+});diff --git a/src/utils/__tests__/changelog.test.ts b/src/utils/__tests__/changelog.test.tsindex e88cae6..03270e3 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.2.0, v1.1.0, v1.0.4, v1.0.3, v1.0.2, and v1.0.1 sections', () => {+ it('parses bundled CHANGELOG.md including v1.2.1, v1.2.0, v1.1.0, v1.0.4, v1.0.3, v1.0.2, and v1.0.1 sections', () => {const entries = getChangelogEntries();- expect(entries.length).toBeGreaterThanOrEqual(6);+ expect(entries.length).toBeGreaterThanOrEqual(7);const latest = getChangelogForVersion();- expect(latest?.version).toBe('1.2.0');+ expect(latest?.version).toBe('1.2.1');++ const v121 = getChangelogForVersion('1.2.1');+ expect(v121).toBeDefined();+ expect(v121?.version).toBe('1.2.1');+ expect(v121?.sections.map((s) => s.title)).toEqual([+ 'New',+ 'Improvements',+ 'Bug Fixes',+ ]);+ expect(v121?.sections[0].items).toContain(+ 'Added 36 new built-in artist brushes across every category'+ );+ expect(v121?.sections[0].items).toContain(+ 'Added an upgraded Time-lapse Studio with a live in-app preview player so you can watch your time-lapse at `15s`, `30s`, `60s`, `2m`, `Full`, or a custom length right inside the app before exporting'+ );+ expect(v121?.sections[0].items).toContain(+ 'Renamed the `Sub View` panel to `References` and upgraded it with a PureRef-style Board mode so you can place, view, zoom, pan, rotate, and flip multiple reference images in one space'+ );+ expect(v121?.sections[1].items).toContain(+ 'Time-lapse recordings are no longer stored inside `.ink` project files'+ );+ expect(v121?.sections[2].items).toContain(+ 'Fixed 1-bit black-and-white manga `.psd` files opening tinted red instead of black and white'+ );const v120 = getChangelogForVersion('1.2.0');expect(v120).toBeDefined();diff --git a/src/utils/__tests__/colorSetImport.test.ts b/src/utils/__tests__/colorSetImport.test.tsnew file mode 100644index 0000000..032eda0--- /dev/null+++ b/src/utils/__tests__/colorSetImport.test.ts@@ -0,0 +1,659 @@+import { zlibSync } from 'fflate';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ decodePngBytes,+ parseClipStudioColorSet,+ parsePngColorSet,+} from '../colorSetImport';+import {+ COLOR_SETS_STORAGE_KEY,+ colorSetsStoreActions,+ parseColorSetBytes,+ useColorSetsStore,+} from '../../stores/useColorSetsStore';++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));+ },+ };+}++/**+ * Encodes a synthetic Clip Studio Paint `.cls` (SLCC) binary buffer matching CSP's exact structure.+ */+function buildClsFile(options: {+ name1?: string;+ name2?: string;+ entries: Array<{ r: number; g: number; b: number; a?: number; name?: string }>;+}): Uint8Array {+ const enc = new TextEncoder();+ const n1 = enc.encode(options.name1 ?? '');+ const n2 = enc.encode(options.name2 ?? '');+ const headerLen = 2 + n1.length + 4 + 2 + n2.length;++ const entryChunks: Uint8Array[] = [];+ let totalEntriesBytes = 0;++ for (const entry of options.entries) {+ const a = entry.a ?? 255;+ let payloadLen = 8;+ let utf16NameBytes: Uint8Array | null = null;+ if (entry.name) {+ utf16NameBytes = new Uint8Array(entry.name.length * 2);+ const dvName = new DataView(utf16NameBytes.buffer);+ for (let i = 0; i < entry.name.length; i++) {+ dvName.setUint16(i * 2, entry.name.charCodeAt(i), true);+ }+ payloadLen = 10 + utf16NameBytes.length;+ }++ const chunk = new Uint8Array(4 + payloadLen);+ const dv = new DataView(chunk.buffer);+ dv.setUint32(0, payloadLen, true);+ chunk[4] = entry.r & 0xff;+ chunk[5] = entry.g & 0xff;+ chunk[6] = entry.b & 0xff;+ chunk[7] = a & 0xff;+ if (utf16NameBytes) {+ dv.setUint32(8, 1, true);+ dv.setUint16(12, utf16NameBytes.length, true);+ chunk.set(utf16NameBytes, 14);+ } else {+ dv.setUint32(8, 0, true);+ }++ entryChunks.push(chunk);+ totalEntriesBytes += chunk.length;+ }++ const totalLen = 10 + headerLen + 12 + totalEntriesBytes;+ const out = new Uint8Array(totalLen);+ const dv = new DataView(out.buffer);++ // Magic "SLCC" + version 256 + headerLen+ out.set([0x53, 0x4c, 0x43, 0x43], 0);+ dv.setUint16(4, 256, true);+ dv.setUint32(6, headerLen, true);++ let pos = 10;+ dv.setUint16(pos, n1.length, true);+ pos += 2;+ out.set(n1, pos);+ pos += n1.length;+ dv.setUint32(pos, 0, true);+ pos += 4;+ dv.setUint16(pos, n2.length, true);+ pos += 2;+ out.set(n2, pos);+ pos += n2.length;++ // Color table header+ dv.setUint32(pos, 4, true); // channels = 4 (RGBA)+ dv.setUint32(pos + 4, options.entries.length, true);+ dv.setUint32(pos + 8, totalEntriesBytes, true);+ pos += 12;++ for (const chunk of entryChunks) {+ out.set(chunk, pos);+ pos += chunk.length;+ }++ return out;+}++/**+ * Minimal PNG encoder for unit tests (supports RGB, RGBA, Grayscale, Indexed PLTE/tRNS,+ * filters, Adam7 interlacing, and tEXt metadata).+ */+function makePngChunk(type: string, data: Uint8Array): Uint8Array {+ const out = new Uint8Array(12 + data.length);+ const dv = new DataView(out.buffer);+ dv.setUint32(0, data.length, false);+ for (let i = 0; i < 4; i++) {+ out[4 + i] = type.charCodeAt(i);+ }+ out.set(data, 8);+ // CRC32 (set 0 for decoder tests; our decoder validates lengths/zlib cleanly)+ dv.setUint32(8 + data.length, 0, false);+ return out;+}++function buildPng(options: {+ width: number;+ height: number;+ colorType: 0 | 2 | 3 | 4 | 6;+ bitDepth?: 1 | 2 | 4 | 8 | 16;+ interlace?: 0 | 1;+ palette?: Uint8Array;+ trns?: Uint8Array;+ title?: string;+ scanlines: Uint8Array; // raw unfiltered/filtered scanlines (already includes filter byte per row)+}): Uint8Array {+ const bitDepth = options.bitDepth ?? 8;+ const interlace = options.interlace ?? 0;++ const ihdr = new Uint8Array(13);+ const dv = new DataView(ihdr.buffer);+ dv.setUint32(0, options.width, false);+ dv.setUint32(4, options.height, false);+ ihdr[8] = bitDepth;+ ihdr[9] = options.colorType;+ ihdr[10] = 0;+ ihdr[11] = 0;+ ihdr[12] = interlace;++ const chunks: Uint8Array[] = [makePngChunk('IHDR', ihdr)];+ if (options.title) {+ const enc = new TextEncoder();+ const titleBytes = enc.encode(`Title\0${options.title}`);+ chunks.push(makePngChunk('tEXt', titleBytes));+ }+ if (options.palette) {+ chunks.push(makePngChunk('PLTE', options.palette));+ }+ if (options.trns) {+ chunks.push(makePngChunk('tRNS', options.trns));+ }++ const compressed = zlibSync(options.scanlines);+ chunks.push(makePngChunk('IDAT', compressed));+ chunks.push(makePngChunk('IEND', new Uint8Array(0)));++ const sig = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+ const totalLen = sig.length + chunks.reduce((s, c) => s + c.length, 0);+ const out = new Uint8Array(totalLen);+ let pos = 0;+ out.set(sig, pos);+ pos += sig.length;+ for (const c of chunks) {+ out.set(c, pos);+ pos += c.length;+ }+ return out;+}++function buildRgbaPng(+ width: number,+ height: number,+ pixels: Uint8Array,+ options?: { title?: string; filterType?: 0 | 1 | 2 | 3 | 4 }+): Uint8Array {+ const filterType = options?.filterType ?? 0;+ const stride = width * 4;+ const raw = new Uint8Array(height * (1 + stride));++ const paeth = (a: number, b: number, c: number) => {+ const p = a + b - c;+ const pa = Math.abs(p - a);+ const pb = Math.abs(p - b);+ const pc = Math.abs(p - c);+ if (pa <= pb && pa <= pc) return a;+ if (pb <= pc) return b;+ return c;+ };++ for (let y = 0; y < height; y++) {+ const rowOff = y * (1 + stride);+ raw[rowOff] = filterType;+ for (let x = 0; x < stride; x++) {+ const cur = pixels[y * stride + x];+ const left = x >= 4 ? pixels[y * stride + x - 4] : 0;+ const up = y > 0 ? pixels[(y - 1) * stride + x] : 0;+ const upLeft = y > 0 && x >= 4 ? pixels[(y - 1) * stride + x - 4] : 0;+ let encoded = cur;+ if (filterType === 1) encoded = (cur - left) & 0xff;+ else if (filterType === 2) encoded = (cur - up) & 0xff;+ else if (filterType === 3) encoded = (cur - ((left + up) >> 1)) & 0xff;+ else if (filterType === 4) encoded = (cur - paeth(left, up, upLeft)) & 0xff;+ raw[rowOff + 1 + x] = encoded;+ }+ }++ return buildPng({+ width,+ height,+ colorType: 6,+ bitDepth: 8,+ title: options?.title,+ scanlines: raw,+ });+}++describe('Color Set Import (.cls & .png)', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;++ beforeEach(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useColorSetsStore.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,+ });+ }+ });++ describe('Clip Studio Color Set (.cls)', () => {+ it('parses SLCC header, UTF-8 set name, RGBA colors, UTF-16LE swatch names, and skips empty transparent slots', () => {+ const clsBytes = buildClsFile({+ name1: 'Fallback ASCII',+ name2: '標準カラーセット',+ entries: [+ { r: 0, g: 0, b: 0, a: 255, name: 'Black' },+ { r: 255, g: 255, b: 255, a: 255, name: '白' },+ { r: 0, g: 0, b: 0, a: 0 }, // Empty CSP grid slot -> skipped+ { r: 255, g: 50, b: 100, a: 255 },+ { r: 55, g: 170, b: 135, a: 255, name: 'Mint Teal' },+ ],+ });++ const res = parseClipStudioColorSet(clsBytes, 'custom.cls');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.format).toBe('cls');+ expect(res.name).toBe('標準カラーセット');+ expect(res.swatches).toEqual([+ { hex: '#000000', name: 'Black' },+ { hex: '#ffffff', name: '白' },+ { hex: '#ff3264' },+ { hex: '#37aa87', name: 'Mint Teal' },+ ]);+ }+ });++ it('falls back to filename when header names are empty', () => {+ const clsBytes = buildClsFile({+ name1: '',+ name2: '',+ entries: [+ { r: 17, g: 34, b: 51, a: 255 },+ { r: 204, g: 68, b: 34, a: 255 },+ ],+ });++ const res = parseClipStudioColorSet(clsBytes, 'Manga Skin Tones.cls');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.name).toBe('Manga Skin Tones');+ expect(res.swatches.map((s) => s.hex)).toEqual(['#112233', '#cc4422']);+ }+ });++ it('parses a 49-swatch CSP "Default color set" layout with mixed named and unnamed entries', () => {+ const entries: Array<{ r: number; g: number; b: number; a?: number; name?: string }> = [+ { r: 0x00, g: 0x00, b: 0x00, a: 0xff, name: 'Black' },+ { r: 0xff, g: 0xff, b: 0xff, a: 0xff, name: 'White' },+ { r: 0xff, g: 0x32, b: 0x64, a: 0xff },+ ];+ for (let i = 3; i < 48; i++) {+ entries.push({ r: (i * 5) & 0xff, g: (i * 7) & 0xff, b: (i * 11) & 0xff, a: 0xff });+ }+ entries.push({ r: 0xe3, g: 0x80, b: 0xdb, a: 0xff });++ const bytes = buildClsFile({+ name1: 'Default color set',+ name2: 'Default color set',+ entries,+ });+ const res = parseClipStudioColorSet(bytes, 'Default color set.cls');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.name).toBe('Default color set');+ expect(res.swatches).toHaveLength(49);+ expect(res.swatches[0]).toEqual({ hex: '#000000', name: 'Black' });+ expect(res.swatches[1]).toEqual({ hex: '#ffffff', name: 'White' });+ expect(res.swatches[2]).toEqual({ hex: '#ff3264' });+ expect(res.swatches[48]).toEqual({ hex: '#e380db' });+ }+ });++ it('rejects invalid, empty, truncated, or all-transparent .cls files cleanly', () => {+ expect(parseClipStudioColorSet(new Uint8Array(0)).ok).toBe(false);+ expect(parseClipStudioColorSet(new Uint8Array([1, 2, 3, 4, 5, 6])).ok).toBe(false);++ const truncated = new Uint8Array([0x53, 0x4c, 0x43, 0x43, 0x00, 0x01, 0x99, 0x00, 0x00, 0x00]);+ expect(parseClipStudioColorSet(truncated).ok).toBe(false);++ const allTransparent = buildClsFile({+ name1: 'Empty Slots',+ name2: 'Empty Slots',+ entries: [+ { r: 0, g: 0, b: 0, a: 0 },+ { r: 10, g: 20, b: 30, a: 0 },+ ],+ });+ expect(parseClipStudioColorSet(allTransparent).ok).toBe(false);+ });++ it('imports .cls into useColorSetsStore, deduplicates set names, and persists', () => {+ const clsBytes = buildClsFile({+ name1: 'CSP Set',+ name2: 'CSP Set',+ entries: [+ { r: 220, g: 38, b: 38, a: 255, name: 'Crimson' },+ { r: 37, g: 99, b: 235, a: 255, name: 'Cobalt' },+ ],+ });++ const first = colorSetsStoreActions.importSetBytes(clsBytes, 'csp-set.cls');+ expect(first.ok).toBe(true);+ if (first.ok) {+ expect(first.set.name).toBe('CSP Set');+ expect(first.set.swatches.map((s) => s.hex)).toEqual(['#dc2626', '#2563eb']);+ expect(first.set.swatches[0].name).toBe('Crimson');+ expect(useColorSetsStore.getState().activeSetId).toBe(first.set.id);+ }++ // Second import with same name deduplicates cleanly+ const second = colorSetsStoreActions.importSetBytes(clsBytes, 'csp-set.cls');+ expect(second.ok).toBe(true);+ if (second.ok) {+ expect(second.set.name).toBe('CSP Set (2)');+ }+ expect(localStorage.getItem(COLOR_SETS_STORAGE_KEY)).toBeTruthy();+ });+ });++ describe('PNG Color Set Palette (.png)', () => {+ it('extracts exact colors in left-to-right order from a 1px palette strip PNG (Paeth filtered)', () => {+ const colors: Array<[number, number, number]> = [+ [26, 28, 44],+ [93, 39, 93],+ [177, 62, 83],+ [239, 125, 87],+ [255, 205, 117],+ [167, 240, 112],+ ];+ const pixels = new Uint8Array(colors.length * 4);+ colors.forEach(([r, g, b], i) => {+ pixels[i * 4] = r;+ pixels[i * 4 + 1] = g;+ pixels[i * 4 + 2] = b;+ pixels[i * 4 + 3] = 255;+ });++ const png = buildRgbaPng(colors.length, 1, pixels, { filterType: 4 });+ const res = parsePngColorSet(png, 'sweetie-16-1x.png');++ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.format).toBe('png');+ expect(res.name).toBe('sweetie-16-1x');+ expect(res.swatches.map((s) => s.hex)).toEqual([+ '#1a1c2c',+ '#5d275d',+ '#b13e53',+ '#ef7d57',+ '#ffcd75',+ '#a7f070',+ ]);+ }+ });++ it('extracts scaled swatch grid PNG in row-major reading order while ignoring transparent gutters', () => {+ // 3x2 grid of 8x8 swatches separated by 2px transparent gaps -> 28x18+ const gridColors = [+ [255, 0, 0],+ [0, 255, 0],+ [0, 0, 255],+ [255, 255, 0],+ [0, 255, 255],+ [255, 0, 255],+ ];+ const w = 28;+ const h = 18;+ const pixels = new Uint8Array(w * h * 4); // initialized to transparent (0,0,0,0)++ for (let row = 0; row < 2; row++) {+ for (let col = 0; col < 3; col++) {+ const [r, g, b] = gridColors[row * 3 + col];+ const x0 = col * 10;+ const y0 = row * 10;+ for (let dy = 0; dy < 8; dy++) {+ for (let dx = 0; dx < 8; dx++) {+ const idx = ((y0 + dy) * w + (x0 + dx)) * 4;+ pixels[idx] = r;+ pixels[idx + 1] = g;+ pixels[idx + 2] = b;+ pixels[idx + 3] = 255;+ }+ }+ }+ }++ const png = buildRgbaPng(w, h, pixels, { title: 'Primary Swatch Grid', filterType: 1 });+ const res = parsePngColorSet(png, 'ignored-filename.png');++ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.name).toBe('Primary Swatch Grid');+ expect(res.swatches.map((s) => s.hex)).toEqual([+ '#ff0000',+ '#00ff00',+ '#0000ff',+ '#ffff00',+ '#00ffff',+ '#ff00ff',+ ]);+ }+ });++ it('decodes indexed PLTE + tRNS 4-bit PNG palettes cleanly', () => {+ // Palette: 0 = transparent bg, 1 = #102030, 2 = #f0a050, 3 = #40c080, 4 = unused (#abcdef)+ const palette = new Uint8Array([+ 0x00, 0x00, 0x00,+ 0x10, 0x20, 0x30,+ 0xf0, 0xa0, 0x50,+ 0x40, 0xc0, 0x80,+ 0xab, 0xcd, 0xef,+ ]);+ const trns = new Uint8Array([0, 255, 255, 255, 255]);+ // 4 pixels wide, 1px tall, 4-bit indexed -> 2 bytes per row: [0x01, 0x23] => indices 0, 1, 2, 3+ const scanlines = new Uint8Array([0, 0x01, 0x23]);+ const png = buildPng({+ width: 4,+ height: 1,+ colorType: 3,+ bitDepth: 4,+ palette,+ trns,+ scanlines,+ });++ const res = parsePngColorSet(png, 'retro-4bit.png');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.name).toBe('retro-4bit');+ // Index 0 is transparent, index 4 is unused -> only indices 1, 2, 3 extracted+ expect(res.swatches.map((s) => s.hex)).toEqual(['#102030', '#f0a050', '#40c080']);+ }+ });++ it('decodes Adam7 interlaced RGB PNG and 8-bit grayscale PNG', () => {+ // 4x1 grayscale PNG with values 0, 85, 170, 255+ const grayScanlines = new Uint8Array([0, 0, 85, 170, 255]);+ const grayPng = buildPng({+ width: 4,+ height: 1,+ colorType: 0,+ bitDepth: 8,+ scanlines: grayScanlines,+ });+ const grayRes = parsePngColorSet(grayPng, 'values.png');+ expect(grayRes.ok).toBe(true);+ if (grayRes.ok) {+ expect(grayRes.swatches.map((s) => s.hex)).toEqual([+ '#000000',+ '#555555',+ '#aaaaaa',+ '#ffffff',+ ]);+ }++ // 2x2 Adam7 interlaced RGB PNG (passes: 1:(0,0), 2:none, 3:none, 4:none, 5:none, 6:(1,0), 7:(0,1),(1,1))+ const adam7 = new Uint8Array([+ 0, 255, 0, 0, // pass 1: (0,0) red+ 0, 0, 255, 0, // pass 6: (1,0) green+ 0, 0, 0, 255, 255, 255, 0, // pass 7: (0,1) blue, (1,1) yellow+ ]);+ const interlacedPng = buildPng({+ width: 2,+ height: 2,+ colorType: 2,+ bitDepth: 8,+ interlace: 1,+ scanlines: adam7,+ });+ const decoded = decodePngBytes(interlacedPng);+ expect(decoded.width).toBe(2);+ expect(decoded.height).toBe(2);+ const interRes = parsePngColorSet(interlacedPng, 'adam7.png');+ expect(interRes.ok).toBe(true);+ if (interRes.ok) {+ expect(interRes.swatches.map((s) => s.hex)).toEqual([+ '#ff0000',+ '#00ff00',+ '#0000ff',+ '#ffff00',+ ]);+ }+ });++ it('filters anti-aliased fringe pixels out of large flat swatch card PNGs', () => {+ // 200x100 = 20,000 pixels: 4 solid vertical bars (50x100 = 5,000px each)+ // plus 60 single-pixel anti-aliased noise colors along the bottom row+ const w = 200;+ const h = 100;+ const pixels = new Uint8Array(w * h * 4);+ const bars: Array<[number, number, number]> = [+ [34, 48, 68],+ [198, 72, 64],+ [238, 178, 76],+ [82, 166, 134],+ ];++ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const barIdx = Math.min(3, Math.floor(x / 50));+ const [r, g, b] = bars[barIdx];+ const idx = (y * w + x) * 4;+ pixels[idx] = r;+ pixels[idx + 1] = g;+ pixels[idx + 2] = b;+ pixels[idx + 3] = 255;+ }+ }++ // Inject 60 anti-aliased fringe pixels on row 99+ for (let i = 0; i < 60; i++) {+ const idx = (99 * w + i) * 4;+ pixels[idx] = 100 + i;+ pixels[idx + 1] = 100 + i;+ pixels[idx + 2] = 100 + i;+ pixels[idx + 3] = 255;+ }++ const png = buildRgbaPng(w, h, pixels);+ const res = parsePngColorSet(png, 'coolors-card.png');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.swatches.map((s) => s.hex)).toEqual([+ '#223044',+ '#c64840',+ '#eeb24c',+ '#52a686',+ ]);+ }+ });++ it('quantizes continuous-tone gradient PNGs into a cohesive palette via Median-Cut', () => {+ const w = 64;+ const h = 64;+ const pixels = new Uint8Array(w * h * 4);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const idx = (y * w + x) * 4;+ pixels[idx] = Math.round((x / (w - 1)) * 255);+ pixels[idx + 1] = Math.round((y / (h - 1)) * 255);+ pixels[idx + 2] = Math.round(((w - 1 - x) / (w - 1)) * 200);+ pixels[idx + 3] = 255;+ }+ }++ const png = buildRgbaPng(w, h, pixels);+ const res = parsePngColorSet(png, 'gradient-ref.png');+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.name).toBe('gradient-ref');+ expect(res.swatches.length).toBeGreaterThanOrEqual(8);+ expect(res.swatches.length).toBeLessThanOrEqual(24);+ }+ });++ it('rejects empty, corrupt, and fully transparent PNGs cleanly', () => {+ expect(parsePngColorSet(new Uint8Array(0)).ok).toBe(false);+ expect(parsePngColorSet(new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8])).ok).toBe(false);++ // Fully transparent 4x4 PNG+ const transparent = new Uint8Array(4 * 4 * 4);+ const transparentPng = buildRgbaPng(4, 4, transparent);+ expect(parsePngColorSet(transparentPng, 'empty.png').ok).toBe(false);+ });++ it('auto-detects .cls, .png, and .json formats via parseColorSetBytes and store importSetBytes', () => {+ const clsBytes = buildClsFile({+ name1: 'Magic CLS',+ name2: 'Magic CLS',+ entries: [{ r: 10, g: 20, b: 30, a: 255 }],+ });+ // Even without filename, SLCC magic routes to .cls parser+ const clsRes = parseColorSetBytes(clsBytes);+ expect(clsRes.ok).toBe(true);+ if (clsRes.ok) {+ expect(clsRes.name).toBe('Magic CLS');+ expect(clsRes.swatches[0].hex).toBe('#0a141e');+ }++ // PNG magic without filename routes to .png parser+ const pngBytes = buildRgbaPng(2, 1, new Uint8Array([1, 2, 3, 255, 250, 240, 230, 255]));+ const pngRes = colorSetsStoreActions.importSetBytes(pngBytes, 'Sunset Palette.png');+ expect(pngRes.ok).toBe(true);+ if (pngRes.ok) {+ expect(pngRes.set.name).toBe('Sunset Palette');+ expect(pngRes.set.swatches.map((s) => s.hex)).toEqual(['#010203', '#faf0e6']);+ }++ // Unsupported extension with plain text fails clearly+ const badRes = parseColorSetBytes(new TextEncoder().encode('hello'), 'notes.txt');+ expect(badRes.ok).toBe(false);+ });+ });+});diff --git a/src/utils/__tests__/compositor.test.ts b/src/utils/__tests__/compositor.test.tsindex 1a5ed47..630c79d 100644--- a/src/utils/__tests__/compositor.test.ts+++ b/src/utils/__tests__/compositor.test.ts@@ -750,6 +750,7 @@ describe('Unified GPU Viewport Compositor', () => {describe('WebGL2 Compositor Optimization Verification (Ping-Pong FBOs, Instanced Batching, Zero CPU Premultiply, In-Stack Draft)', () => {function createMockWebGL2Context(options?: { maxArrayLayers?: number }) {const maxArrayLayers = options?.maxArrayLayers ?? 256;+ const clearEvents: Array<{ mask: number; fbo: any }> = [];const calls: Array<{ name: string; args: any[] }> = [];let activeProgram: any = null;let boundFbo: any = null;@@ -836,6 +837,7 @@ describe('Unified GPU Viewport Compositor', () => {UNSIGNED_BYTE: 0x1401,BLEND: 0x0be2,STENCIL_TEST: 0x0b90,+ SCISSOR_TEST: 0x0c11,ONE: 1,ZERO: 0,ONE_MINUS_SRC_ALPHA: 0x0303,@@ -956,7 +958,9 @@ describe('Unified GPU Viewport Compositor', () => {},viewport: () => {},clearColor: () => {},- clear: () => {},+ clear: (mask: number) => {+ clearEvents.push({ mask, fbo: boundFbo });+ },enable: () => {},disable: () => {},isEnabled: () => false,@@ -1011,7 +1015,7 @@ describe('Unified GPU Viewport Compositor', () => {getContext: (type: string) => (type === 'webgl2' ? gl : null),} as unknown as HTMLCanvasElement;- return { gl, canvas, calls, drawEvents, glSpecErrors };+ return { gl, canvas, calls, drawEvents, clearEvents, glSpecErrors };}const writeTestPixel = (grid: SparseTileGrid, layerId: string, x: number, y: number, rgba = [200, 100, 50, 128]) => {@@ -1680,6 +1684,128 @@ describe('Unified GPU Viewport Compositor', () => {expect((mockDraftCanvas as any).__draftForceFullUpload).toBe(false);expect(glSpecErrors).toEqual([]);});++ it('clamps artboard drop shadow SDF to non-negative outside distance and clips tiles to document bounds', () => {+ // Regression check for the 4-corner black dot artifact: both outsideDoc and shadowOutside+ // must clamp interior negative components with max(vec2(0.0), ...).+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain(+ 'vec2 outsideDoc = max(vec2(0.0), max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions));'+ );+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain(+ 'vec2 shadowOutside = max(vec2(0.0), max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions));'+ );+ // Both standard and instanced tile fragment shaders must discard fragments outside [0, u_docDimensions]+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain('v_docCoord.x > u_docDimensions.x');+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain('v_docCoord.x > u_docDimensions.x');+ });++ it('clears the default framebuffer before presenting so discarded transparent pixels never ghost previous frames', () => {+ const { canvas, clearEvents, drawEvents, glSpecErrors } = createMockWebGL2Context();+ const compositor = new ViewportCompositor(canvas);+ const grid = new SparseTileGrid();+ const dims = { width: 6071, height: 8598, dpi: 600 };+ const layers: LayerItem[] = [+ {+ id: 'layer-ink',+ name: 'Layer 1',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ expressionColor: 'monochrome',+ },+ ];+ writeTestPixel(grid, 'layer-ink', 100, 100, [0, 0, 0, 255]);++ // Render 1 (initial pan/zoom)+ clearEvents.length = 0;+ compositor.render(layers, { pan: { x: 420, y: 300 }, zoom: 0.08, rotation: 0 }, dims, grid, {+ dimensions: dims,+ devicePixelRatio: 1,+ });+ expect(clearEvents.some((e) => e.fbo === null && (e.mask & 0x4000) !== 0)).toBe(true);++ // Render 2 (camera moved to centered pan — hits moving-camera path)+ clearEvents.length = 0;+ drawEvents.length = 0;+ compositor.render(layers, { pan: { x: 350, y: 300 }, zoom: 0.08, rotation: 0 }, dims, grid, {+ dimensions: dims,+ devicePixelRatio: 1,+ });+ expect(clearEvents.some((e) => e.fbo === null && (e.mask & 0x4000) !== 0)).toBe(true);+ expect(glSpecErrors).toEqual([]);+ });++ it('keeps masked pass-through folders isolated and applies u_maskEnabled=1 during folder blit only', () => {+ const { canvas, drawEvents, glSpecErrors } = createMockWebGL2Context();+ const compositor = new ViewportCompositor(canvas);+ const grid = new SparseTileGrid();+ const dims = { width: 512, height: 512, dpi: 300 };++ const mockMaskCanvas = {+ width: 512,+ height: 512,+ } as unknown as HTMLCanvasElement;++ const layers: LayerItem[] = [+ {+ id: 'frame-folder-1',+ name: 'Panel 1',+ type: 'folder',+ visible: true,+ opacity: 1,+ blendMode: 'pass-through',+ locked: false,+ parentId: null,+ maskCanvas: mockMaskCanvas,+ maskEnabled: true,+ maskVersion: 1,+ },+ {+ id: 'child-ink',+ name: 'Ink inside panel',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: 'frame-folder-1',+ },+ {+ id: 'layer-bg',+ name: 'Paper',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];+ grid.fillLayerSolidWhite('layer-bg', 512, 512, 'color-32bit');+ writeTestPixel(grid, 'child-ink', 100, 100, [0, 0, 0, 255]);++ // Masked pass-through folder must NOT be flattened into child-only units+ const partition = partitionLayerStack(layers, 'child-ink');+ expect(partition.activeUnit).not.toBeNull();+ expect(partition.activeUnit!.group.baseNode.layer.id).toBe('frame-folder-1');++ drawEvents.length = 0;+ compositor.render(layers, { pan: { x: 400, y: 300 }, zoom: 1, rotation: 0 }, dims, grid, {+ dimensions: dims,+ devicePixelRatio: 1,+ activeLayerId: 'child-ink',+ });++ const blitDraws = drawEvents.filter((d) => d.programTag === 'blit');+ expect(blitDraws.length).toBeGreaterThanOrEqual(2);+ // Folder blit enables mask sampling; final screen present resets u_maskEnabled to 0+ expect(blitDraws.some((d) => d.uniforms.u_maskEnabled === 1)).toBe(true);+ expect(blitDraws[blitDraws.length - 1].uniforms.u_maskEnabled).toBe(0);+ expect(glSpecErrors).toEqual([]);+ });});});diff --git a/src/utils/__tests__/crashRecoveryModal.test.tsx b/src/utils/__tests__/crashRecoveryModal.test.tsxnew file mode 100644index 0000000..aa27745--- /dev/null+++ b/src/utils/__tests__/crashRecoveryModal.test.tsx@@ -0,0 +1,365 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CrashRecoveryModal } from '../../components/CrashRecoveryModal';+import { CrashedSessionInfo } from '../../services/recoveryService';++interface MiniNode {+ nodeType: number;+ nodeName: string;+ parentNode: MiniElement | null;+ ownerDocument: MiniDocument;+}++class MiniTextNode implements MiniNode {+ public nodeType = 3;+ public nodeName = '#text';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniCommentNode implements MiniNode {+ public nodeType = 8;+ public nodeName = '#comment';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniElement extends EventTarget implements MiniNode {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public ownerDocument: MiniDocument;+ public parentNode: MiniElement | null = null;+ public childNodes: MiniNode[] = [];+ public style: Record<string, string> = {};+ public disabled = false;+ public className = '';+ public isContentEditable = false;+ public value = '';+ public checked = false;+ private attrs = new Map<string, string>();++ constructor(tag: string, ownerDocument: MiniDocument) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ this.ownerDocument = ownerDocument;+ }++ get firstChild(): MiniNode | null {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];+ }++ 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 (!ref) return this.appendChild(child);+ if (child.parentNode) {+ child.parentNode.removeChild(child);+ }+ const idx = this.childNodes.indexOf(ref);+ child.parentNode = this;+ if (idx === -1) {+ 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 !== -1) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ setAttribute(name: string, value: string): void {+ this.attrs.set(name, String(value));+ if (name === 'class') this.className = String(value);+ if (name === 'disabled') this.disabled = true;+ if (name === 'value') this.value = String(value);+ }++ getAttribute(name: string): string | null {+ return this.attrs.get(name) ?? null;+ }++ removeAttribute(name: string): void {+ this.attrs.delete(name);+ if (name === 'disabled') this.disabled = false;+ }++ hasAttribute(name: string): boolean {+ return this.attrs.has(name);+ }++ focus(): void {+ this.ownerDocument.activeElement = this;+ }++ blur(): void {+ if (this.ownerDocument.activeElement === this) {+ this.ownerDocument.activeElement = null;+ }+ }++ override dispatchEvent(event: Event): boolean {+ const path: EventTarget[] = [];+ let cur: MiniElement | null = this;+ while (cur) {+ path.push(cur);+ cur = cur.parentNode;+ }+ path.push(this.ownerDocument);+ if (this.ownerDocument.defaultView) {+ 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 MiniDocument extends EventTarget {+ public nodeType = 9;+ public nodeName = '#document';+ public defaultView: EventTarget | null = null;+ public documentElement: MiniElement;+ public body: MiniElement;+ public activeElement: MiniElement | null = null;++ constructor() {+ super();+ this.documentElement = new MiniElement('html', this);+ this.body = new MiniElement('body', this);+ this.documentElement.appendChild(this.body);+ }++ createElement(tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createElementNS(_ns: string, tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createTextNode(text: string): MiniTextNode {+ return new MiniTextNode(text, this);+ }++ createComment(text: string): MiniCommentNode {+ return new MiniCommentNode(text, this);+ }+}++function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {+ const result: MiniElement[] = [];+ const walk = (el: MiniElement) => {+ if (pred(el)) result.push(el);+ for (const child of el.childNodes) {+ if (child instanceof MiniElement) walk(child);+ }+ };+ walk(root);+ return result;+}++function findByTestId(root: MiniElement, testId: string): MiniElement | undefined {+ return findElements(root, (el) => el.getAttribute('data-testid') === testId)[0];+}++function clickElement(el: MiniElement): void {+ const evt = new Event('click', { bubbles: true, cancelable: true });+ el.dispatchEvent(evt);+}++const makeSession = (id: string, name: string): CrashedSessionInfo => ({+ session_id: id,+ timestamp: 1796081844201,+ pid: 2412,+ manifest_json: JSON.stringify({+ documentName: name,+ width: 1920,+ height: 1080,+ dpi: 300,+ colorMode: 'color',+ layers: [{ id: 'l1' }, { id: 'l2' }],+ }),+ has_thumbnail: false,+ thumbnail_data_url: null,+});++describe('CrashRecoveryModal - Discard All Sessions', () => {+ let doc: MiniDocument;+ let win: EventTarget;+ let container: MiniElement;+ let root: Root;++ const prevWindow = (globalThis as Record<string, unknown>).window;+ const prevDocument = (globalThis as Record<string, unknown>).document;+ const prevHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const prevHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const prevElement = (globalThis as Record<string, unknown>).Element;+ const prevNode = (globalThis as Record<string, unknown>).Node;+ const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ beforeEach(() => {+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ const MockHTMLIFrameElement = class HTMLIFrameElement {};+ doc = new MiniDocument();+ win = Object.assign(new EventTarget(), {+ document: doc,+ HTMLElement: MiniElement,+ HTMLIFrameElement: MockHTMLIFrameElement,+ Element: MiniElement,+ Node: MiniElement,+ });+ doc.defaultView = win;+ container = doc.createElement('div');+ doc.body.appendChild(container);++ (globalThis as Record<string, unknown>).window = win;+ (globalThis as Record<string, unknown>).document = doc;+ (globalThis as Record<string, unknown>).HTMLElement = MiniElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = MockHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = MiniElement;+ (globalThis as Record<string, unknown>).Node = MiniElement;++ root = createRoot(container as unknown as Element);+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ (globalThis as Record<string, unknown>).window = prevWindow;+ (globalThis as Record<string, unknown>).document = prevDocument;+ (globalThis as Record<string, unknown>).HTMLElement = prevHTMLElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = prevHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = prevElement;+ (globalThis as Record<string, unknown>).Node = prevNode;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;+ });++ it('renders "Discard All Sessions" for a single session and invokes onDiscardAll with all sessions', async () => {+ const sessions = [makeSession('doc-1', 'Untitled*')];+ const onRestore = vi.fn(async () => {});+ const onDiscard = vi.fn(async () => {});+ const onDiscardAll = vi.fn(async () => {});++ act(() => {+ root.render(+ <CrashRecoveryModal+ isOpen+ sessions={sessions}+ onRestore={onRestore}+ onDiscard={onDiscard}+ onDiscardAll={onDiscardAll}+ />+ );+ });++ const btn = findByTestId(container, 'discard-all-sessions-btn');+ expect(btn).toBeDefined();+ expect(btn?.textContent.trim()).toBe('Discard All Sessions');++ await act(async () => {+ clickElement(btn!);+ });++ expect(onDiscardAll).toHaveBeenCalledTimes(1);+ expect(onDiscardAll).toHaveBeenCalledWith(sessions);+ expect(onDiscard).not.toHaveBeenCalled();+ });++ it('shows count for multiple sessions, disables buttons while discarding all, and passes all sessions', async () => {+ const sessions = [+ makeSession('doc-1', 'Page 1'),+ makeSession('doc-2', 'Page 2'),+ makeSession('doc-3', 'Page 3'),+ ];+ let resolveDiscardAll!: () => void;+ const onDiscardAll = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveDiscardAll = resolve;+ })+ );++ act(() => {+ root.render(+ <CrashRecoveryModal+ isOpen+ sessions={sessions}+ onRestore={vi.fn(async () => {})}+ onDiscard={vi.fn(async () => {})}+ onDiscardAll={onDiscardAll}+ />+ );+ });++ const discardAllBtn = findByTestId(container, 'discard-all-sessions-btn');+ expect(discardAllBtn?.textContent.trim()).toBe('Discard All Sessions (3)');++ act(() => {+ clickElement(discardAllBtn!);+ });++ expect(onDiscardAll).toHaveBeenCalledTimes(1);+ expect(onDiscardAll).toHaveBeenCalledWith(sessions);+ expect(discardAllBtn?.textContent.trim()).toBe('Discarding All...');+ expect(discardAllBtn?.disabled).toBe(true);++ // Extra clicks while busy are ignored+ act(() => {+ clickElement(discardAllBtn!);+ });+ expect(onDiscardAll).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveDiscardAll();+ });++ expect(discardAllBtn?.disabled).toBe(false);+ expect(discardAllBtn?.textContent.trim()).toBe('Discard All Sessions (3)');+ });+});diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.tsindex 8b7510b..1d5daaa 100644--- a/src/utils/__tests__/cspBrushEngineV2.test.ts+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts@@ -171,6 +171,8 @@ describe('CSP Brush Engine V2 - Mathematics, Sensors & Post-Processing', () => {expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('rough-pen');expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('blend-velvet-soft');expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('impasto-bristle-oil');- expect(BUILTIN_BRUSHES.length).toBe(35);+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('sculptural-hard-square');+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('ethereal-smoke-mist');+ expect(BUILTIN_BRUSHES.length).toBe(71);});});diff --git a/src/utils/__tests__/cspParser.test.ts b/src/utils/__tests__/cspParser.test.tsindex 6693e05..e6f7aa8 100644--- a/src/utils/__tests__/cspParser.test.ts+++ b/src/utils/__tests__/cspParser.test.ts@@ -300,6 +300,135 @@ describe('CSP (.clip) binary helpers & Rust INKD wire hydration (zero sql.js)',expect(Array.from(paperPx.data)).toEqual([255, 255, 255, 255]);});+ it('parses real CSP Parameter + InitColor (header=20) without misreading BlockDataChannelOrder as white fill', () => {+ // Real CSP monochrome 1-plane ink layer: BlockDataChannelOrder=1 at +16, BlockDataChannelBytes=1 at +20,+ // InitColor=[20, 0 (doInitialize=false), 0, 0, 4]+ const realMonoAttr = concatBytes([+ u32BE(88),+ utf16BeTagged('Parameter'),+ u32BE(6071), // width+ u32BE(8598), // height+ u32BE(24), // hBlocks+ u32BE(34), // vBlocks+ u32BE(1), // BlockDataChannelOrder = 1 (Gray/Alpha — NOT defaultFill=1!)+ u32BE(1), // BlockDataChannelBytes = 1+ u32BE(1),+ u32BE(1),+ u32BE(8192),+ u32BE(0),+ u32BE(0),+ u32BE(0),+ u32BE(0),+ u32BE(1),+ utf16BeTagged('InitColor'),+ u32BE(20), // header size+ u32BE(0), // doInitialize = false+ u32BE(0), // alpha+ u32BE(0), // imageValueCount+ u32BE(4), // elemBytes+ ]);++ const parsed = parseOffscreenAttribute(realMonoAttr, 100, 100);+ expect(parsed.bitmapWidth).toBe(6071);+ expect(parsed.bitmapHeight).toBe(8598);+ expect(parsed.blockGridWidth).toBe(24);+ expect(parsed.blockGridHeight).toBe(34);+ expect(parsed.defaultFill).toBe(0);+ expect(parsed.initDoInitialize).toBe(false);++ // 1-plane 1-bit ink tile must decode to opaque BLACK (not invisible white!)+ const rawMono = new Uint8Array(8192);+ rawMono[0] = 0x80; // pixel (0, 0) inked+ const out = new Uint8ClampedArray(BYTES_32BIT);+ expect(decodeCspTileToRgba(rawMono, out, parsed)).toBe(true);+ expect([out[0], out[1], out[2], out[3]]).toEqual([0, 0, 0, 255]);++ // Real CSP initialized Paper/Fill InitColor: header=20, doInitialize=1, alpha=0xFFFFFFFF, RGB=(0xFFFF0000, ...)+ const initPaperAttr = concatBytes([+ u32BE(88),+ utf16BeTagged('Parameter'),+ u32BE(512),+ u32BE(512),+ u32BE(2),+ u32BE(2),+ u32BE(33),+ u32BE(1),+ u32BE(1),+ u32BE(4),+ u32BE(262144),+ utf16BeTagged('InitColor'),+ u32BE(20),+ u32BE(1), // doInitialize = true+ u32BE(0xffffffff), // alpha = 255+ u32BE(3), // 3 color values+ u32BE(4),+ u32BE(0xf0000000),+ u32BE(0xe0000000),+ u32BE(0xd0000000),+ ]);+ const parsedInit = parseOffscreenAttribute(initPaperAttr, 100, 100);+ expect(parsedInit.initDoInitialize).toBe(true);+ expect(parsedInit.initAlpha).toBe(255);+ expect(parsedInit.defaultFill).toBe(1);+ expect(parsedInit.initColor).toEqual([0xf0, 0xe0, 0xd0, 255]);+ });++ it('hydrates expressionColor, monoExpressBlack/White, and layerColor tint fields from INKD metadata', () => {+ const rawTile = new Uint8Array(BYTES_32BIT);+ rawTile[0] = 0;+ rawTile[1] = 0;+ rawTile[2] = 0;+ rawTile[3] = 255;+ const compTile = lz4CompressBlock(rawTile);++ const meta = {+ width: 256,+ height: 256,+ dpi: 600,+ colorMode: 'color',+ preview: null,+ layers: [+ {+ id: 'csp-mono-1',+ name: 'Manga Inks',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ alphaLocked: false,+ clipped: false,+ collapsed: false,+ parentId: null,+ solidFillHex: null,+ expressionColor: 'monochrome',+ monoExpressBlack: true,+ monoExpressWhite: false,+ layerColorEnabled: true,+ layerColor: '#1c73c2',+ layerSubColor: '#ffffff',+ tiles: [{ tx: 0, ty: 0, codec: 2, offset: 0, len: compTile.byteLength }],+ mask: null,+ },+ ],+ };++ const metaBytes = new TextEncoder().encode(JSON.stringify(meta));+ const wire = concatBytes([asciiBytes('INKD'), u32LE(1), u32LE(metaBytes.byteLength), metaBytes, compTile]);+ const doc = hydrateParsedDocumentBinary(wire, 'mori.clip');++ expect(doc.layers).toHaveLength(1);+ expect(doc.layers[0].expressionColor).toBe('monochrome');+ expect(doc.layers[0].monoExpressBlack).toBe(true);+ expect(doc.layers[0].monoExpressWhite).toBe(false);+ expect(doc.layers[0].layerColorEnabled).toBe(true);+ expect(doc.layers[0].layerColor).toBe('#1c73c2');+ expect(doc.layers[0].layerSubColor).toBe('#ffffff');+ const hydratedTile = doc.tileGrid!.getTile(doc.layers[0].id, 0, 0, 0);+ expect(hydratedTile).toBeDefined();+ expect(hydratedTile!.version).toBeGreaterThan(0);+ });+it('rejects .clip parsing gracefully outside Tauri (WASM sql.js removed)', async () => {await expect(parseCspFile(new ArrayBuffer(16), 'test.clip')).rejects.toThrow(/Rust backend/);});diff --git a/src/utils/__tests__/fileSaveDialog.test.ts b/src/utils/__tests__/fileSaveDialog.test.tsnew file mode 100644index 0000000..d2bbec7--- /dev/null+++ b/src/utils/__tests__/fileSaveDialog.test.ts@@ -0,0 +1,407 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockTauriInvoke = vi.fn();++vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+}));++import {+ getRememberedSaveDir,+ normalizePickerExtensions,+ rememberSaveDir,+ saveFileWithDialog,+} from '../fileSaveDialog';+import { exportBrushToInkbFile } from '../inkbBrushFormat';+import type { 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));+ },+ };+}++interface MockAnchorElement {+ href: string;+ download: string;+ style: Record<string, string>;+ click: ReturnType<typeof vi.fn>;+}++describe('fileSaveDialog', () => {+ const g = globalThis as unknown as Record<string, unknown>;+ let prevWindow: unknown;+ let prevDocument: unknown;+ let prevLocalStorage: unknown;+ let prevCreateObjectURL: typeof URL.createObjectURL;+ let prevRevokeObjectURL: typeof URL.revokeObjectURL;++ let mockWindow: Record<string, unknown>;+ let createdAnchors: MockAnchorElement[];++ beforeEach(() => {+ vi.clearAllMocks();+ prevWindow = g.window;+ prevDocument = g.document;+ prevLocalStorage = g.localStorage;+ prevCreateObjectURL = URL.createObjectURL;+ prevRevokeObjectURL = URL.revokeObjectURL;++ const storage = createMemoryStorage();+ createdAnchors = [];+ mockWindow = {+ localStorage: storage,+ };++ g.window = mockWindow;+ g.localStorage = storage;+ g.document = {+ createElement: vi.fn((tag: string) => {+ const el: MockAnchorElement = {+ href: '',+ download: '',+ style: {},+ click: vi.fn(),+ };+ if (tag === 'a') {+ createdAnchors.push(el);+ }+ return el;+ }),+ body: {+ appendChild: vi.fn(),+ removeChild: vi.fn(),+ },+ };+ });++ afterEach(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ if (prevWindow === undefined) delete g.window;+ else g.window = prevWindow;+ if (prevDocument === undefined) delete g.document;+ else g.document = prevDocument;+ if (prevLocalStorage === undefined) delete g.localStorage;+ else g.localStorage = prevLocalStorage;+ URL.createObjectURL = prevCreateObjectURL;+ URL.revokeObjectURL = prevRevokeObjectURL;+ });++ describe('normalizePickerExtensions', () => {+ it('normalizes single and multi-dot extensions cleanly', () => {+ expect(+ normalizePickerExtensions(['.inkb', 'INKTHEME', '.inkcolorset.json', '.json', ' ', ''])+ ).toEqual(['.inkb', '.inktheme', '.json']);+ });+ });++ describe('Tauri Desktop native OS Save As dialog', () => {+ beforeEach(() => {+ mockWindow.__TAURI_INTERNALS__ = {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ };+ });++ it('invokes native_save_file_with_dialog with headers and remembers last directory per category', async () => {+ mockTauriInvoke.mockResolvedValueOnce({+ saved: true,+ canceled: false,+ fileName: 'Ink_Pen.inkb',+ path: 'D:\\Art\\Brushes\\Ink_Pen.inkb',+ directory: 'D:\\Art\\Brushes',+ });++ const res1 = await saveFileWithDialog({+ data: new Uint8Array([1, 2, 3, 4]),+ suggestedName: 'Ink Pen.inkb',+ mimeType: 'application/octet-stream',+ description: 'Ink Studio Brush',+ extensions: ['.inkb'],+ category: 'brush',+ title: 'Save Brush As',+ });++ expect(res1).toEqual({+ saved: true,+ canceled: false,+ fileName: 'Ink_Pen.inkb',+ path: 'D:\\Art\\Brushes\\Ink_Pen.inkb',+ directory: 'D:\\Art\\Brushes',+ method: 'native-dialog',+ });++ expect(mockTauriInvoke).toHaveBeenCalledTimes(1);+ const [cmd, payload, opts] = mockTauriInvoke.mock.calls[0];+ expect(cmd).toBe('native_save_file_with_dialog');+ expect(payload).toBeInstanceOf(Uint8Array);+ expect(Array.from(payload as Uint8Array)).toEqual([1, 2, 3, 4]);+ expect((opts as { headers: Record<string, string> }).headers['x-suggested-name']).toBe(+ encodeURIComponent('Ink Pen.inkb')+ );+ expect((opts as { headers: Record<string, string> }).headers['x-extensions']).toBe('inkb');+ expect((opts as { headers: Record<string, string> }).headers['x-dialog-title']).toBe(+ encodeURIComponent('Save Brush As')+ );+ expect((opts as { headers: Record<string, string> }).headers['x-initial-dir']).toBeUndefined();++ expect(getRememberedSaveDir('brush')).toBe('D:\\Art\\Brushes');+ expect(getRememberedSaveDir('theme')).toBeNull();++ // Second save in the same category passes remembered initial directory+ mockTauriInvoke.mockResolvedValueOnce({+ saved: true,+ canceled: false,+ fileName: 'Watercolor.inkb',+ path: 'D:\\Art\\Brushes\\Watercolor.inkb',+ directory: 'D:\\Art\\Brushes',+ });++ await saveFileWithDialog({+ data: 'brush-data',+ suggestedName: 'Watercolor.inkb',+ description: 'Ink Studio Brush',+ extensions: ['.inkb'],+ category: 'brush',+ });++ const [, , opts2] = mockTauriInvoke.mock.calls[1];+ expect((opts2 as { headers: Record<string, string> }).headers['x-initial-dir']).toBe(+ encodeURIComponent('D:\\Art\\Brushes')+ );++ // Different category remembers its own folder independently+ rememberSaveDir('theme', 'D:\\Art\\Themes');+ mockTauriInvoke.mockResolvedValueOnce({+ saved: true,+ canceled: false,+ fileName: 'Dark.inktheme',+ path: 'D:\\Art\\Themes\\Dark.inktheme',+ directory: 'D:\\Art\\Themes',+ });+ await saveFileWithDialog({+ data: '{}',+ suggestedName: 'Dark.inktheme',+ description: 'Ink Studio Theme',+ extensions: ['.inktheme'],+ category: 'theme',+ });+ const [, , opts3] = mockTauriInvoke.mock.calls[2];+ expect((opts3 as { headers: Record<string, string> }).headers['x-initial-dir']).toBe(+ encodeURIComponent('D:\\Art\\Themes')+ );+ });++ it('respects user cancel in native dialog without falling back to web picker or download', async () => {+ const mockPicker = vi.fn();+ mockWindow.showSaveFilePicker = mockPicker;++ mockTauriInvoke.mockResolvedValueOnce({+ saved: false,+ canceled: true,+ });++ const res = await saveFileWithDialog({+ data: '{"theme":true}',+ suggestedName: 'MyTheme.inktheme',+ description: 'Ink Studio Theme',+ extensions: ['.inktheme'],+ category: 'theme',+ });++ expect(res.canceled).toBe(true);+ expect(res.saved).toBe(false);+ expect(res.method).toBe('native-dialog');+ expect(mockPicker).not.toHaveBeenCalled();+ expect(createdAnchors).toHaveLength(0);+ });+ });++ describe('Browser File System Access API (showSaveFilePicker)', () => {+ it('opens showSaveFilePicker with category id and writes payload', async () => {+ const write = vi.fn().mockResolvedValue(undefined);+ const close = vi.fn().mockResolvedValue(undefined);+ const mockPicker = vi.fn().mockResolvedValue({+ name: 'StudioLayout.inkworkspace',+ createWritable: vi.fn().mockResolvedValue({ write, close }),+ });+ mockWindow.showSaveFilePicker = mockPicker;++ const res = await saveFileWithDialog({+ data: '{"workspace":1}',+ suggestedName: 'StudioLayout.inkworkspace',+ mimeType: 'application/json;charset=utf-8',+ description: 'Ink Studio Workspace',+ extensions: ['.inkworkspace', '.json'],+ category: 'workspace',+ });++ expect(res).toEqual({+ saved: true,+ canceled: false,+ fileName: 'StudioLayout.inkworkspace',+ method: 'web-picker',+ });+ expect(mockPicker).toHaveBeenCalledWith({+ suggestedName: 'StudioLayout.inkworkspace',+ id: 'inkstudio-workspace',+ types: [+ {+ description: 'Ink Studio Workspace',+ accept: { 'application/json': ['.inkworkspace', '.json'] },+ },+ ],+ });+ expect(write).toHaveBeenCalledTimes(1);+ expect(close).toHaveBeenCalledTimes(1);+ });++ it('treats AbortError as a clean cancel without falling back to anchor download', async () => {+ const abortErr = new DOMException('The user aborted a request.', 'AbortError');+ const mockPicker = vi.fn().mockRejectedValue(abortErr);+ mockWindow.showSaveFilePicker = mockPicker;++ const res = await saveFileWithDialog({+ data: '{}',+ suggestedName: 'Palette.inkcolorset.json',+ mimeType: 'application/json',+ description: 'Ink Studio Color Set',+ extensions: ['.inkcolorset.json'],+ category: 'color-set',+ });++ expect(res.canceled).toBe(true);+ expect(res.saved).toBe(false);+ expect(res.method).toBe('web-picker');+ expect(createdAnchors).toHaveLength(0);+ });++ it('retries showSaveFilePicker without restrictive types if custom extension throws TypeError', async () => {+ const write = vi.fn().mockResolvedValue(undefined);+ const close = vi.fn().mockResolvedValue(undefined);+ const mockPicker = vi+ .fn()+ .mockRejectedValueOnce(new TypeError('Invalid file extension'))+ .mockResolvedValueOnce({+ name: 'Custom.inkb',+ createWritable: vi.fn().mockResolvedValue({ write, close }),+ });+ mockWindow.showSaveFilePicker = mockPicker;++ const res = await saveFileWithDialog({+ data: new Uint8Array([9, 8, 7]),+ suggestedName: 'Custom.inkb',+ description: 'Ink Studio Brush',+ extensions: ['.inkb'],+ category: 'brush',+ });++ expect(res.saved).toBe(true);+ expect(res.method).toBe('web-picker');+ expect(mockPicker).toHaveBeenCalledTimes(2);+ expect(mockPicker.mock.calls[1][0]).toEqual({+ suggestedName: 'Custom.inkb',+ id: 'inkstudio-brush',+ });+ });+ });++ describe('Anchor download fallback', () => {+ it('triggers anchor download when neither Tauri nor showSaveFilePicker is available', async () => {+ URL.createObjectURL = vi.fn(() => 'blob:mock-url');+ URL.revokeObjectURL = vi.fn();++ const res = await saveFileWithDialog({+ data: 'hello',+ suggestedName: 'actions.json',+ mimeType: 'application/json',+ description: 'Auto Actions',+ extensions: ['.json'],+ category: 'auto-action',+ });++ expect(res).toEqual({+ saved: true,+ canceled: false,+ fileName: 'actions.json',+ method: 'download',+ });+ expect(createdAnchors).toHaveLength(1);+ expect(createdAnchors[0].download).toBe('actions.json');+ expect(createdAnchors[0].click).toHaveBeenCalledTimes(1);+ });++ it('does not download when fallbackToDownload is false', async () => {+ await expect(+ saveFileWithDialog({+ data: 'hello',+ suggestedName: 'doc.ink',+ description: 'Ink Project',+ extensions: ['.ink'],+ category: 'project',+ fallbackToDownload: false,+ })+ ).rejects.toThrow('Save dialog is not available');++ expect(createdAnchors).toHaveLength(0);+ });+ });++ describe('exportBrushToInkbFile integration', () => {+ it('routes .inkb export through native save dialog and handles cancel cleanly', async () => {+ mockWindow.__TAURI_INTERNALS__ = {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ };+ mockTauriInvoke.mockResolvedValueOnce({+ saved: false,+ canceled: true,+ });++ const brush: CspBrush = {+ id: 'test-ink-pen',+ name: 'Test Ink Pen',+ category: 'pen',+ badge: 'INKB',+ desc: 'Test',+ tipDataUrl:+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==',+ tipWidth: 1,+ tipHeight: 1,+ size: 16,+ minSizeFactor: 0.1,+ opacity: 1,+ flow: 1,+ spacing: 0.05,+ hardness: 0.9,+ thickness: 1,+ angle: 0,+ usePressure: true,+ smoothing: true,+ stabilization: 10,+ importedAt: Date.now(),+ };++ const res = await exportBrushToInkbFile(brush);+ expect(res.exported).toBe(false);+ expect(mockTauriInvoke).toHaveBeenCalledTimes(1);+ expect(mockTauriInvoke.mock.calls[0][0]).toBe('native_save_file_with_dialog');+ });+ });+});diff --git a/src/utils/__tests__/layerOrganization.test.tsx b/src/utils/__tests__/layerOrganization.test.tsxnew file mode 100644index 0000000..a7f33a9--- /dev/null+++ b/src/utils/__tests__/layerOrganization.test.tsx@@ -0,0 +1,609 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { LayerColorLabel, LayerItem } from '../../types/editor';+import { RightSidebar } from '../../components/RightSidebar';+import {+ DEFAULT_LAYER_FILTER_CRITERIA,+ computeBatchColorLabel,+ computeRestoreSolo,+ computeSoloToggle,+ filterLayerTree,+ fromPsdLayerColor,+ toPsdLayerColor,+} from '../layerOrganization';+import { sanitizeJsonLayer } from '../saveManager/types';+import { sanitizeWireLayerPatch } from '../collabSyncUtils';++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;+ 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 options(): MiniEl[] {+ return this.childNodes.filter(+ (c): c is MiniEl => c instanceof MiniEl && c.tagName === 'OPTION'+ );+ }++ selected = false;+ defaultSelected = false;++ 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: 200,+ height: 28,+ right: 200,+ bottom: 28,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ };+ }++ focus() {}+ blur() {}+ select() {}++ 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) break;+ cur = cur.parentNode;+ }+ return !event.defaultPrevented;+ }++ 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;+ }++ findAllByAttr(attr: string): MiniEl[] {+ const out: MiniEl[] = [];+ if (this.attrs.has(attr)) out.push(this);+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) out.push(...c.findAllByAttr(attr));+ }+ return out;+ }+}++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,+ 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>,+ 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 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),+ };+ mockDoc.defaultView = mockWin;++ g.window = mockWin;+ g.document = mockDoc;+ g.HTMLElement = MiniEl;+ g.Node = MiniEl;+ g.Element = MiniEl;++ 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 makeSampleLayers(): LayerItem[] {+ return [+ {+ id: 'folder-char',+ name: 'Character',+ type: 'folder',+ visible: true,+ opacity: 1,+ blendMode: 'pass-through',+ locked: false,+ collapsed: true, // Collapsed on purpose to test search revealing nested matches+ parentId: null,+ colorLabel: 'blue',+ },+ {+ id: 'layer-eyes',+ name: 'Eyes Highlight',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'add-glow',+ locked: false,+ parentId: 'folder-char',+ colorLabel: 'red',+ },+ {+ id: 'layer-inks',+ name: 'Lineart Inks',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: true,+ isReference: true,+ parentId: 'folder-char',+ colorLabel: 'green',+ },+ {+ id: 'layer-sketch',+ name: 'Rough Sketch',+ type: 'raster',+ visible: false, // Pre-hidden layer to verify solo restore preserves hidden state!+ opacity: 0.5,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ colorLabel: 'orange',+ },+ {+ id: 'layer-title',+ name: 'Title Text',+ type: 'text',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];+}++describe('Layer Organization Pure Logic (Search/Filter, Color Labels, Solo/Isolate)', () => {+ it('filters layers by search query, color label, and kind while preserving ancestor folders', () => {+ const layers = makeSampleLayers();++ // Name search for nested child inside collapsed folder+ const eyesRes = filterLayerTree(layers, {+ ...DEFAULT_LAYER_FILTER_CRITERIA,+ query: 'eyes',+ });+ expect(eyesRes.isActive).toBe(true);+ expect(eyesRes.matchCount).toBe(1);+ expect(eyesRes.directMatchIds.has('layer-eyes')).toBe(true);+ expect(eyesRes.ancestorOnlyIds.has('folder-char')).toBe(true);+ expect(eyesRes.visibleLayerIds.has('folder-char')).toBe(true);+ expect(eyesRes.visibleLayerIds.has('layer-eyes')).toBe(true);+ expect(eyesRes.visibleLayerIds.has('layer-bg')).toBe(false);++ // Filter by color label+ const redRes = filterLayerTree(layers, {+ ...DEFAULT_LAYER_FILTER_CRITERIA,+ colorLabel: 'red',+ });+ expect(redRes.matchCount).toBe(1);+ expect(redRes.directMatchIds.has('layer-eyes')).toBe(true);++ // Filter unlabeled layers ('none')+ const unlabeledRes = filterLayerTree(layers, {+ ...DEFAULT_LAYER_FILTER_CRITERIA,+ colorLabel: 'none',+ });+ expect(unlabeledRes.matchCount).toBe(2); // layer-title + layer-bg+ expect(unlabeledRes.directMatchIds.has('layer-title')).toBe(true);+ expect(unlabeledRes.directMatchIds.has('layer-bg')).toBe(true);++ // Filter by kind: hidden / locked / reference / text+ expect(+ filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'hidden' }).matchCount+ ).toBe(1);+ expect(+ filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'locked' }).matchCount+ ).toBe(1);+ expect(+ filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'reference' }).matchCount+ ).toBe(1);+ expect(+ filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'text' }).matchCount+ ).toBe(1);+ });++ it('batch-applies and clears layer color labels and round-trips through PSD, .ink, and collab sanitization', () => {+ const layers = makeSampleLayers();+ const updated = computeBatchColorLabel(+ layers,+ ['layer-title', 'layer-bg'],+ 'layer-title',+ 'purple'+ );+ expect(updated.find((l) => l.id === 'layer-title')?.colorLabel).toBe('purple');+ expect(updated.find((l) => l.id === 'layer-bg')?.colorLabel).toBe('purple');++ const cleared = computeBatchColorLabel(updated, ['layer-title'], 'layer-title', 'none');+ expect(cleared.find((l) => l.id === 'layer-title')?.colorLabel).toBeUndefined();++ // PSD color mapping parity+ expect(toPsdLayerColor('purple')).toBe('violet');+ expect(fromPsdLayerColor('violet')).toBe('purple');+ expect(toPsdLayerColor('red')).toBe('red');+ expect(fromPsdLayerColor('none')).toBeUndefined();++ // .ink JSON & collab wire sanitization+ expect(sanitizeJsonLayer({ id: 'x', colorLabel: 'cyan' }).colorLabel).toBe('cyan');+ expect(sanitizeJsonLayer({ id: 'x', colorLabel: 'invalid-color' }).colorLabel).toBeUndefined();+ expect(sanitizeWireLayerPatch({ colorLabel: 'orange' }).colorLabel).toBe('orange');+ });++ it('isolates a nested layer with ancestor preservation, switches solo targets cleanly, and restores exact pre-solo visibility', () => {+ const layers = makeSampleLayers();++ // 1. Alt+Click Eyes (nested inside Character folder) -> only Character + Eyes stay visible+ const step1 = computeSoloToggle(layers, 'layer-eyes', null);+ expect(step1.action).toBe('solo');+ expect(step1.nextSolo?.layerId).toBe('layer-eyes');+ expect(step1.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);+ expect(step1.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(true);+ expect(step1.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(false);+ expect(step1.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(false);+ expect(step1.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(false);++ // 2. Switch solo directly to Rough Sketch (which was originally hidden!) -> becomes visible, original snapshot preserved+ const step2 = computeSoloToggle(step1.nextLayers, 'layer-sketch', step1.nextSolo);+ expect(step2.action).toBe('switch-solo');+ expect(step2.nextSolo?.layerId).toBe('layer-sketch');+ expect(step2.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(true);+ expect(step2.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(false);+ expect(step2.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(false);++ // 3. Alt+Click Rough Sketch again -> restores ORIGINAL pre-solo visibility (Rough Sketch returns to false!)+ const step3 = computeSoloToggle(step2.nextLayers, 'layer-sketch', step2.nextSolo);+ expect(step3.action).toBe('restore');+ expect(step3.nextSolo).toBeNull();+ expect(step3.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(false);+ expect(step3.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);+ expect(step3.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(true);+ expect(step3.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(true);++ // 4. Soloing a folder isolates folder + preserves descendants' visibility while hiding outside layers+ const folderSolo = computeSoloToggle(layers, 'folder-char', null);+ expect(folderSolo.action).toBe('solo');+ expect(folderSolo.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(true);+ expect(folderSolo.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);+ expect(folderSolo.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(true);+ expect(folderSolo.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(false);++ // 5. Explicit restore helper restores cleanly+ const restored = computeRestoreSolo(folderSolo.nextLayers, folderSolo.nextSolo);+ expect(restored.nextSolo).toBeNull();+ expect(restored.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(true);+ });+});++describe('RightSidebar Layer Organization UI (Search/Filter, Color Labels, Alt+Click Solo)', () => {+ let dom: ReturnType<typeof installMiniDom>;+ let root: Root | null = null;++ beforeEach(() => {+ dom = installMiniDom();+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root?.unmount();+ });+ root = null;+ }+ dom.cleanup();+ });++ it('supports search/filter, color label picker, and Alt+Click solo with restore banner in RightSidebar', () => {+ const layers = makeSampleLayers();+ const onToggleVisibility = vi.fn();+ const onSoloLayer = vi.fn();+ const onExitSoloLayer = vi.fn();+ const onSetLayerColorLabel = vi.fn();++ const renderSidebar = (soloLayerId: string | null = null, currentLayers = layers) => {+ act(() => {+ if (!root) {+ root = createRoot(dom.container as unknown as Element);+ }+ root.render(+ <RightSidebar+ dockedMode="layers"+ hideColorPanel+ hasOpenDocument+ layers={currentLayers}+ activeLayerId="layer-eyes"+ soloLayerId={soloLayerId}+ historyList={[]}+ historyIndex={-1}+ onJumpToHistory={vi.fn()}+ canUndo={false}+ canRedo={false}+ onUndo={vi.fn()}+ onRedo={vi.fn()}+ onSelectLayer={vi.fn()}+ onAddLayer={vi.fn()}+ onDuplicateLayer={vi.fn()}+ onDeleteLayer={vi.fn()}+ onToggleVisibility={onToggleVisibility}+ onSoloLayer={onSoloLayer}+ onExitSoloLayer={onExitSoloLayer}+ onSetLayerColorLabel={onSetLayerColorLabel}+ onSetOpacity={vi.fn()}+ onSetBlendMode={vi.fn()}+ onToggleLock={vi.fn()}+ onToggleCollapse={vi.fn()}+ onRenameLayer={vi.fn()}+ onMoveLayerToFolder={vi.fn()}+ />+ );+ });+ };++ renderSidebar(null);++ // 1. Color label tags render on labeled rows+ expect(dom.container.findByAttr('data-testid', 'layer-color-tag-folder-char')).not.toBeNull();+ expect(dom.container.findByAttr('data-testid', 'layer-color-tag-layer-sketch')).not.toBeNull();++ // 2. Open Filter strip and filter by color label 'red' -> reveals nested 'layer-eyes' inside collapsed 'folder-char'+ act(() => {+ dom.container+ .findByAttr('data-testid', 'layer-filter-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(dom.container.findByAttr('data-testid', 'layer-filter-strip')).not.toBeNull();++ act(() => {+ dom.container+ .findByAttr('data-testid', 'layer-filter-color-red')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ const redFilteredRows = dom.container+ .findByAttr('data-testid', 'layers-scroll-stack')!+ .findAllByAttr('data-layer-id')+ .map((el) => el.getAttribute('data-layer-id'));+ expect(redFilteredRows).toEqual(['folder-char', 'layer-eyes']);++ // Reset filter+ act(() => {+ dom.container+ .findByAttr('data-testid', 'layer-filter-reset')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });++ // 3. Assign color label from active-layer quick picker+ act(() => {+ dom.container+ .findByAttr('data-testid', 'active-layer-color-label-btn')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ act(() => {+ dom.container+ .findByAttr('data-testid', 'active-color-label-option-purple')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(onSetLayerColorLabel).toHaveBeenCalledWith('layer-eyes', 'purple');++ // 4. Normal eye click calls onToggleVisibility; Alt+Click eye calls onSoloLayer+ const bgEyeBtn = dom.container.findByAttr('data-testid', 'layer-eye-layer-bg')!;+ act(() => {+ bgEyeBtn.dispatchEvent(Object.assign(new Event('click', { bubbles: true }), { altKey: false }));+ });+ expect(onToggleVisibility).toHaveBeenCalledWith('layer-bg');+ expect(onSoloLayer).not.toHaveBeenCalled();++ act(() => {+ bgEyeBtn.dispatchEvent(Object.assign(new Event('click', { bubbles: true }), { altKey: true }));+ });+ expect(onSoloLayer).toHaveBeenCalledWith('layer-bg');++ // 5. Render with soloLayerId active -> displays Solo banner and Restore button+ renderSidebar('layer-bg');+ const banner = dom.container.findByAttr('data-testid', 'layer-solo-banner');+ expect(banner).not.toBeNull();+ expect(banner?.textContent).toContain('Background');+ expect(+ dom.container.findByAttr('data-testid', 'layer-eye-layer-bg')?.getAttribute('data-solo-active')+ ).toBe('true');++ act(() => {+ dom.container+ .findByAttr('data-testid', 'layer-solo-restore-btn')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(onExitSoloLayer).toHaveBeenCalledTimes(1);++ // 6. Right-click context menu exposes color labels and solo button+ const bgRow = dom.container.findByAttr('data-layer-id', 'layer-bg')!;+ act(() => {+ bgRow.dispatchEvent(+ Object.assign(new Event('contextmenu', { bubbles: true }), { clientX: 100, clientY: 120 })+ );+ });+ expect(dom.container.findByAttr('data-testid', 'context-menu-color-labels')).not.toBeNull();+ act(() => {+ dom.container+ .findByAttr('data-testid', 'context-color-label-cyan')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(onSetLayerColorLabel).toHaveBeenCalledWith('layer-bg', 'cyan' satisfies LayerColorLabel);+ });+});diff --git a/src/utils/__tests__/mangaTextEngine.test.ts b/src/utils/__tests__/mangaTextEngine.test.tsindex a57b11c..419c45a 100644--- a/src/utils/__tests__/mangaTextEngine.test.ts+++ b/src/utils/__tests__/mangaTextEngine.test.ts@@ -1,5 +1,9 @@-import { describe, it, expect } from 'vitest';-import { computeMangaTextLayout, isLatinChar } from '../mangaTextEngine';+import { describe, it, expect, vi } from 'vitest';+import {+ computeMangaTextLayout,+ isLatinChar,+ renderMangaTextToCanvas,+} from '../mangaTextEngine';describe('Manga Text Engine (Tate-gaki & Yokogaki)', () => {it('correctly identifies Latin characters', () => {@@ -61,4 +65,98 @@ describe('Manga Text Engine (Tate-gaki & Yokogaki)', () => {expect(dash!.rotateDeg).toBe(90);expect(kanji!.rotateDeg).toBe(0);});++ it('uses proportional character widths rather than fixed monospace spacing in horizontal mode', () => {+ const narrow = computeMangaTextLayout('iiiii', {+ fontSize: 36,+ fontFamily: "Inter, 'Segoe UI', sans-serif",+ writingMode: 'horizontal-tb',+ });+ const wide = computeMangaTextLayout('WWWWW', {+ fontSize: 36,+ fontFamily: "Inter, 'Segoe UI', sans-serif",+ writingMode: 'horizontal-tb',+ });++ expect(wide.width).toBeGreaterThan(narrow.width * 1.5);+ expect(narrow.lines).toHaveLength(1);+ expect(wide.lines).toHaveLength(1);+ });++ it('wraps horizontal paragraphs cleanly when maxWidth is specified', () => {+ const layout = computeMangaTextLayout('Ink Studio creates natural authentic typography', {+ fontSize: 24,+ fontFamily: 'Arial, sans-serif',+ writingMode: 'horizontal-tb',+ maxWidth: 160,+ });++ expect(layout.lines.length).toBeGreaterThan(2);+ expect(layout.lines.map((l) => l.text).join(' ')).toContain('natural');+ expect(layout.height).toBeGreaterThan(layout.lineHeight * 2);+ });++ it('renders plain white text without outlines by default and uses two-pass outline-then-fill when outline is enabled', () => {+ const callOrder: string[] = [];+ const fillStyles: string[] = [];+ const mockCtx = {+ save: vi.fn(),+ restore: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ stroke: vi.fn(),+ fillRect: vi.fn(),+ measureText: vi.fn((s: string) => ({ width: s.length * 10 })),+ strokeText: vi.fn((text: string) => {+ callOrder.push(`stroke:${text}`);+ }),+ fillText: vi.fn((text: string) => {+ callOrder.push(`fill:${text}`);+ fillStyles.push(String(mockCtx.fillStyle));+ }),+ font: '',+ fillStyle: '',+ strokeStyle: '',+ lineWidth: 1,+ lineJoin: 'miter',+ lineCap: 'butt',+ miterLimit: 10,+ textAlign: 'left',+ textBaseline: 'alphabetic',+ globalAlpha: 1,+ } as unknown as CanvasRenderingContext2D;++ // Plain white without outline+ renderMangaTextToCanvas(mockCtx, 'Hello\nWorld', 100, 120, {+ fontSize: 36,+ fontFamily: 'Arial, sans-serif',+ outline: false,+ anchorTopLeft: true,+ });++ expect(callOrder).toEqual(['fill:Hello', 'fill:World']);+ expect(fillStyles).toEqual(['#ffffff', '#ffffff']);++ // Two-pass outline: ALL strokes before ANY fills+ callOrder.length = 0;+ renderMangaTextToCanvas(mockCtx, 'Line 1\nLine 2', 100, 120, {+ fontSize: 36,+ fontFamily: 'Arial, sans-serif',+ color: '#ffffff',+ outline: true,+ outlineColor: '#000000',+ outlineWidth: 3,+ anchorTopLeft: true,+ });++ expect(callOrder).toEqual([+ 'stroke:Line 1',+ 'stroke:Line 2',+ 'fill:Line 1',+ 'fill:Line 2',+ ]);+ });});diff --git a/src/utils/__tests__/naturalPaintEngine.test.ts b/src/utils/__tests__/naturalPaintEngine.test.tsindex 4d6f041..2438b24 100644--- a/src/utils/__tests__/naturalPaintEngine.test.ts+++ b/src/utils/__tests__/naturalPaintEngine.test.ts@@ -603,9 +603,9 @@ describe('Natural Paint Engine — Bristles, Spatial Mixing, Surface Textures &expect(parsedV1.size).toBe(10);});- it('provides all 9 calibrated Natural Paint presets with valid surface textures, bristle profiles, and settings', () => {+ it('provides all 13 calibrated Natural Paint presets with valid surface textures, bristle profiles, and settings', () => {const naturalDefs = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint');- expect(naturalDefs.length).toBe(9);+ expect(naturalDefs.length).toBe(13);for (const def of naturalDefs) {const cfg = getBuiltinBrushConfig(def.id);diff --git a/src/utils/__tests__/navigatorAndSubView.test.tsx b/src/utils/__tests__/navigatorAndSubView.test.tsxindex aa54417..e7e32de 100644--- a/src/utils/__tests__/navigatorAndSubView.test.tsx+++ b/src/utils/__tests__/navigatorAndSubView.test.tsx@@ -471,7 +471,7 @@ describe('Navigator & Sub View Dock Integration and Presets', () => {expect(ALL_DOCK_PANEL_IDS).toContain('navigator');expect(ALL_DOCK_PANEL_IDS).toContain('sub-view');expect(DOCK_PANEL_META.navigator.title).toBe('Navigator');- expect(DOCK_PANEL_META['sub-view'].title).toBe('Sub View');+ expect(DOCK_PANEL_META['sub-view'].title).toBe('References');for (const preset of ['default-illustration', 'manga-studio', 'minimalist-tablet'] as const) {const layout = getPresetLayout(preset);@@ -766,6 +766,13 @@ describe('SubViewPanel Reference Management, Transforms & CORS-Safe Eyedropper',root.render(<SubViewPanel colorMode="color" themePreset="modern" />);});+ // Switch to Single Focus mode to verify single-image per-item transforms & eyedropper+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-mode-single')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().viewMode).toBe('single');expect(dom.container.findByAttr('data-testid', 'subview-counter')?.textContent).toBe('2/2');// Navigate to previous reference (<)diff --git a/src/utils/__tests__/osFileOpen.test.ts b/src/utils/__tests__/osFileOpen.test.tsnew file mode 100644index 0000000..8b07af5--- /dev/null+++ b/src/utils/__tests__/osFileOpen.test.ts@@ -0,0 +1,123 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ OPEN_FILES_EVENT,+ findOpenDocumentBySourcePath,+ listenForOpenFiles,+ normalizePathForComparison,+ takePendingOpenFiles,+} from '../osFileOpen';+import { DocumentTab } from '../../types/editor';++const mockInvoke = vi.fn();+const mockListen = vi.fn();++vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => mockInvoke(...args),+}));++vi.mock('@tauri-apps/api/event', () => ({+ listen: (...args: unknown[]) => mockListen(...args),+}));++function makeTab(id: string, name: string, sourcePath?: string, savedPath?: string): DocumentTab {+ return {+ id,+ name,+ dimensions: { width: 1920, height: 1080, dpi: 300 },+ colorMode: 'color',+ layers: [],+ activeLayerId: 'layer-1',+ sourcePath,+ savedFileInfo: savedPath+ ? { name, path: savedPath, extension: '.ink' }+ : undefined,+ };+}++describe('OS file-open & single-instance path handling', () => {+ const g = globalThis as unknown as Record<string, unknown>;+ const savedWindow = g.window;++ beforeEach(() => {+ mockInvoke.mockReset();+ mockListen.mockReset();+ });++ afterEach(() => {+ if (savedWindow === undefined) {+ delete g.window;+ } else {+ g.window = savedWindow;+ }+ });++ it('normalizes Windows verbatim prefixes, slashes, and drive casing consistently', () => {+ expect(normalizePathForComparison('\\\\?\\C:\\Users\\Artist\\Chapter 1.ink')).toBe(+ 'c:/users/artist/chapter 1.ink'+ );+ expect(normalizePathForComparison('C:/Users/Artist/Chapter 1.ink')).toBe(+ 'c:/users/artist/chapter 1.ink'+ );+ expect(normalizePathForComparison('\\\\?\\UNC\\Server\\Share\\Art.ink')).toBe(+ '//server/share/art.ink'+ );+ expect(normalizePathForComparison('/Users/artist/Art.ink')).toBe('/Users/artist/Art.ink');+ expect(normalizePathForComparison('')).toBe('');+ });++ it('matches already-open document tabs by sourcePath or savedFileInfo.path to prevent duplicate tabs', () => {+ const docs: DocumentTab[] = [+ makeTab('doc-1', 'Cover.ink', 'C:\\Projects\\Manga\\Cover.ink'),+ makeTab('doc-2', 'Page 2.ink', undefined, '\\\\?\\C:\\Projects\\Manga\\Page 2.ink'),+ ];++ expect(findOpenDocumentBySourcePath(docs, 'c:/projects/manga/cover.ink')?.id).toBe('doc-1');+ expect(findOpenDocumentBySourcePath(docs, '\\\\?\\C:\\Projects\\Manga\\Cover.ink')?.id).toBe(+ 'doc-1'+ );+ expect(findOpenDocumentBySourcePath(docs, 'C:\\Projects\\Manga\\PAGE 2.INK')?.id).toBe('doc-2');+ expect(findOpenDocumentBySourcePath(docs, 'C:\\Projects\\Manga\\Page 3.ink')).toBeUndefined();+ });++ it('returns empty array and no-op unlisten outside Tauri desktop environment', async () => {+ g.window = {};+ expect(await takePendingOpenFiles()).toEqual([]);+ const unlisten = await listenForOpenFiles(() => {});+ expect(typeof unlisten).toBe('function');+ expect(mockInvoke).not.toHaveBeenCalled();+ expect(mockListen).not.toHaveBeenCalled();+ });++ it('drains cold-launch pending .ink files and forwards warm single-instance events in Tauri', async () => {+ g.window = { __TAURI_INTERNALS__: {} };++ mockInvoke.mockResolvedValueOnce(['C:\\Art\\LaunchDoc.ink', '', 'C:\\Art\\Second.ink']);+ const pending = await takePendingOpenFiles();+ expect(mockInvoke).toHaveBeenCalledWith('take_pending_open_files');+ expect(pending).toEqual(['C:\\Art\\LaunchDoc.ink', 'C:\\Art\\Second.ink']);++ let capturedHandler: ((event: { payload: string[] }) => void) | null = null;+ const mockUnlisten = vi.fn();+ mockListen.mockImplementationOnce(+ async (eventName: string, cb: (event: { payload: string[] }) => void) => {+ expect(eventName).toBe(OPEN_FILES_EVENT);+ capturedHandler = cb;+ return mockUnlisten;+ }+ );++ const received: string[][] = [];+ const unlisten = await listenForOpenFiles((paths) => {+ received.push(paths);+ });++ expect(capturedHandler).not.toBeNull();+ capturedHandler!({ payload: ['C:\\Art\\WarmOpened.ink'] });+ capturedHandler!({ payload: [] });+ capturedHandler!({ payload: ['C:\\Art\\WarmOpened2.ink', ' '] });++ expect(received).toEqual([['C:\\Art\\WarmOpened.ink'], ['C:\\Art\\WarmOpened2.ink']]);+ unlisten();+ expect(mockUnlisten).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/utils/__tests__/recovery.test.ts b/src/utils/__tests__/recovery.test.tsindex b85deff..6260249 100644--- a/src/utils/__tests__/recovery.test.ts+++ b/src/utils/__tests__/recovery.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import {computeCrc32,formatWalFrame,@@ -473,4 +473,67 @@ describe('Crash Recovery & WAL Architecture Engine', () => {expect(emptySnapDecoded.wal_entries).toEqual([]);});});++ describe('discardAllCrashedSessions', () => {+ const prevWindow = (globalThis as Record<string, unknown>).window;++ afterEach(() => {+ (globalThis as Record<string, unknown>).window = prevWindow;+ vi.restoreAllMocks();+ });++ it('deduplicates and discards all sessions in non-Tauri environments', async () => {+ (globalThis as Record<string, unknown>).window = {};+ const result = await recoveryService.discardAllCrashedSessions([+ 'sess-a',+ 'sess-b',+ 'sess-a',+ '',+ ]);+ expect(result).toEqual({+ discardedIds: ['sess-a', 'sess-b'],+ failedIds: [],+ });+ });++ it('invokes recovery_close_session for every unique session and reports partial failures cleanly', async () => {+ (globalThis as Record<string, unknown>).window = { __TAURI_INTERNALS__: {} };+ const mockInvoke = vi.fn(async (_cmd: string, args?: { sessionId?: string }) => {+ if (args?.sessionId === 'sess-fail') {+ throw new Error('disk locked');+ }+ });+ const serviceAny = recoveryService as unknown as {+ invokePromise: Promise<typeof mockInvoke> | null;+ };+ const prevInvokePromise = serviceAny.invokePromise;+ serviceAny.invokePromise = Promise.resolve(mockInvoke);++ try {+ const result = await recoveryService.discardAllCrashedSessions([+ 'sess-1',+ 'sess-fail',+ 'sess-2',+ 'sess-1',+ ]);++ expect(mockInvoke).toHaveBeenCalledTimes(3);+ expect(mockInvoke).toHaveBeenNthCalledWith(1, 'recovery_close_session', {+ sessionId: 'sess-1',+ });+ expect(mockInvoke).toHaveBeenNthCalledWith(2, 'recovery_close_session', {+ sessionId: 'sess-fail',+ });+ expect(mockInvoke).toHaveBeenNthCalledWith(3, 'recovery_close_session', {+ sessionId: 'sess-2',+ });+ expect(result).toEqual({+ discardedIds: ['sess-1', 'sess-2'],+ failedIds: ['sess-fail'],+ });+ } finally {+ serviceAny.invokePromise = prevInvokePromise;+ }+ });+ });});diff --git a/src/utils/__tests__/saveFileOptimization.test.ts b/src/utils/__tests__/saveFileOptimization.test.tsnew file mode 100644index 0000000..f695969--- /dev/null+++ b/src/utils/__tests__/saveFileOptimization.test.ts@@ -0,0 +1,288 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { LayerItem } from '../../types/editor';+import { SparseTileGrid, setPixel1Bit } from '../tileEngine';++const mockTauriInvoke = vi.fn();++vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+}));++import {+ buildCleanFileName,+ getParentDirectory,+ normalizeSavedFileName,+ parseInkProject,+ promptSaveAs,+ sanitizeDocumentStem,+ saveToExistingHandle,+ stripDocumentExtensions,+} from '../saveManager';+import { loadRecentDocuments, saveRecentDocument } from '../recentDocumentsManager';++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 makeTestSaveDoc(name: string) {+ const grid = new SparseTileGrid();+ const tile = grid.getOrCreateTile('layer-1', 0, 0, 'monochrome-1bit', 0);+ setPixel1Bit(tile.data!, 4, 4, 1);+ grid.setLayerFormat('layer-1', 'monochrome-1bit');++ const layers: LayerItem[] = [+ {+ id: 'layer-1',+ name: 'Ink Lineart',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ },+ ];++ return {+ name,+ dimensions: { width: 256, height: 256, dpi: 300 },+ colorMode: 'monochrome' as const,+ layers,+ tileGrid: grid,+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ };+}++describe('File saving, resaving, and filename extension hygiene', () => {+ const g = globalThis as unknown as Record<string, unknown>;+ let prevWindow: unknown;+ let prevLocalStorage: unknown;++ beforeEach(() => {+ mockTauriInvoke.mockReset();+ prevWindow = g.window;+ prevLocalStorage = g.localStorage;+ const storage = createMemoryStorage();+ g.localStorage = storage;+ g.window = {+ localStorage: storage,+ __TAURI_INTERNALS__: {},+ };+ });++ afterEach(() => {+ if (prevWindow === undefined) delete g.window;+ else g.window = prevWindow;+ if (prevLocalStorage === undefined) delete g.localStorage;+ else g.localStorage = prevLocalStorage;+ });++ describe('filename & extension hygiene', () => {+ it('strips endlessly chained extensions while preserving version numbers and Unicode names', () => {+ expect(stripDocumentExtensions('Hero.ink.ink.ink.png.ink')).toBe('Hero');+ expect(stripDocumentExtensions('Hero.ink.ink.ink.png.ink*')).toBe('Hero');+ expect(stripDocumentExtensions('Chapter 1.2 (Final).ink')).toBe('Chapter 1.2 (Final)');+ expect(stripDocumentExtensions('イラスト.psd.png.ink')).toBe('イラスト');+ expect(stripDocumentExtensions('Untitled*')).toBe('Untitled');+ expect(stripDocumentExtensions('C:\\Projects\\Manga\\Page 04.ink.png')).toBe('Page 04');+ });++ it('builds clean single-extension filenames and normalizes saved names', () => {+ expect(sanitizeDocumentStem('My:Art?.ink.png.ink')).toBe('MyArt');+ expect(sanitizeDocumentStem('イラスト v2.1.ink')).toBe('イラスト v2.1');+ expect(buildCleanFileName('Hero.ink.ink.ink.png.ink', '.ink')).toBe('Hero.ink');+ expect(buildCleanFileName('Hero.ink', '.png')).toBe('Hero.png');+ expect(buildCleanFileName('Untitled*', '.ink')).toBe('Untitled.ink');++ expect(normalizeSavedFileName('Hero.ink.png', '.png')).toEqual({+ fileName: 'Hero.png',+ stem: 'Hero',+ extension: '.png',+ });+ expect(normalizeSavedFileName('Hero.png.ink', '.ink')).toEqual({+ fileName: 'Hero.ink',+ stem: 'Hero',+ extension: '.ink',+ });+ expect(normalizeSavedFileName('Chapter 1.2.ink', '.ink')).toEqual({+ fileName: 'Chapter 1.2.ink',+ stem: 'Chapter 1.2',+ extension: '.ink',+ });+ });++ it('extracts parent directories across Windows and POSIX paths', () => {+ expect(getParentDirectory('C:\\Projects\\Art\\Hero.ink')).toBe('C:\\Projects\\Art');+ expect(getParentDirectory('C:\\Hero.ink')).toBe('C:\\');+ expect(getParentDirectory('/Users/artist/Hero.ink')).toBe('/Users/artist');+ expect(getParentDirectory('Hero.ink')).toBeUndefined();+ });+ });++ describe('Tauri pick-first promptSaveAs & atomic direct resave', () => {+ it('canceling Save As performs zero serialization work', async () => {+ const onProgress = vi.fn();+ mockTauriInvoke.mockImplementation(async (cmd: string) => {+ if (cmd === 'scratch_disk_init') return undefined;+ if (cmd === 'native_pick_save_path') {+ return {+ canceled: true,+ fileName: null,+ path: null,+ directory: null,+ extension: null,+ filterIndex: 0,+ };+ }+ throw new Error(`Unexpected invoke: ${cmd}`);+ });++ const docData = { ...makeTestSaveDoc('Hero.ink.ink'), onProgress };+ await expect(promptSaveAs(docData, '.ink', false)).rejects.toThrow('Save canceled');++ const saveCalls = mockTauriInvoke.mock.calls.filter(([cmd]) => cmd !== 'scratch_disk_init');+ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0]).toEqual([+ 'native_pick_save_path',+ expect.objectContaining({ suggestedName: 'Hero', defaultFilterIndex: 0 }),+ ]);+ expect(onProgress).not.toHaveBeenCalled();+ });++ it('heals chained extensions on Save As, embeds clean manifest.name, and resaves repeatedly without extension growth', async () => {+ let lastWrittenBytes: Uint8Array | null = null;+ let lastWrittenPath = '';++ mockTauriInvoke.mockImplementation(+ async (cmd: string, payload?: unknown, options?: { headers?: Record<string, string> }) => {+ if (cmd === 'scratch_disk_init') return undefined;+ if (cmd === 'native_pick_save_path') {+ const args = payload as { suggestedName: string };+ expect(args.suggestedName).toBe('Hero');+ return {+ canceled: false,+ fileName: 'Hero.ink',+ path: 'C:\\Art\\Hero.ink',+ directory: 'C:\\Art',+ extension: '.ink',+ filterIndex: 0,+ };+ }+ if (cmd === 'write_allowed_file_binary') {+ lastWrittenBytes = payload as Uint8Array;+ lastWrittenPath = decodeURIComponent(options?.headers?.['x-path'] || '');+ return lastWrittenBytes.byteLength;+ }+ throw new Error(`Unexpected invoke: ${cmd}`);+ }+ );++ // Start from a mangled document name as reported after many restarts+ const docData = makeTestSaveDoc('Hero.ink.ink.ink.png.ink');+ const saved = await promptSaveAs(docData, '.ink', false);++ expect(saved.name).toBe('Hero.ink');+ expect(saved.path).toBe('C:\\Art\\Hero.ink');+ expect(saved.extension).toBe('.ink');+ expect(lastWrittenPath).toBe('C:\\Art\\Hero.ink');+ expect(lastWrittenBytes).not.toBeNull();++ // Verify manifest.name inside the saved .ink archive is clean ("Hero", not "Hero.ink.ink...")+ const parsed1 = await parseInkProject(lastWrittenBytes!);+ expect(parsed1.name).toBe('Hero');++ // Perform 5 consecutive direct Ctrl+S resaves and verify filename & manifest stay 100% clean+ mockTauriInvoke.mockClear();+ for (let i = 0; i < 5; i++) {+ const res = await saveToExistingHandle({ ...docData, name: saved.name }, saved);+ expect(res.size).toBeGreaterThan(0);+ }++ // Never triggered Save As dialog during direct resaves+ const resaveCalls = mockTauriInvoke.mock.calls.filter(([cmd]) => cmd !== 'scratch_disk_init');+ expect(resaveCalls).toHaveLength(5);+ for (const call of resaveCalls) {+ expect(call[0]).toBe('write_allowed_file_binary');+ }+ expect(lastWrittenPath).toBe('C:\\Art\\Hero.ink');++ const parsedAfter5 = await parseInkProject(lastWrittenBytes!);+ expect(parsedAfter5.name).toBe('Hero');+ });++ it('verifies FileSystemFileHandle readwrite permission before saving in browser mode', async () => {+ g.window = { localStorage: g.localStorage };+ const write = vi.fn().mockResolvedValue(undefined);+ const close = vi.fn().mockResolvedValue(undefined);+ const queryPermission = vi.fn().mockResolvedValue('prompt');+ const requestPermission = vi.fn().mockResolvedValue('granted');+ const createWritable = vi.fn().mockResolvedValue({ write, close });++ const docData = makeTestSaveDoc('Sketch.ink.ink');+ const res = await saveToExistingHandle(docData, {+ name: 'Sketch.ink',+ extension: '.ink',+ handle: { queryPermission, requestPermission, createWritable },+ });++ expect(queryPermission).toHaveBeenCalledWith({ mode: 'readwrite' });+ expect(requestPermission).toHaveBeenCalledWith({ mode: 'readwrite' });+ expect(createWritable).toHaveBeenCalledTimes(1);+ expect(write).toHaveBeenCalledTimes(1);+ expect(close).toHaveBeenCalledTimes(1);+ expect(res.size).toBeGreaterThan(0);+ });+ });++ describe('Recent documents deduplication on resave across restarts', () => {+ it('deduplicates entries sharing the same disk path and preserves starred state', async () => {+ await saveRecentDocument({+ id: 'session-1',+ title: 'Hero.ink',+ path: 'C:\\Art\\Hero.ink',+ size: 102400,+ isStarred: true,+ isSaved: true,+ fileType: '.ink',+ });++ // Simulate restart -> new session id saving the same disk path (with different casing/slashes)+ await saveRecentDocument({+ id: 'session-2',+ title: 'Hero.ink',+ path: 'c:/art/hero.ink',+ size: 204800,+ isStarred: false,+ isSaved: true,+ fileType: '.ink',+ });++ const docs = await loadRecentDocuments();+ expect(docs).toHaveLength(1);+ expect(docs[0].id).toBe('session-2');+ expect(docs[0].size).toBe(204800);+ expect(docs[0].isStarred).toBe(true);+ });+ });+});diff --git a/src/utils/__tests__/subView2References.test.tsx b/src/utils/__tests__/subView2References.test.tsxnew file mode 100644index 0000000..dd422e4--- /dev/null+++ b/src/utils/__tests__/subView2References.test.tsx@@ -0,0 +1,747 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ SUB_VIEW_STORAGE_KEY,+ subViewStoreActions,+ useSubViewStore,+} from '../../stores/useSubViewStore';+import { useToolStore } from '../../stores/useToolStore';+import { SubViewPanel } from '../../components/SubViewPanel';+import {+ BoardCardGeometry,+ SubViewTransform,+ applyStudyFilterToImageData,+ boardPointToCardLocal,+ boardPointToStagePoint,+ cardLocalToBoardPoint,+ computeBoardAutoLayout,+ computeBoardFitTransform,+ extractDominantColorsFromCanvas,+ getCardStageOverlay,+ hitTestBoardCards,+ hitTestCardHandle,+ stagePointToBoardPoint,+} from '../subViewEngine';++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(pixelColor: [number, number, number, number] = [230, 90, 40, 255]) {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ setTransform: vi.fn(),+ clearRect: vi.fn(),+ fillRect: vi.fn(),+ strokeRect: vi.fn(),+ beginPath: vi.fn(),+ rect: vi.fn(),+ clip: vi.fn(),+ arc: 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(),+ createImageData: (w: number, h: number) => ({+ data: new Uint8ClampedArray(w * h * 4),+ width: w,+ height: h,+ }),+ putImageData: vi.fn(),+ getImageData: vi.fn((_x: number, _y: number, w: number, h: number) => {+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = pixelColor[0];+ data[i + 1] = pixelColor[1];+ data[i + 2] = pixelColor[2];+ data[i + 3] = pixelColor[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 = 240;+ height = 180;+ clientWidth = 240;+ clientHeight = 180;+ attrs = new Map<string, string>();+ private 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) break;+ cur = cur.parentNode;+ }+ return !event.defaultPrevented;+ }++ getContext(type: string) {+ if (type === '2d') {+ if (!this.mockCtx) this.mockCtx = createMock2DContext(this.ownerDocument.mockSampleColor);+ 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;+ }++ findAllByAttrPrefix(attr: string, prefix: string): MiniEl[] {+ const out: MiniEl[] = [];+ const val = this.getAttribute(attr);+ if (val && val.startsWith(prefix)) out.push(this);+ for (const c of this.childNodes) {+ if (c instanceof MiniEl) {+ out.push(...c.findAllByAttrPrefix(attr, prefix));+ }+ }+ return out;+ }+}++interface MiniDoc {+ nodeType: number;+ nodeName: string;+ documentElement: MiniEl;+ body: MiniEl;+ activeElement: MiniEl;+ defaultView: Record<string, unknown>;+ mockSampleColor: [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(sampleColor: [number, number, number, number] = [230, 90, 40, 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,+ Image: g.Image,+ 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>,+ mockSampleColor: sampleColor,+ 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 MockImage {+ naturalWidth = 100;+ naturalHeight = 100;+ width = 100;+ height = 100;+ crossOrigin = '';+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ private _src = '';+ get src() {+ return this._src;+ }+ set src(val: string) {+ this._src = val;+ if (val && this.onload) this.onload();+ }+ }++ class MockIFrame extends MiniEl {}+ const rafMock = (cb: FrameRequestCallback) => {+ cb(16);+ return 1;+ };++ 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: () => {},+ };+ mockDoc.defaultView = mockWin;++ g.window = mockWin;+ g.document = mockDoc;+ g.HTMLElement = MiniEl;+ g.Node = MiniEl;+ g.Element = MiniEl;+ g.Image = MockImage;+ g.requestAnimationFrame = rafMock;+ g.cancelAnimationFrame = () => {};++ 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;+ }+ },+ };+}++describe('Sub View 2.0 PureRef Board Engine & Study Filters', () => {+ it('round-trips board <-> stage and board <-> card local coordinates under rotation, zoom, pan, and flipX', () => {+ const transforms: SubViewTransform[] = [+ { zoom: 1, pan: { x: 0, y: 0 }, rotation: 0, flipX: false },+ { zoom: 1.75, pan: { x: 42, y: -28 }, rotation: 33, flipX: false },+ { zoom: 0.65, pan: { x: -18, y: 55 }, rotation: -72, flipX: true },+ ];++ for (const t of transforms) {+ const pt = { x: 37.5, y: -61.2 };+ const stagePt = boardPointToStagePoint(pt.x, pt.y, 320, 240, t);+ const back = stagePointToBoardPoint(stagePt.x, stagePt.y, 320, 240, t);+ expect(back.x).toBeCloseTo(pt.x, 4);+ expect(back.y).toBeCloseTo(pt.y, 4);+ }++ const card: BoardCardGeometry = {+ id: 'c1',+ width: 200,+ height: 100,+ boardX: 50,+ boardY: -30,+ boardScale: 1.5,+ boardRotation: 40,+ boardFlipX: true,+ boardFlipY: false,+ zIndex: 1,+ };+ const bPt = cardLocalToBoardPoint(25, -15, card);+ const backLocal = boardPointToCardLocal(bPt.x, bPt.y, card);+ expect(backLocal.x).toBeCloseTo(25, 4);+ expect(backLocal.y).toBeCloseTo(-15, 4);+ });++ it('hit-tests overlapping PureRef cards by highest zIndex and detects resize/rotate handles cleanly', () => {+ const boardTransform: SubViewTransform = {+ zoom: 1,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+ };+ const cards: BoardCardGeometry[] = [+ {+ id: 'back',+ width: 100,+ height: 100,+ boardX: 0,+ boardY: 0,+ boardScale: 1,+ boardRotation: 0,+ boardFlipX: false,+ boardFlipY: false,+ zIndex: 1,+ },+ {+ id: 'front',+ width: 100,+ height: 100,+ boardX: 20,+ boardY: 0,+ boardScale: 1,+ boardRotation: 0,+ boardFlipX: false,+ boardFlipY: false,+ zIndex: 5,+ },+ ];++ // Overlap region at board (10, 0) -> stage (160, 100) for 300x200 stage+ const hitOverlap = hitTestBoardCards(160, 100, cards, 300, 200, boardTransform);+ expect(hitOverlap?.card.id).toBe('front');++ // Left-only region of back card at board (-40, 0) -> stage (110, 100)+ const hitBack = hitTestBoardCards(110, 100, cards, 300, 200, boardTransform);+ expect(hitBack?.card.id).toBe('back');++ // Handle hit-testing on front card+ const ov = getCardStageOverlay(cards[1], 300, 200, boardTransform);+ expect(hitTestCardHandle(ov.rotHandle.x, ov.rotHandle.y, cards[1], 300, 200, boardTransform)).toBe(+ 'rotate'+ );+ expect(hitTestCardHandle(ov.br.x, ov.br.y, cards[1], 300, 200, boardTransform)).toBe('br');+ expect(+ hitTestCardHandle(ov.br.x, ov.br.y, { ...cards[1], locked: true }, 300, 200, boardTransform)+ ).toBeNull();+ });++ it('auto-arranges multiple cards in grid, row, and column layouts without overlapping and computes fit transform', () => {+ const items = [+ { id: 'a', width: 800, height: 600 },+ { id: 'b', width: 400, height: 800 },+ { id: 'c', width: 500, height: 500 },+ { id: 'd', width: 1000, height: 500 },+ ];++ for (const mode of ['grid', 'row', 'column'] as const) {+ const layout = computeBoardAutoLayout(items, mode, 12);+ expect(layout.size).toBe(4);+ const boxes = items.map((it) => {+ const p = layout.get(it.id)!;+ const hw = (it.width * p.boardScale) / 2;+ const hh = (it.height * p.boardScale) / 2;+ return { minX: p.boardX - hw, maxX: p.boardX + hw, minY: p.boardY - hh, maxY: p.boardY + hh };+ });+ // Verify zero pairwise overlap+ for (let i = 0; i < boxes.length; i++) {+ for (let j = i + 1; j < boxes.length; j++) {+ const a = boxes[i];+ const b = boxes[j];+ const overlapX = a.minX < b.maxX - 0.1 && a.maxX > b.minX + 0.1;+ const overlapY = a.minY < b.maxY - 0.1 && a.maxY > b.minY + 0.1;+ expect(overlapX && overlapY).toBe(false);+ }+ }+ }++ const fit = computeBoardFitTransform(+ [+ {+ id: 'a',+ width: 200,+ height: 100,+ boardX: 100,+ boardY: -50,+ boardScale: 1,+ boardRotation: 0,+ boardFlipX: false,+ boardFlipY: false,+ zIndex: 1,+ },+ ],+ 300,+ 200,+ 20+ );+ const centerInStage = boardPointToStagePoint(100, -50, 300, 200, fit);+ expect(centerInStage.x).toBeCloseTo(150, 2);+ expect(centerInStage.y).toBeCloseTo(100, 2);+ });++ it('applies perceptual B/W grayscale and 2-value Notan / 3-value shape study posterization accurately', () => {+ // Pixels: dark blue (0,0,120), bright yellow (250,240,20), mid gray (128,128,128)+ const buf = new Uint8ClampedArray([+ 0, 0, 120, 255,+ 250, 240, 20, 255,+ 128, 128, 128, 255,+ ]);+ const grayImg = { data: new Uint8ClampedArray(buf), width: 3, height: 1 };+ applyStudyFilterToImageData(grayImg, {+ grayscale: true,+ valueSteps: 0,+ notanThreshold: 128,+ brightness: 0,+ contrast: 0,+ });+ // Each pixel is neutral gray (R===G===B) and bright yellow is much brighter than dark blue+ expect(grayImg.data[0]).toBe(grayImg.data[1]);+ expect(grayImg.data[1]).toBe(grayImg.data[2]);+ expect(grayImg.data[4]).toBe(grayImg.data[5]);+ expect(grayImg.data[4]).toBeGreaterThan(grayImg.data[0] + 150);++ // 2-Value Notan study splits dark blue to black (16) and bright yellow to white (248)+ const notanImg = { data: new Uint8ClampedArray(buf), width: 3, height: 1 };+ applyStudyFilterToImageData(notanImg, {+ grayscale: true,+ valueSteps: 2,+ notanThreshold: 140,+ brightness: 0,+ contrast: 0,+ });+ expect(notanImg.data[0]).toBe(16);+ expect(notanImg.data[4]).toBe(248);+ expect(notanImg.data[8]).toBe(16);+ });++ it('extracts dominant distinct colors sorted by perceptual luminance', () => {+ const dom = installMiniDom([40, 120, 210, 255]);+ try {+ const fakeCanvas = dom.mockDoc.createElement('canvas') as unknown as HTMLCanvasElement;+ fakeCanvas.width = 20;+ fakeCanvas.height = 20;+ const swatches = extractDominantColorsFromCanvas(fakeCanvas, 5);+ expect(swatches.length).toBeGreaterThanOrEqual(1);+ expect(swatches[0].hex).toMatch(/^#[0-9a-f]{6}$/);+ expect(swatches[0].luminance).toBeGreaterThanOrEqual(0);+ expect(swatches[0].luminance).toBeLessThanOrEqual(100);+ } finally {+ dom.cleanup();+ }+ });+});++describe('SubViewPanel (References 2.0) PureRef UI, B/W Study Overlay & Persistence', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;++ beforeEach(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useSubViewStore.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('defaults to PureRef Board mode, rotates & flips the board, and manipulates per-card B/W, flip, lock, duplicate, and arrange', () => {+ const dom = installMiniDom([230, 90, 40, 255]); // #e65a28+ let root: Root | null = null;++ try {+ subViewStoreActions.addImages([+ { id: 'ref-a', name: 'lighting_ref.png', src: 'data:image/png;base64,AAA', width: 200, height: 200 },+ { id: 'ref-b', name: 'pose_ref.png', src: 'data:image/png;base64,BBB', width: 200, height: 200 },+ ]);++ act(() => {+ root = createRoot(dom.container as unknown as Element);+ root.render(<SubViewPanel colorMode="color" themePreset="modern" />);+ });++ const panel = dom.container.findByAttr('data-testid', 'sub-view-panel');+ expect(panel?.getAttribute('data-view-mode')).toBe('board');++ // Rotate & flip entire PureRef board viewport+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-rotate-right')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ dom.container+ .findByAttr('data-testid', 'subview-flip-h')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().boardTransform.rotation).toBe(15);+ expect(useSubViewStore.getState().boardTransform.flipX).toBe(true);++ // Floating B/W study controls right on top of the reference+ expect(dom.container.findByAttr('data-testid', 'subview-study-overlay')).not.toBeNull();+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-bw-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().studyFilter.grayscale).toBe(true);++ // Cycle value study steps (2V Notan -> 3V -> 5V)+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-value-steps')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().studyFilter.valueSteps).toBe(2);++ // Toggle Squint Blur & Proportional Grid+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-squint-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ dom.container+ .findByAttr('data-testid', 'subview-grid-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().studyFilter.squintBlur).toBe(true);+ expect(useSubViewStore.getState().studyFilter.gridMode).toBe('thirds');++ // Toggle Split Color | B/W compare curtain+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-split-bw-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().studyFilter.splitBw).toBe(true);+ expect(dom.container.findByAttr('data-testid', 'subview-split-handle')).not.toBeNull();++ // Turn split off to access per-card PureRef toolbar+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-split-bw-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });++ // Per-card B/W, Flip H, Lock, and Duplicate+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-card-bw-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ dom.container+ .findByAttr('data-testid', 'subview-card-flip-h')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ dom.container+ .findByAttr('data-testid', 'subview-card-lock')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ const cardB = useSubViewStore.getState().items.find((i) => i.id === 'ref-b')!;+ expect(cardB.grayscale).toBe(true);+ expect(cardB.boardFlipX).toBe(true);+ expect(cardB.locked).toBe(true);++ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-card-duplicate')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useSubViewStore.getState().items.length).toBe(3);++ // Auto-arrange menu -> Horizontal Strip+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-arrange-btn')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-arrange-row')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ const arrangedItems = useSubViewStore.getState().items;+ expect(arrangedItems.every((it) => it.boardY === 0)).toBe(true);++ // Dominant Color Palette strip picks primaryColor+ act(() => {+ dom.container+ .findByAttr('data-testid', 'subview-palette-toggle')!+ .dispatchEvent(new Event('click', { bubbles: true }));+ });+ const swatches = dom.container.findAllByAttrPrefix('data-testid', 'subview-palette-swatch-');+ expect(swatches.length).toBeGreaterThanOrEqual(1);+ act(() => {+ swatches[0].dispatchEvent(new Event('click', { bubbles: true }));+ });+ expect(useToolStore.getState().primaryColor).toBe('#e65a28');++ // Reload persistence of v2 PureRef board state & study filter+ expect(localStorage.getItem(SUB_VIEW_STORAGE_KEY)).toBeTruthy();+ act(() => {+ useSubViewStore.reset();+ });+ expect(useSubViewStore.getState().items.length).toBe(3);+ expect(useSubViewStore.getState().viewMode).toBe('board');+ expect(useSubViewStore.getState().studyFilter.squintBlur).toBe(true);+ expect(useSubViewStore.getState().studyFilter.gridMode).toBe('thirds');+ expect(useSubViewStore.getState().items.find((i) => i.id === 'ref-b')?.grayscale).toBe(true);+ } finally {+ if (root) {+ act(() => {+ root?.unmount();+ });+ }+ dom.cleanup();+ }+ });+});diff --git a/src/utils/__tests__/textToolWorkflow.test.tsx b/src/utils/__tests__/textToolWorkflow.test.tsxnew file mode 100644index 0000000..82512af--- /dev/null+++ b/src/utils/__tests__/textToolWorkflow.test.tsx@@ -0,0 +1,453 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ DEFAULT_TEXT_SETTINGS,+ loadInitialTextSettings,+ TEXT_SETTINGS_STORAGE_KEY,+} from '../textSettings';+import { toolStoreActions, useToolStore } from '../../stores/useToolStore';+import { TextEditorOverlay } from '../../components/TextEditorOverlay';+import { TextSettings } from '../../types/editor';++interface MiniNode {+ nodeType: number;+ nodeName: string;+ parentNode: MiniElement | null;+ ownerDocument: MiniDocument;+}++class MiniTextNode implements MiniNode {+ public nodeType = 3;+ public nodeName = '#text';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniCommentNode implements MiniNode {+ public nodeType = 8;+ public nodeName = '#comment';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniElement extends EventTarget implements MiniNode {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public ownerDocument: MiniDocument;+ public parentNode: MiniElement | null = null;+ public childNodes: MiniNode[] = [];+ public style: Record<string, string> = {};+ public disabled = false;+ public className = '';+ public isContentEditable = false;+ public value = '';+ public type = '';+ public checked = false;+ public selected = false;+ public defaultSelected = false;+ public multiple = false;+ public width = 0;+ public height = 0;+ private attrs = new Map<string, string>();++ get options(): MiniElement[] {+ return this.childNodes.filter(+ (n): n is MiniElement => n instanceof MiniElement && n.tagName === 'OPTION'+ );+ }++ constructor(tag: string, ownerDocument: MiniDocument) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ if (this.tagName === 'TEXTAREA') this.type = 'textarea';+ this.ownerDocument = ownerDocument;+ }++ get firstChild(): MiniNode | null {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];+ }++ getContext(): null {+ return null;+ }++ setSelectionRange(): void {}++ 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 (!ref) return this.appendChild(child);+ if (child.parentNode) child.parentNode.removeChild(child);+ const idx = this.childNodes.indexOf(ref);+ child.parentNode = this;+ if (idx === -1) 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 !== -1) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ setAttribute(name: string, value: string): void {+ this.attrs.set(name, String(value));+ if (name === 'class') this.className = String(value);+ if (name === 'disabled') this.disabled = true;+ if (name === 'value') this.value = String(value);+ }++ getAttribute(name: string): string | null {+ return this.attrs.get(name) ?? null;+ }++ removeAttribute(name: string): void {+ this.attrs.delete(name);+ if (name === 'disabled') this.disabled = false;+ }++ hasAttribute(name: string): boolean {+ return this.attrs.has(name);+ }++ focus(): void {+ this.ownerDocument.activeElement = this;+ this.dispatchEvent(new Event('focusin', { bubbles: true }));+ }++ attachEvent(): void {}++ detachEvent(): void {}++ blur(): void {+ if (this.ownerDocument.activeElement === this) {+ this.ownerDocument.activeElement = null;+ }+ }++ override dispatchEvent(event: Event): boolean {+ const path: EventTarget[] = [];+ let cur: MiniElement | null = this;+ while (cur) {+ path.push(cur);+ cur = cur.parentNode;+ }+ path.push(this.ownerDocument);+ if (this.ownerDocument.defaultView) {+ 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 MiniDocument extends EventTarget {+ public nodeType = 9;+ public nodeName = '#document';+ public oninput = null;+ public defaultView: EventTarget | null = null;+ public documentElement: MiniElement;+ public body: MiniElement;+ public activeElement: MiniElement | null = null;++ constructor() {+ super();+ this.documentElement = new MiniElement('html', this);+ this.body = new MiniElement('body', this);+ this.documentElement.appendChild(this.body);+ }++ createElement(tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createElementNS(_ns: string, tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createTextNode(text: string): MiniTextNode {+ return new MiniTextNode(text, this);+ }++ createComment(text: string): MiniCommentNode {+ return new MiniCommentNode(text, this);+ }+}++function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {+ const result: MiniElement[] = [];+ const walk = (el: MiniElement) => {+ if (pred(el)) result.push(el);+ for (const child of el.childNodes) {+ if (child instanceof MiniElement) walk(child);+ }+ };+ walk(root);+ return result;+}++function findByTestId(root: MiniElement, testId: string): MiniElement | undefined {+ return findElements(root, (el) => el.getAttribute('data-testid') === testId)[0];+}++function createMemoryStorage(): Storage {+ const map = new Map<string, string>();+ return {+ get length() {+ return map.size;+ },+ clear() {+ map.clear();+ },+ getItem(key: string) {+ return map.get(key) ?? null;+ },+ key(index: number) {+ return Array.from(map.keys())[index] ?? null;+ },+ removeItem(key: string) {+ map.delete(key);+ },+ setItem(key: string, value: string) {+ map.set(key, String(value));+ },+ };+}++describe('Text Tool Defaults, Persistence & WYSIWYG Editor', () => {+ const prevLocalStorage = (globalThis as Record<string, unknown>).localStorage;+ const prevWindow = (globalThis as Record<string, unknown>).window;+ const prevDocument = (globalThis as Record<string, unknown>).document;+ const prevHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const prevHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const prevElement = (globalThis as Record<string, unknown>).Element;+ const prevNode = (globalThis as Record<string, unknown>).Node;+ const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ let doc: MiniDocument;+ let container: MiniElement;+ let root: Root;++ beforeEach(() => {+ const storage = createMemoryStorage();+ (globalThis as Record<string, unknown>).localStorage = storage;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ const MockHTMLIFrameElement = class HTMLIFrameElement {};+ doc = new MiniDocument();+ const win = Object.assign(new EventTarget(), {+ document: doc,+ localStorage: storage,+ devicePixelRatio: 1,+ getSelection: () => ({+ anchorNode: null,+ anchorOffset: 0,+ focusNode: null,+ focusOffset: 0,+ }),+ HTMLElement: MiniElement,+ HTMLIFrameElement: MockHTMLIFrameElement,+ Element: MiniElement,+ Node: MiniElement,+ });+ doc.defaultView = win;+ container = doc.createElement('div');+ doc.body.appendChild(container);++ (globalThis as Record<string, unknown>).window = win;+ (globalThis as Record<string, unknown>).document = doc;+ (globalThis as Record<string, unknown>).HTMLElement = MiniElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = MockHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = MiniElement;+ (globalThis as Record<string, unknown>).Node = MiniElement;++ toolStoreActions.resetTextSettings();+ root = createRoot(container as unknown as Element);+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ (globalThis as Record<string, unknown>).localStorage = prevLocalStorage;+ (globalThis as Record<string, unknown>).window = prevWindow;+ (globalThis as Record<string, unknown>).document = prevDocument;+ (globalThis as Record<string, unknown>).HTMLElement = prevHTMLElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = prevHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = prevElement;+ (globalThis as Record<string, unknown>).Node = prevNode;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;+ });++ it('defaults to plain white text without outlines and natural left alignment', () => {+ expect(DEFAULT_TEXT_SETTINGS.color).toBe('#ffffff');+ expect(DEFAULT_TEXT_SETTINGS.outline).toBe(false);+ expect(DEFAULT_TEXT_SETTINGS.align).toBe('left');+ expect(DEFAULT_TEXT_SETTINGS.letterSpacing).toBe(0);+ expect(DEFAULT_TEXT_SETTINGS.opacity).toBe(1);+ });++ it('persists latest text settings to localStorage and restores them cleanly (excluding draft text)', () => {+ toolStoreActions.updateTextSettings({+ text: 'Transient draft',+ fontFamily: "Georgia, 'Times New Roman', serif",+ fontSize: 54,+ lineSpacing: 1.4,+ letterSpacing: 2.5,+ bold: true,+ italic: true,+ underline: true,+ align: 'center',+ color: '#38bdf8',+ outline: true,+ outlineColor: '#111111',+ outlineWidth: 5,+ opacity: 0.85,+ });++ const raw = localStorage.getItem(TEXT_SETTINGS_STORAGE_KEY);+ expect(raw).toBeTruthy();+ const parsed = JSON.parse(raw!);+ expect(parsed.text).toBeUndefined();+ expect(parsed.maxWidth).toBeUndefined();++ const reloaded = loadInitialTextSettings();+ expect(reloaded.text).toBe('');+ expect(reloaded.fontFamily).toBe("Georgia, 'Times New Roman', serif");+ expect(reloaded.fontSize).toBe(54);+ expect(reloaded.lineSpacing).toBe(1.4);+ expect(reloaded.letterSpacing).toBe(2.5);+ expect(reloaded.bold).toBe(true);+ expect(reloaded.italic).toBe(true);+ expect(reloaded.underline).toBe(true);+ expect(reloaded.align).toBe('center');+ expect(reloaded.color).toBe('#38bdf8');+ expect(reloaded.outline).toBe(true);+ expect(reloaded.outlineWidth).toBe(5);+ expect(reloaded.opacity).toBe(0.85);++ toolStoreActions.resetTextSettings();+ expect(useToolStore.getState().textSettings.color).toBe('#ffffff');+ expect(useToolStore.getState().textSettings.outline).toBe(false);+ expect(loadInitialTextSettings().color).toBe('#ffffff');+ expect(loadInitialTextSettings().outline).toBe(false);+ });++ it('supports WYSIWYG on-canvas keyboard shortcuts (Ctrl+B, Ctrl+U, Alt+Arrow nudge, Ctrl+Enter) and delete button', () => {+ let currentSettings: TextSettings = { ...DEFAULT_TEXT_SETTINGS, text: 'Hello' };+ const onUpdateSettings = vi.fn((updater: (prev: TextSettings) => TextSettings) => {+ currentSettings = updater(currentSettings);+ });+ const onMove = vi.fn();+ const onConfirm = vi.fn();+ const onCancel = vi.fn();+ const onDelete = vi.fn();++ act(() => {+ root.render(+ <TextEditorOverlay+ x={200}+ y={150}+ settings={currentSettings}+ editingLayerId="text-layer-1"+ primaryColor="#ff0000"+ zoom={1}+ onUpdateSettings={onUpdateSettings}+ onMove={onMove}+ onConfirm={onConfirm}+ onCancel={onCancel}+ onDelete={onDelete}+ />+ );+ });++ const textarea = findByTestId(container, 'text-editor-textarea');+ expect(textarea).toBeDefined();++ const dispatchKeyDown = (+ el: MiniElement,+ init: { key: string; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean; shiftKey?: boolean }+ ) => {+ const evt = Object.assign(new Event('keydown', { bubbles: true, cancelable: true }), {+ key: init.key,+ ctrlKey: Boolean(init.ctrlKey),+ metaKey: Boolean(init.metaKey),+ altKey: Boolean(init.altKey),+ shiftKey: Boolean(init.shiftKey),+ });+ el.dispatchEvent(evt);+ };++ // Ctrl+B toggles bold+ act(() => {+ dispatchKeyDown(textarea!, { key: 'b', ctrlKey: true });+ });+ expect(currentSettings.bold).toBe(true);++ // Ctrl+U toggles underline+ act(() => {+ dispatchKeyDown(textarea!, { key: 'u', ctrlKey: true });+ });+ expect(currentSettings.underline).toBe(true);++ // Alt+Shift+ArrowRight nudges +10px horizontally+ act(() => {+ dispatchKeyDown(textarea!, { key: 'ArrowRight', altKey: true, shiftKey: true });+ });+ expect(onMove).toHaveBeenCalledWith(210, 150);++ // Ctrl+Enter confirms+ act(() => {+ dispatchKeyDown(textarea!, { key: 'Enter', ctrlKey: true });+ });+ expect(onConfirm).toHaveBeenCalledTimes(1);++ // Delete button works for existing text layer+ const deleteBtn = findByTestId(container, 'text-delete-btn');+ expect(deleteBtn).toBeDefined();+ act(() => {+ deleteBtn!.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));+ });+ expect(onDelete).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/utils/__tests__/timelapsePersistence.test.tsx b/src/utils/__tests__/timelapsePersistence.test.tsxindex 124487c..02df11f 100644--- a/src/utils/__tests__/timelapsePersistence.test.tsx+++ b/src/utils/__tests__/timelapsePersistence.test.tsx@@ -20,12 +20,9 @@ import {useDocumentLifecycle,UseDocumentLifecycleParams,} from '../../components/DocumentLifecycleManager';-import {- uiStoreActions,- useDocumentStore,-} from '../../stores';+import { uiStoreActions, useDocumentStore } from '../../stores';-// Mock @tauri-apps/api/core so we can test Tauri scratch-disk batch offload/restore/save+// Mock @tauri-apps/api/core so we can test Tauri persistent local disk storage across restartsconst mockTauriInvoke = vi.fn();vi.mock('@tauri-apps/api/core', () => ({invoke: (...args: unknown[]) => mockTauriInvoke(...args),@@ -50,7 +47,6 @@ function makeBaseLayer(): LayerItem {function makeFakeWebpBytes(tag: number, len = 32): Uint8Array {const bytes = new Uint8Array(len);- // RIFF....WEBP header bytes followed by deterministic payloadbytes[0] = 0x52;bytes[1] = 0x49;bytes[2] = 0x46;@@ -92,6 +88,159 @@ function stubCanvasForCapture(payloadQueue: Uint8Array[]) {});}+interface MockPersistedFrame {+ index: number;+ ext: string;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: Uint8Array;+ captureArea?: string;+}++function installTauriPersistentDiskMock() {+ const diskFrames = new Map<string, Map<number, MockPersistedFrame>>();+ const diskMeta = new Map<string, Record<string, unknown>>();++ 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_save_meta') {+ const { sessionId, metaJson } = bodyOrArgs as { sessionId: string; metaJson: string };+ diskMeta.set(sessionId, JSON.parse(metaJson));+ return undefined;+ }+ 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';+ const timestamp = Number(opts?.headers?.['x-timestamp'] || '0');+ const width = Number(opts?.headers?.['x-width'] || '512');+ const height = Number(opts?.headers?.['x-height'] || '512');+ const captureArea = opts?.headers?.['x-capture-area']+ ? decodeURIComponent(opts.headers['x-capture-area'])+ : undefined;+ if (!diskFrames.has(sid)) diskFrames.set(sid, new Map());+ const bytes =+ bodyOrArgs instanceof ArrayBuffer+ ? new Uint8Array(bodyOrArgs.slice(0))+ : new Uint8Array(bodyOrArgs as Uint8Array);+ diskFrames.get(sid)!.set(idx, {+ index: idx,+ ext,+ timestamp,+ width,+ height,+ mimeType: ext === 'jpg' ? 'image/jpeg' : 'image/webp',+ bytes,+ captureArea,+ });+ return undefined;+ }+ if (cmd === 'timelapse_write_frames_batch') {+ const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');+ if (!diskFrames.has(sid)) diskFrames.set(sid, new Map());+ const entries = unpackBatchJs(bodyOrArgs as Uint8Array);+ for (const e of entries) {+ diskFrames.get(sid)!.set(e.index, {+ index: e.index,+ ext: e.ext,+ timestamp: 0,+ width: 512,+ height: 512,+ mimeType: e.ext === 'jpg' ? 'image/jpeg' : 'image/webp',+ bytes: 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 entry = diskFrames.get(sid)?.get(idx);+ if (!entry) throw new Error('Frame not found');+ return entry.bytes.slice().buffer;+ }+ if (cmd === 'timelapse_load_session') {+ const sid = (bodyOrArgs as { sessionId: string }).sessionId;+ const meta = diskMeta.get(sid) ?? null;+ const map = diskFrames.get(sid);+ const sorted = map+ ? Array.from(map.values()).sort((a, b) => a.index - b.index)+ : [];+ let totalBytes = 0;+ const frames = sorted.map((f) => {+ totalBytes += f.bytes.byteLength;+ return {+ index: f.index,+ timestamp: f.timestamp,+ width: f.width,+ height: f.height,+ mimeType: f.mimeType,+ bytes: f.bytes.byteLength,+ ...(f.captureArea ? { captureArea: f.captureArea } : {}),+ };+ });+ return { meta, frames, totalBytes };+ }+ if (cmd === 'timelapse_list_sessions') {+ const ids = new Set<string>([...diskMeta.keys(), ...diskFrames.keys()]);+ return Array.from(ids).map((id) => {+ const m = diskMeta.get(id) as Record<string, unknown> | undefined;+ const map = diskFrames.get(id);+ const list = map ? Array.from(map.values()) : [];+ const totalBytes = list.reduce((acc, f) => acc + f.bytes.byteLength, 0);+ return {+ recordingId: id,+ documentName: String(m?.documentName || 'Untitled'),+ enabled: Boolean(m?.enabled),+ captureArea: String(m?.captureArea || 'artwork'),+ captureResolution: String(m?.captureResolution || '1080p'),+ frameCount: list.length,+ totalBytes,+ createdAt: Number(m?.createdAt || 0),+ updatedAt: Number(m?.updatedAt || 0),+ };+ });+ }+ if (cmd === 'timelapse_list_frames') {+ const sid = (bodyOrArgs as { sessionId: string }).sessionId;+ const map = diskFrames.get(sid);+ if (!map) return [];+ return Array.from(map.values())+ .sort((a, b) => a.index - b.index)+ .map((f): [number, string] => [f.index, f.ext]);+ }+ if (cmd === 'timelapse_clear') {+ const sid = (bodyOrArgs as { sessionId: string }).sessionId;+ diskFrames.delete(sid);+ diskMeta.delete(sid);+ return undefined;+ }+ return undefined;+ }+ );++ return { diskFrames, diskMeta };+}+// Minimal DOM shim for mounting useDocumentLifecycle hookclass MiniNode {public parentNode: MiniEl | null = null;@@ -150,8 +299,9 @@ class MiniDoc extends EventTarget {}}-describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {+describe('External Persistent Time-lapse Storage & Restart Resume (Zero .ink Bloat)', () => {afterEach(async () => {+ await new Promise((r) => setTimeout(r, 0));vi.restoreAllMocks();vi.unstubAllGlobals();mockTauriInvoke.mockReset();@@ -160,7 +310,7 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {}});- it('saves recorded timelapse frames into .ink, resumes automatically after exit/reopen, and continues appending across multiple sessions', async () => {+ it('keeps .ink files free of frame binaries while preserving & resuming recording across app restarts', async () => {const f0 = makeFakeWebpBytes(1, 40);const f1 = makeFakeWebpBytes(2, 48);const f2 = makeFakeWebpBytes(3, 52);@@ -168,18 +318,39 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {const f4 = makeFakeWebpBytes(5, 64);stubCanvasForCapture([f0, f1, f2, f3, f4]);+ (globalThis as unknown as Record<string, unknown>).window = {+ __TAURI_INTERNALS__: {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ },+ };+ const { diskFrames } = installTauriPersistentDiskMock();+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);+ // --- Session 1: enable recording, capture 3 frames, save .ink, detach & exit app ---+ const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ mgr1.setRecording('doc-session-1', true, 'Illustration');+ mgr1.setCaptureArea('doc-session-1', 'canvas-view');+ mgr1.setCaptureResolution('doc-session-1', '4k');++ expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);+ expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);+ expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, grid, true)).toBe(true);++ const recId = mgr1.getRecordingId('doc-session-1');+ expect(recId).toBeTruthy();+ expect(mgr1.getStats('doc-session-1')).toMatchObject({+ recordingId: recId,+ enabled: true,+ frameCount: 3,+ diskFrames: 3,+ memoryBytes: 0,+ captureArea: 'canvas-view',+ captureResolution: '4k',+ });const saved1 = await serializeInkProject({@@ -190,58 +361,72 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {tileGrid: grid,getEffectiveOpacity: (l) => l.opacity,isLayerEffectivelyVisible: (l) => l.visible,- timelapseFrameProvider: session1Manager.createPersistenceProvider('doc-session-1'),+ timelapse: mgr1.getRecoveryMetadata('doc-session-1'),+ timelapseFrameProvider: mgr1.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',+ // CRITICAL: Verify ZERO timelapse image files were written into the .ink ZIP!+ const zipEntries1 = unzipSync(saved1.bytes);+ const embeddedTlPaths = Object.keys(zipEntries1).filter((k) => k.startsWith('timelapse/'));+ expect(embeddedTlPaths).toEqual([]);+ expect(saved1.manifest.timelapse).toMatchObject({+ recordingId: recId,+ storageMode: 'external',+ enabled: true,+ frameCount: 3,+ captureArea: 'canvas-view',+ captureResolution: '4k',});- 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(saved1.manifest.timelapse?.frames).toBeUndefined();++ // App exit detaches session from RAM WITHOUT deleting external persistent frames+ await mgr1.detachSession('doc-session-1');+ expect(mgr1.getStats('doc-session-1').frameCount).toBe(0);+ expect(diskFrames.get(recId!)?.size).toBe(3);++ // --- Session 2: brand new manager after app restart reopens .ink ---+ const mgr2 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const loaded1 = await openFile(+ new File([saved1.bytes as BlobPart], 'Illustration.ink', {+ type: 'application/octet-stream',+ }));+ expect(loaded1.timelapse?.recordingId).toBe(recId);+ expect(loaded1.timelapseFrames).toBeUndefined();++ const restored1 = await mgr2.attachOrRestoreSession('doc-session-2', {+ documentName: loaded1.name,+ metadata: loaded1.timelapse,+ fallbackDims: dims,+ });expect(restored1).toEqual({ enabled: true, frameCount: 3 });- expect(session2Manager.isRecording('doc-session-2')).toBe(true);- expect(session2Manager.getStats('doc-session-2').frameCount).toBe(3);+ expect(mgr2.getStats('doc-session-2')).toMatchObject({+ recordingId: recId,+ enabled: true,+ frameCount: 3,+ diskFrames: 3,+ memoryBytes: 0,+ captureArea: 'canvas-view',+ captureResolution: '4k',+ });- // 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(+ // Byte-for-byte fidelity of all 3 externally persisted frames+ const frames2 = mgr2.getFrames('doc-session-2');+ expect(Array.from((await mgr2.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(+ expect(Array.from((await mgr2.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]);+ // Continue drawing in Session 2 -> seamlessly appends frames 3 & 4+ expect(await mgr2.captureKeyframe('doc-session-2', layers, dims, grid, true)).toBe(true);+ expect(await mgr2.captureKeyframe('doc-session-2', layers, dims, grid, true)).toBe(true);+ expect(mgr2.getFrames('doc-session-2').map((f) => f.index)).toEqual([0, 1, 2, 3, 4]);- // Save again via serializeDocument('.ink')+ // Re-save .ink via serializeDocument -> still ZERO embedded frames in .ink!const saved2Res = await serializeDocument({name: 'Illustration',@@ -251,233 +436,150 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {tileGrid: grid,getEffectiveOpacity: (l) => l.opacity,isLayerEffectivelyVisible: (l) => l.visible,- timelapseFrameProvider: session2Manager.createPersistenceProvider('doc-session-2'),+ timelapse: mgr2.getRecoveryMetadata('doc-session-2'),+ timelapseFrameProvider: mgr2.createPersistenceProvider('doc-session-2'),},'.ink');- const saved2Buf = await (saved2Res.data as Blob).arrayBuffer();+ const saved2Bytes = new Uint8Array(await (saved2Res.data as Blob).arrayBuffer());+ expect(Object.keys(unzipSync(saved2Bytes)).filter((k) => k.startsWith('timelapse/'))).toEqual([]);- // --- Session 3: relaunch again and verify all 5 frames survive intact ---- const session3Manager = new TimelapseRecorderManager({ minIntervalMs: 0 });+ // Detach again, launch Session 3 -> all 5 frames survive intact!+ await mgr2.detachSession('doc-session-2');+ const mgr3 = 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+ new File([saved2Bytes], 'Illustration.ink', { type: 'application/octet-stream' }));+ const restored2 = await mgr3.attachOrRestoreSession('doc-session-3', {+ documentName: loaded2.name,+ metadata: loaded2.timelapse,+ fallbackDims: dims,+ });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]));+ const frames3 = mgr3.getFrames('doc-session-3');+ const expectedAll = [f0, f1, f2, f3, f4];+ for (let i = 0; i < expectedAll.length; i++) {+ const bytes = await mgr3.loadFrameBytes('doc-session-3', frames3[i]);+ expect(Array.from(bytes!)).toEqual(Array.from(expectedAll[i]));}++ // Explicit clearSession deletes persisted frames from disk+ await mgr3.clearSession('doc-session-3');+ expect(mgr3.getStats('doc-session-3').frameCount).toBe(0);+ expect(diskFrames.has(recId!)).toBe(false);});- it('preserves recorded frames when paused before saving and keeps recording paused on reopen', async () => {+ it('migrates legacy .ink archives with embedded frames into external storage and slims down re-saves', async () => {const f0 = makeFakeWebpBytes(10, 36);const f1 = makeFakeWebpBytes(11, 36);- stubCanvasForCapture([f0, f1]);+ stubCanvasForCapture([]);++ (globalThis as unknown as Record<string, unknown>).window = {+ __TAURI_INTERNALS__: {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ },+ };+ const { diskFrames } = installTauriPersistentDiskMock();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(+ // Construct a legacy .ink archive that STILL had embedded frames+ const legacySaved = await serializeInkProject({- name: 'PausedArt',+ name: 'LegacyArt',dimensions: dims,colorMode: 'color',layers,tileGrid: grid,getEffectiveOpacity: () => 1,isLayerEffectivelyVisible: () => true,- timelapseFrameProvider: mgr1.createPersistenceProvider('doc-paused'),+ embedTimelapseFrames: true,+ timelapse: { enabled: false, 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);+ expect(Object.keys(unzipSync(legacySaved.bytes))).toContain('timelapse/frame_000000.webp');- const parsed = await parseInkProject(saved.bytes);- expect(parsed.timelapse?.enabled).toBe(false);- expect(parsed.timelapse?.frameCount).toBe(2);+ const parsed = await parseInkProject(legacySaved.bytes);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,+ // Restoring migrates frames into external persistent storage and keeps paused state+ const mgr = new TimelapseRecorderManager();+ const restored = await mgr.attachOrRestoreSession('doc-legacy', {+ documentName: parsed.name,+ metadata: parsed.timelapse,+ legacyFrames: parsed.timelapseFrames,});+ expect(restored).toEqual({ enabled: false, frameCount: 2 });+ expect(mgr.isRecording('doc-legacy')).toBe(false);+ const migratedRecId = mgr.getRecordingId('doc-legacy')!;+ expect(diskFrames.get(migratedRecId)?.size).toBe(2);- // Save .ink -> streams frames back from scratch disk into ZIP- const saved = await serializeInkProject(+ // Re-saving produces a clean lightweight .ink file with ZERO embedded frame binaries+ const slimResaved = await serializeInkProject({- name: 'DesktopArt',+ name: 'LegacyArt',dimensions: dims,colorMode: 'color',layers,tileGrid: grid,getEffectiveOpacity: () => 1,isLayerEffectivelyVisible: () => true,- timelapseFrameProvider: mgr1.createPersistenceProvider('tauri-doc-1'),+ timelapse: mgr.getRecoveryMetadata('doc-legacy'),+ timelapseFrameProvider: mgr.createPersistenceProvider('doc-legacy'),},grid);+ expect(Object.keys(unzipSync(slimResaved.bytes)).filter((k) => k.startsWith('timelapse/'))).toEqual([]);+ expect(slimResaved.manifest.timelapse?.recordingId).toBe(migratedRecId);+ });- // 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' } })- );+ it('recovers persisted frames after a crash and supports listing stored recordings', async () => {+ const f0 = makeFakeWebpBytes(21, 44);+ const f1 = makeFakeWebpBytes(22, 46);+ stubCanvasForCapture([f0, f1]);- // 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);+ (globalThis as unknown as Record<string, unknown>).window = {+ __TAURI_INTERNALS__: {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ },+ };+ installTauriPersistentDiskMock();- // 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 grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 512, 512, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 512, height: 512, dpi: 300 };- 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));+ const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });+ mgr1.setRecording('crash-doc', true, 'ComicPage01');+ await mgr1.captureKeyframe('crash-doc', layers, dims, grid, true);+ await mgr1.captureKeyframe('crash-doc', layers, dims, grid, true);+ await mgr1.waitForPendingCapture('crash-doc');++ const recoveryMeta = mgr1.getRecoveryMetadata('crash-doc');+ expect(recoveryMeta?.recordingId).toBeTruthy();++ // Simulate sudden crash (no detach called, new manager boots up)+ const crashMgr = new TimelapseRecorderManager({ minIntervalMs: 0 });+ const recovered = await crashMgr.restoreFromScratchDisk('crash-doc', recoveryMeta, dims);+ expect(recovered).toEqual({ enabled: true, frameCount: 2 });++ const library = await crashMgr.listStoredRecordings();+ expect(library).toHaveLength(1);+ expect(library[0].documentName).toBe('ComicPage01');+ expect(library[0].frameCount).toBe(2);});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',@@ -502,11 +604,15 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {expect(parsedLegacy.timelapseFrames).toBeUndefined();const mgr = new TimelapseRecorderManager();- const res = await mgr.restoreSession('legacy-doc', parsedLegacy.timelapse, parsedLegacy.timelapseFrames);+ 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+ // Rejects unsafe timelapse frame path in manifestconst evilZip = zipSync({'manifest.json': new TextEncoder().encode(JSON.stringify({@@ -531,7 +637,7 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {});await expect(parseInkProject(evilZip)).rejects.toThrow(/Unsafe time-lapse frame path/);- // 3. Binary batch packer format check+ // Binary batch packer format checkconst packed = packTimelapseFrameBatch([{ index: 7, ext: 'webp', bytes: new Uint8Array([1, 2, 3]) },{ index: 8, ext: 'jpg', bytes: new Uint8Array([9, 8]) },@@ -539,17 +645,17 @@ describe('.ink Attached Time-lapse Persistence & Auto-Resume', () => {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(packed[8]).toBe(0);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(packed[20]).toBe(1);expect(dv.getUint32(21, true)).toBe(2);expect(Array.from(packed.subarray(25, 27))).toEqual([9, 8]);});});-describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {+describe('DocumentLifecycleManager External Time-lapse Reconnect & Preserve on Close', () => {let root: Root | null = null;let container: MiniEl | null = null;let hookApi: ReturnType<typeof useDocumentLifecycle> | null = null;@@ -592,12 +698,20 @@ describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {}root = null;container = null;+ await new Promise((r) => setTimeout(r, 0));+ delete (globalThis as unknown as Record<string, unknown>).__TAURI_INTERNALS__;+ mockTauriInvoke.mockReset();(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 () => {+ it('migrates legacy .ink on open, preserves frames on tab close, and reconnects on reopen', async () => {+ (globalThis as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ };+ const { diskFrames } = installTauriPersistentDiskMock();+const baseLayer = makeBaseLayer();const grid = new SparseTileGrid();grid.fillLayerSolidWhite('layer-1', 256, 256, 'color-32bit');@@ -614,7 +728,8 @@ describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {tileGrid: grid,getEffectiveOpacity: () => 1,isLayerEffectivelyVisible: () => true,- timelapse: { enabled: true, frameCount: 2 },+ embedTimelapseFrames: true,+ timelapse: { recordingId: 'rec-lifecycle-1', 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 },@@ -663,7 +778,7 @@ describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {await hookApi!.handleProcessFile(inkFile);});- const openedId = useDocumentStore.getState().activeDocumentId;+ const openedId = useDocumentStore.getState().activeDocumentId!;expect(openedId).toBeTruthy();expect(globalTimelapseManager.isRecording(openedId)).toBe(true);expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(2);@@ -671,19 +786,44 @@ describe('DocumentLifecycleManager Time-lapse Open & Close Integration', () => {'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+ // Closing the tab detaches from RAM while PRESERVING frames in external disk storage!await act(async () => {- hookApi!.handleCloseDocument(openedId!);+ hookApi!.handleCloseDocument(openedId);});- expect(globalTimelapseManager.isRecording(openedId)).toBe(false);expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(0);+ expect(diskFrames.get('rec-lifecycle-1')?.size).toBe(2);++ // Reopening a slim external-pointer .ink reconnects straight to the 2 preserved frames!+ const slimInk = await serializeInkProject(+ {+ name: 'AttachedTL',+ dimensions: { width: 256, height: 256, dpi: 300 },+ colorMode: 'color',+ layers: [baseLayer],+ tileGrid: grid,+ getEffectiveOpacity: () => 1,+ isLayerEffectivelyVisible: () => true,+ timelapse: {+ recordingId: 'rec-lifecycle-1',+ storageMode: 'external',+ enabled: true,+ frameCount: 2,+ },+ },+ grid+ );+ expect(Object.keys(unzipSync(slimInk.bytes)).filter((k) => k.startsWith('timelapse/'))).toEqual([]);++ await act(async () => {+ await hookApi!.handleProcessFile(+ new File([slimInk.bytes as BlobPart], 'AttachedTL.ink', {+ type: 'application/octet-stream',+ })+ );+ });++ const reopenedId = useDocumentStore.getState().activeDocumentId!;+ expect(globalTimelapseManager.isRecording(reopenedId)).toBe(true);+ expect(globalTimelapseManager.getStats(reopenedId).frameCount).toBe(2);});});diff --git a/src/utils/__tests__/timelapseStudioFeatures.test.tsx b/src/utils/__tests__/timelapseStudioFeatures.test.tsxnew file mode 100644index 0000000..5aaf0e7--- /dev/null+++ b/src/utils/__tests__/timelapseStudioFeatures.test.tsx@@ -0,0 +1,631 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { LayerItem } from '../../types/editor';+import { SparseTileGrid } from '../tileEngine';+import { ViewportCompositor } from '../compositor';+import {+ captureResolutionToMaxDim,+ computeMediaRecorderBitrate,+ computeTimelapseDimensions,+ globalTimelapseManager,+ resolveTimelapseTargetSeconds,+ sampleTimelapseFrameIndices,+ TimelapseRecorderManager,+} from '../timelapseEngine';+import {+ computeWatermarkPosition,+ DEFAULT_TIMELAPSE_WATERMARK,+ drawWatermarkOnContext,+ TimelapseWatermarkConfig,+} from '../timelapseWatermark';+import { computeCanvasViewDimensions } from '../timelapseCanvasView';+import { TimelapseExportModal } from '../../components/TimelapseExportModal';++const mockTauriInvoke = vi.fn();+vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+}));++function makeBaseLayer(): LayerItem {+ return {+ id: 'layer-1',+ name: 'Lineart',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ };+}++function makeFakeWebpBytes(tag: number, len = 36): Uint8Array {+ const bytes = new Uint8Array(len);+ 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 * 17 + i) & 0xff;+ return bytes;+}++describe('Time-lapse Studio Math: Intervals, FPS, Quality, 4K & Watermark', () => {+ it('computes even dimensions across 720p, 1080p, 2k, 4k and all aspect ratios including 4:5', () => {+ expect(captureResolutionToMaxDim('720p')).toBe(1280);+ expect(captureResolutionToMaxDim('1080p')).toBe(1920);+ expect(captureResolutionToMaxDim('2k')).toBe(2560);+ expect(captureResolutionToMaxDim('4k')).toBe(3840);++ expect(computeTimelapseDimensions(3000, 3000, '16:9', '4k')).toEqual({+ width: 3840,+ height: 2160,+ });+ expect(computeTimelapseDimensions(3000, 3000, '9:16', '2k')).toEqual({+ width: 1440,+ height: 2560,+ });+ expect(computeTimelapseDimensions(2000, 2000, '4:5', '1080p')).toEqual({+ width: 1080,+ height: 1350,+ });+ expect(computeCanvasViewDimensions(1920, 1080, 1280)).toEqual({+ width: 1280,+ height: 720,+ });+ });++ it('samples timeline accurately for 15s, 30s, 60s, 120s, custom, and full at 24/30/60 FPS', () => {+ expect(sampleTimelapseFrameIndices(100, '15s', 24)).toHaveLength(360);+ expect(sampleTimelapseFrameIndices(100, '30s', 30)).toHaveLength(900);+ expect(sampleTimelapseFrameIndices(100, '60s', 60)).toHaveLength(3600);+ expect(sampleTimelapseFrameIndices(100, '120s', 30)).toHaveLength(3600);+ expect(sampleTimelapseFrameIndices(100, 'custom', 30, 42)).toHaveLength(1260);+ expect(resolveTimelapseTargetSeconds(100, 'custom', 30, 42)).toBe(42);+ expect(resolveTimelapseTargetSeconds(100, '120s', 30)).toBe(120);++ // Higher quality and FPS produce strictly higher MediaRecorder bitrates+ const std30 = computeMediaRecorderBitrate('1080p', 30, 'standard');+ const high30 = computeMediaRecorderBitrate('1080p', 30, 'high');+ const ultra60 = computeMediaRecorderBitrate('1080p', 60, 'ultra');+ const max4k = computeMediaRecorderBitrate('4k', 60, 'lossless');+ expect(std30).toBeLessThan(high30);+ expect(high30).toBeLessThan(ultra60);+ expect(ultra60).toBeLessThan(max4k);+ });++ it('computes watermark placement across all anchors and renders text watermark onto Canvas 2D', () => {+ const tl = computeWatermarkPosition(1920, 1080, 200, 50, 'top-left', 3);+ const br = computeWatermarkPosition(1920, 1080, 200, 50, 'bottom-right', 3);+ const center = computeWatermarkPosition(1920, 1080, 200, 50, 'center', 3);++ expect(tl).toEqual({ x: 32, y: 32 });+ expect(br).toEqual({ x: 1920 - 200 - 32, y: 1080 - 50 - 32 });+ expect(center).toEqual({ x: 860, y: 515 });++ const fillText = vi.fn();+ const fill = vi.fn();+ const fakeCtx = {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ quadraticCurveTo: vi.fn(),+ closePath: vi.fn(),+ fill,+ fillText,+ measureText: () => ({ width: 120 }),+ font: '',+ textBaseline: '',+ textAlign: '',+ globalAlpha: 1,+ fillStyle: '',+ shadowColor: '',+ shadowBlur: 0,+ shadowOffsetX: 0,+ shadowOffsetY: 0,+ } as unknown as CanvasRenderingContext2D;++ const cfg: TimelapseWatermarkConfig = {+ ...DEFAULT_TIMELAPSE_WATERMARK,+ enabled: true,+ mode: 'text',+ text: '@ArtistName',+ position: 'bottom-right',+ };+ const rect = drawWatermarkOnContext(fakeCtx, 1920, 1080, cfg);+ expect(rect).toBeTruthy();+ expect(fillText).toHaveBeenCalledWith('@ArtistName', expect.any(Number), expect.any(Number), expect.any(Number));+ expect(fill).toHaveBeenCalled();++ // Disabled watermark draws nothing+ expect(drawWatermarkOnContext(fakeCtx, 1920, 1080, { ...cfg, enabled: false })).toBeNull();+ });+});++describe('Time-lapse Capture Area Modes, Deduplication & FFmpeg Export Options', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ mockTauriInvoke.mockReset();+ if (typeof window !== 'undefined') {+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;+ }+ });++ it('captures artwork, canvas-view, and native app-window frames, deduplicates unchanged frames, and defers during active strokes', async () => {+ const renderPreviewSpy = vi+ .spyOn(ViewportCompositor, 'renderLowResPreview')+ .mockImplementation(() => {});++ const putImageDataSpy = vi.fn();+ vi.stubGlobal('document', {+ createElement: (tag: string) => {+ if (tag !== 'canvas') return {};+ return {+ width: 0,+ height: 0,+ getContext: () => ({+ save: () => {},+ restore: () => {},+ setTransform: () => {},+ scale: () => {},+ translate: () => {},+ rotate: () => {},+ beginPath: () => {},+ moveTo: () => {},+ lineTo: () => {},+ quadraticCurveTo: () => {},+ closePath: () => {},+ fill: () => {},+ fillText: () => {},+ measureText: () => ({ width: 120 }),+ rect: () => {},+ clip: () => {},+ fillRect: () => {},+ clearRect: () => {},+ drawImage: () => {},+ createImageData: (w: number, h: number) => ({+ width: w,+ height: h,+ data: new Uint8ClampedArray(w * h * 4),+ }),+ putImageData: putImageDataSpy,+ }),+ toBlob: (cb: (b: Blob | null) => void, mime?: string) => {+ cb(new Blob([makeFakeWebpBytes(7) as BlobPart], { type: mime || 'image/webp' }));+ },+ };+ },+ });++ (globalThis as unknown as Record<string, unknown>).window = {+ __TAURI_INTERNALS__: {+ invoke: (...args: unknown[]) => mockTauriInvoke(...args),+ },+ };++ mockTauriInvoke.mockImplementation(async (cmd: string) => {+ if (cmd === 'timelapse_capture_app_window') {+ // Return valid 4x4 packed RGBA frame: [w:u32 LE][h:u32 LE][rgba...]+ const out = new Uint8Array(8 + 4 * 4 * 4);+ const dv = new DataView(out.buffer);+ dv.setUint32(0, 4, true);+ dv.setUint32(4, 4, true);+ out.fill(200, 8);+ return out.buffer;+ }+ if (cmd === 'timelapse_check_ffmpeg') return true;+ if (cmd === 'timelapse_export_ffmpeg') return new Uint8Array([0, 0, 0, 24]).buffer;+ return undefined;+ });++ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 800, 600, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 800, height: 600, dpi: 300 };++ const mgr = new TimelapseRecorderManager({ minIntervalMs: 0 });+ mgr.setRecording('doc-cap', true, 'Scene');++ // 1. Active stroke deferral: capture skipped immediately while stylus is down+ const deferred = await mgr.captureKeyframe('doc-cap', layers, dims, grid, false, {+ isDrawingActive: () => true,+ });+ expect(deferred).toBe(false);+ expect(mgr.getStats('doc-cap').frameCount).toBe(0);++ // 2. Artwork only capture+ expect(await mgr.captureKeyframe('doc-cap', layers, dims, grid, true)).toBe(true);+ expect(renderPreviewSpy).toHaveBeenCalledTimes(1);+ expect(mgr.getFrames('doc-cap')[0].captureArea).toBe('artwork');++ // 3. Deduplication: unchanged visual state with force=false skips redundant encode+ expect(await mgr.captureKeyframe('doc-cap', layers, dims, grid, false)).toBe(false);+ expect(mgr.getStats('doc-cap').frameCount).toBe(1);++ // 4. Canvas view capture with live camera transform+ mgr.setCaptureArea('doc-cap', 'canvas-view');+ const fakeViewport = { clientWidth: 1280, clientHeight: 720 } as HTMLElement;+ expect(+ await mgr.captureKeyframe('doc-cap', layers, dims, grid, true, {+ viewportElement: fakeViewport,+ camera: { pan: { x: 640, y: 360 }, zoom: 1.25, rotation: 15, flipX: false, flipY: false },+ })+ ).toBe(true);+ expect(mgr.getFrames('doc-cap')[1].captureArea).toBe('canvas-view');+ expect(mgr.getFrames('doc-cap')[1].width).toBe(1280);+ expect(mgr.getFrames('doc-cap')[1].height).toBe(720);++ // 5. Native App Window capture calls Rust `timelapse_capture_app_window`+ mgr.setCaptureArea('doc-cap', 'app-window');+ mgr.setCaptureResolution('doc-cap', '4k');+ expect(await mgr.captureKeyframe('doc-cap', layers, dims, grid, true)).toBe(true);+ expect(mockTauriInvoke).toHaveBeenCalledWith('timelapse_capture_app_window', { maxDim: 3840 });+ expect(putImageDataSpy).toHaveBeenCalled();+ expect(mgr.getFrames('doc-cap')[2].captureArea).toBe('app-window');+ expect(mgr.getFrames('doc-cap')[2].width).toBe(4);+ expect(mgr.getFrames('doc-cap')[2].height).toBe(4);++ // 6. Export via FFmpeg passes FPS, quality, blur backdrop, and watermark PNG headers+ const exportRes = await mgr.exportVideo('doc-cap', {+ duration: '15s',+ fps: 60,+ quality: 'ultra',+ resolution: '1080p',+ aspectRatio: '9:16',+ backgroundMode: 'blur',+ backgroundColor: '#141414',+ preferFfmpeg: true,+ watermark: {+ ...DEFAULT_TIMELAPSE_WATERMARK,+ enabled: true,+ mode: 'text',+ text: 'Made in InkStudio',+ },+ });+ expect(exportRes.extension).toBe('.mp4');+ expect(exportRes.frameCount).toBe(900); // 15s @ 60 FPS++ const ffmpegCall = mockTauriInvoke.mock.calls.find((c) => c[0] === 'timelapse_export_ffmpeg');+ expect(ffmpegCall).toBeDefined();+ const ffmpegHeaders = (ffmpegCall![2] as { headers: Record<string, string> }).headers;+ expect(ffmpegHeaders['x-fps']).toBe('60');+ expect(ffmpegHeaders['x-quality']).toBe('ultra');+ expect(ffmpegHeaders['x-bg-blur']).toBe('1');+ expect(ffmpegHeaders['x-width']).toBe('1080');+ expect(ffmpegHeaders['x-height']).toBe('1920');+ expect(Number(ffmpegHeaders['x-watermark-bytes'])).toBeGreaterThan(0);++ await mgr.clearSession('doc-cap');+ });+});++// Minimal DOM harness for rendering TimelapseExportModal UI interactions+interface MiniNode {+ nodeType: number;+ nodeName: string;+ parentNode: MiniElement | null;+ ownerDocument: MiniDocument;+}++class MiniTextNode implements MiniNode {+ public nodeType = 3;+ public nodeName = '#text';+ public parentNode: MiniElement | null = null;+ constructor(public nodeValue: string, public ownerDocument: MiniDocument) {}+}++class MiniCommentNode implements MiniNode {+ public nodeType = 8;+ public nodeName = '#comment';+ public parentNode: MiniElement | null = null;+ constructor(public nodeValue: string, public ownerDocument: MiniDocument) {}+}++class MiniElement extends EventTarget implements MiniNode {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public parentNode: MiniElement | null = null;+ public childNodes: MiniNode[] = [];+ public style: Record<string, string> = {};+ public disabled = false;+ public className = '';+ public isContentEditable = false;+ public value = '';+ public width = 0;+ public height = 0;+ private attrs = new Map<string, string>();++ constructor(tag: string, public ownerDocument: MiniDocument) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ }+ get firstChild(): MiniNode | null {+ return this.childNodes[0] ?? null;+ }+ get textContent(): string {+ return this.childNodes+ .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))+ .join('');+ }+ set textContent(val: string) {+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];+ }+ 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 idx = this.childNodes.indexOf(child);+ if (idx >= 0) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }+ insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {+ if (newNode.parentNode) newNode.parentNode.removeChild(newNode);+ newNode.parentNode = this;+ if (!refNode) {+ this.childNodes.push(newNode);+ return newNode;+ }+ const idx = this.childNodes.indexOf(refNode);+ if (idx < 0) this.childNodes.push(newNode);+ else this.childNodes.splice(idx, 0, newNode);+ return newNode;+ }+ 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);+ }+ hasAttribute(k: string): boolean {+ return this.attrs.has(k);+ }+ contains(node: unknown): boolean {+ if (node === this) return true;+ for (const c of this.childNodes) {+ if (c === node) return true;+ if (c instanceof MiniElement && c.contains(node)) return true;+ }+ return false;+ }+ getContext() {+ return {+ save: () => {},+ restore: () => {},+ setTransform: () => {},+ fillRect: () => {},+ drawImage: () => {},+ beginPath: () => {},+ moveTo: () => {},+ lineTo: () => {},+ quadraticCurveTo: () => {},+ closePath: () => {},+ fill: () => {},+ fillText: () => {},+ measureText: () => ({ width: 80 }),+ filter: 'none',+ fillStyle: '',+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ };+ }+ toBlob(cb: (b: Blob | null) => void, mime?: string) {+ cb(new Blob([makeFakeWebpBytes(99) as BlobPart], { type: mime || 'image/webp' }));+ }+ focus() {}+ blur() {}+}++class MiniDocument extends EventTarget {+ public nodeType = 9;+ public nodeName = '#document';+ public body: MiniElement;+ public documentElement: MiniElement;+ public activeElement: MiniElement | null = null;+ public fullscreenElement: MiniElement | null = null;+ constructor(public defaultView: unknown) {+ super();+ this.documentElement = new MiniElement('html', this);+ this.body = new MiniElement('body', this);+ this.documentElement.appendChild(this.body);+ }+ createElement(tag: string) {+ return new MiniElement(tag, this);+ }+ createElementNS(_ns: string, tag: string) {+ return new MiniElement(tag, this);+ }+ createTextNode(text: string) {+ return new MiniTextNode(text, this);+ }+ createComment(text: string) {+ return new MiniCommentNode(text, this);+ }+}++function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {+ const out: MiniElement[] = [];+ const walk = (node: MiniNode) => {+ if (node instanceof MiniElement) {+ if (pred(node)) out.push(node);+ for (const c of node.childNodes) walk(c);+ }+ };+ walk(root);+ return out;+}++function dispatchClick(el: MiniElement) {+ const ev = new Event('click', { bubbles: true, cancelable: true });+ Object.defineProperty(ev, 'target', { value: el, enumerable: true });+ let cur: MiniElement | null = el;+ while (cur) {+ cur.dispatchEvent(ev);+ cur = cur.parentNode;+ }+}++describe('TimelapseExportModal UI: Capture Dropdown, Interval Preview, Full-Screen & Watermark', () => {+ let prevWindow: unknown;+ let prevDocument: unknown;+ let prevAct: unknown;+ let miniWin: EventTarget & Record<string, unknown>;+ let miniDoc: MiniDocument;+ let container: MiniElement;+ let root: Root | null = null;++ beforeEach(() => {+ prevWindow = (globalThis as Record<string, unknown>).window;+ prevDocument = (globalThis as Record<string, unknown>).document;+ prevAct = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ miniWin = Object.assign(new EventTarget(), {+ HTMLElement: MiniElement,+ HTMLIFrameElement: class HTMLIFrameElement {},+ Element: MiniElement,+ Node: MiniElement,+ setTimeout: globalThis.setTimeout.bind(globalThis),+ clearTimeout: globalThis.clearTimeout.bind(globalThis),+ setInterval: globalThis.setInterval.bind(globalThis),+ clearInterval: globalThis.clearInterval.bind(globalThis),+ }) as unknown as EventTarget & Record<string, unknown>;+ miniDoc = new MiniDocument(miniWin);+ miniWin.document = miniDoc;++ (globalThis as Record<string, unknown>).window = miniWin;+ (globalThis as Record<string, unknown>).document = miniDoc;+ (globalThis as Record<string, unknown>).HTMLElement = MiniElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = miniWin.HTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = MiniElement;+ (globalThis as Record<string, unknown>).Node = MiniElement;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;++ container = miniDoc.createElement('div');+ miniDoc.body.appendChild(container);+ });++ afterEach(async () => {+ if (root) {+ await act(async () => {+ root!.unmount();+ });+ root = null;+ }+ await globalTimelapseManager.removeSession('ui-doc-1');+ vi.restoreAllMocks();+ (globalThis as Record<string, unknown>).window = prevWindow;+ (globalThis as Record<string, unknown>).document = prevDocument;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevAct;+ });++ it('supports switching Capture Area, previewing at 15s/30s/60s, entering/exiting Full-Screen, and enabling Watermark', async () => {+ vi.spyOn(ViewportCompositor, 'renderLowResPreview').mockImplementation(() => {});+ const grid = new SparseTileGrid();+ grid.fillLayerSolidWhite('layer-1', 600, 400, 'color-32bit');+ const layers = [makeBaseLayer()];+ const dims = { width: 600, height: 400, dpi: 300 };++ globalTimelapseManager.setRecording('ui-doc-1', true, 'Brainy 10');+ await globalTimelapseManager.captureKeyframe('ui-doc-1', layers, dims, grid, true);+ await globalTimelapseManager.captureKeyframe('ui-doc-1', layers, dims, grid, true);++ const onClose = vi.fn();+ await act(async () => {+ root = createRoot(container as unknown as Element);+ root.render(+ <TimelapseExportModal+ isOpen={true}+ onClose={onClose}+ documentId="ui-doc-1"+ documentName="Brainy 10"+ />+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ // 1. Capture Area dropdown shows Artwork only / Canvas view / App window and updates manager+ const captureTrigger = findElements(+ container,+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Artwork only'+ )[0];+ expect(captureTrigger).toBeDefined();+ await act(async () => {+ dispatchClick(captureTrigger);+ });+ expect(container.textContent).toContain('Canvas view');+ expect(container.textContent).toContain('App window');++ const canvasViewOption = findElements(+ container,+ (el) => el.getAttribute('role') === 'option' && el.textContent.includes('Canvas view')+ )[0];+ await act(async () => {+ dispatchClick(canvasViewOption);+ });+ expect(globalTimelapseManager.getStats('ui-doc-1').captureArea).toBe('canvas-view');++ // 2. Direct in-app preview interval switching updates total duration readout immediately+ expect(container.textContent).toContain('00:30.0');+ const btn15s = findElements(+ container,+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === '15s'+ )[0];+ await act(async () => {+ dispatchClick(btn15s);+ });+ expect(container.textContent).toContain('00:15.0');++ // 3. Full-Screen mode opens overlay and Esc exits full-screen WITHOUT closing the modal+ const fsBtn = findElements(+ container,+ (el) => el.getAttribute('aria-label') === 'View in full-screen'+ )[0];+ expect(fsBtn).toBeDefined();+ await act(async () => {+ dispatchClick(fsBtn);+ });+ expect(+ findElements(container, (el) => el.getAttribute('aria-label') === 'Time-lapse Full-screen Preview')+ ).toHaveLength(1);++ await act(async () => {+ const escEv = new Event('keydown', { bubbles: true, cancelable: true }) as KeyboardEvent;+ Object.defineProperty(escEv, 'key', { value: 'Escape' });+ miniWin.dispatchEvent(escEv);+ });+ expect(+ findElements(container, (el) => el.getAttribute('aria-label') === 'Time-lapse Full-screen Preview')+ ).toHaveLength(0);+ expect(onClose).not.toHaveBeenCalled();++ // 4. Watermark tab exposes toggle & text/image modes+ const wmTab = findElements(+ container,+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Watermark'+ )[0];+ await act(async () => {+ dispatchClick(wmTab);+ });+ expect(container.textContent).toContain('Enable Watermark');+ expect(container.textContent).toContain('Logo / Signature');+ });+});diff --git a/src/utils/animationEngine.ts b/src/utils/animationEngine.tsindex 096171e..33e6581 100644--- a/src/utils/animationEngine.ts+++ b/src/utils/animationEngine.ts@@ -1,6 +1,7 @@import { zipSync } from 'fflate';import { AnimationTimeline, OnionSkinSettings, LayerItem } from '../types/editor';import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';+import { saveFileWithDialog, SaveFileDialogResult } from './fileSaveDialog';export interface OnionSkinFrameInfo {frame: number;@@ -279,6 +280,39 @@ export function renderAnimationFrame(return canvas;}+/**+ * Prompts the user to choose where to save an exported animation file.+ */+export async function saveAnimationBlob(+ blob: Blob,+ filename: string+): Promise<SaveFileDialogResult> {+ const dotIdx = filename.lastIndexOf('.');+ const ext = dotIdx >= 0 ? filename.slice(dotIdx).toLowerCase() : '.gif';+ const description =+ ext === '.gif'+ ? 'GIF Animation'+ : ext === '.png'+ ? 'Animated PNG (APNG)'+ : ext === '.mp4'+ ? 'MP4 Video'+ : ext === '.webm'+ ? 'WebM Video'+ : ext === '.zip'+ ? 'PNG Sequence Archive'+ : 'Animation File';++ return saveFileWithDialog({+ data: blob,+ suggestedName: filename,+ mimeType: blob.type || 'application/octet-stream',+ description,+ extensions: [ext],+ category: 'animation',+ title: 'Save Animation As',+ });+}+/*** Downloads a Blob directly to the client's filesystem.*/diff --git a/src/utils/appCloseFlow.ts b/src/utils/appCloseFlow.tsindex 6d0f22d..718bc49 100644--- a/src/utils/appCloseFlow.ts+++ b/src/utils/appCloseFlow.ts@@ -128,7 +128,7 @@ export async function finalizeAppClose(deps: FinalizeAppCloseDeps = {}): Promiseconst closeRecovery =deps.closeRecoverySession ?? ((id: string) => recoveryService.closeSession(id));const closeTimelapse =- deps.closeTimelapseSession ?? ((id: string) => globalTimelapseManager.removeSession(id));+ deps.closeTimelapseSession ?? ((id: string) => globalTimelapseManager.detachSession(id));const checkTauri = deps.isTauri ?? isTauriEnvironment;try {diff --git a/src/utils/canvasResizeCrop.ts b/src/utils/canvasResizeCrop.tsnew file mode 100644index 0000000..c1357fa--- /dev/null+++ b/src/utils/canvasResizeCrop.ts@@ -0,0 +1,896 @@+import { CanvasDimensions } from '../types/editor';+import { AnchorPosition, ResizeCanvasOptions } from '../types/settings';++export const MIN_CANVAS_DIM = 1;+export const MAX_CANVAS_DIM = 16384;++export type CropHandleId = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move';+export type CropResizeHandleId = Exclude<CropHandleId, 'move'>;+export type CropGridMode = 'thirds' | 'golden' | 'none';++export interface CropRect {+ /** Left edge of the new canvas in current document pixel coordinates (negative expands left). */+ x: number;+ /** Top edge of the new canvas in current document pixel coordinates (negative expands top). */+ y: number;+ /** Width of the new canvas in pixels. */+ width: number;+ /** Height of the new canvas in pixels. */+ height: number;+}++export interface SnapTargets {+ x: number[];+ y: number[];+ threshold: number;+}++export interface SnapGuides {+ x?: number;+ y?: number;+}++export interface CanvasResizeDraft {+ originWidth: number;+ originHeight: number;+ cropX: number;+ cropY: number;+ width: number;+ height: number;+ dpi: number;+ scaleContent: boolean;+ /** Active anchor preset, or null when manually cropped/offset. */+ anchor: AnchorPosition | null;+ lockRatio: boolean;+ ratioX: number;+ ratioY: number;+ gridMode: CropGridMode;+}++export interface RatioPreset {+ label: string;+ x: number;+ y: number;+}++export const RATIO_PRESETS: RatioPreset[] = [+ { label: '16:9', x: 16, y: 9 },+ { label: '1:1', x: 1, y: 1 },+ { label: '4:3', x: 4, y: 3 },+ { label: '3:2', x: 3, y: 2 },+ { label: '9:16', x: 9, y: 16 },+ { label: '2:3', x: 2, y: 3 },+ { label: '21:9', x: 21, y: 9 },+];++export function clampCanvasDimension(value: number, min = MIN_CANVAS_DIM, max = MAX_CANVAS_DIM): number {+ if (!Number.isFinite(value)) return min;+ return Math.max(min, Math.min(max, Math.round(value)));+}++export function clampCropCoordinate(value: number): number {+ if (!Number.isFinite(value)) return 0;+ return Math.max(-MAX_CANVAS_DIM, Math.min(MAX_CANVAS_DIM, Math.round(value))) || 0;+}++/**+ * Computes the crop rectangle origin (cropX, cropY) in current document coordinates+ * corresponding to a standard 3x3 anchor alignment.+ *+ * Since ResizeCanvas shifts existing pixels by (offsetX, offsetY) into the new canvas,+ * the new canvas's (0, 0) lies at (-offsetX, -offsetY) in the old document coordinate system.+ */+export function computeCropOriginForAnchor(+ originWidth: number,+ originHeight: number,+ targetWidth: number,+ targetHeight: number,+ anchor: AnchorPosition+): { cropX: number; cropY: number } {+ let offsetX: number;+ if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {+ offsetX = 0;+ } else if (anchor === 'top-right' || anchor === 'right' || anchor === 'bottom-right') {+ offsetX = targetWidth - originWidth;+ } else {+ offsetX = Math.round((targetWidth - originWidth) / 2);+ }++ let offsetY: number;+ if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {+ offsetY = 0;+ } else if (anchor === 'bottom-left' || anchor === 'bottom' || anchor === 'bottom-right') {+ offsetY = targetHeight - originHeight;+ } else {+ offsetY = Math.round((targetHeight - originHeight) / 2);+ }++ return {+ cropX: -offsetX || 0,+ cropY: -offsetY || 0,+ };+}++export function createInitialCanvasResizeDraft(dimensions: CanvasDimensions): CanvasResizeDraft {+ const w = clampCanvasDimension(dimensions.width || 1920);+ const h = clampCanvasDimension(dimensions.height || 1080);+ const dpi = Math.max(1, Math.min(4800, Math.round(dimensions.dpi || 300)));+ return {+ originWidth: w,+ originHeight: h,+ cropX: 0,+ cropY: 0,+ width: w,+ height: h,+ dpi,+ scaleContent: false,+ anchor: 'center',+ lockRatio: false,+ ratioX: w,+ ratioY: h,+ gridMode: 'thirds',+ };+}++export function isCropModified(draft: CanvasResizeDraft): boolean {+ return (+ Math.round(draft.cropX) !== 0 ||+ Math.round(draft.cropY) !== 0 ||+ Math.round(draft.width) !== Math.round(draft.originWidth) ||+ Math.round(draft.height) !== Math.round(draft.originHeight)+ );+}++export function draftToResizeCanvasOptions(draft: CanvasResizeDraft): ResizeCanvasOptions {+ const width = clampCanvasDimension(draft.width);+ const height = clampCanvasDimension(draft.height);+ const dpi = Math.max(1, Math.min(4800, Math.round(draft.dpi || 300)));++ if (draft.scaleContent) {+ return {+ width,+ height,+ dpi,+ scaleContent: true,+ anchor: draft.anchor ?? 'center',+ };+ }++ return {+ width,+ height,+ dpi,+ scaleContent: false,+ anchor: draft.anchor ?? 'center',+ offsetX: -clampCropCoordinate(draft.cropX) || 0,+ offsetY: -clampCropCoordinate(draft.cropY) || 0,+ };+}++export function applyWidthToDraft(draft: CanvasResizeDraft, rawWidth: number): CanvasResizeDraft {+ const newW = clampCanvasDimension(rawWidth);+ let newH = draft.height;+ if (draft.lockRatio && draft.ratioX > 0 && draft.ratioY > 0) {+ newH = clampCanvasDimension((newW * draft.ratioY) / draft.ratioX);+ }+ const origin = draft.anchor+ ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)+ : { cropX: draft.cropX, cropY: draft.cropY };+ return {+ ...draft,+ width: newW,+ height: newH,+ cropX: origin.cropX,+ cropY: origin.cropY,+ ratioX: draft.lockRatio ? draft.ratioX : newW,+ ratioY: draft.lockRatio ? draft.ratioY : newH,+ };+}++export function applyHeightToDraft(draft: CanvasResizeDraft, rawHeight: number): CanvasResizeDraft {+ const newH = clampCanvasDimension(rawHeight);+ let newW = draft.width;+ if (draft.lockRatio && draft.ratioX > 0 && draft.ratioY > 0) {+ newW = clampCanvasDimension((newH * draft.ratioX) / draft.ratioY);+ }+ const origin = draft.anchor+ ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)+ : { cropX: draft.cropX, cropY: draft.cropY };+ return {+ ...draft,+ width: newW,+ height: newH,+ cropX: origin.cropX,+ cropY: origin.cropY,+ ratioX: draft.lockRatio ? draft.ratioX : newW,+ ratioY: draft.lockRatio ? draft.ratioY : newH,+ };+}++export function applyCropXToDraft(draft: CanvasResizeDraft, rawCropX: number): CanvasResizeDraft {+ return {+ ...draft,+ cropX: clampCropCoordinate(rawCropX),+ anchor: null,+ };+}++export function applyCropYToDraft(draft: CanvasResizeDraft, rawCropY: number): CanvasResizeDraft {+ return {+ ...draft,+ cropY: clampCropCoordinate(rawCropY),+ anchor: null,+ };+}++export function applyAnchorToDraft(+ draft: CanvasResizeDraft,+ anchor: AnchorPosition+): CanvasResizeDraft {+ const { cropX, cropY } = computeCropOriginForAnchor(+ draft.originWidth,+ draft.originHeight,+ draft.width,+ draft.height,+ anchor+ );+ return {+ ...draft,+ anchor,+ cropX,+ cropY,+ };+}++export function applyLockRatioToggleToDraft(+ draft: CanvasResizeDraft,+ lockRatio: boolean+): CanvasResizeDraft {+ return {+ ...draft,+ lockRatio,+ ratioX: lockRatio ? Math.max(1, draft.width) : draft.ratioX,+ ratioY: lockRatio ? Math.max(1, draft.height) : draft.ratioY,+ };+}++export function applyRatioPresetToDraft(+ draft: CanvasResizeDraft,+ ratioX: number,+ ratioY: number+): CanvasResizeDraft {+ if (ratioX <= 0 || ratioY <= 0) return draft;+ const prevCx = draft.cropX + draft.width / 2;+ const prevCy = draft.cropY + draft.height / 2;++ let newW = draft.width;+ let newH = Math.round((newW * ratioY) / ratioX);+ if (newH > MAX_CANVAS_DIM) {+ newH = MAX_CANVAS_DIM;+ newW = clampCanvasDimension((newH * ratioX) / ratioY);+ } else {+ newH = clampCanvasDimension(newH);+ }++ const origin = draft.anchor+ ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)+ : {+ cropX: clampCropCoordinate(prevCx - newW / 2),+ cropY: clampCropCoordinate(prevCy - newH / 2),+ };++ return {+ ...draft,+ width: newW,+ height: newH,+ cropX: origin.cropX,+ cropY: origin.cropY,+ lockRatio: true,+ ratioX,+ ratioY,+ };+}++export function applySwapDimensionsToDraft(draft: CanvasResizeDraft): CanvasResizeDraft {+ const prevCx = draft.cropX + draft.width / 2;+ const prevCy = draft.cropY + draft.height / 2;+ const newW = draft.height;+ const newH = draft.width;++ const origin = draft.anchor+ ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)+ : {+ cropX: clampCropCoordinate(prevCx - newW / 2),+ cropY: clampCropCoordinate(prevCy - newH / 2),+ };++ return {+ ...draft,+ width: newW,+ height: newH,+ cropX: origin.cropX,+ cropY: origin.cropY,+ ratioX: draft.ratioY,+ ratioY: draft.ratioX,+ };+}++export function applyResetCropToDraft(draft: CanvasResizeDraft): CanvasResizeDraft {+ return {+ ...draft,+ cropX: 0,+ cropY: 0,+ width: draft.originWidth,+ height: draft.originHeight,+ anchor: 'center',+ lockRatio: false,+ ratioX: draft.originWidth,+ ratioY: draft.originHeight,+ };+}++export function applyFitBoundsToDraft(+ draft: CanvasResizeDraft,+ bounds: { x: number; y: number; width: number; height: number }+): CanvasResizeDraft {+ const x = clampCropCoordinate(bounds.x);+ const y = clampCropCoordinate(bounds.y);+ const width = clampCanvasDimension(bounds.width);+ const height = clampCanvasDimension(bounds.height);+ return {+ ...draft,+ scaleContent: false,+ cropX: x,+ cropY: y,+ width,+ height,+ anchor: null,+ lockRatio: false,+ ratioX: width,+ ratioY: height,+ };+}++export function applyCropRectToDraft(+ draft: CanvasResizeDraft,+ rect: CropRect+): CanvasResizeDraft {+ const width = clampCanvasDimension(rect.width);+ const height = clampCanvasDimension(rect.height);+ const cropX = clampCropCoordinate(rect.x);+ const cropY = clampCropCoordinate(rect.y);+ return {+ ...draft,+ cropX,+ cropY,+ width,+ height,+ anchor: null,+ ratioX: draft.lockRatio ? draft.ratioX : width,+ ratioY: draft.lockRatio ? draft.ratioY : height,+ };+}++export function applyScaleContentToggleToDraft(+ draft: CanvasResizeDraft,+ scaleContent: boolean,+ autoLockRatioForResample = false+): CanvasResizeDraft {+ if (scaleContent === draft.scaleContent) return draft;+ if (scaleContent) {+ return {+ ...draft,+ scaleContent: true,+ lockRatio: autoLockRatioForResample ? true : draft.lockRatio,+ ratioX: autoLockRatioForResample ? draft.width : draft.ratioX,+ ratioY: autoLockRatioForResample ? draft.height : draft.ratioY,+ };+ }+ return {+ ...draft,+ scaleContent: false,+ };+}++export function nudgeCropDraft(+ draft: CanvasResizeDraft,+ dx: number,+ dy: number+): CanvasResizeDraft {+ if (draft.scaleContent) return draft;+ return {+ ...draft,+ cropX: clampCropCoordinate(draft.cropX + dx),+ cropY: clampCropCoordinate(draft.cropY + dy),+ anchor: null,+ };+}++export function cycleCropGridMode(current: CropGridMode): CropGridMode {+ if (current === 'thirds') return 'golden';+ if (current === 'golden') return 'none';+ return 'thirds';+}++function findClosestSnap(+ value: number,+ targets: number[],+ threshold: number+): { snapped: number; target?: number } {+ let bestTarget: number | undefined;+ let bestDist = threshold;+ for (let i = 0; i < targets.length; i++) {+ const d = Math.abs(value - targets[i]);+ if (d <= bestDist) {+ bestDist = d;+ bestTarget = targets[i];+ }+ }+ if (bestTarget !== undefined) {+ return { snapped: bestTarget, target: bestTarget };+ }+ return { snapped: value };+}++export interface HandleResizeOptions {+ lockAspect?: boolean;+ aspectRatio?: number;+ fromCenter?: boolean;+ minSize?: number;+ maxSize?: number;+ snapTargets?: SnapTargets | null;+}++/**+ * Resizes a CropRect by dragging one of the 8 corner or edge handles.+ * Supports free resize, aspect-locked resize (corners & edges), symmetric Alt-from-center,+ * clamping to [minSize, maxSize], and magnetic edge/center snapping.+ */+export function resizeCropRectByHandle(+ startRect: CropRect,+ handle: CropResizeHandleId,+ dx: number,+ dy: number,+ options: HandleResizeOptions = {}+): { rect: CropRect; snapGuides: SnapGuides } {+ const minSize = options.minSize ?? MIN_CANVAS_DIM;+ const maxSize = options.maxSize ?? MAX_CANVAS_DIM;+ const lockAspect = Boolean(options.lockAspect);+ const fromCenter = Boolean(options.fromCenter);+ const snapTargets = options.snapTargets ?? null;+ const snapGuides: SnapGuides = {};++ const startLeft = Math.round(startRect.x);+ const startTop = Math.round(startRect.y);+ const startW = clampCanvasDimension(startRect.width, minSize, maxSize);+ const startH = clampCanvasDimension(startRect.height, minSize, maxSize);+ const startRight = startLeft + startW;+ const startBottom = startTop + startH;+ const cx = startLeft + startW / 2;+ const cy = startTop + startH / 2;++ const hasW = handle.includes('w');+ const hasE = handle.includes('e');+ const hasN = handle.includes('n');+ const hasS = handle.includes('s');++ if (!lockAspect) {+ let x = startLeft;+ let y = startTop;+ let width = startW;+ let height = startH;++ if (fromCenter) {+ if (hasW || hasE) {+ const rawHalf = Math.max(minSize / 2, startW / 2 + (hasE ? dx : -dx));+ let targetW = rawHalf * 2;+ if (snapTargets) {+ const edgePos = hasE ? cx + rawHalf : cx - rawHalf;+ const snap = findClosestSnap(edgePos, snapTargets.x, snapTargets.threshold);+ if (snap.target !== undefined) {+ targetW = Math.abs(snap.snapped - cx) * 2;+ snapGuides.x = snap.target;+ }+ }+ width = clampCanvasDimension(targetW, minSize, maxSize);+ x = Math.round(cx - width / 2);+ }+ if (hasN || hasS) {+ const rawHalf = Math.max(minSize / 2, startH / 2 + (hasS ? dy : -dy));+ let targetH = rawHalf * 2;+ if (snapTargets) {+ const edgePos = hasS ? cy + rawHalf : cy - rawHalf;+ const snap = findClosestSnap(edgePos, snapTargets.y, snapTargets.threshold);+ if (snap.target !== undefined) {+ targetH = Math.abs(snap.snapped - cy) * 2;+ snapGuides.y = snap.target;+ }+ }+ height = clampCanvasDimension(targetH, minSize, maxSize);+ y = Math.round(cy - height / 2);+ }+ } else {+ if (hasW) {+ let nextLeft = startLeft + dx;+ if (snapTargets) {+ const snap = findClosestSnap(nextLeft, snapTargets.x, snapTargets.threshold);+ if (snap.target !== undefined) {+ nextLeft = snap.snapped;+ snapGuides.x = snap.target;+ }+ }+ width = clampCanvasDimension(startRight - nextLeft, minSize, maxSize);+ x = startRight - width;+ } else if (hasE) {+ let nextRight = startRight + dx;+ if (snapTargets) {+ const snap = findClosestSnap(nextRight, snapTargets.x, snapTargets.threshold);+ if (snap.target !== undefined) {+ nextRight = snap.snapped;+ snapGuides.x = snap.target;+ }+ }+ width = clampCanvasDimension(nextRight - startLeft, minSize, maxSize);+ x = startLeft;+ }++ if (hasN) {+ let nextTop = startTop + dy;+ if (snapTargets) {+ const snap = findClosestSnap(nextTop, snapTargets.y, snapTargets.threshold);+ if (snap.target !== undefined) {+ nextTop = snap.snapped;+ snapGuides.y = snap.target;+ }+ }+ height = clampCanvasDimension(startBottom - nextTop, minSize, maxSize);+ y = startBottom - height;+ } else if (hasS) {+ let nextBottom = startBottom + dy;+ if (snapTargets) {+ const snap = findClosestSnap(nextBottom, snapTargets.y, snapTargets.threshold);+ if (snap.target !== undefined) {+ nextBottom = snap.snapped;+ snapGuides.y = snap.target;+ }+ }+ height = clampCanvasDimension(nextBottom - startTop, minSize, maxSize);+ y = startTop;+ }+ }++ return {+ rect: {+ x: clampCropCoordinate(x),+ y: clampCropCoordinate(y),+ width,+ height,+ },+ snapGuides,+ };+ }++ // Aspect-locked resize+ const rawRatio = options.aspectRatio;+ const r =+ typeof rawRatio === 'number' && Number.isFinite(rawRatio) && rawRatio > 0+ ? rawRatio+ : startW / Math.max(1, startH);++ const minW = Math.min(maxSize, Math.max(minSize, Math.ceil(minSize * r)));+ const maxW = Math.max(minW, Math.min(maxSize, Math.floor(maxSize * r)));+ const minH = Math.min(maxSize, Math.max(minSize, Math.ceil(minSize / r)));+ const maxH = Math.max(minH, Math.min(maxSize, Math.floor(maxSize / r)));++ const isCorner = (hasW || hasE) && (hasN || hasS);+ let width = startW;+ let height = startH;++ if (isCorner) {+ let rawW = fromCenter+ ? startW + 2 * (hasE ? dx : -dx)+ : startW + (hasE ? dx : -dx);+ let rawH = fromCenter+ ? startH + 2 * (hasS ? dy : -dy)+ : startH + (hasS ? dy : -dy);++ // Optional edge snap before aspect projection+ if (snapTargets && !fromCenter) {+ const candX = hasE ? startLeft + rawW : startRight - rawW;+ const snapX = findClosestSnap(candX, snapTargets.x, snapTargets.threshold);+ const candY = hasS ? startTop + rawH : startBottom - rawH;+ const snapY = findClosestSnap(candY, snapTargets.y, snapTargets.threshold);+ if (snapX.target !== undefined) {+ rawW = hasE ? snapX.snapped - startLeft : startRight - snapX.snapped;+ rawH = rawW / r;+ snapGuides.x = snapX.target;+ } else if (snapY.target !== undefined) {+ rawH = hasS ? snapY.snapped - startTop : startBottom - snapY.snapped;+ rawW = rawH * r;+ snapGuides.y = snapY.target;+ }+ }++ // Smooth orthogonal projection onto aspect line (w = h * r)+ const projH = (rawW * r + rawH) / (r * r + 1);+ const projW = projH * r;+ width = clampCanvasDimension(projW, minW, maxW);+ height = clampCanvasDimension(width / r, minSize, maxSize);++ const x = fromCenter+ ? Math.round(cx - width / 2)+ : hasW+ ? startRight - width+ : startLeft;+ const y = fromCenter+ ? Math.round(cy - height / 2)+ : hasN+ ? startBottom - height+ : startTop;++ return {+ rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },+ snapGuides,+ };+ }++ // Horizontal edge handle (e or w) with locked aspect+ if (hasW || hasE) {+ let rawW = fromCenter+ ? startW + 2 * (hasE ? dx : -dx)+ : startW + (hasE ? dx : -dx);+ if (snapTargets && !fromCenter) {+ const candX = hasE ? startLeft + rawW : startRight - rawW;+ const snapX = findClosestSnap(candX, snapTargets.x, snapTargets.threshold);+ if (snapX.target !== undefined) {+ rawW = hasE ? snapX.snapped - startLeft : startRight - snapX.snapped;+ snapGuides.x = snapX.target;+ }+ }+ width = clampCanvasDimension(rawW, minW, maxW);+ height = clampCanvasDimension(width / r, minSize, maxSize);+ const x = fromCenter+ ? Math.round(cx - width / 2)+ : hasW+ ? startRight - width+ : startLeft;+ const y = Math.round(cy - height / 2);+ return {+ rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },+ snapGuides,+ };+ }++ // Vertical edge handle (n or s) with locked aspect+ let rawH = fromCenter+ ? startH + 2 * (hasS ? dy : -dy)+ : startH + (hasS ? dy : -dy);+ if (snapTargets && !fromCenter) {+ const candY = hasS ? startTop + rawH : startBottom - rawH;+ const snapY = findClosestSnap(candY, snapTargets.y, snapTargets.threshold);+ if (snapY.target !== undefined) {+ rawH = hasS ? snapY.snapped - startTop : startBottom - snapY.snapped;+ snapGuides.y = snapY.target;+ }+ }+ height = clampCanvasDimension(rawH, minH, maxH);+ width = clampCanvasDimension(height * r, minSize, maxSize);+ const x = Math.round(cx - width / 2);+ const y = fromCenter+ ? Math.round(cy - height / 2)+ : hasN+ ? startBottom - height+ : startTop;+ return {+ rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },+ snapGuides,+ };+}++export interface MoveCropOptions {+ constrainAxis?: boolean;+ snapTargets?: SnapTargets | null;+}++/**+ * Moves a CropRect by (dx, dy) in document pixel space with optional Shift axis locking+ * and magnetic snapping of left/center/right and top/middle/bottom edges.+ */+export function moveCropRect(+ startRect: CropRect,+ dx: number,+ dy: number,+ options: MoveCropOptions = {}+): { rect: CropRect; snapGuides: SnapGuides } {+ let effDx = dx;+ let effDy = dy;+ if (options.constrainAxis) {+ if (Math.abs(effDx) >= Math.abs(effDy)) {+ effDy = 0;+ } else {+ effDx = 0;+ }+ }++ let nextX = Math.round(startRect.x + effDx);+ let nextY = Math.round(startRect.y + effDy);+ const width = clampCanvasDimension(startRect.width);+ const height = clampCanvasDimension(startRect.height);+ const snapGuides: SnapGuides = {};++ const snapTargets = options.snapTargets;+ if (snapTargets) {+ // Check left, right, center X+ let bestDx = Infinity;+ let bestTargetX: number | undefined;+ const xEdges = [nextX, nextX + width, nextX + width / 2];+ for (const edge of xEdges) {+ for (const t of snapTargets.x) {+ const dist = Math.abs(edge - t);+ if (dist <= snapTargets.threshold && dist < Math.abs(bestDx)) {+ bestDx = t - edge;+ bestTargetX = t;+ }+ }+ }+ if (bestTargetX !== undefined) {+ nextX = Math.round(nextX + bestDx);+ snapGuides.x = bestTargetX;+ }++ // Check top, bottom, center Y+ let bestDy = Infinity;+ let bestTargetY: number | undefined;+ const yEdges = [nextY, nextY + height, nextY + height / 2];+ for (const edge of yEdges) {+ for (const t of snapTargets.y) {+ const dist = Math.abs(edge - t);+ if (dist <= snapTargets.threshold && dist < Math.abs(bestDy)) {+ bestDy = t - edge;+ bestTargetY = t;+ }+ }+ }+ if (bestTargetY !== undefined) {+ nextY = Math.round(nextY + bestDy);+ snapGuides.y = bestTargetY;+ }+ }++ return {+ rect: {+ x: clampCropCoordinate(nextX),+ y: clampCropCoordinate(nextY),+ width,+ height,+ },+ snapGuides,+ };+}++export interface MarqueeCropOptions {+ lockAspect?: boolean;+ aspectRatio?: number;+ fromCenter?: boolean;+ minSize?: number;+ maxSize?: number;+ snapTargets?: SnapTargets | null;+}++/**+ * Creates a brand-new CropRect by click-dragging on the canvas outside the current crop box.+ */+export function createCropRectFromDrag(+ startPt: { x: number; y: number },+ curPt: { x: number; y: number },+ options: MarqueeCropOptions = {}+): { rect: CropRect; snapGuides: SnapGuides } {+ const minSize = options.minSize ?? MIN_CANVAS_DIM;+ const maxSize = options.maxSize ?? MAX_CANVAS_DIM;+ const lockAspect = Boolean(options.lockAspect);+ const fromCenter = Boolean(options.fromCenter);+ const snapTargets = options.snapTargets ?? null;+ const snapGuides: SnapGuides = {};++ let sx = Math.round(startPt.x);+ let sy = Math.round(startPt.y);+ let ex = Math.round(curPt.x);+ let ey = Math.round(curPt.y);++ if (snapTargets) {+ const snapEx = findClosestSnap(ex, snapTargets.x, snapTargets.threshold);+ if (snapEx.target !== undefined) {+ ex = Math.round(snapEx.snapped);+ snapGuides.x = snapEx.target;+ }+ const snapEy = findClosestSnap(ey, snapTargets.y, snapTargets.threshold);+ if (snapEy.target !== undefined) {+ ey = Math.round(snapEy.snapped);+ snapGuides.y = snapEy.target;+ }+ }++ let rawDx = ex - sx;+ let rawDy = ey - sy;+ const signX = rawDx >= 0 ? 1 : -1;+ const signY = rawDy >= 0 ? 1 : -1;+ let absW = Math.abs(rawDx) * (fromCenter ? 2 : 1);+ let absH = Math.abs(rawDy) * (fromCenter ? 2 : 1);++ if (lockAspect) {+ const r =+ typeof options.aspectRatio === 'number' &&+ Number.isFinite(options.aspectRatio) &&+ options.aspectRatio > 0+ ? options.aspectRatio+ : 1;+ if (absW / r >= absH) {+ absH = absW / r;+ } else {+ absW = absH * r;+ }+ }++ const width = clampCanvasDimension(absW, minSize, maxSize);+ const height = clampCanvasDimension(absH, minSize, maxSize);++ let x: number;+ let y: number;+ if (fromCenter) {+ x = Math.round(sx - width / 2);+ y = Math.round(sy - height / 2);+ } else {+ x = signX >= 0 ? sx : sx - width;+ y = signY >= 0 ? sy : sy - height;+ }++ return {+ rect: {+ x: clampCropCoordinate(x),+ y: clampCropCoordinate(y),+ width,+ height,+ },+ snapGuides,+ };+}++const HANDLE_NORMALS: Record<CropResizeHandleId, [number, number]> = {+ e: [1, 0],+ se: [1, 1],+ s: [0, 1],+ sw: [-1, 1],+ w: [-1, 0],+ nw: [-1, -1],+ n: [0, -1],+ ne: [1, -1],+};++/**+ * Computes the true screen-space CSS resize cursor for a crop handle,+ * compensating for arbitrary viewport rotation, flipX, and flipY.+ */+export function getRotatedResizeCursor(+ handle: CropHandleId,+ rotationDeg: number,+ flipX = false,+ flipY = false+): string {+ if (handle === 'move') return 'move';+ const [nx, ny] = HANDLE_NORMALS[handle];+ const fx = flipX ? -nx : nx;+ const fy = flipY ? -ny : ny;+ const rad = (rotationDeg * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const sx = fx * cos - fy * sin;+ const sy = fx * sin + fy * cos;++ let deg = (Math.atan2(sy, sx) * 180) / Math.PI;+ deg = ((deg % 180) + 180) % 180;++ if (deg < 22.5 || deg >= 157.5) return 'ew-resize';+ if (deg < 67.5) return 'nwse-resize';+ if (deg < 112.5) return 'ns-resize';+ return 'nesw-resize';+}diff --git a/src/utils/collabSyncUtils.ts b/src/utils/collabSyncUtils.tsindex 11e15cb..686d028 100644--- a/src/utils/collabSyncUtils.ts+++ b/src/utils/collabSyncUtils.ts@@ -24,6 +24,7 @@ import { PerspectiveRuler, StraightRuler, VanishingPoint } from '../types/perspeimport { AnchorPosition, ResizeCanvasOptions } from '../types/settings';import { get2DContext } from './canvasUtils';import { releaseTemporaryCanvas } from './tileEngine';+import { normalizeLayerColorLabel } from './layerOrganization';export const MAX_SYNC_LAYERS = 512;export const MAX_SYNC_VECTOR_STROKES = 20000;@@ -62,6 +63,7 @@ const CLEARABLE_FIELDS_SET = new Set<LayerClearableField>(['alphaLocked','clipped','isReference',+ 'colorLabel','isToneLayer','toneEnabled','toneFrequency',@@ -105,6 +107,7 @@ const SYNCED_LAYER_KEYS: ReadonlyArray<keyof WireLayerItem> = ['clipped','parentId','isReference',+ 'colorLabel','isToneLayer','toneEnabled','toneFrequency',@@ -287,6 +290,10 @@ export function sanitizeWireLayerPatch(raw: unknown): Partial<WireLayerItem> {out.parentId = src.parentId === null ? null : safeString(src.parentId, 256) || null;}if (typeof src.isReference === 'boolean') out.isReference = src.isReference;+ if (typeof src.colorLabel === 'string') {+ const normalizedLabel = normalizeLayerColorLabel(src.colorLabel);+ if (normalizedLabel) out.colorLabel = normalizedLabel;+ }// Screentoneif (typeof src.isToneLayer === 'boolean') out.isToneLayer = src.isToneLayer;@@ -570,6 +577,14 @@ export function sanitizeCanvasResize(const anchor: AnchorPosition = ALLOWED_ANCHORS.has(o?.anchor as AnchorPosition)? (o!.anchor as AnchorPosition): 'center';+ const offsetX =+ typeof o?.offsetX === 'number' && Number.isFinite(o.offsetX)+ ? Math.round(clampFinite(o.offsetX, -MAX_SYNC_CANVAS_DIM, MAX_SYNC_CANVAS_DIM, 0))+ : undefined;+ const offsetY =+ typeof o?.offsetY === 'number' && Number.isFinite(o.offsetY)+ ? Math.round(clampFinite(o.offsetY, -MAX_SYNC_CANVAS_DIM, MAX_SYNC_CANVAS_DIM, 0))+ : undefined;return {dimensions: { width, height, dpi },@@ -579,6 +594,8 @@ export function sanitizeCanvasResize(dpi,scaleContent: Boolean(o?.scaleContent),anchor,+ ...(offsetX !== undefined ? { offsetX } : {}),+ ...(offsetY !== undefined ? { offsetY } : {}),backgroundColor: safeString(o?.backgroundColor, 64, '#ffffff'),},};diff --git a/src/utils/colorSetImport.ts b/src/utils/colorSetImport.tsnew file mode 100644index 0000000..94f5654--- /dev/null+++ b/src/utils/colorSetImport.ts@@ -0,0 +1,1001 @@+import { unzlibSync } from 'fflate';++export type ColorSetImportFormat = 'json' | 'cls' | 'png';++export interface ParsedColorSet {+ ok: true;+ format: ColorSetImportFormat;+ name: string;+ swatches: Array<{ hex: string; name?: string }>;+}++export interface ParsedColorSetError {+ ok: false;+ error: string;+}++export type ParseColorSetResult = ParsedColorSet | ParsedColorSetError;++export const COLOR_SET_IMPORT_ACCEPT = '.json,.cls,.png,application/json,image/png';+export const SUPPORTED_COLOR_SET_EXTENSIONS = new Set(['.json', '.cls', '.png']);++const DEFAULT_MAX_SWATCHES = 512;+const MAX_CLS_BYTES = 8 * 1024 * 1024; // 8 MB safety ceiling+const MAX_PNG_BYTES = 25 * 1024 * 1024; // 25 MB safety ceiling+const MAX_PNG_PIXELS = 64_000_000; // 64 MP safety ceiling+const MAX_QUANTIZED_SWATCHES = 24;+const EXACT_SCAN_MAP_LIMIT = 65_536;++const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;++export function isSupportedColorSetFilename(filename: string): boolean {+ const lower = filename.trim().toLowerCase();+ const dot = lower.lastIndexOf('.');+ if (dot <= 0) return false;+ return SUPPORTED_COLOR_SET_EXTENSIONS.has(lower.slice(dot));+}++export function deriveColorSetNameFromFilename(+ filename: string | undefined,+ fallback: string+): string {+ if (!filename || typeof filename !== 'string') return fallback;+ const normalized = filename.replace(/\\/g, '/');+ const base = normalized.slice(normalized.lastIndexOf('/') + 1);+ // Strip `.inkcolorset.json` or any single extension+ const stripped = base.replace(/\.inkcolorset\.json$/i, '').replace(/\.[^/.]+$/, '');+ const clean = stripControlChars(stripped).trim().slice(0, 48);+ return clean || fallback;+}++function stripControlChars(value: string): string {+ let out = '';+ for (let i = 0; i < value.length; i++) {+ const code = value.charCodeAt(i);+ if (code >= 0x20 && code !== 0x7f) {+ out += value[i];+ }+ }+ return out;+}++function rgbBytesToHex(r: number, g: number, b: number): string {+ return (+ '#' ++ ((1 << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff))+ .toString(16)+ .slice(1)+ );+}++export function hasSlccMagic(bytes: Uint8Array): boolean {+ return (+ bytes.byteLength >= 4 &&+ bytes[0] === 0x53 && // 'S'+ bytes[1] === 0x4c && // 'L'+ bytes[2] === 0x43 && // 'C'+ bytes[3] === 0x43 // 'C'+ );+}++export function hasPngSignature(bytes: Uint8Array): boolean {+ if (bytes.byteLength < 8) return false;+ for (let i = 0; i < 8; i++) {+ if (bytes[i] !== PNG_SIGNATURE[i]) return false;+ }+ return true;+}++function decodeUtf8Strict(bytes: Uint8Array): string | null {+ try {+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);+ } catch {+ return null;+ }+}++function decodeLatin1(bytes: Uint8Array): string {+ let out = '';+ for (let i = 0; i < bytes.length; i++) {+ out += String.fromCharCode(bytes[i]);+ }+ return out;+}++function decodeClsSwatchName(bytes: Uint8Array): string | undefined {+ if (bytes.byteLength === 0) return undefined;+ let decoded: string;+ if (bytes.byteLength % 2 === 0) {+ try {+ decoded = new TextDecoder('utf-16le', { fatal: true }).decode(bytes);+ } catch {+ decoded = decodeUtf8Strict(bytes) ?? decodeLatin1(bytes);+ }+ } else {+ decoded = decodeUtf8Strict(bytes) ?? decodeLatin1(bytes);+ }+ const cleaned = stripControlChars(decoded.replace(/\0+$/g, '')).trim().slice(0, 48);+ return cleaned || undefined;+}++/**+ * Parses a Clip Studio Paint Color Set (`.cls`, magic `"SLCC"`) binary buffer.+ *+ * Binary layout:+ * - `[0..3]` `"SLCC"` magic+ * - `[4..5]` version `uint16 LE` (typically `0x0100` / 256)+ * - `[6..9]` `headerByteLength` (`uint32 LE`) starting at offset 10+ * - `[10..10+headerByteLength)` metadata:+ * `uint16 LE` name1Len + name1 bytes,+ * optional `uint32 LE` flags/padding + `uint16 LE` name2Len + UTF-8 name2 bytes+ * - `[headerEnd..headerEnd+12)`:+ * `uint32 LE` channelCount (4),+ * `uint32 LE` colorCount,+ * `uint32 LE` colorDataByteLength+ * - Repeated `colorCount` times:+ * `uint32 LE` entryPayloadLength,+ * `[r, g, b, a]` (4 bytes; `a === 0` represents an empty slot in CSP),+ * optional `uint32 LE` hasNameFlag,+ * if `hasNameFlag !== 0`: `uint16 LE` nameByteLength + UTF-16LE name bytes+ */+export function parseClipStudioColorSet(+ data: Uint8Array | ArrayBuffer,+ filename?: string,+ maxSwatches: number = DEFAULT_MAX_SWATCHES+): ParseColorSetResult {+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);+ if (bytes.byteLength === 0) {+ return { ok: false, error: 'Clip Studio color set file is empty.' };+ }+ if (bytes.byteLength > MAX_CLS_BYTES) {+ return { ok: false, error: 'Clip Studio color set file exceeds 8 MB limit.' };+ }+ if (!hasSlccMagic(bytes)) {+ return { ok: false, error: 'Invalid Clip Studio color set (.cls): missing SLCC header.' };+ }+ if (bytes.byteLength < 22) {+ return { ok: false, error: 'Clip Studio color set (.cls) is truncated.' };+ }++ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const headerByteLength = view.getUint32(6, true);+ const headerStart = 10;+ const headerEnd = headerStart + headerByteLength;++ if (headerEnd + 12 > bytes.byteLength) {+ return { ok: false, error: 'Clip Studio color set (.cls) header is truncated.' };+ }++ // Extract set name from header metadata (preferring the secondary UTF-8 name when present)+ let primaryName: string | null = null;+ let utf8Name: string | null = null;++ if (headerByteLength >= 2) {+ const l1 = view.getUint16(headerStart, true);+ const name1Start = headerStart + 2;+ const name1End = name1Start + l1;+ if (name1End <= headerEnd) {+ if (l1 > 0) {+ const raw1 = bytes.subarray(name1Start, name1End);+ const s1 = stripControlChars(decodeUtf8Strict(raw1) ?? decodeLatin1(raw1)).trim();+ if (s1) primaryName = s1;+ }+ // Secondary UTF-8 name block: 4-byte reserved/flags + uint16 length + UTF-8 bytes+ const l2Pos = name1End + 4;+ if (l2Pos + 2 <= headerEnd) {+ const l2 = view.getUint16(l2Pos, true);+ const name2Start = l2Pos + 2;+ const name2End = name2Start + l2;+ if (l2 > 0 && name2End <= headerEnd) {+ const raw2 = bytes.subarray(name2Start, name2End);+ const s2 = stripControlChars(decodeUtf8Strict(raw2) ?? decodeLatin1(raw2)).trim();+ if (s2) utf8Name = s2;+ }+ }+ }+ }++ const colorCount = view.getUint32(headerEnd + 4, true);+ const colorDataByteLength = view.getUint32(headerEnd + 8, true);++ let pos = headerEnd + 12;+ const entriesEnd =+ colorDataByteLength > 0+ ? Math.min(bytes.byteLength, pos + colorDataByteLength)+ : bytes.byteLength;++ if (colorCount === 0) {+ return { ok: false, error: 'Clip Studio color set contains no color swatches.' };+ }++ const swatches: Array<{ hex: string; name?: string }> = [];+ for (let i = 0; i < colorCount; i++) {+ if (pos + 4 > entriesEnd) {+ if (swatches.length === 0) {+ return { ok: false, error: 'Clip Studio color set (.cls) color table is truncated.' };+ }+ break;+ }++ const entryPayloadLen = view.getUint32(pos, true);+ pos += 4;+ if (entryPayloadLen < 4 || pos + entryPayloadLen > bytes.byteLength) {+ if (swatches.length === 0) {+ return { ok: false, error: 'Clip Studio color set (.cls) has an invalid swatch entry.' };+ }+ break;+ }++ const payloadEnd = pos + entryPayloadLen;+ const r = bytes[pos];+ const g = bytes[pos + 1];+ const b = bytes[pos + 2];+ const a = bytes[pos + 3];++ // Alpha 0 represents an empty grid cell in Clip Studio Paint color sets.+ if (a > 0 && swatches.length < maxSwatches) {+ let swatchName: string | undefined;+ if (entryPayloadLen >= 10) {+ const hasNameFlag = view.getUint32(pos + 4, true);+ if (hasNameFlag !== 0) {+ const nameByteLen = view.getUint16(pos + 8, true);+ const nameStart = pos + 10;+ const nameEnd = Math.min(payloadEnd, nameStart + nameByteLen);+ if (nameByteLen > 0 && nameEnd > nameStart) {+ swatchName = decodeClsSwatchName(bytes.subarray(nameStart, nameEnd));+ }+ }+ }++ const hex = rgbBytesToHex(r, g, b);+ swatches.push(swatchName ? { hex, name: swatchName } : { hex });+ }++ pos = payloadEnd;+ }++ if (swatches.length === 0) {+ return { ok: false, error: 'No opaque colors found in Clip Studio color set.' };+ }++ const resolvedName = (+ utf8Name ||+ primaryName ||+ deriveColorSetNameFromFilename(filename, 'Clip Studio Color Set')+ ).slice(0, 48);++ return {+ ok: true,+ format: 'cls',+ name: resolvedName,+ swatches,+ };+}++// ============================================================================+// Pure PNG Decoder + Smart Palette Extractor+// ============================================================================++export interface DecodedPng {+ width: number;+ height: number;+ rgba: Uint8ClampedArray;+ title?: string;+}++function paethPredictor(a: number, b: number, c: number): number {+ const p = a + b - c;+ const pa = Math.abs(p - a);+ const pb = Math.abs(p - b);+ const pc = Math.abs(p - c);+ if (pa <= pb && pa <= pc) return a;+ if (pb <= pc) return b;+ return c;+}++function unfilterScanline(+ filterType: number,+ raw: Uint8Array,+ rawOffset: number,+ dest: Uint8Array,+ prev: Uint8Array | null,+ stride: number,+ bpp: number+): void {+ switch (filterType) {+ case 0: // None+ for (let i = 0; i < stride; i++) {+ dest[i] = raw[rawOffset + i];+ }+ break;+ case 1: // Sub+ for (let i = 0; i < stride; i++) {+ const left = i >= bpp ? dest[i - bpp] : 0;+ dest[i] = (raw[rawOffset + i] + left) & 0xff;+ }+ break;+ case 2: // Up+ for (let i = 0; i < stride; i++) {+ const up = prev ? prev[i] : 0;+ dest[i] = (raw[rawOffset + i] + up) & 0xff;+ }+ break;+ case 3: // Average+ for (let i = 0; i < stride; i++) {+ const left = i >= bpp ? dest[i - bpp] : 0;+ const up = prev ? prev[i] : 0;+ dest[i] = (raw[rawOffset + i] + ((left + up) >> 1)) & 0xff;+ }+ break;+ case 4: // Paeth+ for (let i = 0; i < stride; i++) {+ const left = i >= bpp ? dest[i - bpp] : 0;+ const up = prev ? prev[i] : 0;+ const upLeft = prev && i >= bpp ? prev[i - bpp] : 0;+ dest[i] = (raw[rawOffset + i] + paethPredictor(left, up, upLeft)) & 0xff;+ }+ break;+ default:+ throw new Error(`Unsupported PNG filter type: ${filterType}`);+ }+}++function readSample(scanline: Uint8Array, pixelIndex: number, bitDepth: number): number {+ if (bitDepth === 8) return scanline[pixelIndex];+ if (bitDepth === 16) return scanline[pixelIndex * 2]; // High byte+ const pixelsPerByte = 8 / bitDepth;+ const byteIndex = Math.floor(pixelIndex / pixelsPerByte);+ const shift = 8 - bitDepth * ((pixelIndex % pixelsPerByte) + 1);+ const mask = (1 << bitDepth) - 1;+ return (scanline[byteIndex] >> shift) & mask;+}++function writePngRowToRgba(+ scanline: Uint8Array,+ rowWidth: number,+ colorType: number,+ bitDepth: number,+ palette: Uint8Array | null,+ trns: Uint8Array | null,+ rgba: Uint8ClampedArray,+ imageWidth: number,+ destY: number,+ destXStart: number,+ destXStep: number+): void {+ const maxSample = bitDepth < 8 ? (1 << bitDepth) - 1 : 255;++ let trnsGray = -1;+ let trnsR = -1;+ let trnsG = -1;+ let trnsB = -1;+ if (trns) {+ if (colorType === 0 && trns.length >= 2) {+ trnsGray = bitDepth === 16 ? trns[0] : ((trns[0] << 8) | trns[1]) & maxSample;+ } else if (colorType === 2 && trns.length >= 6) {+ if (bitDepth === 16) {+ trnsR = trns[0];+ trnsG = trns[2];+ trnsB = trns[4];+ } else {+ trnsR = trns[1];+ trnsG = trns[3];+ trnsB = trns[5];+ }+ }+ }++ for (let x = 0; x < rowWidth; x++) {+ const outIdx = (destY * imageWidth + (destXStart + x * destXStep)) * 4;+ let r = 0;+ let g = 0;+ let b = 0;+ let a = 255;++ if (colorType === 3) {+ // Indexed color (PLTE)+ const idx = readSample(scanline, x, bitDepth);+ if (palette && idx * 3 + 2 < palette.length) {+ r = palette[idx * 3];+ g = palette[idx * 3 + 1];+ b = palette[idx * 3 + 2];+ }+ if (trns && idx < trns.length) {+ a = trns[idx];+ }+ } else if (colorType === 0) {+ // Grayscale+ const sample = readSample(scanline, x, bitDepth);+ const v = bitDepth < 8 ? Math.round((sample * 255) / maxSample) : sample;+ r = v;+ g = v;+ b = v;+ if (trnsGray >= 0 && sample === trnsGray) {+ a = 0;+ }+ } else if (colorType === 2) {+ // Truecolor RGB+ const step = bitDepth === 16 ? 2 : 1;+ const base = x * 3 * step;+ r = scanline[base];+ g = scanline[base + step];+ b = scanline[base + 2 * step];+ if (trnsR >= 0 && r === trnsR && g === trnsG && b === trnsB) {+ a = 0;+ }+ } else if (colorType === 4) {+ // Grayscale + Alpha+ const step = bitDepth === 16 ? 2 : 1;+ const base = x * 2 * step;+ const v = scanline[base];+ r = v;+ g = v;+ b = v;+ a = scanline[base + step];+ } else if (colorType === 6) {+ // Truecolor RGBA+ const step = bitDepth === 16 ? 2 : 1;+ const base = x * 4 * step;+ r = scanline[base];+ g = scanline[base + step];+ b = scanline[base + 2 * step];+ a = scanline[base + 3 * step];+ }++ rgba[outIdx] = r;+ rgba[outIdx + 1] = g;+ rgba[outIdx + 2] = b;+ rgba[outIdx + 3] = a;+ }+}++const ADAM7_PASSES: ReadonlyArray<readonly [number, number, number, number]> = [+ [0, 0, 8, 8],+ [4, 0, 8, 8],+ [0, 4, 4, 8],+ [2, 0, 4, 4],+ [0, 2, 2, 4],+ [1, 0, 2, 2],+ [0, 1, 1, 2],+];++export function decodePngBytes(data: Uint8Array | ArrayBuffer): DecodedPng {+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);+ if (!hasPngSignature(bytes)) {+ throw new Error('Invalid PNG file: missing PNG signature.');+ }++ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let offset = 8;++ let width = 0;+ let height = 0;+ let bitDepth = 0;+ let colorType = 0;+ let interlace = 0;+ let sawIhdr = false;+ let palette: Uint8Array | null = null;+ let trns: Uint8Array | null = null;+ let title: string | undefined;+ const idatChunks: Uint8Array[] = [];+ let totalIdatLen = 0;++ while (offset + 12 <= bytes.byteLength) {+ const length = view.getUint32(offset, false);+ const type = String.fromCharCode(+ bytes[offset + 4],+ bytes[offset + 5],+ bytes[offset + 6],+ bytes[offset + 7]+ );+ const dataStart = offset + 8;+ const dataEnd = dataStart + length;+ if (dataEnd + 4 > bytes.byteLength) {+ throw new Error('PNG file is truncated.');+ }++ if (type === 'IHDR') {+ if (length < 13) throw new Error('Invalid PNG IHDR chunk.');+ width = view.getUint32(dataStart, false);+ height = view.getUint32(dataStart + 4, false);+ bitDepth = bytes[dataStart + 8];+ colorType = bytes[dataStart + 9];+ const compression = bytes[dataStart + 10];+ const filterMethod = bytes[dataStart + 11];+ interlace = bytes[dataStart + 12];+ if (width === 0 || height === 0) {+ throw new Error('PNG image has zero dimensions.');+ }+ if (width * height > MAX_PNG_PIXELS) {+ throw new Error('PNG image dimensions exceed safety limit.');+ }+ if (compression !== 0 || filterMethod !== 0 || (interlace !== 0 && interlace !== 1)) {+ throw new Error('Unsupported PNG encoding parameters.');+ }+ sawIhdr = true;+ } else if (type === 'PLTE') {+ palette = bytes.subarray(dataStart, dataEnd);+ } else if (type === 'tRNS') {+ trns = bytes.subarray(dataStart, dataEnd);+ } else if (type === 'IDAT') {+ const chunk = bytes.subarray(dataStart, dataEnd);+ idatChunks.push(chunk);+ totalIdatLen += chunk.byteLength;+ } else if ((type === 'tEXt' || type === 'iTXt') && !title) {+ const chunk = bytes.subarray(dataStart, dataEnd);+ const nul = chunk.indexOf(0);+ if (nul > 0) {+ const keyword = decodeLatin1(chunk.subarray(0, nul)).toLowerCase();+ if (keyword === 'title') {+ if (type === 'tEXt') {+ const rawVal = stripControlChars(decodeLatin1(chunk.subarray(nul + 1))).trim();+ if (rawVal) title = rawVal.slice(0, 48);+ } else if (type === 'iTXt' && nul + 3 < chunk.length && chunk[nul + 1] === 0) {+ const langEnd = chunk.indexOf(0, nul + 3);+ if (langEnd >= 0) {+ const transEnd = chunk.indexOf(0, langEnd + 1);+ if (transEnd >= 0) {+ const textBytes = chunk.subarray(transEnd + 1);+ const rawVal = stripControlChars(+ decodeUtf8Strict(textBytes) ?? decodeLatin1(textBytes)+ ).trim();+ if (rawVal) title = rawVal.slice(0, 48);+ }+ }+ }+ }+ }+ } else if (type === 'IEND') {+ break;+ }++ offset = dataEnd + 4; // skip CRC+ }++ if (!sawIhdr) {+ throw new Error('Invalid PNG file: missing IHDR chunk.');+ }+ if (idatChunks.length === 0) {+ throw new Error('Invalid PNG file: missing IDAT image data.');+ }++ let channels: number;+ switch (colorType) {+ case 0:+ channels = 1;+ break;+ case 2:+ channels = 3;+ break;+ case 3:+ channels = 1;+ if (!palette) throw new Error('Indexed PNG is missing PLTE palette chunk.');+ break;+ case 4:+ channels = 2;+ break;+ case 6:+ channels = 4;+ break;+ default:+ throw new Error(`Unsupported PNG color type: ${colorType}`);+ }++ if (![1, 2, 4, 8, 16].includes(bitDepth)) {+ throw new Error(`Unsupported PNG bit depth: ${bitDepth}`);+ }++ const combinedIdat = new Uint8Array(totalIdatLen);+ let idatPos = 0;+ for (const chunk of idatChunks) {+ combinedIdat.set(chunk, idatPos);+ idatPos += chunk.byteLength;+ }++ let inflated: Uint8Array;+ try {+ inflated = unzlibSync(combinedIdat);+ } catch {+ throw new Error('Failed to decompress PNG image data.');+ }++ const bitsPerPixel = channels * bitDepth;+ const bpp = Math.max(1, Math.ceil(bitsPerPixel / 8));+ const rgba = new Uint8ClampedArray(width * height * 4);++ if (interlace === 0) {+ const stride = Math.ceil((width * bitsPerPixel) / 8);+ let curr: Uint8Array = new Uint8Array(stride);+ let prev: Uint8Array | null = null;+ let srcOff = 0;++ for (let y = 0; y < height; y++) {+ if (srcOff + 1 + stride > inflated.byteLength) {+ throw new Error('PNG scanline data is truncated.');+ }+ const filterType = inflated[srcOff];+ unfilterScanline(filterType, inflated, srcOff + 1, curr, prev, stride, bpp);+ srcOff += 1 + stride;++ writePngRowToRgba(curr, width, colorType, bitDepth, palette, trns, rgba, width, y, 0, 1);++ const nextPrev = prev ?? new Uint8Array(stride);+ prev = curr;+ curr = nextPrev;+ }+ } else {+ let srcOff = 0;+ for (const [xStart, yStart, xStep, yStep] of ADAM7_PASSES) {+ const passW = Math.ceil((width - xStart) / xStep);+ const passH = Math.ceil((height - yStart) / yStep);+ if (passW <= 0 || passH <= 0) continue;++ const stride = Math.ceil((passW * bitsPerPixel) / 8);+ let curr: Uint8Array = new Uint8Array(stride);+ let prev: Uint8Array | null = null;++ for (let py = 0; py < passH; py++) {+ if (srcOff + 1 + stride > inflated.byteLength) {+ throw new Error('Interlaced PNG scanline data is truncated.');+ }+ const filterType = inflated[srcOff];+ unfilterScanline(filterType, inflated, srcOff + 1, curr, prev, stride, bpp);+ srcOff += 1 + stride;++ writePngRowToRgba(+ curr,+ passW,+ colorType,+ bitDepth,+ palette,+ trns,+ rgba,+ width,+ yStart + py * yStep,+ xStart,+ xStep+ );++ const nextPrev = prev ?? new Uint8Array(stride);+ prev = curr;+ curr = nextPrev;+ }+ }+ }++ return { width, height, rgba, title };+}++interface ColorStat {+ rgb: number;+ r: number;+ g: number;+ b: number;+ count: number;+ firstIndex: number;+ sumX: number;+ sumY: number;+}++interface QuantizedCluster {+ r: number;+ g: number;+ b: number;+ count: number;+ centerX: number;+ centerY: number;+}++function medianCutExtract(+ rgba: Uint8ClampedArray,+ width: number,+ height: number,+ maxColors: number+): Array<{ hex: string }> {+ const totalPixels = width * height;+ const maxSamples = 65536;+ const step = Math.max(1, Math.floor(Math.sqrt(totalPixels / maxSamples)));++ const samples: Array<[number, number, number, number, number]> = [];+ for (let y = 0; y < height; y += step) {+ const rowOff = y * width;+ for (let x = 0; x < width; x += step) {+ const idx = (rowOff + x) * 4;+ if (rgba[idx + 3] < 128) continue;+ samples.push([rgba[idx], rgba[idx + 1], rgba[idx + 2], x, y]);+ }+ }++ if (samples.length === 0) return [];++ interface Box {+ items: Array<[number, number, number, number, number]>;+ rMin: number;+ rMax: number;+ gMin: number;+ gMax: number;+ bMin: number;+ bMax: number;+ }++ const makeBox = (items: Array<[number, number, number, number, number]>): Box => {+ let rMin = 255;+ let rMax = 0;+ let gMin = 255;+ let gMax = 0;+ let bMin = 255;+ let bMax = 0;+ for (let i = 0; i < items.length; i++) {+ const [r, g, b] = items[i];+ if (r < rMin) rMin = r;+ if (r > rMax) rMax = r;+ if (g < gMin) gMin = g;+ if (g > gMax) gMax = g;+ if (b < bMin) bMin = b;+ if (b > bMax) bMax = b;+ }+ return { items, rMin, rMax, gMin, gMax, bMin, bMax };+ };++ const boxes: Box[] = [makeBox(samples)];++ while (boxes.length < maxColors) {+ let bestIdx = -1;+ let bestScore = 0;+ for (let i = 0; i < boxes.length; i++) {+ const box = boxes[i];+ if (box.items.length < 2) continue;+ const range = Math.max(box.rMax - box.rMin, box.gMax - box.gMin, box.bMax - box.bMin);+ if (range <= 4) continue;+ const score = range * Math.sqrt(box.items.length);+ if (score > bestScore) {+ bestScore = score;+ bestIdx = i;+ }+ }+ if (bestIdx < 0) break;++ const target = boxes[bestIdx];+ const rRange = target.rMax - target.rMin;+ const gRange = target.gMax - target.gMin;+ const bRange = target.bMax - target.bMin;+ const channel = rRange >= gRange && rRange >= bRange ? 0 : gRange >= bRange ? 1 : 2;++ target.items.sort((a, b) => a[channel] - b[channel]);+ const mid = Math.floor(target.items.length / 2);+ const left = target.items.slice(0, mid);+ const right = target.items.slice(mid);+ if (left.length === 0 || right.length === 0) break;++ boxes.splice(bestIdx, 1, makeBox(left), makeBox(right));+ }++ const rawClusters: QuantizedCluster[] = boxes.map((box) => {+ let sumR = 0;+ let sumG = 0;+ let sumB = 0;+ let sumX = 0;+ let sumY = 0;+ const n = box.items.length;+ for (let i = 0; i < n; i++) {+ const [r, g, b, x, y] = box.items[i];+ sumR += r;+ sumG += g;+ sumB += b;+ sumX += x;+ sumY += y;+ }+ return {+ r: Math.round(sumR / n),+ g: Math.round(sumG / n),+ b: Math.round(sumB / n),+ count: n,+ centerX: sumX / n,+ centerY: sumY / n,+ };+ });++ // Merge near-duplicate clusters so lossy-reencoded flat blocks collapse cleanly+ rawClusters.sort((a, b) => b.count - a.count);+ const merged: QuantizedCluster[] = [];+ const MERGE_DIST_SQ = 12 * 12;++ for (const cluster of rawClusters) {+ let found = false;+ for (const existing of merged) {+ const dr = existing.r - cluster.r;+ const dg = existing.g - cluster.g;+ const db = existing.b - cluster.b;+ if (dr * dr + dg * dg + db * db <= MERGE_DIST_SQ) {+ const total = existing.count + cluster.count;+ existing.r = Math.round((existing.r * existing.count + cluster.r * cluster.count) / total);+ existing.g = Math.round((existing.g * existing.count + cluster.g * cluster.count) / total);+ existing.b = Math.round((existing.b * existing.count + cluster.b * cluster.count) / total);+ existing.centerX =+ (existing.centerX * existing.count + cluster.centerX * cluster.count) / total;+ existing.centerY =+ (existing.centerY * existing.count + cluster.centerY * cluster.count) / total;+ existing.count = total;+ found = true;+ break;+ }+ }+ if (!found) {+ merged.push({ ...cluster });+ }+ }++ // Order spatially top-to-bottom, left-to-right+ const rowBand = Math.max(1, height / 8);+ merged.sort((a, b) => {+ const bandA = Math.floor(a.centerY / rowBand);+ const bandB = Math.floor(b.centerY / rowBand);+ if (bandA !== bandB) return bandA - bandB;+ return a.centerX - b.centerX;+ });++ const seenHex = new Set<string>();+ const out: Array<{ hex: string }> = [];+ for (const c of merged) {+ const hex = rgbBytesToHex(c.r, c.g, c.b);+ if (!seenHex.has(hex)) {+ seenHex.add(hex);+ out.push({ hex });+ }+ }+ return out;+}++/**+ * Extracts color swatches from an RGBA image buffer.+ *+ * Strategy:+ * 1. Exact palette PNGs (1px strips, 8x/32x Lospec/Aseprite strips, swatch grids):+ * preserves every exact opaque RGB color in reading order (top-to-bottom, left-to-right).+ * On large images (>= 10k opaque pixels), filters out tiny anti-aliased text/border fringes+ * if dominant flat colors already cover >= 90% of opaque pixels.+ * 2. Large flat-swatch palette sheets with anti-aliased labels (>512 unique colors):+ * detects dominant exact flat colors when they cover >= 75% of opaque pixels.+ * 3. General / photographic / gradient PNGs:+ * runs deterministic Median-Cut quantization to extract up to 24 cohesive swatches.+ */+export function extractSwatchesFromRgba(+ rgba: Uint8ClampedArray,+ width: number,+ height: number,+ maxSwatches: number = DEFAULT_MAX_SWATCHES+): Array<{ hex: string }> {+ const colorMap = new Map<number, ColorStat>();+ let totalOpaque = 0;+ let maxColorCount = 0;+ let exceededExactCap = false;++ for (let y = 0; y < height; y++) {+ const rowOff = y * width;+ for (let x = 0; x < width; x++) {+ const pixelIndex = rowOff + x;+ const idx = pixelIndex * 4;+ if (rgba[idx + 3] < 128) continue;++ totalOpaque++;+ if (exceededExactCap) continue;++ const r = rgba[idx];+ const g = rgba[idx + 1];+ const b = rgba[idx + 2];+ const key = (r << 16) | (g << 8) | b;++ const stat = colorMap.get(key);+ if (stat) {+ stat.count++;+ stat.sumX += x;+ stat.sumY += y;+ if (stat.count > maxColorCount) maxColorCount = stat.count;+ } else if (colorMap.size < EXACT_SCAN_MAP_LIMIT) {+ colorMap.set(key, {+ rgb: key,+ r,+ g,+ b,+ count: 1,+ firstIndex: pixelIndex,+ sumX: x,+ sumY: y,+ });+ if (1 > maxColorCount) maxColorCount = 1;+ } else {+ exceededExactCap = true;+ }+ }+ }++ if (totalOpaque === 0) return [];++ // Tier 1: Clean palette PNG (<= maxSwatches exact unique opaque colors)+ if (!exceededExactCap && colorMap.size <= maxSwatches) {+ const allStats = Array.from(colorMap.values());++ if (totalOpaque >= 10_000 && allStats.length > 2) {+ const minMajorCount = Math.max(maxColorCount * 0.015, totalOpaque * 0.001);+ const majorStats = allStats.filter((s) => s.count >= minMajorCount);+ if (majorStats.length >= 2 && majorStats.length < allStats.length) {+ const majorPixels = majorStats.reduce((sum, s) => sum + s.count, 0);+ if (majorPixels / totalOpaque >= 0.9) {+ majorStats.sort((a, b) => a.firstIndex - b.firstIndex);+ return majorStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));+ }+ }+ }++ allStats.sort((a, b) => a.firstIndex - b.firstIndex);+ return allStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));+ }++ // Tier 2: Flat palette card with anti-aliased text/borders pushing exact unique colors > maxSwatches+ if (!exceededExactCap && colorMap.size > 0 && totalOpaque >= 10_000) {+ const minMajorCount = Math.max(maxColorCount * 0.015, totalOpaque * 0.002);+ const majorStats = Array.from(colorMap.values()).filter((s) => s.count >= minMajorCount);+ if (majorStats.length >= 2 && majorStats.length <= 64) {+ const majorPixels = majorStats.reduce((sum, s) => sum + s.count, 0);+ if (majorPixels / totalOpaque >= 0.75) {+ const rowBand = Math.max(1, height / 12);+ majorStats.sort((a, b) => {+ const ay = a.sumY / a.count;+ const by = b.sumY / b.count;+ const bandA = Math.floor(ay / rowBand);+ const bandB = Math.floor(by / rowBand);+ if (bandA !== bandB) return bandA - bandB;+ return a.sumX / a.count - b.sumX / b.count;+ });+ return majorStats.map((s) => ({ hex: rgbBytesToHex(s.r, s.g, s.b) }));+ }+ }+ }++ // Tier 3: Continuous-tone / photographic / gradient PNG -> Median-Cut extraction+ return medianCutExtract(rgba, width, height, Math.min(MAX_QUANTIZED_SWATCHES, maxSwatches));+}++/**+ * Parses a PNG color palette image (`.png`) into a Color Set.+ */+export function parsePngColorSet(+ data: Uint8Array | ArrayBuffer,+ filename?: string,+ maxSwatches: number = DEFAULT_MAX_SWATCHES+): ParseColorSetResult {+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);+ if (bytes.byteLength === 0) {+ return { ok: false, error: 'PNG palette file is empty.' };+ }+ if (bytes.byteLength > MAX_PNG_BYTES) {+ return { ok: false, error: 'PNG palette file exceeds 25 MB limit.' };+ }+ if (!hasPngSignature(bytes)) {+ return { ok: false, error: 'Invalid PNG palette file: missing PNG signature.' };+ }++ let decoded: DecodedPng;+ try {+ decoded = decodePngBytes(bytes);+ } catch (err) {+ const msg = err instanceof Error ? err.message : 'Failed to decode PNG palette file.';+ return { ok: false, error: msg };+ }++ const swatches = extractSwatchesFromRgba(decoded.rgba, decoded.width, decoded.height, maxSwatches);+ if (swatches.length === 0) {+ return { ok: false, error: 'No opaque colors found in PNG palette image.' };+ }++ const name = (+ decoded.title || deriveColorSetNameFromFilename(filename, 'PNG Color Palette')+ ).slice(0, 48);++ return {+ ok: true,+ format: 'png',+ name,+ swatches,+ };+}diff --git a/src/utils/compositor.ts b/src/utils/compositor.tsindex 518b279..3711c64 100644--- a/src/utils/compositor.ts+++ b/src/utils/compositor.ts@@ -246,9 +246,18 @@ function createInitialCompositorState(blitProgram: null,uBlitTextureLoc: null,uBlitBackdropTextureLoc: null,+ uBlitMaskTextureLoc: null,uBlitHasBackdropLoc: null,uBlitBlendModeLoc: null,uBlitOpacityLoc: null,+ uBlitMaskEnabledLoc: null,+ uBlitDocDimensionsLoc: null,+ uBlitViewportSizeLoc: null,+ uBlitPanLoc: null,+ uBlitZoomLoc: null,+ uBlitRotationRadLoc: null,+ uBlitFlipLoc: null,+ uBlitDprLoc: null,framePolyProgram: null,framePolyBuffer: null,aFramePolyDocPosLoc: -1,diff --git a/src/utils/compositor/effectsPass.ts b/src/utils/compositor/effectsPass.tsindex 978a66b..cd72026 100644--- a/src/utils/compositor/effectsPass.ts+++ b/src/utils/compositor/effectsPass.ts@@ -223,7 +223,8 @@ export function blitFolderTexture(viewportW: number,viewportH: number,target: PingPongTarget | null = null,- preserveStencil: boolean = false+ preserveStencil: boolean = false,+ maskTex: WebGLTexture | null = null): void {if (!state.blitProgram) return;@@ -257,12 +258,38 @@ export function blitFolderTexture(gl.bindTexture(gl.TEXTURE_2D, texture);gl.uniform1i(state.uBlitTextureLoc, 0);gl.uniform1i(state.uBlitBackdropTextureLoc, 2);+ gl.uniform1i(state.uBlitMaskTextureLoc, 1);gl.uniform1i(state.uBlitHasBackdropLoc, hasBackdrop);gl.uniform1i(state.uBlitBlendModeLoc, modeCode);gl.uniform1f(state.uBlitOpacityLoc, opacity);+ const fs = state.currentFrameState;+ if (maskTex && fs) {+ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, maskTex);+ gl.uniform1i(state.uBlitMaskEnabledLoc, 1);+ gl.uniform2f(state.uBlitDocDimensionsLoc, fs.dimensions.width, fs.dimensions.height);+ gl.uniform2f(state.uBlitViewportSizeLoc, fs.viewportW, fs.viewportH);+ gl.uniform2f(state.uBlitPanLoc, fs.transform.pan.x, fs.transform.pan.y);+ gl.uniform1f(state.uBlitZoomLoc, fs.transform.zoom);+ gl.uniform1f(state.uBlitRotationRadLoc, fs.rotRad);+ gl.uniform2f(+ state.uBlitFlipLoc,+ fs.transform.flipX ? -1.0 : 1.0,+ fs.transform.flipY ? -1.0 : 1.0+ );+ gl.uniform1f(state.uBlitDprLoc, fs.dpr);+ } else {+ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.uniform1i(state.uBlitMaskEnabledLoc, 0);+ }+ gl.activeTexture(gl.TEXTURE0);+gl.drawArrays(gl.TRIANGLES, 0, 6);+ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, null);unbindSceneTextureUnits(gl);restoreStandardProgram(state, gl);}@@ -335,6 +362,9 @@ export function presentTextureToScreen(gl.bindFramebuffer(gl.FRAMEBUFFER, null);gl.viewport(0, 0, viewportW, viewportH);gl.disable(gl.STENCIL_TEST);+ gl.disable(gl.SCISSOR_TEST);+ gl.clearColor(0.0, 0.0, 0.0, 0.0);+ gl.clear(gl.COLOR_BUFFER_BIT);const needsPostProcess = Boolean(valueCheck || (softProof && (softProof.enabled || softProof.gamutWarning))@@ -345,8 +375,6 @@ export function presentTextureToScreen(}if (!state.blitProgram) {- gl.clearColor(0.0, 0.0, 0.0, 0.0);- gl.clear(gl.COLOR_BUFFER_BIT);return;}gl.disable(gl.BLEND);@@ -361,9 +389,11 @@ export function presentTextureToScreen(gl.bindTexture(gl.TEXTURE_2D, texture);gl.uniform1i(state.uBlitTextureLoc, 0);gl.uniform1i(state.uBlitBackdropTextureLoc, 2);+ gl.uniform1i(state.uBlitMaskTextureLoc, 1);gl.uniform1i(state.uBlitHasBackdropLoc, 0);gl.uniform1i(state.uBlitBlendModeLoc, 0);gl.uniform1f(state.uBlitOpacityLoc, 1.0);+ gl.uniform1i(state.uBlitMaskEnabledLoc, 0);gl.drawArrays(gl.TRIANGLES, 0, 6);unbindSceneTextureUnits(gl);diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.tsindex a5dde11..473167c 100644--- a/src/utils/compositor/fallback2d.ts+++ b/src/utils/compositor/fallback2d.ts@@ -429,6 +429,45 @@ export function render2DSingleLayer(targetCtx.restore();}+function applyGrayscaleMaskTo2DCanvas(+ targetCtx: CanvasRenderingContext2D,+ maskCanvas: HTMLCanvasElement,+ width: number,+ height: number+): void {+ if (width <= 0 || height <= 0 || typeof document === 'undefined') return;+ try {+ let maskCtx = maskCanvas.getContext('2d', { willReadFrequently: true });+ let tempMask: HTMLCanvasElement | null = null;+ if (!maskCtx || maskCanvas.width !== width || maskCanvas.height !== height) {+ tempMask = document.createElement('canvas');+ tempMask.width = width;+ tempMask.height = height;+ const tCtx = tempMask.getContext('2d', { willReadFrequently: true });+ if (!tCtx) return;+ tCtx.drawImage(maskCanvas, 0, 0, width, height);+ maskCtx = tCtx;+ }+ const imgData = targetCtx.getImageData(0, 0, width, height);+ const maskData = maskCtx.getImageData(0, 0, width, height).data;+ const d = imgData.data;+ for (let i = 0; i < d.length; i += 4) {+ if (d[i + 3] === 0) continue;+ const maskLum =+ ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *+ (maskData[i + 3] / 255);+ d[i + 3] = Math.round(d[i + 3] * maskLum);+ }+ targetCtx.putImageData(imgData, 0, 0);+ if (tempMask) {+ tempMask.width = 0;+ tempMask.height = 0;+ }+ } catch {+ // Ignore in headless/mock 2D contexts without getImageData+ }+}+/*** Recursive tree rendering for 2D fallback context supporting pass-through and isolated folders.*/@@ -488,6 +527,10 @@ export function render2DNodeList(renderFrameBorder(fCtx, frame, false);}+ if (baseLayer.maskCanvas && baseLayer.maskEnabled !== false) {+ applyGrayscaleMaskTo2DCanvas(fCtx, baseLayer.maskCanvas, dimensions.width, dimensions.height);+ }+targetCtx.save();targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;@@ -499,7 +542,8 @@ export function render2DNodeList(}if (baseLayer.type === 'folder') {- const isPassThrough = baseLayer.blendMode === 'pass-through';+ const hasFolderMask = Boolean(baseLayer.maskCanvas && baseLayer.maskEnabled !== false);+ const isPassThrough = baseLayer.blendMode === 'pass-through' && !hasFolderMask;const folderEffectiveOpacity = opacityMultiplier * baseLayer.opacity;if (isPassThrough) {@@ -534,9 +578,13 @@ export function render2DNodeList(1.0);}+ if (hasFolderMask && baseLayer.maskCanvas) {+ applyGrayscaleMaskTo2DCanvas(fCtx, baseLayer.maskCanvas, dimensions.width, dimensions.height);+ }targetCtx.save();targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);targetCtx.drawImage(folderCanvas, 0, 0);targetCtx.restore();}@@ -665,6 +713,17 @@ export function render2DFallback(ctx.fillRect(0, 0, dimensions.width, dimensions.height);}+ // Clip layer tiles strictly to document bounds so padded edge/LOD tiles never bleed off-canvas+ if (+ typeof ctx.beginPath === 'function' &&+ typeof ctx.rect === 'function' &&+ typeof ctx.clip === 'function'+ ) {+ ctx.beginPath();+ ctx.rect(0, 0, dimensions.width, dimensions.height);+ ctx.clip();+ }+if (!state.fallbackTileCanvas && typeof document !== 'undefined') {state.fallbackTileCanvas = document.createElement('canvas');state.fallbackTileCanvas.width = TILE_SIZE;diff --git a/src/utils/compositor/fboManager.ts b/src/utils/compositor/fboManager.tsindex 5c5ddaf..346a596 100644--- a/src/utils/compositor/fboManager.ts+++ b/src/utils/compositor/fboManager.ts@@ -173,9 +173,11 @@ export function copyFboSurface(gl.bindTexture(gl.TEXTURE_2D, src.texture);gl.uniform1i(state.uBlitTextureLoc, 0);gl.uniform1i(state.uBlitBackdropTextureLoc, 2);+ gl.uniform1i(state.uBlitMaskTextureLoc, 1);gl.uniform1i(state.uBlitHasBackdropLoc, 0);gl.uniform1i(state.uBlitBlendModeLoc, 0);gl.uniform1f(state.uBlitOpacityLoc, 1.0);+ gl.uniform1i(state.uBlitMaskEnabledLoc, 0);gl.drawArrays(gl.TRIANGLES, 0, 6);unbindSceneTextureUnits(gl);diff --git a/src/utils/compositor/glInit.ts b/src/utils/compositor/glInit.tsindex 5516451..646497c 100644--- a/src/utils/compositor/glInit.ts+++ b/src/utils/compositor/glInit.ts@@ -424,9 +424,18 @@ export function initGL(state: CompositorState): boolean {state.aBlitQuadPosLoc = gl.getAttribLocation(bProg, 'a_quadPos');state.uBlitTextureLoc = gl.getUniformLocation(bProg, 'u_blitTexture');state.uBlitBackdropTextureLoc = gl.getUniformLocation(bProg, 'u_backdropTexture');+ state.uBlitMaskTextureLoc = gl.getUniformLocation(bProg, 'u_maskTexture');state.uBlitHasBackdropLoc = gl.getUniformLocation(bProg, 'u_hasBackdrop');state.uBlitBlendModeLoc = gl.getUniformLocation(bProg, 'u_blendMode');state.uBlitOpacityLoc = gl.getUniformLocation(bProg, 'u_blitOpacity');+ state.uBlitMaskEnabledLoc = gl.getUniformLocation(bProg, 'u_maskEnabled');+ state.uBlitDocDimensionsLoc = gl.getUniformLocation(bProg, 'u_docDimensions');+ state.uBlitViewportSizeLoc = gl.getUniformLocation(bProg, 'u_viewportSize');+ state.uBlitPanLoc = gl.getUniformLocation(bProg, 'u_pan');+ state.uBlitZoomLoc = gl.getUniformLocation(bProg, 'u_zoom');+ state.uBlitRotationRadLoc = gl.getUniformLocation(bProg, 'u_rotationRad');+ state.uBlitFlipLoc = gl.getUniformLocation(bProg, 'u_flip');+ state.uBlitDprLoc = gl.getUniformLocation(bProg, 'u_dpr');}}diff --git a/src/utils/compositor/layerTree.ts b/src/utils/compositor/layerTree.tsindex 61cd263..b0cfaf3 100644--- a/src/utils/compositor/layerTree.ts+++ b/src/utils/compositor/layerTree.ts@@ -103,7 +103,8 @@ export function flattenLayerTreeToUnits(continue;}- if (baseLayer.type === 'folder' && baseLayer.blendMode === 'pass-through') {+ const hasFolderMask = Boolean(baseLayer.maskCanvas && baseLayer.maskEnabled !== false);+ if (baseLayer.type === 'folder' && baseLayer.blendMode === 'pass-through' && !hasFolderMask) {const nested = flattenLayerTreeToUnits(group.baseNode.children,inheritedOpacity * baseLayer.opacitydiff --git a/src/utils/compositor/layerUniforms.ts b/src/utils/compositor/layerUniforms.tsindex 97de0cc..dcbb0f6 100644--- a/src/utils/compositor/layerUniforms.ts+++ b/src/utils/compositor/layerUniforms.ts@@ -154,7 +154,7 @@ export function renderArtboardBackground(gl.uniform1i(state.stdLocs.uExpressionMode, 0);gl.uniform1i(state.uShowCheckerboardLoc, showCheckerboard ? 1 : 0);if (drawShadow) {- const marginDoc = 56 / Math.max(0.01, state.currentZoom);+ const marginDoc = 64 / Math.max(0.01, state.currentZoom);gl.uniform2f(state.uTileOriginLoc, -marginDoc, -marginDoc);gl.uniform2f(state.uTileSizeLoc,diff --git a/src/utils/compositor/previewRenderer.ts b/src/utils/compositor/previewRenderer.tsindex f639330..aa9abb5 100644--- a/src/utils/compositor/previewRenderer.ts+++ b/src/utils/compositor/previewRenderer.ts@@ -10,8 +10,44 @@ let previewTileCanvas: HTMLCanvasElement | null = null;let previewTileImgData: ImageData | null = null;let previewScratchCanvas: HTMLCanvasElement | null = null;let previewDraftScratchCanvas: HTMLCanvasElement | null = null;+let previewMaskScratchCanvas: HTMLCanvasElement | null = null;const previewFolderCanvasPool: HTMLCanvasElement[] = [];+function applyPreviewFolderMask(+ dstCtx: CanvasRenderingContext2D,+ maskCanvas: HTMLCanvasElement,+ outW: number,+ outH: number+): void {+ if (outW <= 0 || outH <= 0 || typeof document === 'undefined') return;+ try {+ if (!previewMaskScratchCanvas) {+ previewMaskScratchCanvas = document.createElement('canvas');+ }+ if (previewMaskScratchCanvas.width !== outW) previewMaskScratchCanvas.width = outW;+ if (previewMaskScratchCanvas.height !== outH) previewMaskScratchCanvas.height = outH;+ const mCtx = previewMaskScratchCanvas.getContext('2d', { willReadFrequently: true });+ if (!mCtx) return;+ mCtx.setTransform(1, 0, 0, 1, 0, 0);+ mCtx.clearRect(0, 0, outW, outH);+ mCtx.drawImage(maskCanvas, 0, 0, outW, outH);++ const imgData = dstCtx.getImageData(0, 0, outW, outH);+ const maskData = mCtx.getImageData(0, 0, outW, outH).data;+ const d = imgData.data;+ for (let i = 0; i < d.length; i += 4) {+ if (d[i + 3] === 0) continue;+ const maskLum =+ ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *+ (maskData[i + 3] / 255);+ d[i + 3] = Math.round(d[i + 3] * maskLum);+ }+ dstCtx.putImageData(imgData, 0, 0);+ } catch {+ // Ignore in mock contexts without getImageData+ }+}+function acquirePreviewFolderCanvas(depth: number, width: number, height: number): HTMLCanvasElement {let c = previewFolderCanvasPool[depth];if (!c) {@@ -265,6 +301,9 @@ export function renderLowResPreview(for (const sf of scaledFrames) {renderFrameBorder(tmpCtx, sf, false);}+ if (baseLayer.maskCanvas && baseLayer.maskEnabled !== false) {+ applyPreviewFolderMask(tmpCtx, baseLayer.maskCanvas, outW, outH);+ }dstCtx.save();dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;@@ -277,7 +316,8 @@ export function renderLowResPreview(if (baseLayer.type === 'folder') {const folderOpacity = opacityMul * baseLayer.opacity;- if (baseLayer.blendMode === 'pass-through') {+ const hasFolderMask = Boolean(baseLayer.maskCanvas && baseLayer.maskEnabled !== false);+ if (baseLayer.blendMode === 'pass-through' && !hasFolderMask) {if (baseNode.children.length > 0) {renderNodes(dstCtx, baseNode.children, folderOpacity, depth);}@@ -290,9 +330,13 @@ export function renderLowResPreview(if (baseNode.children.length > 0) {renderNodes(tmpCtx, baseNode.children, 1.0, depth + 1);}+ if (hasFolderMask && baseLayer.maskCanvas) {+ applyPreviewFolderMask(tmpCtx, baseLayer.maskCanvas, outW, outH);+ }dstCtx.save();dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));- dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);dstCtx.drawImage(tmp, 0, 0);dstCtx.restore();}diff --git a/src/utils/compositor/renderFrame.ts b/src/utils/compositor/renderFrame.tsindex 0799f2e..a4a193f 100644--- a/src/utils/compositor/renderFrame.ts+++ b/src/utils/compositor/renderFrame.ts@@ -158,6 +158,8 @@ export function renderFrame(}}+ const drawArtboardShadow = !_options.hideArtboardChrome;+if ((bypassStackCache || isCameraMoving) && scenePP) {restoreStandardProgram(state, gl);syncFrameUniforms(state, gl, state.stdLocs);@@ -169,11 +171,18 @@ export function renderFrame(gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);gl.viewport(0, 0, viewportW, viewportH);gl.disable(gl.STENCIL_TEST);+ gl.disable(gl.SCISSOR_TEST);gl.clearColor(0.0, 0.0, 0.0, 0.0);gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);if (!_options.transparentBackground) {- renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard), false);+ renderArtboardBackground(+ state,+ gl,+ dimensions,+ Boolean(_options.showCheckerboard),+ drawArtboardShadow+ );}renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);@@ -221,6 +230,7 @@ export function renderFrame(transform,showCheckerboard: Boolean(_options.showCheckerboard),transparentBackground: Boolean(_options.transparentBackground),+ hideArtboardChrome: Boolean(_options.hideArtboardChrome),colorMode: _options.colorMode,onionSkinFrames: _options.onionSkinFrames,getLayerContentVersion: (id) =>@@ -243,6 +253,7 @@ export function renderFrame(gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);gl.viewport(0, 0, viewportW, viewportH);gl.disable(gl.STENCIL_TEST);+ gl.disable(gl.SCISSOR_TEST);gl.clearColor(0.0, 0.0, 0.0, 0.0);gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);@@ -284,11 +295,18 @@ export function renderFrame(gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);gl.viewport(0, 0, viewportW, viewportH);gl.disable(gl.STENCIL_TEST);+ gl.disable(gl.SCISSOR_TEST);gl.clearColor(0.0, 0.0, 0.0, 0.0);gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);if (!_options.transparentBackground) {- renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard));+ renderArtboardBackground(+ state,+ gl,+ dimensions,+ Boolean(_options.showCheckerboard),+ drawArtboardShadow+ );}renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);@@ -412,11 +430,19 @@ export function renderFrame(// Safe fallback when offscreen FBOs are unsupported in a minimal WebGL contextgl.bindFramebuffer(gl.FRAMEBUFFER, null);gl.viewport(0, 0, viewportW, viewportH);+ gl.disable(gl.STENCIL_TEST);+ gl.disable(gl.SCISSOR_TEST);gl.clearColor(0.0, 0.0, 0.0, 0.0);gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);if (!_options.transparentBackground) {- renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard), false);+ renderArtboardBackground(+ state,+ gl,+ dimensions,+ Boolean(_options.showCheckerboard),+ drawArtboardShadow+ );}renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, null);diff --git a/src/utils/compositor/shaders/coreShaders.ts b/src/utils/compositor/shaders/coreShaders.tsindex eaf3a84..fd7fa87 100644--- a/src/utils/compositor/shaders/coreShaders.ts+++ b/src/utils/compositor/shaders/coreShaders.ts@@ -74,9 +74,18 @@ precision highp float;in vec2 v_uv;uniform sampler2D u_blitTexture;uniform sampler2D u_backdropTexture;+uniform sampler2D u_maskTexture;uniform int u_hasBackdrop;uniform int u_blendMode;uniform float u_blitOpacity;+uniform int u_maskEnabled;+uniform vec2 u_docDimensions;+uniform vec2 u_viewportSize;+uniform vec2 u_pan;+uniform float u_zoom;+uniform float u_rotationRad;+uniform vec2 u_flip;+uniform float u_dpr;out vec4 fragColor;${buildBlendModeGlsl('Folder')}@@ -87,6 +96,33 @@ void main() {if (srcA < 0.002) {discard;}+ if (u_maskEnabled == 1) {+ vec2 screenPos = vec2(v_uv.x * u_viewportSize.x, (1.0 - v_uv.y) * u_viewportSize.y);+ vec2 cssScreen = screenPos / max(0.0001, u_dpr);+ vec2 unscaled = (cssScreen - u_pan) / max(0.0001, u_zoom);+ float cosR = cos(u_rotationRad);+ float sinR = sin(u_rotationRad);+ vec2 unrotated = vec2(+ unscaled.x * cosR + unscaled.y * sinR,+ -unscaled.x * sinR + unscaled.y * cosR+ );+ vec2 docCoord = unrotated * u_flip + u_docDimensions * 0.5;+ if (+ docCoord.x < 0.0 ||+ docCoord.y < 0.0 ||+ docCoord.x > u_docDimensions.x ||+ docCoord.y > u_docDimensions.y+ ) {+ discard;+ }+ vec2 maskCoord = clamp(docCoord / max(vec2(1.0), u_docDimensions), 0.0, 1.0);+ vec4 maskPixel = texture(u_maskTexture, maskCoord);+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;+ srcA *= maskLum;+ if (srcA < 0.002) {+ discard;+ }+ }vec3 Cs = srcPremul.a > 0.001 ? clamp(srcPremul.rgb / srcPremul.a, 0.0, 1.0) : vec3(0.0);if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {vec4 dstPremul = texture(u_backdropTexture, v_uv);@@ -206,7 +242,7 @@ vec4 applyLayerTint(vec4 color) {void main() {if (u_isBackground == 1) {- vec2 outsideDoc = max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions);+ vec2 outsideDoc = max(vec2(0.0), max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions));if (outsideDoc.x > 0.0 || outsideDoc.y > 0.0) {float safeZoom = max(0.01, u_zoom);vec2 outsidePx = outsideDoc * safeZoom;@@ -216,7 +252,7 @@ void main() {return;}vec2 shadowCoord = v_docCoord - vec2(0.0, 10.0 / safeZoom);- vec2 shadowOutside = max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions);+ vec2 shadowOutside = max(vec2(0.0), max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions));float shadowDist = length(shadowOutside * safeZoom);float shadowA = 0.55 * exp(-shadowDist * shadowDist / 520.0) * smoothstep(48.0, 0.0, shadowDist);if (shadowA < 0.002) {@@ -236,6 +272,15 @@ void main() {return;}+ if (+ v_docCoord.x < 0.0 ||+ v_docCoord.y < 0.0 ||+ v_docCoord.x > u_docDimensions.x ||+ v_docCoord.y > u_docDimensions.y+ ) {+ discard;+ }+vec4 rawTex = texture(u_tileTexture, v_texCoord);if (rawTex.a < 0.002) {diff --git a/src/utils/compositor/shaders/instancedShaders.ts b/src/utils/compositor/shaders/instancedShaders.tsindex 360f34a..711622a 100644--- a/src/utils/compositor/shaders/instancedShaders.ts+++ b/src/utils/compositor/shaders/instancedShaders.ts@@ -103,6 +103,15 @@ vec4 applyLayerTint(vec4 color) {}void main() {+ if (+ v_docCoord.x < 0.0 ||+ v_docCoord.y < 0.0 ||+ v_docCoord.x > u_docDimensions.x ||+ v_docCoord.y > u_docDimensions.y+ ) {+ discard;+ }+// Single hardware TMU fetch on premultiplied RGBA8 TEXTURE_2D_ARRAYvec4 rawTex = texture(u_tileArrayTexture, vec3(v_texCoord, v_sliceIndex));diff --git a/src/utils/compositor/stackCache.ts b/src/utils/compositor/stackCache.tsindex 264388f..8c90632 100644--- a/src/utils/compositor/stackCache.ts+++ b/src/utils/compositor/stackCache.ts@@ -132,7 +132,7 @@ export class LayerStackCacheTracker implements LayerStackCacheTrackerLike {const belowUnitSigs = partition.belowUnits.map((u) =>serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch));- const belowSignature = `${viewportSig}|cm:${modeTag}|cb:${input.showCheckerboard ? 1 : 0}|tb:${input.transparentBackground ? 1 : 0}|os:${onionSig}|below:[${belowUnitSigs.join('||')}]`;+ const belowSignature = `${viewportSig}|cm:${modeTag}|cb:${input.showCheckerboard ? 1 : 0}|tb:${input.transparentBackground ? 1 : 0}|hc:${input.hideArtboardChrome ? 1 : 0}|os:${onionSig}|below:[${belowUnitSigs.join('||')}]`;let aboveSignature = '';if (partition.aboveCachedUnits.length > 0) {diff --git a/src/utils/compositor/types.ts b/src/utils/compositor/types.tsindex 423541b..e8a0512 100644--- a/src/utils/compositor/types.ts+++ b/src/utils/compositor/types.ts@@ -81,6 +81,8 @@ export interface CompositorOptions {colorMode?: CanvasColorMode;showCheckerboard?: boolean;transparentBackground?: boolean;+ /** Suppress the 1px viewport artboard border & drop shadow (used for offscreen export/render). */+ hideArtboardChrome?: boolean;bypassStackCache?: boolean;devicePixelRatio?: number;onionSkinFrames?: OnionSkinCompositorFrame[];@@ -138,6 +140,7 @@ export interface LayerStackCacheInput {transform: ViewportTransform;showCheckerboard?: boolean;transparentBackground?: boolean;+ hideArtboardChrome?: boolean;colorMode?: CanvasColorMode;onionSkinFrames?: OnionSkinCompositorFrame[];getLayerContentVersion: (layerId: string) => number;@@ -398,9 +401,18 @@ export interface CompositorState {blitProgram: WebGLProgram | null;uBlitTextureLoc: WebGLUniformLocation | null;uBlitBackdropTextureLoc: WebGLUniformLocation | null;+ uBlitMaskTextureLoc: WebGLUniformLocation | null;uBlitHasBackdropLoc: WebGLUniformLocation | null;uBlitBlendModeLoc: WebGLUniformLocation | null;uBlitOpacityLoc: WebGLUniformLocation | null;+ uBlitMaskEnabledLoc: WebGLUniformLocation | null;+ uBlitDocDimensionsLoc: WebGLUniformLocation | null;+ uBlitViewportSizeLoc: WebGLUniformLocation | null;+ uBlitPanLoc: WebGLUniformLocation | null;+ uBlitZoomLoc: WebGLUniformLocation | null;+ uBlitRotationRadLoc: WebGLUniformLocation | null;+ uBlitFlipLoc: WebGLUniformLocation | null;+ uBlitDprLoc: WebGLUniformLocation | null;// Frame Border Folder polygon program & dynamic vertex bufferframePolyProgram: WebGLProgram | null;diff --git a/src/utils/compositor/unitRenderer.ts b/src/utils/compositor/unitRenderer.tsindex 2f56744..47f9e1d 100644--- a/src/utils/compositor/unitRenderer.ts+++ b/src/utils/compositor/unitRenderer.ts@@ -17,6 +17,7 @@ import { renderLayerWithStyles, renderSingleLayer } from './layerRenderer';import { flattenLayerTreeToUnits, partitionUnitsForActiveLayer } from './layerTree';import { serializeUnitSignature } from './stackCache';import { hasActiveLayerStyles } from './shaders/effectShaders';+import { getMaskTexture } from './tileTexturePool';import {CompositingUnit,CompositorState,@@ -606,6 +607,10 @@ export function renderCompositingUnit(gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);gl.viewport(0, 0, viewportW, viewportH);+ const folderMaskTex =+ baseLayer.maskCanvas && baseLayer.maskEnabled !== false+ ? getMaskTexture(state, baseLayer)+ : null;const folderBlend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;blitFolderTexture(state,@@ -616,7 +621,8 @@ export function renderCompositingUnit(viewportW,viewportH,target,- false+ false,+ folderMaskTex);return;}@@ -649,16 +655,22 @@ export function renderCompositingUnit(gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);gl.viewport(0, 0, viewportW, viewportH);+ const folderMaskTex =+ baseLayer.maskCanvas && baseLayer.maskEnabled !== false+ ? getMaskTexture(state, baseLayer)+ : null;+ const folderBlend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;blitFolderTexture(state,gl,folderTarget.surfaces[folderTarget.activeIndex].texture,- baseLayer.blendMode,+ folderBlend,baseLayer.opacity * unit.inheritedOpacity,viewportW,viewportH,target,- false+ false,+ folderMaskTex);return;}diff --git a/src/utils/cspParser.ts b/src/utils/cspParser.tsindex e4a71d8..0276c92 100644--- a/src/utils/cspParser.ts+++ b/src/utils/cspParser.ts@@ -262,6 +262,8 @@ interface ParsedOffscreenAttribute {firstPackingChannels: number;secondPackingChannels: number;bitDepthFlag: number;+ initDoInitialize?: boolean;+ initAlpha?: number;initColor: [number, number, number, number] | null; // RGBA 0..255}@@ -282,6 +284,8 @@ export function parseOffscreenAttribute(firstPackingChannels: 1,secondPackingChannels: 4,bitDepthFlag: 8,+ initDoInitialize: false,+ initAlpha: 0,initColor: null,};@@ -319,10 +323,21 @@ export function parseOffscreenAttribute(def.blockGridWidth = view.getUint32(base + 8, false);def.blockGridHeight = view.getUint32(base + 12, false);- if (base + 20 <= blob.byteLength) {- def.defaultFill = view.getUint32(base + 16, false);+ if (base + 24 <= blob.byteLength) {+ // Real CSP Parameter layout stores BlockDataChannelOrder (1/17/33) at +16 and+ // BlockDataChannelBytes (>= 1) at +20; legacy synthetic blobs leave +20 as 0 and put defaultFill at +16.+ const v16 = view.getUint32(base + 16, false);+ const v20 = view.getUint32(base + 20, false);+ if (v20 === 0 && v16 <= 1) {+ def.defaultFill = v16;+ }+ } else if (base + 20 <= blob.byteLength) {+ const v16 = view.getUint32(base + 16, false);+ if (v16 <= 1) {+ def.defaultFill = v16;+ }}- // Packing parameters follow defaultFill (up to 11 u32 values)+ // Packing parameters follow (up to 11 u32 values)if (base + 32 <= blob.byteLength) {const ch1 = view.getUint32(base + 24, false);const ch2 = view.getUint32(base + 28, false);@@ -340,26 +355,41 @@ export function parseOffscreenAttribute(const initIdx = indexOfBytes(blob, TAG_INIT_COLOR, 0);if (initIdx >= 0) {const p = initIdx + TAG_INIT_COLOR.length;- // InitColor stores either:- // - 4 u32 BE (flag + R/G/B or A/R/G/B in 0..255 or 0..65535 or 0..0xffffffff)- // - or u32 enable + 3/4 u32 color channels- if (p + 16 <= blob.byteLength) {+ const norm = (v: number) =>+ v <= 255 ? v : v <= 65535 ? (v >> 8) & 0xff : (v >>> 24) & 0xff;+ // Real CSP InitColor layout:+ // [0] headerBytes (= 20), [1] doInitialize (0/1), [2] alphaValue, [3] imageValueCount (0..4), [4] elemBytes (= 4), [5..] values+ if (p + 20 <= blob.byteLength) {const a0 = view.getUint32(p, false);const a1 = view.getUint32(p + 4, false);const a2 = view.getUint32(p + 8, false);const a3 = view.getUint32(p + 12, false);- // Detect normalized 8-bit or 16-bit or 32-bit color values- if (p + 20 <= blob.byteLength) {- const enabled = a0;- const c0 = a1;- const c1 = a2;- const c2 = a3;- const c3 = view.getUint32(p + 16, false);- if (enabled === 1 && c0 <= 0xffffffff && c1 <= 0xffffffff && c2 <= 0xffffffff) {- const norm = (v: number) =>- v <= 255 ? v : v <= 65535 ? (v >> 8) & 0xff : (v >>> 24) & 0xff;- def.initColor = [norm(c0), norm(c1), norm(c2), c3 > 0 ? norm(c3) : 255];+ const a4 = view.getUint32(p + 16, false);+ if (a0 === 20 && a1 <= 1 && a3 <= 4 && (a4 === 4 || a4 === 0)) {+ def.initDoInitialize = a1 === 1;+ def.initAlpha = norm(a2);+ if (def.initDoInitialize) {+ def.defaultFill = def.initAlpha > 0 ? 1 : 0;+ if (a3 >= 3 && p + 20 + a3 * 4 <= blob.byteLength) {+ const c0 = norm(view.getUint32(p + 20, false));+ const c1 = norm(view.getUint32(p + 24, false));+ const c2 = norm(view.getUint32(p + 28, false));+ // Real CSP stores RGB channels or BGRA depending on count; standard Color uses R,G,B+ def.initColor = [c0, c1, c2, def.initAlpha > 0 ? def.initAlpha : 255];+ } else if (a3 === 1 && p + 24 <= blob.byteLength) {+ const g = norm(view.getUint32(p + 20, false));+ def.initColor = [g, g, g, def.initAlpha > 0 ? def.initAlpha : 255];+ } else {+ def.initColor = [255, 255, 255, def.initAlpha > 0 ? def.initAlpha : 255];+ }+ } else {+ def.defaultFill = 0;}+ } else if (a0 === 1 && a1 <= 0xffffffff && a2 <= 0xffffffff && a3 <= 0xffffffff) {+ // Legacy synthetic layout: [enabled=1, R, G, B, A]+ def.initDoInitialize = true;+ def.initAlpha = a4 > 0 ? norm(a4) : 255;+ def.initColor = [norm(a1), norm(a2), norm(a3), def.initAlpha];}}}diff --git a/src/utils/fileDropImport.ts b/src/utils/fileDropImport.tsindex 7443e1b..9f47f83 100644--- a/src/utils/fileDropImport.ts+++ b/src/utils/fileDropImport.ts@@ -299,7 +299,12 @@ export function resolveDropZoneFromElement(clientY: number): ExternalFileDropTarget | null {if (!element) return null;- if (element.closest('[data-testid="sub-view-panel"]')) return null;+ if (+ element.closest('[data-testid="sub-view-panel"]') ||+ element.closest('[data-testid="color-sets-panel"]')+ ) {+ return null;+ }const zoneEl = element.closest('[data-drop-zone]') as HTMLElement | null;if (!zoneEl) return null;@@ -343,7 +348,7 @@ export function isSameDropTarget();}-async function readTauriFileBytes(path: string): Promise<Uint8Array> {+export async function readTauriFileBytes(path: string): Promise<Uint8Array> {const { invoke } = await import('@tauri-apps/api/core');try {const buf = await invoke<ArrayBuffer>('read_file_binary', { path });diff --git a/src/utils/fileSaveDialog.ts b/src/utils/fileSaveDialog.tsnew file mode 100644index 0000000..7cc3746--- /dev/null+++ b/src/utils/fileSaveDialog.ts@@ -0,0 +1,355 @@+/**+ * Unified "Save As" File Dialog Utility+ *+ * Lets the user choose the exact destination folder & filename whenever saving/exporting+ * brushes (.inkb), workspaces (.inkworkspace), themes (.inktheme), color sets (.inkcolorset.json),+ * auto actions (.json), time-lapses (.mp4/.webm), webtoon archives (.zip), animations, etc.+ *+ * Priority chain:+ * 1. Tauri Desktop native OS Save As dialog (`native_save_file_with_dialog`) — supports arbitrary+ * custom extensions, never expires user-gesture activation, and remembers the last chosen folder+ * per asset category.+ * 2. Browser File System Access API (`window.showSaveFilePicker`) with sanitized single-dot+ * extensions and per-category picker IDs so Chromium/Edge also remember folders per type.+ * 3. Standard anchor `<a download>` fallback when neither picker is supported.+ */++import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';++export type ExportFileCategory =+ | 'brush'+ | 'workspace'+ | 'theme'+ | 'color-set'+ | 'auto-action'+ | 'timelapse'+ | 'webtoon'+ | 'animation'+ | 'project'+ | 'other';++export interface SaveFileDialogOptions {+ data: Blob | Uint8Array | ArrayBuffer | string;+ suggestedName: string;+ mimeType?: string;+ description: string;+ extensions: string[];+ category?: ExportFileCategory;+ title?: string;+ /** Allow anchor download fallback if picker APIs are unavailable (defaults to true). */+ fallbackToDownload?: boolean;+}++export interface SaveFileDialogResult {+ saved: boolean;+ canceled: boolean;+ fileName: string;+ path?: string;+ directory?: string;+ method: 'native-dialog' | 'web-picker' | 'download';+}++interface NativeSaveDialogResponse {+ saved: boolean;+ canceled: boolean;+ fileName?: string;+ path?: string | null;+ directory?: string | null;+}++interface FilePickerAcceptType {+ description?: string;+ accept: Record<string, string[]>;+}++interface SaveFilePickerHandle {+ name?: string;+ createWritable: () => Promise<{+ write: (data: Blob | Uint8Array | ArrayBuffer | string) => Promise<void>;+ close: () => Promise<void>;+ }>;+}++interface PickerCapableWindow extends Window {+ __TAURI_INTERNALS__?: unknown;+ showSaveFilePicker?: (options?: {+ suggestedName?: string;+ id?: string;+ types?: FilePickerAcceptType[];+ excludeAcceptAllOption?: boolean;+ }) => Promise<SaveFilePickerHandle>;+}++const REMEMBERED_DIRS_LS_KEY = 'inkstudio_export_dirs_v1';++let cachedInvokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;++function getTauriInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {+ if (!cachedInvokePromise) {+ cachedInvokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);+ }+ return cachedInvokePromise;+}++function isTauriDesktop(): boolean {+ return (+ typeof window !== 'undefined' &&+ Boolean((window as unknown as PickerCapableWindow).__TAURI_INTERNALS__)+ );+}++function readRememberedDirs(): Record<string, string> {+ try {+ const raw = safeLocalStorageGetItem(REMEMBERED_DIRS_LS_KEY);+ if (!raw) return {};+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return {};+ const out: Record<string, string> = {};+ for (const [k, v] of Object.entries(parsed)) {+ if (typeof v === 'string' && v.trim()) {+ out[k] = v.trim();+ }+ }+ return out;+ } catch {+ return {};+ }+}++export function getRememberedSaveDir(category: ExportFileCategory): string | null {+ const dirs = readRememberedDirs();+ return dirs[category] ?? null;+}++export function rememberSaveDir(category: ExportFileCategory, dir: string | null | undefined): void {+ if (!dir || !dir.trim()) return;+ const dirs = readRememberedDirs();+ dirs[category] = dir.trim();+ safeLocalStorageSetItem(REMEMBERED_DIRS_LS_KEY, JSON.stringify(dirs), 'export folder memory');+}++/**+ * Normalizes extensions for browser `showSaveFilePicker` `accept` map (Chromium requires each+ * extension to begin with `.` and contain only a single leading dot — e.g. `.inkcolorset.json` -> `.json`).+ */+export function normalizePickerExtensions(extensions: string[]): string[] {+ const out: string[] = [];+ for (const raw of extensions) {+ const trimmed = (raw || '').trim().toLowerCase();+ if (!trimmed) continue;+ const lastDot = trimmed.lastIndexOf('.');+ const tail = lastDot >= 0 ? trimmed.slice(lastDot + 1) : trimmed;+ const clean = tail.replace(/[^a-z0-9_-]/g, '');+ if (!clean) continue;+ const ext = `.${clean}`;+ if (!out.includes(ext)) out.push(ext);+ }+ return out;+}++/**+ * Sanitizes a MIME type for File System Access API `accept` keys (`type/subtype` without parameters).+ */+function sanitizeAcceptMime(mimeType: string | undefined): string {+ const base = (mimeType || 'application/octet-stream').split(';')[0].trim().toLowerCase();+ if (/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(base)) {+ return base;+ }+ return 'application/octet-stream';+}++async function payloadToUint8Array(+ data: Blob | Uint8Array | ArrayBuffer | string+): Promise<Uint8Array> {+ if (typeof data === 'string') {+ return new TextEncoder().encode(data);+ }+ if (data instanceof Uint8Array) {+ return data.byteOffset === 0 && data.byteLength === data.buffer.byteLength+ ? data+ : data.slice();+ }+ if (data instanceof ArrayBuffer) {+ return new Uint8Array(data);+ }+ const buf = await data.arrayBuffer();+ return new Uint8Array(buf);+}++function payloadToBlob(+ data: Blob | Uint8Array | ArrayBuffer | string,+ mimeType: string+): Blob {+ if (data instanceof Blob) return data;+ if (typeof data === 'string') return new Blob([data], { type: mimeType });+ if (data instanceof Uint8Array) return new Blob([data as BlobPart], { type: mimeType });+ return new Blob([data], { type: mimeType });+}++function triggerAnchorDownload(blob: Blob, fileName: string): void {+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = fileName;+ a.style.display = 'none';+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++/**+ * Prompts the user to choose where to save a file (native OS dialog in Tauri Desktop,+ * File System Access API `showSaveFilePicker` in supported browsers, or anchor download fallback).+ */+export async function saveFileWithDialog(+ options: SaveFileDialogOptions+): Promise<SaveFileDialogResult> {+ const category: ExportFileCategory = options.category ?? 'other';+ const mimeType = options.mimeType || 'application/octet-stream';+ const suggestedName = options.suggestedName.trim() || 'export';+ const normalizedExts = normalizePickerExtensions(options.extensions);++ // 1. Native OS Save As dialog in Tauri Desktop (supports custom extensions & remembers folder per category)+ if (isTauriDesktop()) {+ try {+ const bytes = await payloadToUint8Array(options.data);+ const invoke = await getTauriInvoke();+ const headers: Record<string, string> = {+ 'x-suggested-name': encodeURIComponent(suggestedName),+ 'x-filter-name': encodeURIComponent(options.description || 'File'),+ 'x-extensions': encodeURIComponent(+ normalizedExts.map((e) => e.replace(/^\./, '')).join(',')+ ),+ };+ if (options.title) {+ headers['x-dialog-title'] = encodeURIComponent(options.title);+ }+ const rememberedDir = getRememberedSaveDir(category);+ if (rememberedDir) {+ headers['x-initial-dir'] = encodeURIComponent(rememberedDir);+ }++ const res = await invoke<NativeSaveDialogResponse>(+ 'native_save_file_with_dialog',+ bytes,+ { headers }+ );+ if (res?.canceled) {+ return {+ saved: false,+ canceled: true,+ fileName: suggestedName,+ method: 'native-dialog',+ };+ }+ if (res?.saved) {+ if (res.directory) {+ rememberSaveDir(category, res.directory);+ }+ return {+ saved: true,+ canceled: false,+ fileName: res.fileName || suggestedName,+ path: res.path ?? undefined,+ directory: res.directory ?? undefined,+ method: 'native-dialog',+ };+ }+ } catch {+ // Fall through to web File System Access API or download fallback+ }+ }++ // 2. Browser File System Access API (`showSaveFilePicker`) with per-category ID+ const pickerWin =+ typeof window !== 'undefined' ? (window as unknown as PickerCapableWindow) : undefined;+ if (pickerWin && typeof pickerWin.showSaveFilePicker === 'function') {+ const pickerTypes: FilePickerAcceptType[] =+ normalizedExts.length > 0+ ? [+ {+ description: options.description,+ accept: {+ [sanitizeAcceptMime(mimeType)]: normalizedExts,+ },+ },+ ]+ : [];+ const pickerId = `inkstudio-${category}`.replace(/[^a-z0-9_-]/gi, '-').slice(0, 32);++ try {+ const handle = await pickerWin.showSaveFilePicker({+ suggestedName,+ id: pickerId,+ ...(pickerTypes.length > 0 ? { types: pickerTypes } : {}),+ });+ const blob = payloadToBlob(options.data, mimeType);+ const writable = await handle.createWritable();+ await writable.write(blob);+ await writable.close();+ return {+ saved: true,+ canceled: false,+ fileName: handle.name || suggestedName,+ method: 'web-picker',+ };+ } catch (err: unknown) {+ if (err && typeof err === 'object' && 'name' in err && (err as { name?: string }).name === 'AbortError') {+ return {+ saved: false,+ canceled: true,+ fileName: suggestedName,+ method: 'web-picker',+ };+ }+ // Retry without restrictive MIME/extension filter if Chromium rejected a custom extension+ if (pickerTypes.length > 0) {+ try {+ const handle = await pickerWin.showSaveFilePicker({+ suggestedName,+ id: pickerId,+ });+ const blob = payloadToBlob(options.data, mimeType);+ const writable = await handle.createWritable();+ await writable.write(blob);+ await writable.close();+ return {+ saved: true,+ canceled: false,+ fileName: handle.name || suggestedName,+ method: 'web-picker',+ };+ } catch (retryErr: unknown) {+ if (+ retryErr &&+ typeof retryErr === 'object' &&+ 'name' in retryErr &&+ (retryErr as { name?: string }).name === 'AbortError'+ ) {+ return {+ saved: false,+ canceled: true,+ fileName: suggestedName,+ method: 'web-picker',+ };+ }+ }+ }+ }+ }++ // 3. Fallback anchor download+ if (options.fallbackToDownload === false) {+ throw new Error('Save dialog is not available in this environment');+ }++ const blob = payloadToBlob(options.data, mimeType);+ triggerAnchorDownload(blob, suggestedName);+ return {+ saved: true,+ canceled: false,+ fileName: suggestedName,+ method: 'download',+ };+}diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.tsindex 224b666..7e07ec6 100644--- a/src/utils/imageLoader.ts+++ b/src/utils/imageLoader.ts@@ -1,7 +1,11 @@import { LoadedDocument, LayerItem, CanvasColorMode } from '../types/editor';import { renderVectorLayer } from './vectorEngine';import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';-import { PRIMARY_PROJECT_EXTENSION, parseInkProject } from './saveManager';+import {+ PRIMARY_PROJECT_EXTENSION,+ parseInkProject,+ sanitizeDocumentStem,+} from './saveManager';import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';/**@@ -36,10 +40,11 @@ export async function loadStandardImage(file: File): Promise<LoadedDocument> {const thumb = grid.generateThumbnail(layerId, 64, 64, { width, height }, true);const bgThumb = grid.generateThumbnail(bgId, 64, 64, { width, height }, false);+ const cleanName = sanitizeDocumentStem(file.name, 'Untitled');const layers: LayerItem[] = [{id: layerId,- name: file.name.replace(/\.[^/.]+$/, ''),+ name: cleanName,type: 'raster',visible: true,opacity: 1,@@ -62,7 +67,7 @@ export async function loadStandardImage(file: File): Promise<LoadedDocument> {];resolve({- name: file.name.replace(/\.[^/.]+$/, ''),+ name: cleanName,dimensions: { width, height, dpi: 600 },colorMode: 'color' as CanvasColorMode,layers,@@ -139,8 +144,14 @@ export async function openFile(file: File): Promise<LoadedDocument> {}}+ // Prefer the actual disk filename (healed of any chained extensions) over stale manifest.name+ // so files renamed on disk keep their real filename on reopen and resave.+ const resolvedDocName = file.name+ ? sanitizeDocumentStem(file.name, sanitizeDocumentStem(project.name, 'Untitled'))+ : sanitizeDocumentStem(project.name, 'Untitled');+return {- name: project.name || file.name.replace(/\.[^/.]+$/, ''),+ name: resolvedDocName,dimensions: { width, height, dpi },colorMode,layers,diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.tsindex 6ea166b..a82c026 100644--- a/src/utils/inkbBrushFormat.ts+++ b/src/utils/inkbBrushFormat.ts@@ -33,6 +33,7 @@ import {prepareBrushSettingsForCsp,saveCustomBrush,} from './brushStorage';+import { saveFileWithDialog } from './fileSaveDialog';import { parseSutFile } from './sutParser';import { normalizeDualBrushCompositeMode } from '../engine/DualBrushEngine';import { toolStoreActions } from '../stores';@@ -114,6 +115,7 @@ const VALID_CATEGORIES = new Set<BrushCategory | 'custom'>(['brush','blend','natural-paint',+ 'texture-fx','deco-background','deco-clothing','deco-effect',@@ -932,48 +934,27 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink}/**- * Triggers a save dialog (or browser download fallback) for a `[brush].inkb` file.+ * Triggers a native Save As dialog (or browser picker / download fallback) for a `[brush].inkb` file.*/export async function exportBrushToInkbFile(brush: CspBrush-): Promise<{ exported: boolean; fileName: string }> {+): Promise<{ exported: boolean; fileName: string; path?: string }> {const bytes = serializeInkbBrush(brush);const suggestedName = sanitizeBrushFileName(brush.name);- const blob = new Blob([bytes.buffer as ArrayBuffer], { type: 'application/octet-stream' });-- if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {- try {- const handle = await (window as any).showSaveFilePicker({- suggestedName,- types: [- {- description: 'Ink Studio Brush (.inkb)',- accept: { 'application/octet-stream': [INKB_EXTENSION] },- },- ],- });- const writable = await handle.createWritable();- await writable.write(blob);- await writable.close();- return { exported: true, fileName: handle.name || suggestedName };- } catch (err: unknown) {- if ((err as { name?: string })?.name === 'AbortError') {- return { exported: false, fileName: suggestedName };- }- // Fall through to anchor download- }- }-- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = suggestedName;- a.style.display = 'none';- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- setTimeout(() => URL.revokeObjectURL(url), 1000);- return { exported: true, fileName: suggestedName };+ const res = await saveFileWithDialog({+ data: bytes,+ suggestedName,+ mimeType: 'application/octet-stream',+ description: 'Ink Studio Brush',+ extensions: [INKB_EXTENSION],+ category: 'brush',+ title: 'Save Brush As',+ });+ return {+ exported: res.saved && !res.canceled,+ fileName: res.fileName,+ ...(res.path ? { path: res.path } : {}),+ };}export function isSupportedBrushFileName(fileName: string): boolean {diff --git a/src/utils/layerOrganization.ts b/src/utils/layerOrganization.tsnew file mode 100644index 0000000..a9b5367--- /dev/null+++ b/src/utils/layerOrganization.ts@@ -0,0 +1,436 @@+import { LayerColorLabel, LayerItem, isFolderLikeLayer } from '../types/editor';++export interface LayerColorLabelPreset {+ id: LayerColorLabel;+ name: string;+ swatchHex: string;+ rowTint: string;+ rowTintHover: string;+}++export const LAYER_COLOR_LABEL_PRESETS: readonly LayerColorLabelPreset[] = [+ {+ id: 'none',+ name: 'None',+ swatchHex: 'transparent',+ rowTint: 'transparent',+ rowTintHover: 'transparent',+ },+ {+ id: 'red',+ name: 'Red',+ swatchHex: '#e05555',+ rowTint: 'rgba(224, 85, 85, 0.11)',+ rowTintHover: 'rgba(224, 85, 85, 0.17)',+ },+ {+ id: 'orange',+ name: 'Orange',+ swatchHex: '#e58a3c',+ rowTint: 'rgba(229, 138, 60, 0.11)',+ rowTintHover: 'rgba(229, 138, 60, 0.17)',+ },+ {+ id: 'yellow',+ name: 'Yellow',+ swatchHex: '#dfbe3a',+ rowTint: 'rgba(223, 190, 58, 0.11)',+ rowTintHover: 'rgba(223, 190, 58, 0.17)',+ },+ {+ id: 'green',+ name: 'Green',+ swatchHex: '#4cae6b',+ rowTint: 'rgba(76, 174, 107, 0.11)',+ rowTintHover: 'rgba(76, 174, 107, 0.17)',+ },+ {+ id: 'cyan',+ name: 'Cyan',+ swatchHex: '#38b2ac',+ rowTint: 'rgba(56, 178, 172, 0.11)',+ rowTintHover: 'rgba(56, 178, 172, 0.17)',+ },+ {+ id: 'blue',+ name: 'Blue',+ swatchHex: '#4a90e2',+ rowTint: 'rgba(74, 144, 226, 0.12)',+ rowTintHover: 'rgba(74, 144, 226, 0.18)',+ },+ {+ id: 'purple',+ name: 'Purple',+ swatchHex: '#9b6be8',+ rowTint: 'rgba(155, 107, 232, 0.12)',+ rowTintHover: 'rgba(155, 107, 232, 0.18)',+ },+ {+ id: 'gray',+ name: 'Gray',+ swatchHex: '#8c929c',+ rowTint: 'rgba(140, 146, 156, 0.12)',+ rowTintHover: 'rgba(140, 146, 156, 0.18)',+ },+] as const;++export const LAYER_COLOR_LABEL_MAP = new Map<LayerColorLabel, LayerColorLabelPreset>(+ LAYER_COLOR_LABEL_PRESETS.map((p) => [p.id, p])+);++const VALID_COLOR_LABELS = new Set<string>(LAYER_COLOR_LABEL_PRESETS.map((p) => p.id));++export function isValidLayerColorLabel(value: unknown): value is LayerColorLabel {+ return typeof value === 'string' && VALID_COLOR_LABELS.has(value);+}++export function normalizeLayerColorLabel(value: unknown): LayerColorLabel | undefined {+ if (!isValidLayerColorLabel(value) || value === 'none') return undefined;+ return value;+}++export function getLayerColorLabelPreset(+ label: LayerColorLabel | undefined+): LayerColorLabelPreset | null {+ if (!label || label === 'none') return null;+ return LAYER_COLOR_LABEL_MAP.get(label) ?? null;+}++export type PsdSheetColor =+ | 'none'+ | 'red'+ | 'orange'+ | 'yellow'+ | 'green'+ | 'blue'+ | 'violet'+ | 'gray';++export function toPsdLayerColor(label?: LayerColorLabel): PsdSheetColor | undefined {+ if (!label || label === 'none') return undefined;+ switch (label) {+ case 'red':+ case 'orange':+ case 'yellow':+ case 'green':+ case 'blue':+ case 'gray':+ return label;+ case 'purple':+ return 'violet';+ case 'cyan':+ return 'blue';+ }+}++export function fromPsdLayerColor(psdColor?: string): LayerColorLabel | undefined {+ if (!psdColor || psdColor === 'none') return undefined;+ switch (psdColor) {+ case 'red':+ case 'orange':+ case 'yellow':+ case 'green':+ case 'blue':+ case 'gray':+ return psdColor;+ case 'violet':+ return 'purple';+ default:+ return undefined;+ }+}++export type LayerKindFilter =+ | 'all'+ | 'raster'+ | 'folder'+ | 'text'+ | 'adjustment'+ | 'tone'+ | 'masked'+ | 'reference'+ | 'locked'+ | 'hidden';++export interface LayerFilterCriteria {+ query: string;+ colorLabel: LayerColorLabel | 'all';+ kind: LayerKindFilter;+}++export const DEFAULT_LAYER_FILTER_CRITERIA: LayerFilterCriteria = {+ query: '',+ colorLabel: 'all',+ kind: 'all',+};++export interface LayerFilterResult {+ isActive: boolean;+ visibleLayerIds: Set<string>;+ directMatchIds: Set<string>;+ ancestorOnlyIds: Set<string>;+ matchCount: number;+}++export function isLayerFilterActive(criteria: LayerFilterCriteria): boolean {+ return (+ criteria.query.trim().length > 0 ||+ criteria.colorLabel !== 'all' ||+ criteria.kind !== 'all'+ );+}++export function matchesLayerFilter(layer: LayerItem, criteria: LayerFilterCriteria): boolean {+ const trimmed = criteria.query.trim().toLowerCase();+ if (trimmed.length > 0 && !layer.name.toLowerCase().includes(trimmed)) {+ return false;+ }++ if (criteria.colorLabel !== 'all') {+ const effectiveLabel: LayerColorLabel =+ layer.colorLabel && layer.colorLabel !== 'none' ? layer.colorLabel : 'none';+ if (effectiveLabel !== criteria.colorLabel) {+ return false;+ }+ }++ switch (criteria.kind) {+ case 'all':+ return true;+ case 'raster':+ return layer.type === 'raster';+ case 'folder':+ return isFolderLikeLayer(layer);+ case 'text':+ return layer.type === 'text' || layer.type === 'balloon';+ case 'adjustment':+ return layer.type === 'adjustment';+ case 'tone':+ return Boolean(layer.toneEnabled || layer.isToneLayer);+ case 'masked':+ return Boolean(+ layer.maskCanvas || layer.maskEnabled !== undefined || layer.maskThumbnailUrl+ );+ case 'reference':+ return Boolean(layer.isReference);+ case 'locked':+ return Boolean(layer.locked || layer.alphaLocked);+ case 'hidden':+ return !layer.visible;+ }+}++/**+ * Evaluates search + color label + kind/state filtering across a nested layer tree,+ * keeping ancestor folders visible as structural context whenever a descendant matches.+ */+export function filterLayerTree(+ layers: readonly LayerItem[],+ criteria: LayerFilterCriteria+): LayerFilterResult {+ if (!isLayerFilterActive(criteria)) {+ const allIds = new Set(layers.map((l) => l.id));+ return {+ isActive: false,+ visibleLayerIds: allIds,+ directMatchIds: allIds,+ ancestorOnlyIds: new Set<string>(),+ matchCount: layers.length,+ };+ }++ const byId = new Map(layers.map((l) => [l.id, l]));+ const directMatchIds = new Set<string>();+ const visibleLayerIds = new Set<string>();+ const ancestorOnlyIds = new Set<string>();++ for (const layer of layers) {+ if (matchesLayerFilter(layer, criteria)) {+ directMatchIds.add(layer.id);+ visibleLayerIds.add(layer.id);+ }+ }++ for (const matchedId of directMatchIds) {+ const seen = new Set<string>([matchedId]);+ let parentId = byId.get(matchedId)?.parentId ?? null;+ while (parentId && !seen.has(parentId)) {+ seen.add(parentId);+ const parent = byId.get(parentId);+ if (!parent) break;+ visibleLayerIds.add(parent.id);+ if (!directMatchIds.has(parent.id)) {+ ancestorOnlyIds.add(parent.id);+ }+ parentId = parent.parentId;+ }+ }++ return {+ isActive: true,+ visibleLayerIds,+ directMatchIds,+ ancestorOnlyIds,+ matchCount: directMatchIds.size,+ };+}++/**+ * Pure batch update for assigning a LayerColorLabel to one layer or a multi-selected group.+ */+export function computeBatchColorLabel(+ layers: LayerItem[],+ selectedIds: string[],+ targetId: string,+ colorLabel: LayerColorLabel+): LayerItem[] {+ const normalized = normalizeLayerColorLabel(colorLabel);+ const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);+ const targetSet = isMulti ? new Set(selectedIds) : new Set([targetId]);++ let changed = false;+ const next = layers.map((l) => {+ if (!targetSet.has(l.id)) return l;+ const current = normalizeLayerColorLabel(l.colorLabel);+ if (current === normalized) return l;+ changed = true;+ return { ...l, colorLabel: normalized };+ });++ return changed ? next : layers;+}++export interface SoloLayerState {+ layerId: string;+ previousVisibility: Record<string, boolean>;+}++export interface ComputeSoloResult {+ nextLayers: LayerItem[];+ nextSolo: SoloLayerState | null;+ action: 'solo' | 'switch-solo' | 'restore' | 'show-all' | 'noop';+}++function collectAncestorFolderIds(+ byId: Map<string, LayerItem>,+ layerId: string+): Set<string> {+ const ancestors = new Set<string>();+ const seen = new Set<string>([layerId]);+ let parentId = byId.get(layerId)?.parentId ?? null;+ while (parentId && !seen.has(parentId)) {+ seen.add(parentId);+ const parent = byId.get(parentId);+ if (!parent) break;+ ancestors.add(parent.id);+ parentId = parent.parentId;+ }+ return ancestors;+}++function collectDescendantIds(layers: readonly LayerItem[], folderId: string): Set<string> {+ const descendants = new Set<string>();+ const collect = (parentId: string) => {+ for (const l of layers) {+ if (l.parentId === parentId && !descendants.has(l.id)) {+ descendants.add(l.id);+ if (isFolderLikeLayer(l)) {+ collect(l.id);+ }+ }+ }+ };+ collect(folderId);+ return descendants;+}++/**+ * Pure state transition for Alt+Click Solo/Isolate Layer:+ * - First Alt+Click: snapshots all layer visibilities and hides everything except `targetId`+ * (plus ancestor folders so nested layers stay renderable, and preserves descendants' visibility if soloing a folder).+ * - Alt+Click on the same soloed layer: restores exact pre-solo visibility for every layer.+ * - Alt+Click on a different layer while soloed: switches solo target while preserving the original restore snapshot.+ * - Alt+Click when all other layers are already manually hidden (no active snapshot): reveals all layers.+ */+export function computeSoloToggle(+ layers: LayerItem[],+ targetId: string,+ currentSolo: SoloLayerState | null+): ComputeSoloResult {+ const byId = new Map(layers.map((l) => [l.id, l]));+ const target = byId.get(targetId);+ if (!target) {+ return { nextLayers: layers, nextSolo: currentSolo, action: 'noop' };+ }++ // Clicking Alt+Eye on the currently soloed layer restores pre-solo visibility+ if (currentSolo && currentSolo.layerId === targetId) {+ return computeRestoreSolo(layers, currentSolo);+ }++ const ancestors = collectAncestorFolderIds(byId, targetId);+ const descendants = isFolderLikeLayer(target)+ ? collectDescendantIds(layers, targetId)+ : new Set<string>();++ const baselineVisibility: Record<string, boolean> = currentSolo+ ? currentSolo.previousVisibility+ : Object.fromEntries(layers.map((l) => [l.id, l.visible]));++ // If not currently in solo mode and everything outside target/ancestors/descendants is already hidden,+ // Alt+Click reveals all layers cleanly (Photoshop / CSP convention).+ if (!currentSolo) {+ const outsideLayers = layers.filter(+ (l) => l.id !== targetId && !ancestors.has(l.id) && !descendants.has(l.id)+ );+ const allOutsideAlreadyHidden =+ outsideLayers.length > 0 && outsideLayers.every((l) => !l.visible);+ const targetAndAncestorsVisible =+ target.visible && Array.from(ancestors).every((aid) => Boolean(byId.get(aid)?.visible));++ if (allOutsideAlreadyHidden && targetAndAncestorsVisible) {+ const nextLayers = layers.map((l) => (l.visible ? l : { ...l, visible: true }));+ return { nextLayers, nextSolo: null, action: 'show-all' };+ }+ }++ const nextLayers = layers.map((l) => {+ let desiredVisible: boolean;+ if (l.id === targetId || ancestors.has(l.id)) {+ desiredVisible = true;+ } else if (descendants.has(l.id)) {+ desiredVisible = baselineVisibility[l.id] ?? l.visible;+ } else {+ desiredVisible = false;+ }+ return l.visible === desiredVisible ? l : { ...l, visible: desiredVisible };+ });++ return {+ nextLayers,+ nextSolo: {+ layerId: targetId,+ previousVisibility: baselineVisibility,+ },+ action: currentSolo ? 'switch-solo' : 'solo',+ };+}++export function computeRestoreSolo(+ layers: LayerItem[],+ currentSolo: SoloLayerState | null+): ComputeSoloResult {+ if (!currentSolo) {+ return { nextLayers: layers, nextSolo: null, action: 'noop' };+ }+ const nextLayers = layers.map((l) => {+ const restored = currentSolo.previousVisibility[l.id];+ if (restored === undefined || l.visible === restored) return l;+ return { ...l, visible: restored };+ });+ return {+ nextLayers,+ nextSolo: null,+ action: 'restore',+ };+}diff --git a/src/utils/mangaTextEngine.ts b/src/utils/mangaTextEngine.tsindex bbe998b..39e91ad 100644--- a/src/utils/mangaTextEngine.ts+++ b/src/utils/mangaTextEngine.ts@@ -1,11 +1,10 @@/**- * Manga Lettering & Text Layout Engine+ * Authentic Typography & Manga Text Layout Engine*- * Implements Clip Studio Paint EX-grade text formatting with support for:- * - Traditional Japanese / East Asian vertical lettering (tate-gaki: vertical-rl, right-to-left columns)- * - Punctuation shifting (e.g. Japanese full stops and commas positioned top-right)- * - Glyphs and Latin/dash rotation (90° clockwise rotation for em-dashes, brackets, tildes)- * - Automatic centering and boundary containment for speech balloons+ * Provides crisp, natural proportional text rendering with native OS/browser kerning+ * and shaping for horizontal text, plus traditional East Asian vertical lettering+ * (tate-gaki: vertical-rl, right-to-left columns) with punctuation rotation/shifting,+ * word wrapping, letter spacing, underline, opacity, and clean two-pass outlines.*/export interface MangaTextOptions {@@ -14,13 +13,16 @@ export interface MangaTextOptions {writingMode?: 'horizontal-tb' | 'vertical-rl';bold?: boolean;italic?: boolean;+ underline?: boolean;align?: 'left' | 'center' | 'right';color?: string;outline?: boolean;outlineColor?: string;outlineWidth?: number;lineHeightRatio?: number;- maxWidth?: number;+ letterSpacing?: number;+ opacity?: number;+ maxWidth?: number | null;maxHeight?: number;anchorTopLeft?: boolean;}@@ -34,97 +36,365 @@ export interface PositionedGlyph {scaleY?: number;}+export interface PositionedLine {+ text: string;+ x: number;+ y: number;+ baselineY: number;+ width: number;+ height: number;+}+export interface TextLayoutResult {glyphs: PositionedGlyph[];+ lines: PositionedLine[];width: number;height: number;+ ascent: number;+ descent: number;+ lineHeight: number;}// Characters that should be rotated 90 degrees clockwise in vertical writing modeconst ROTATED_PUNCTUATION = new Set([- '—', '―', '–', '-', '―', '…', '‥', '~', '~', ':', ';',+ '—', '―', '–', '-', '…', '‥', '~', '~', ':', ';','「', '」', '『', '』', '(', ')', '(', ')', '【', '】','[', ']', '[', ']', '{', '}', '{', '}', '〈', '〉','《', '》', '<', '>', '<', '>', '〔', '〕', '|', '|',- '=' , '=', '_', '_'+ '=', '=', '_', '_',]);// Japanese punctuation that needs shifting to the upper right corner in vertical modeconst SHIFTED_PUNCTUATION = new Set([- '。', '、', ',', '.', '・'+ '。', '、', ',', '.', '・',]);+let cachedMeasureCtx: CanvasRenderingContext2D | null | undefined;+let supportsNativeLetterSpacing: boolean | undefined;++function getMeasureContext(): CanvasRenderingContext2D | null {+ if (cachedMeasureCtx !== undefined) return cachedMeasureCtx;+ if (typeof document === 'undefined') {+ cachedMeasureCtx = null;+ return null;+ }+ try {+ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ const ctx = canvas.getContext('2d');+ cachedMeasureCtx = ctx ?? null;+ } catch {+ cachedMeasureCtx = null;+ }+ return cachedMeasureCtx;+}++function checkNativeLetterSpacing(ctx: CanvasRenderingContext2D): boolean {+ if (supportsNativeLetterSpacing !== undefined) return supportsNativeLetterSpacing;+ try {+ const anyCtx = ctx as unknown as { letterSpacing?: string };+ if (typeof anyCtx.letterSpacing !== 'string') {+ supportsNativeLetterSpacing = false;+ return false;+ }+ const prev = anyCtx.letterSpacing;+ anyCtx.letterSpacing = '4px';+ supportsNativeLetterSpacing = anyCtx.letterSpacing === '4px';+ anyCtx.letterSpacing = prev;+ } catch {+ supportsNativeLetterSpacing = false;+ }+ return supportsNativeLetterSpacing;+}++function setContextLetterSpacing(ctx: CanvasRenderingContext2D, letterSpacing: number): boolean {+ if (!checkNativeLetterSpacing(ctx)) return false;+ (ctx as unknown as { letterSpacing: string }).letterSpacing =+ letterSpacing === 0 ? '0px' : `${letterSpacing}px`;+ return true;+}++/**+ * Builds a consistent CSS font descriptor shared by measurement, canvas rendering, and DOM preview.+ */+export function buildCanvasFontString(options: {+ fontSize?: number;+ fontFamily?: string;+ bold?: boolean;+ italic?: boolean;+}): string {+ const fontSize = Math.max(1, options.fontSize || 20);+ const style = options.italic ? 'italic ' : '';+ const weight = options.bold ? '700 ' : '400 ';+ const family = options.fontFamily?.trim() || "Inter, 'Segoe UI', system-ui, sans-serif";+ return `${style}${weight}${fontSize}px ${family}`;+}+/**- * Checks if a character is an ASCII Latin letter or digit+ * Checks if a character is an ASCII Latin letter or digit.*/export function isLatinChar(char: string): boolean {const code = char.charCodeAt(0);return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57);}+function isWideCjkChar(char: string): boolean {+ const cp = char.codePointAt(0) ?? 0;+ return (+ (cp >= 0x3000 && cp <= 0x9fff) ||+ (cp >= 0xac00 && cp <= 0xd7af) ||+ (cp >= 0xf900 && cp <= 0xfaff) ||+ (cp >= 0xff01 && cp <= 0xff60)+ );+}++function estimateFallbackCharWidth(char: string, fontSize: number, bold?: boolean): number {+ const boldBoost = bold ? 1.06 : 1.0;+ if (char === ' ') return fontSize * 0.28;+ if (char === '\t') return fontSize * 1.12;+ if (isWideCjkChar(char)) return fontSize * 1.0;+ if ("ilI1|.,:;'!`".includes(char)) return fontSize * 0.3 * boldBoost;+ if ('WM@%#&'.includes(char)) return fontSize * 0.86 * boldBoost;+ if ('mwGOQD'.includes(char)) return fontSize * 0.72 * boldBoost;+ return fontSize * 0.56 * boldBoost;+}++function measureTextWidth(+ ctx: CanvasRenderingContext2D | null,+ str: string,+ fontSize: number,+ letterSpacing: number,+ bold?: boolean+): number {+ if (!str) return 0;+ if (ctx) {+ if (letterSpacing === 0) {+ setContextLetterSpacing(ctx, 0);+ return ctx.measureText(str).width;+ }+ if (setContextLetterSpacing(ctx, letterSpacing)) {+ const w = ctx.measureText(str).width;+ setContextLetterSpacing(ctx, 0);+ // Native letterSpacing applies after the final glyph in some engines; subtract trailing spacing+ const chars = Array.from(str);+ return Math.max(0, chars.length > 0 ? w - letterSpacing : w);+ }+ const chars = Array.from(str);+ let total = 0;+ for (let i = 0; i < chars.length; i++) {+ total += ctx.measureText(chars[i]).width;+ if (i < chars.length - 1) total += letterSpacing;+ }+ return Math.max(0, total);+ }++ const chars = Array.from(str);+ let total = 0;+ for (let i = 0; i < chars.length; i++) {+ total += estimateFallbackCharWidth(chars[i], fontSize, bold);+ if (i < chars.length - 1) total += letterSpacing;+ }+ return Math.max(0, total);+}++function measureFontVerticalMetrics(+ ctx: CanvasRenderingContext2D | null,+ fontSize: number+): { ascent: number; descent: number } {+ if (ctx) {+ try {+ const m = ctx.measureText('MgÅjpq');+ const ascent =+ (typeof m.fontBoundingBoxAscent === 'number' && m.fontBoundingBoxAscent > 0+ ? m.fontBoundingBoxAscent+ : m.actualBoundingBoxAscent) || fontSize * 0.82;+ const descent =+ (typeof m.fontBoundingBoxDescent === 'number' && m.fontBoundingBoxDescent > 0+ ? m.fontBoundingBoxDescent+ : m.actualBoundingBoxDescent) || fontSize * 0.2;+ return { ascent, descent };+ } catch {+ // Fallback below+ }+ }+ return {+ ascent: fontSize * 0.82,+ descent: fontSize * 0.2,+ };+}++function wrapParagraph(+ paragraph: string,+ maxWidth: number,+ measure: (s: string) => number+): string[] {+ if (!paragraph) return [''];+ if (measure(paragraph) <= maxWidth) return [paragraph];++ const tokens = paragraph.match(/\S+|\s+/g) ?? [paragraph];+ const wrapped: string[] = [];+ let current = '';++ const pushBreakLongWord = (word: string) => {+ const chars = Array.from(word);+ let chunk = '';+ for (const ch of chars) {+ const candidate = chunk + ch;+ if (chunk && measure(candidate) > maxWidth) {+ wrapped.push(chunk);+ chunk = ch;+ } else {+ chunk = candidate;+ }+ }+ current = chunk;+ };++ for (const token of tokens) {+ const candidate = current + token;+ if (measure(candidate) <= maxWidth) {+ current = candidate;+ continue;+ }+ if (/^\s+$/.test(token)) {+ // Drop overflowing trailing whitespace at line wrap+ if (current) {+ wrapped.push(current);+ current = '';+ }+ continue;+ }+ if (current) {+ wrapped.push(current.replace(/\s+$/, ''));+ current = '';+ }+ if (measure(token) <= maxWidth) {+ current = token;+ } else {+ pushBreakLongWord(token);+ }+ }++ if (current || wrapped.length === 0) {+ wrapped.push(current);+ }+ return wrapped;+}+/**- * Computes glyph positions for horizontal or vertical manga lettering.+ * Computes natural proportional horizontal layout or traditional vertical-rl layout.*/export function computeMangaTextLayout(text: string,options: MangaTextOptions): TextLayoutResult {const isVertical = options.writingMode === 'vertical-rl';- const fontSize = options.fontSize || 20;+ const fontSize = Math.max(1, options.fontSize || 20);const lineHeightRatio = options.lineHeightRatio || (isVertical ? 1.4 : 1.25);- const lineSpacing = fontSize * lineHeightRatio;- const rawLines = text.split('\n');+ const lineHeight = fontSize * lineHeightRatio;+ const letterSpacing = options.letterSpacing ?? 0;+ const rawParagraphs = text.split('\n');++ const measureCtx = getMeasureContext();+ if (measureCtx) {+ measureCtx.font = buildCanvasFontString(options);+ }+ const { ascent, descent } = measureFontVerticalMetrics(measureCtx, fontSize);if (!isVertical) {- // Standard horizontal-tb layout+ const measure = (s: string) =>+ measureTextWidth(measureCtx, s, fontSize, letterSpacing, options.bold);++ const wrapWidth =+ typeof options.maxWidth === 'number' && Number.isFinite(options.maxWidth) && options.maxWidth >= 24+ ? options.maxWidth+ : null;++ const visualLines: string[] = [];+ for (const para of rawParagraphs) {+ if (wrapWidth !== null) {+ visualLines.push(...wrapParagraph(para, wrapWidth, measure));+ } else {+ visualLines.push(para);+ }+ }++ const lineWidths = visualLines.map((l) => measure(l));+ let maxMeasuredWidth = 0;+ for (const w of lineWidths) {+ if (w > maxMeasuredWidth) maxMeasuredWidth = w;+ }++ const boxWidth = wrapWidth !== null ? Math.max(wrapWidth, maxMeasuredWidth) : Math.max(fontSize * 0.6, maxMeasuredWidth);+ const leading = lineHeight - (ascent + descent);+ const baselineInLine = leading * 0.5 + ascent;++ const lines: PositionedLine[] = [];const glyphs: PositionedGlyph[] = [];- const charWidth = fontSize * 0.6; // estimated fallback- const linesChars = rawLines.map((line) => Array.from(line));- let maxLineWidth = 0;- for (const chars of linesChars) {- const w = chars.length * charWidth;- if (w > maxLineWidth) maxLineWidth = w;- }- const boxWidth = Math.max(fontSize, maxLineWidth);-- linesChars.forEach((chars, lineIdx) => {- const lineY = lineIdx * lineSpacing + fontSize * 0.5;- const lineWidth = chars.length * charWidth;++ visualLines.forEach((lineText, lineIdx) => {+ const lineY = lineIdx * lineHeight;+ const baselineY = lineY + baselineInLine;+ const lw = lineWidths[lineIdx];+let startX = 0;if (options.align === 'center') {- startX = (boxWidth - lineWidth) * 0.5;+ startX = (boxWidth - lw) * 0.5;} else if (options.align === 'right') {- startX = boxWidth - lineWidth;+ startX = boxWidth - lw;}- for (let cIdx = 0; cIdx < chars.length; cIdx++) {+ lines.push({+ text: lineText,+ x: startX,+ y: lineY,+ baselineY,+ width: lw,+ height: lineHeight,+ });++ // Populate per-character glyph coordinates for hit-testing and consumers+ const chars = Array.from(lineText);+ let cursorX = startX;+ const glyphCenterY = lineY + lineHeight * 0.5;+ for (let i = 0; i < chars.length; i++) {+ const ch = chars[i];+ const cw = measureTextWidth(measureCtx, ch, fontSize, 0, options.bold);glyphs.push({- char: chars[cIdx],- x: startX + cIdx * charWidth + charWidth * 0.5,- y: lineY,+ char: ch,+ x: cursorX + cw * 0.5,+ y: glyphCenterY,rotateDeg: 0,});+ cursorX += cw + letterSpacing;}});- const totalHeight = rawLines.length * lineSpacing;+ const totalHeight = Math.max(lineHeight, visualLines.length * lineHeight);return {glyphs,+ lines,width: boxWidth,- height: Math.max(fontSize, totalHeight),+ height: totalHeight,+ ascent,+ descent,+ lineHeight,};}// Vertical-rl layout: Columns proceed Right to Left, characters Top to Bottom- const numColumns = rawLines.length;- const totalWidth = numColumns * lineSpacing;+ const numColumns = rawParagraphs.length;+ const totalWidth = numColumns * lineHeight;+ const stepY = Math.max(fontSize * 0.5, fontSize + letterSpacing);let maxColHeight = 0;const glyphs: PositionedGlyph[] = [];+ const lines: PositionedLine[] = [];- rawLines.forEach((line, colIndex) => {+ rawParagraphs.forEach((line, colIndex) => {const chars = Array.from(line);- // In vertical-rl, col 0 is at rightmost position (x = (numColumns - 1 - colIndex) * lineSpacing)- const colX = (numColumns - 1 - colIndex) * lineSpacing + lineSpacing * 0.5;+ // In vertical-rl, col 0 is at rightmost position+ const colX = (numColumns - 1 - colIndex) * lineHeight + lineHeight * 0.5;let currentY = fontSize * 0.6;for (let cIdx = 0; cIdx < chars.length; cIdx++) {@@ -132,12 +402,10 @@ export function computeMangaTextLayout(let rotateDeg = 0;let dx = 0;let dy = 0;- const stepY = fontSize;if (ROTATED_PUNCTUATION.has(char)) {rotateDeg = 90;} else if (SHIFTED_PUNCTUATION.has(char)) {- // Shift to top-right quadrantdx = fontSize * 0.28;dy = -fontSize * 0.28;}@@ -152,21 +420,81 @@ export function computeMangaTextLayout(currentY += stepY;}- if (currentY > maxColHeight) {- maxColHeight = currentY;+ const colHeight = chars.length > 0 ? currentY - stepY + fontSize * 0.6 : fontSize;+ lines.push({+ text: line,+ x: colX - lineHeight * 0.5,+ y: 0,+ baselineY: fontSize * 0.6,+ width: lineHeight,+ height: colHeight,+ });++ if (colHeight > maxColHeight) {+ maxColHeight = colHeight;}});return {glyphs,+ lines,width: Math.max(fontSize, totalWidth),height: Math.max(fontSize, maxColHeight),+ ascent,+ descent,+ lineHeight,};}+function drawHorizontalLine(+ ctx: CanvasRenderingContext2D,+ line: PositionedLine,+ offsetX: number,+ offsetY: number,+ letterSpacing: number,+ mode: 'stroke' | 'fill'+): void {+ if (!line.text) return;+ const drawX = offsetX + line.x;+ const drawY = offsetY + line.baselineY;++ if (letterSpacing === 0) {+ setContextLetterSpacing(ctx, 0);+ if (mode === 'stroke') {+ ctx.strokeText(line.text, drawX, drawY);+ } else {+ ctx.fillText(line.text, drawX, drawY);+ }+ return;+ }++ if (setContextLetterSpacing(ctx, letterSpacing)) {+ if (mode === 'stroke') {+ ctx.strokeText(line.text, drawX, drawY);+ } else {+ ctx.fillText(line.text, drawX, drawY);+ }+ setContextLetterSpacing(ctx, 0);+ return;+ }++ // Fallback per-grapheme rendering when native ctx.letterSpacing is unavailable+ const chars = Array.from(line.text);+ let cursorX = drawX;+ for (let i = 0; i < chars.length; i++) {+ const ch = chars[i];+ if (mode === 'stroke') {+ ctx.strokeText(ch, cursorX, drawY);+ } else {+ ctx.fillText(ch, cursorX, drawY);+ }+ cursorX += ctx.measureText(ch).width + letterSpacing;+ }+}+/**- * Renders manga text onto a 2D Canvas context.- * Automatically aligns to (originX, originY) according to options.+ * Renders authentic typography onto a 2D Canvas context using two-pass outline-then-fill+ * rendering and native font shaping for horizontal text.*/export function renderMangaTextToCanvas(ctx: CanvasRenderingContext2D,@@ -177,49 +505,104 @@ export function renderMangaTextToCanvas(): void {if (!text || !text.trim()) return;- const fontSize = options.fontSize || 20;- const fontStyle = `${options.italic ? 'italic ' : ''}${options.bold ? 'bold ' : ''}${fontSize}px ${options.fontFamily || 'sans-serif'}`;+ const isVertical = options.writingMode === 'vertical-rl';+ const fontSize = Math.max(1, options.fontSize || 20);+ const letterSpacing = options.letterSpacing ?? 0;+ const opacity =+ typeof options.opacity === 'number' && Number.isFinite(options.opacity)+ ? Math.max(0.05, Math.min(1, options.opacity))+ : 1;+ const fontStyle = buildCanvasFontString(options);const layout = computeMangaTextLayout(text, options);ctx.save();+ ctx.globalAlpha *= opacity;ctx.font = fontStyle;- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';+ ctx.lineJoin = 'round';+ ctx.lineCap = 'round';+ ctx.miterLimit = 2;- // Compute bounding offset so text is centered or aligned around (originX, originY)let offsetX = originX - layout.width * 0.5;let offsetY = originY - layout.height * 0.5;if (options.anchorTopLeft) {- offsetX = originX + 6;- offsetY = originY + 6;+ offsetX = originX;+ offsetY = originY;} else if (options.align === 'left') {offsetX = originX;} else if (options.align === 'right') {offsetX = originX - layout.width;}- for (const g of layout.glyphs) {- const gx = offsetX + g.x;- const gy = offsetY + g.y;+ const hasOutline = Boolean(options.outline && (options.outlineWidth ?? 0) > 0);+ const outlineStrokeWidth = (options.outlineWidth ?? 2) * 2;+ const outlineColor = options.outlineColor || '#000000';+ const fillColor = options.color || '#ffffff';- ctx.save();- ctx.translate(gx, gy);- if (g.rotateDeg !== 0) {- ctx.rotate((g.rotateDeg * Math.PI) / 180);+ if (!isVertical) {+ ctx.textAlign = 'left';+ ctx.textBaseline = 'alphabetic';++ const underlineThickness = Math.max(1, fontSize * 0.065);+ const underlineOffset = Math.max(2, fontSize * 0.13);++ // Pass 1: Draw ALL outlines first so strokes never bleed over adjacent glyphs+ if (hasOutline) {+ ctx.strokeStyle = outlineColor;+ ctx.lineWidth = outlineStrokeWidth;+ for (const line of layout.lines) {+ drawHorizontalLine(ctx, line, offsetX, offsetY, letterSpacing, 'stroke');+ if (options.underline && line.width > 0) {+ const uy = offsetY + line.baselineY + underlineOffset;+ ctx.beginPath();+ ctx.lineWidth = underlineThickness + outlineStrokeWidth;+ ctx.moveTo(offsetX + line.x, uy);+ ctx.lineTo(offsetX + line.x + line.width, uy);+ ctx.stroke();+ ctx.lineWidth = outlineStrokeWidth;+ }+ }+ }++ // Pass 2: Draw crisp main text fill on top+ ctx.fillStyle = fillColor;+ for (const line of layout.lines) {+ drawHorizontalLine(ctx, line, offsetX, offsetY, letterSpacing, 'fill');+ if (options.underline && line.width > 0) {+ const uy = offsetY + line.baselineY + underlineOffset - underlineThickness * 0.5;+ ctx.fillRect(offsetX + line.x, uy, line.width, underlineThickness);+ }}- // Outline stroke- if (options.outline && (options.outlineWidth || 0) > 0) {- ctx.strokeStyle = options.outlineColor || '#ffffff';- ctx.lineWidth = (options.outlineWidth || 2) * 2;- ctx.lineJoin = 'round';- ctx.miterLimit = 2;+ ctx.restore();+ return;+ }++ // Vertical-rl two-pass rendering+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';++ if (hasOutline) {+ ctx.strokeStyle = outlineColor;+ ctx.lineWidth = outlineStrokeWidth;+ for (const g of layout.glyphs) {+ ctx.save();+ ctx.translate(offsetX + g.x, offsetY + g.y);+ if (g.rotateDeg !== 0) {+ ctx.rotate((g.rotateDeg * Math.PI) / 180);+ }ctx.strokeText(g.char, 0, 0);+ ctx.restore();}+ }- // Main fill- ctx.fillStyle = options.color || '#000000';+ ctx.fillStyle = fillColor;+ for (const g of layout.glyphs) {+ ctx.save();+ ctx.translate(offsetX + g.x, offsetY + g.y);+ if (g.rotateDeg !== 0) {+ ctx.rotate((g.rotateDeg * Math.PI) / 180);+ }ctx.fillText(g.char, 0, 0);ctx.restore();}diff --git a/src/utils/nativeBackend.ts b/src/utils/nativeBackend.tsindex ceb02c7..836205d 100644--- a/src/utils/nativeBackend.ts+++ b/src/utils/nativeBackend.ts@@ -3,10 +3,18 @@* Zero JSON pixel encoding: all buffers cross IPC as raw Uint8Array / ArrayBuffer frames.*/-import { BlendMode, CanvasColorMode, DirtyRect, FilterType, LayerItem, LoadedDocument } from '../types/editor';+import {+ BlendMode,+ CanvasColorMode,+ DirtyRect,+ ExpressionColor,+ FilterType,+ LayerItem,+ LoadedDocument,+} from '../types/editor';import { createCanvasThumbnail } from './canvasUtils';import { lz4DecompressBlock } from './lz4';-import { BYTES_32BIT, SparseTileGrid } from './tileEngine';+import { allocateTileVersion, BYTES_32BIT, SparseTileGrid } from './tileEngine';import { isTauriEnvironment } from './tileEngine/scratchDriver';import { performanceManager } from './performanceManager';import type { LiquifyMode } from './liquifyEngine';@@ -76,6 +84,12 @@ interface WireLayerMeta {collapsed: boolean;parentId: string | null;solidFillHex: string | null;+ expressionColor?: ExpressionColor;+ monoExpressBlack?: boolean;+ monoExpressWhite?: boolean;+ layerColorEnabled?: boolean;+ layerColor?: string;+ layerSubColor?: string;tiles: WireTileRef[];mask: WireMaskRef | null;}@@ -214,6 +228,7 @@ export function hydrateParsedDocumentBinary(tileGrid.setLayerFormat(id, 'color-32bit');tileGrid.markLayerIngested(id);+ let hydratedTiles = false;if (wl.tiles.length > 0) {for (const t of wl.tiles) {const payload = blobSection.subarray(t.offset, t.offset + t.len);@@ -226,20 +241,30 @@ export function hydrateParsedDocumentBinary(rgba = null;}if (rgba) {- tileGrid.setTile(id, t.tx, t.ty, {- layerId: id,- tileX: t.tx,- tileY: t.ty,- format: 'color-32bit',- data: rgba,- dirty: true,- version: 1,- isPagedToDisk: false,- lastAccessTimestamp: stamp,- lod: 0,- });+ tileGrid.setTile(+ id,+ t.tx,+ t.ty,+ {+ layerId: id,+ tileX: t.tx,+ tileY: t.ty,+ format: 'color-32bit',+ data: rgba,+ dirty: true,+ version: allocateTileVersion(),+ isPagedToDisk: false,+ lastAccessTimestamp: stamp,+ lod: 0,+ },+ true+ );+ hydratedTiles = true;}}+ if (hydratedTiles) {+ tileGrid.notifyChange();+ }} else if (wl.solidFillHex) {tileGrid.fillLayerSolidColor(id, width, height, wl.solidFillHex, 'color-32bit');}@@ -249,6 +274,7 @@ export function hydrateParsedDocumentBinary(true);+ const exprColor = normalizeExpressionColor(wl.expressionColor);layers.push({id,name: wl.name,@@ -261,6 +287,16 @@ export function hydrateParsedDocumentBinary(clipped: wl.clipped,parentId,thumbnailUrl: thumb,+ ...(exprColor ? { expressionColor: exprColor } : {}),+ ...(typeof wl.monoExpressBlack === 'boolean'+ ? { monoExpressBlack: wl.monoExpressBlack }+ : {}),+ ...(typeof wl.monoExpressWhite === 'boolean'+ ? { monoExpressWhite: wl.monoExpressWhite }+ : {}),+ ...(wl.layerColorEnabled ? { layerColorEnabled: true } : {}),+ ...(wl.layerColor ? { layerColor: wl.layerColor } : {}),+ ...(wl.layerSubColor ? { layerSubColor: wl.layerSubColor } : {}),...maskFields,});}diff --git a/src/utils/osFileOpen.ts b/src/utils/osFileOpen.tsnew file mode 100644index 0000000..9f1a243--- /dev/null+++ b/src/utils/osFileOpen.ts@@ -0,0 +1,112 @@+import { DocumentTab } from '../types/editor';+import {+ extractFilenameFromPath,+ getMimeTypeForFilename,+ readTauriFileBytes,+} from './fileDropImport';++export const OPEN_FILES_EVENT = 'inkstudio://open-files';++interface TauriWindow extends Window {+ __TAURI_INTERNALS__?: unknown;+}++export function isTauriDesktop(): boolean {+ return typeof window !== 'undefined' && Boolean((window as TauriWindow).__TAURI_INTERNALS__);+}++/**+ * Strips Windows verbatim prefixes (`\\?\` / `\\?\UNC\`) and normalizes path separators+ * and casing (case-insensitive for Windows drive/UNC paths) for reliable tab deduplication.+ */+export function normalizePathForComparison(rawPath: string | null | undefined): string {+ if (!rawPath || typeof rawPath !== 'string') return '';+ let p = rawPath.trim();+ if (!p) return '';+ if (p.startsWith('\\\\?\\UNC\\') || p.startsWith('//?/UNC/')) {+ p = '\\\\' + p.slice(8);+ } else if (p.startsWith('\\\\?\\') || p.startsWith('//?/')) {+ p = p.slice(4);+ }+ const normalizedSlashes = p.replace(/\\/g, '/').replace(/\/+$/, '');+ const isWindowsPath =+ /^[a-zA-Z]:\//.test(normalizedSlashes) || normalizedSlashes.startsWith('//');+ return isWindowsPath ? normalizedSlashes.toLowerCase() : normalizedSlashes;+}++/**+ * Finds an already-open DocumentTab matching the given OS filesystem path so re-opening+ * the same `.ink` file focuses the existing tab instead of creating a duplicate.+ */+export function findOpenDocumentBySourcePath(+ documents: readonly DocumentTab[],+ filePath: string+): DocumentTab | undefined {+ const target = normalizePathForComparison(filePath);+ if (!target) return undefined;+ return documents.find((doc) => {+ const tabPath = doc.sourcePath ?? doc.savedFileInfo?.path ?? null;+ if (!tabPath) return false;+ return normalizePathForComparison(tabPath) === target;+ });+}++/**+ * Reads an OS-authorized local file from Tauri's backend and wraps it as a standard Web `File`.+ */+export async function readTauriPathAsFile(filePath: string): Promise<File> {+ const bytes = await readTauriFileBytes(filePath);+ if (bytes.byteLength === 0) {+ throw new Error('File is empty');+ }+ const filename = extractFilenameFromPath(filePath);+ const mime = getMimeTypeForFilename(filename);+ const copy = new Uint8Array(bytes.byteLength);+ copy.set(bytes);+ return new File([copy.buffer], filename, { type: mime });+}++/**+ * Atomically marks the frontend ready in the Tauri backend and drains any OS launch file paths+ * (e.g. from double-clicking a `.ink` file on cold startup).+ */+export async function takePendingOpenFiles(): Promise<string[]> {+ if (!isTauriDesktop()) return [];+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const paths = await invoke<string[]>('take_pending_open_files');+ return Array.isArray(paths)+ ? paths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0)+ : [];+ } catch (err) {+ console.warn('[osFileOpen] Failed to query pending launch files:', err);+ return [];+ }+}++/**+ * Subscribes to warm OS file-open events forwarded by the Tauri single-instance plugin+ * (and macOS `RunEvent::Opened`) so files opened while Ink Studio is running open inside+ * the existing app window.+ */+export async function listenForOpenFiles(+ onPaths: (paths: string[]) => void+): Promise<() => void> {+ if (!isTauriDesktop()) return () => {};+ try {+ const { listen } = await import('@tauri-apps/api/event');+ return await listen<string[]>(OPEN_FILES_EVENT, (event) => {+ const payload = event.payload;+ if (!Array.isArray(payload) || payload.length === 0) return;+ const valid = payload.filter(+ (p): p is string => typeof p === 'string' && p.trim().length > 0+ );+ if (valid.length > 0) {+ onPaths(valid);+ }+ });+ } catch (err) {+ console.warn('[osFileOpen] Failed to attach open-files listener:', err);+ return () => {};+ }+}diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.tsindex 7f554ce..5663ed4 100644--- a/src/utils/presetBrushes.ts+++ b/src/utils/presetBrushes.ts@@ -46,6 +46,14 @@ import {isDecorationPresetId,resolveStaticBrushAssetUrl,} from './decorationBrushes';+import {+ PRO_BLEND_BRUSHES,+ PRO_NATURAL_PAINT_BRUSHES,+ PRO_PAINT_BRUSHES,+ PRO_PEN_BRUSHES,+ PRO_SKETCH_BRUSHES,+ PRO_TEXTURE_FX_BRUSHES,+} from './proPresetBrushes';export {DECORATION_BRUSHES,@@ -94,6 +102,7 @@ export const BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [{ id: 'brush', label: 'Brush' },{ id: 'blend', label: 'Blend' },{ id: 'natural-paint', label: 'Natural Paint' },+ { id: 'texture-fx', label: 'Texture & FX' },];export const ALL_BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [@@ -411,6 +420,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},+ ...PRO_PEN_BRUSHES,// =========================================================================// SKETCH SECTION@@ -663,6 +673,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},+ ...PRO_SKETCH_BRUSHES,// =========================================================================// BRUSH SECTION (PRO PAINTERLY ILLUSTRATION & COLORING SUITE)@@ -1129,6 +1140,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},+ ...PRO_PAINT_BRUSHES,// =========================================================================// BLEND SECTION (DEDICATED PURE BLENDERS PAIRED TO EVERY PAINTING STYLE)@@ -1415,6 +1427,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},+ ...PRO_BLEND_BRUSHES,// =========================================================================// NATURAL PAINT SECTION (Realistic Impasto, Bristle Ribbon & Pigment Mixing)@@ -2087,6 +2100,12 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},+ ...PRO_NATURAL_PAINT_BRUSHES,++ // =========================================================================+ // TEXTURE & FX SECTION (FOLIAGE, FRECKLES, SMOKE, ROCK, EMBER, CLOUDS, GLOW)+ // =========================================================================+ ...PRO_TEXTURE_FX_BRUSHES,];export const ALL_BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [@@ -2105,6 +2124,30 @@ export function findBuiltinBrush(presetId: BrushPresetId): BuiltinBrushDefinitiolet _assetsPrewarmed = false;let _decorationAssetsPrewarmed = false;+function prewarmSingleBuiltinBrush(def: BuiltinBrushDefinition): void {+ if (def.tipGenerator) {+ const url = def.tipGenerator();+ if (url) getPreloadedBuiltinTipImage(url);+ }+ if (def.subTipGenerators && def.subTipGenerators.length > 0) {+ for (let j = 0; j < def.subTipGenerators.length; j++) {+ const url = def.subTipGenerators[j]();+ if (url) getPreloadedBuiltinTipImage(url);+ }+ }+ if (def.dualTipGenerator) {+ const url = def.dualTipGenerator();+ if (url) getPreloadedBuiltinTipImage(url);+ }+ if (def.paperTextureGenerator) {+ const url = def.paperTextureGenerator();+ if (url) getPreloadedBuiltinTipImage(url);+ }+ if (def.settings.surfaceTextureId) {+ getSurfaceTextureGradField(def.settings.surfaceTextureId);+ }+}+/*** Decodes all procedural builtin tip and paper PNG images into browser memory once* so the very first stroke on any preset hits already-decoded textures with zero latency.@@ -2113,28 +2156,7 @@ export function prewarmBuiltinBrushAssets(): void {if (_assetsPrewarmed || typeof document === 'undefined' || typeof Image === 'undefined') return;_assetsPrewarmed = true;for (let i = 0; i < BUILTIN_BRUSHES.length; i++) {- const def = BUILTIN_BRUSHES[i];- if (def.tipGenerator) {- const url = def.tipGenerator();- if (url) getPreloadedBuiltinTipImage(url);- }- if (def.subTipGenerators && def.subTipGenerators.length > 0) {- for (let j = 0; j < def.subTipGenerators.length; j++) {- const url = def.subTipGenerators[j]();- if (url) getPreloadedBuiltinTipImage(url);- }- }- if (def.dualTipGenerator) {- const url = def.dualTipGenerator();- if (url) getPreloadedBuiltinTipImage(url);- }- if (def.paperTextureGenerator) {- const url = def.paperTextureGenerator();- if (url) getPreloadedBuiltinTipImage(url);- }- if (def.settings.surfaceTextureId) {- getSurfaceTextureGradField(def.settings.surfaceTextureId);- }+ prewarmSingleBuiltinBrush(BUILTIN_BRUSHES[i]);}}@@ -2154,17 +2176,31 @@ export function prewarmDecorationBrushAssets(): void {}}-// Schedule non-blocking prewarm in browser environments after initial paint+// Schedule non-blocking chunked prewarm in browser environments after initial paintif (typeof window !== 'undefined' && typeof document !== 'undefined') {const scheduleWarm =typeof (window as unknown as { requestIdleCallback?: (cb: () => void) => number }).requestIdleCallback ==='function'? (window as unknown as { requestIdleCallback: (cb: () => void) => number }).requestIdleCallback- : (cb: () => void) => window.setTimeout(cb, 60);- scheduleWarm(() => {- prewarmBuiltinBrushAssets();- prewarmDecorationBrushAssets();- });+ : (cb: () => void) => window.setTimeout(cb, 32);++ let nextWarmIndex = 0;+ const CHUNK_SIZE = 5;+ const runWarmChunk = () => {+ if (_assetsPrewarmed) return;+ const end = Math.min(BUILTIN_BRUSHES.length, nextWarmIndex + CHUNK_SIZE);+ for (let i = nextWarmIndex; i < end; i++) {+ prewarmSingleBuiltinBrush(BUILTIN_BRUSHES[i]);+ }+ nextWarmIndex = end;+ if (nextWarmIndex < BUILTIN_BRUSHES.length) {+ scheduleWarm(runWarmChunk);+ } else {+ _assetsPrewarmed = true;+ prewarmDecorationBrushAssets();+ }+ };+ scheduleWarm(runWarmChunk);}/**diff --git a/src/utils/proPresetBrushes.ts b/src/utils/proPresetBrushes.tsnew file mode 100644index 0000000..9d745dd--- /dev/null+++ b/src/utils/proPresetBrushes.ts@@ -0,0 +1,2014 @@+/**+ * proPresetBrushes.ts+ * Expanded world-class professional brush presets for InkStudio across all 6 built-in sections:+ * Pen (+4), Sketch (+4), Brush (+10), Blend (+4), Natural Paint (+4), and Texture & FX (+10).+ *+ * Strictly additive — leaves all 35 original built-in brushes completely untouched.+ */++import { DEFAULT_BRUSH_DYNAMICS } from '../types/editor';+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/BrushEngine';+import type { BuiltinBrushDefinition } from './presetBrushes';+import {+ generateCharcoalPaperTexture,+ generateFinePaperTexture,+ generateMineralGrainDualTip,+ generateNaturalTipByProfile,+ generatePainterlyChalkGrainTexture,+ generateSketchPaperTexture,+ getSurfaceTextureDataUrl,+} from './proceduralBrushTips';+import {+ generateBlendGouachePadTip,+ generateBlendKnifeSmearTip,+ generateBlendSmokeWispTip,+ generateBlendTortillonTip,+ generateBokehLeafSubTip,+ generateCharcoalBlockTip,+ generateColErasePencilTip,+ generateConceptBristleSubTip,+ generateConteCrayonTip,+ generateCraggyRockSubTip,+ generateDryHairSheenTip,+ generateEmberSpatterSubTip,+ generateFineStippleSubTip,+ generateHairLocksTip,+ generateHairWispTip,+ generateHardSquareTip,+ generateLuminousBloomTip,+ generateMetallicGlintTip,+ generatePainterlyCloudSubTip,+ generatePainterlyGouacheFlatTip,+ generatePainterlyLeafSubTip,+ generatePainterlyOvalTip,+ generateSilkThreadRibbonTip,+ generateSkinFrecklesSubTip,+ generateSmokeDualMaskTip,+ generateSmokeTendrilSubTip,+ generateSoftTaperedLinerTip,+ generateSumiBrushTip,+ generateVineCharcoalTip,+ generateWatercolorWashTip,+ generateWedgeChiselTip,+ generateWovenFabricTip,+} from './proProceduralBrushTips';++// =============================================================================+// PEN SECTION PRO ADDITIONS (+4)+// =============================================================================++export const PRO_PEN_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'tapered-ink-liner',+ category: 'pen',+ name: 'Soft Tapered Liner',+ badge: 'Pen',+ badgeBg: 'bg-indigo-500/15',+ badgeText: 'text-indigo-300',+ badgeBorder: 'border-indigo-500/30',+ desc: 'Silky Painted-Ink Sable Nib — Razor Start/End Taper for Hair Wisps, Glasses & Painterly Lineart',+ icon: 'pen',+ tipGenerator: generateSoftTaperedLinerTip,+ settings: {+ size: 10,+ minSizeFactor: 0.04,+ flow: 0.96,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 3,+ thickness: 0.92,+ customTipAngleDynamics: 'direction',+ spacing: 0.04,+ stabilization: 12,+ sharpCorners: true,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ pressureCurve: [+ [0.0, 0.0],+ [0.32, 0.22],+ [0.72, 0.78],+ [1.0, 1.0],+ ],+ opacitySensor: { usePressure: true, pressureMin: 0.35 },+ taper: {+ useIn: true,+ inLength: 22,+ inRatio: 0.2,+ useOut: true,+ outLength: 28,+ outRatio: 0.25,+ inOutType: 2,+ startingSharpness: 0.85,+ endingSharpness: 0.88,+ affectSize: true,+ minSizeRatio: 0.04,+ },+ useGpu: true,+ },+ },+ {+ id: 'sumi-fude-brush',+ category: 'pen',+ name: 'Sumi Brush Pen',+ badge: 'Pen',+ badgeBg: 'bg-indigo-500/15',+ badgeText: 'text-indigo-300',+ badgeBorder: 'border-indigo-500/30',+ desc: 'Expressive Wolf-Hair Fude Brush — Juicy Ink Pools with Organic Dry-Paper Bristle Breakup',+ icon: 'pen',+ tipGenerator: generateSumiBrushTip,+ paperTextureGenerator: generateSketchPaperTexture,+ settings: {+ size: 18,+ minSizeFactor: 0.05,+ flow: 0.98,+ opacity: 1.0,+ hardness: 0.94,+ antiAlias: 2,+ thickness: 0.82,+ customTipAngleDynamics: 'direction',+ spacing: 0.045,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ useVelocity: true,+ smoothing: true,+ sizeSensor: {+ usePressure: true,+ pressureMin: 0.04,+ pressureCurve: [+ [0.0, 0.0],+ [0.45, 0.36],+ [1.0, 1.0],+ ],+ useTilt: true,+ tiltMin: 1.0,+ tiltMax: 1.75,+ useVelocity: true,+ velocityMin: 0.55,+ velocityCurve: [+ [0.0, 1.0],+ [1.0, 0.0],+ ],+ },+ grain: 0.28,+ textureDensity: 0.28,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 28,+ taper: {+ useIn: false,+ inLength: 0,+ inRatio: 0,+ useOut: true,+ outLength: 26,+ outRatio: 0.24,+ inOutType: 2,+ endingSharpness: 0.86,+ affectSize: true,+ minSizeRatio: 0.05,+ },+ useGpu: true,+ },+ },+ {+ id: 'silk-embroidery-ribbon',+ category: 'pen',+ name: 'Silk Thread Multi-Line',+ badge: 'Ribbon',+ badgeBg: 'bg-indigo-500/15',+ badgeText: 'text-indigo-300',+ badgeBorder: 'border-indigo-500/30',+ desc: 'Flowing 5-Filament Embroidery Ribbon — Curved Gold Veil Patterns, Filigree & Hair Ribbons',+ icon: 'pen',+ subTipGenerators: [+ () => generateSilkThreadRibbonTip(0),+ () => generateSilkThreadRibbonTip(1),+ () => generateSilkThreadRibbonTip(2),+ ],+ subTipDimensions: { width: 64, height: 512 },+ settings: {+ size: 34,+ minSizeFactor: 0.4,+ flow: 0.94,+ opacity: 0.96,+ hardness: 0.96,+ antiAlias: 2,+ thickness: 1.0,+ thicknessVertical: true,+ spacing: 0.06,+ stabilization: 16,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ isRibbon: true,+ subTipOrder: 'random-no-repeat',+ flipH: 'none',+ flipV: 'none',+ opacitySensor: { usePressure: true, pressureMin: 0.24 },+ taper: {+ useIn: true,+ inLength: 42,+ inRatio: 0.25,+ useOut: true,+ outLength: 56,+ outRatio: 0.3,+ inOutType: 2,+ affectSize: true,+ affectOpacity: true,+ minSizeRatio: 0.35,+ },+ useGpu: true,+ },+ },+ {+ id: 'fine-hair-wisp',+ category: 'pen',+ name: 'Hair Strand & Lash',+ badge: 'Pen',+ badgeBg: 'bg-indigo-500/15',+ badgeText: 'text-indigo-300',+ badgeBorder: 'border-indigo-500/30',+ desc: 'Gossamer 3-Filament Hair Liner — Natural Flyaway Strands, Wispy Bangs, Brows & Eyelashes',+ icon: 'pen',+ tipGenerator: generateHairWispTip,+ settings: {+ size: 11,+ minSizeFactor: 0.08,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ thickness: 0.88,+ customTipAngleDynamics: 'direction',+ spacing: 0.04,+ stabilization: 11,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.88,+ densityOfPaint: 0.96,+ colorStretch: 0.32,+ opacitySensor: { usePressure: true, pressureMin: 0.22 },+ taper: {+ useIn: true,+ inLength: 18,+ inRatio: 0.2,+ useOut: true,+ outLength: 28,+ outRatio: 0.26,+ inOutType: 2,+ startingSharpness: 0.84,+ endingSharpness: 0.9,+ affectSize: true,+ minSizeRatio: 0.05,+ },+ useGpu: true,+ },+ },+];++// =============================================================================+// SKETCH SECTION PRO ADDITIONS (+4)+// =============================================================================++export const PRO_SKETCH_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'vine-charcoal-wash',+ category: 'sketch',+ name: 'Vine Charcoal Wash',+ badge: 'Sketch',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: 'Velvety Soft Willow Charcoal — Sweeping Chiaroscuro Value Washes & Smoky Portrait Grounds',+ icon: 'pencil',+ tipGenerator: generateVineCharcoalTip,+ paperTextureGenerator: generateCharcoalPaperTexture,+ settings: {+ size: 36,+ minSizeFactor: 0.45,+ flow: 0.34,+ opacity: 0.96,+ hardness: 0.26,+ antiAlias: 2,+ thickness: 0.78,+ spacing: 0.14,+ stabilization: 4,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 2.3,+ smoothing: true,+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,+ opacitySensor: { usePressure: true, pressureMin: 0.12 },+ densitySensor: { usePressure: true, pressureMin: 0.22 },+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ grain: 0.72,+ textureDensity: 0.72,+ paperTextureMode: 'compare',+ paperTextureScale: 1.05,+ paperTextureContrast: 38,+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.08,+ angleJitter: 1.0,+ flowJitter: 0.14,+ },+ useGpu: true,+ },+ },+ {+ id: 'compressed-charcoal-block',+ category: 'sketch',+ name: 'Flat Charcoal Block',+ badge: 'Sketch',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: 'Snapped Square Carbon Stick — Razor Chisel Corner for Planes & Broad Matte Tilt Shading',+ icon: 'pencil',+ tipGenerator: generateCharcoalBlockTip,+ paperTextureGenerator: generateCharcoalPaperTexture,+ settings: {+ size: 26,+ minSizeFactor: 0.42,+ flow: 0.72,+ opacity: 1.0,+ hardness: 0.72,+ antiAlias: 2,+ thickness: 0.44,+ customTipAngle: -24,+ customTipAngleDynamics: 'none',+ spacing: 0.12,+ stabilization: 5,+ sharpCorners: true,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.9,+ smoothing: true,+ opacitySensor: { usePressure: true, pressureMin: 0.2 },+ grain: 0.82,+ textureDensity: 0.82,+ paperTextureMode: 'compare',+ paperTextureScale: 1.0,+ paperTextureContrast: 46,+ paperTextureBrightness: -4,+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.05,+ flowJitter: 0.12,+ },+ useGpu: true,+ },+ },+ {+ id: 'conte-sanguine-crayon',+ category: 'sketch',+ name: 'Conté Crayon',+ badge: 'Sketch',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: 'Old Master Wax-Mineral Crayon — Creamy Life-Drawing Buildup & Crisp Gesso Tooth',+ icon: 'pencil',+ tipGenerator: generateConteCrayonTip,+ paperTextureGenerator: generatePainterlyChalkGrainTexture,+ settings: {+ size: 18,+ minSizeFactor: 0.38,+ flow: 0.64,+ opacity: 1.0,+ hardness: 0.74,+ antiAlias: 2,+ thickness: 0.76,+ customTipAngle: -16,+ customTipAngleDynamics: 'direction-random',+ customTipRotationRandomScale: 0.22,+ spacing: 0.12,+ stabilization: 5,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.65,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.86,+ densityOfPaint: 0.92,+ colorStretch: 0.28,+ grain: 0.68,+ textureDensity: 0.68,+ paperTextureMode: 'compare',+ paperTextureScale: 0.92,+ paperTextureContrast: 32,+ opacitySensor: { usePressure: true, pressureMin: 0.18 },+ useGpu: true,+ },+ },+ {+ id: 'col-erase-sketch-pencil',+ category: 'sketch',+ name: 'Animation Sketch Pencil',+ badge: 'Sketch',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: 'Smooth Waxy Col-Erase Rough Pencil — Effortless Gesture Lines, Character Roughs & Clean Tooth',+ icon: 'pencil',+ tipGenerator: generateColErasePencilTip,+ paperTextureGenerator: generateFinePaperTexture,+ settings: {+ size: 4.5,+ minSizeFactor: 0.36,+ flow: 0.54,+ opacity: 0.96,+ hardness: 0.86,+ antiAlias: 2,+ spacing: 0.09,+ stabilization: 7,+ sharpCorners: true,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.35,+ smoothing: true,+ pressureCurve: [+ [0, 0],+ [0.28, 0.22],+ [0.68, 0.74],+ [1, 1],+ ],+ opacitySensor: { usePressure: true, pressureMin: 0.16 },+ densitySensor: { usePressure: true, pressureMin: 0.28 },+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ grain: 0.44,+ textureDensity: 0.44,+ paperTextureMode: 'compare',+ paperTextureScale: 0.75,+ paperTextureContrast: 24,+ useGpu: true,+ },+ },+];++// =============================================================================+// BRUSH SECTION PRO PAINTERLY ADDITIONS (+10)+// =============================================================================++export const PRO_PAINT_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'sculptural-hard-square',+ category: 'brush',+ name: 'Hard Square Block-In',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Architectural Chisel Square — Crisp Facial Planes, Cast Shadows & Faceted Metallic Reflections',+ icon: 'paintbrush',+ tipGenerator: generateHardSquareTip,+ settings: {+ size: 36,+ minSizeFactor: 0.68,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.96,+ antiAlias: 2,+ thickness: 0.62,+ customTipAngle: -18,+ customTipAngleDynamics: 'none',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.055,+ adjustDensityByGap: false,+ stabilization: 7,+ sharpCorners: true,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.84,+ densityOfPaint: 0.94,+ colorStretch: 0.34,+ opacitySensor: { usePressure: true, pressureMin: 0.16 },+ useGpu: true,+ },+ },+ {+ id: 'opaque-gouache-flat',+ category: 'brush',+ name: 'Painterly Gouache Flat',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Layered Opaque-Watercolor Flat — Overlapping Translucent Cloth Folds with Subtle Wet-Edge Pooling',+ icon: 'paintbrush',+ tipGenerator: generatePainterlyGouacheFlatTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),+ settings: {+ size: 38,+ minSizeFactor: 0.36,+ flow: 0.84,+ opacity: 0.96,+ hardness: 0.86,+ antiAlias: 2,+ thickness: 0.68,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.055,+ adjustDensityByGap: false,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.15,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.72,+ densityOfPaint: 0.86,+ colorStretch: 0.44,+ wetEdge: 0.24,+ wetEdgeRadius: 2.0,+ wetEdgeAlphaPower: 0.18,+ wetEdgeValuePower: 0.14,+ surfaceTextureId: 'gesso-board',+ paperTextureMode: 'multiply',+ grain: 0.22,+ textureDensity: 0.22,+ paperTextureScale: 0.9,+ paperTextureContrast: 14,+ opacitySensor: { usePressure: true, pressureMin: 0.22 },+ useGpu: true,+ },+ },+ {+ id: 'tapered-painterly-oval',+ category: 'brush',+ name: 'Hard Round Pressure Painter',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Pro Digital Painting Workhorse — Crisp Tapered Oval with Smooth Pressure Opacity & Perceptual Glazing',+ icon: 'paintbrush',+ tipGenerator: generatePainterlyOvalTip,+ settings: {+ size: 28,+ minSizeFactor: 0.28,+ flow: 0.86,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 3,+ thickness: 0.78,+ customTipAngle: -25,+ customTipAngleDynamics: 'none',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.05,+ adjustDensityByGap: false,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ pressureCurve: [+ [0, 0],+ [0.26, 0.22],+ [0.68, 0.78],+ [1, 1],+ ],+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.76,+ densityOfPaint: 0.9,+ colorStretch: 0.48,+ opacitySensor: { usePressure: true, pressureMin: 0.12 },+ useGpu: true,+ },+ },+ {+ id: 'silky-hair-locks',+ category: 'brush',+ name: 'Silky Hair & Fur Locks',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Tapered Multi-Strand Sable Hair Brush — Glossy Layered Bangs, Flowing Locks & Soft Fur',+ icon: 'paintbrush',+ tipGenerator: generateHairLocksTip,+ settings: {+ size: 46,+ minSizeFactor: 0.2,+ flow: 0.9,+ opacity: 1.0,+ hardness: 0.84,+ antiAlias: 2,+ thickness: 0.88,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.05,+ adjustDensityByGap: false,+ stabilization: 9,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.15,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'running_color',+ amountOfPaint: 0.82,+ densityOfPaint: 0.92,+ colorStretch: 0.64,+ opacitySensor: { usePressure: true, pressureMin: 0.2 },+ taper: {+ useIn: true,+ inLength: 20,+ inRatio: 0.2,+ useOut: true,+ outLength: 32,+ outRatio: 0.28,+ inOutType: 2,+ startingSharpness: 0.76,+ endingSharpness: 0.86,+ affectSize: true,+ minSizeRatio: 0.12,+ },+ useGpu: true,+ },+ },+ {+ id: 'dry-hair-sheen',+ category: 'brush',+ name: 'Dry-Brush Hair Sheen',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Textured Flat Highlight Bristle + Mineral Dual Brush — Luminous Crown Hair Sheen & Silk Shimmer',+ icon: 'paintbrush',+ tipGenerator: generateDryHairSheenTip,+ dualTipGenerator: generateMineralGrainDualTip,+ settings: {+ size: 54,+ minSizeFactor: 0.36,+ flow: 0.88,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ thickness: 0.78,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.058,+ adjustDensityByGap: false,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.88,+ densityOfPaint: 0.94,+ colorStretch: 0.36,+ opacitySensor: { usePressure: true, pressureMin: 0.14 },+ dualBrush: true,+ dualBrushCompositeMode: 'multiply',+ dualLinkSize: true,+ dualScale: 1.1,+ dualSpacing: 0.14,+ dualDensity: 0.92,+ dualAngleDynamics: 'random',+ dualFlipH: 'random',+ dualFlipV: 'random',+ dualBrushConfig: {+ enabled: true,+ compositeMode: 'multiply',+ linkSizeWithMain: true,+ sizeRatio: 1.1,+ spacing: 0.14,+ density: 0.92,+ angleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ },+ useGpu: true,+ },+ },+ {+ id: 'rough-concept-bristle',+ category: 'brush',+ name: 'Expressive Concept Bristle',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: '4-Tip Fractured Hog-Bristle + Dual Tooth — Sweeping Fantasy Cloaks, Moody Skies & Bold Concept Strokes',+ icon: 'paintbrush',+ subTipGenerators: [+ () => generateConceptBristleSubTip(0),+ () => generateConceptBristleSubTip(1),+ () => generateConceptBristleSubTip(2),+ () => generateConceptBristleSubTip(3),+ ],+ dualTipGenerator: generateMineralGrainDualTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 48,+ minSizeFactor: 0.32,+ flow: 0.92,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 2,+ thickness: 0.64,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'random',+ spacing: 0.065,+ adjustDensityByGap: false,+ stabilization: 7,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'running_color',+ amountOfPaint: 0.84,+ densityOfPaint: 0.94,+ colorStretch: 0.68,+ surfaceTextureId: 'linen-canvas',+ paperTextureMode: 'compare',+ grain: 0.34,+ textureDensity: 0.34,+ paperTextureScale: 0.9,+ paperTextureContrast: 22,+ opacitySensor: { usePressure: true, pressureMin: 0.2 },+ dualBrush: true,+ dualBrushCompositeMode: 'multiply',+ dualLinkSize: true,+ dualScale: 1.12,+ dualSpacing: 0.14,+ dualDensity: 0.94,+ dualAngleDynamics: 'random',+ dualFlipH: 'random',+ dualFlipV: 'random',+ dualBrushConfig: {+ enabled: true,+ compositeMode: 'multiply',+ linkSizeWithMain: true,+ sizeRatio: 1.12,+ spacing: 0.14,+ density: 0.94,+ angleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.06,+ flowJitter: 0.08,+ colorJitterEnabled: true,+ brightnessJitter: 0.025,+ temperatureJitter: 0.025,+ },+ useGpu: true,+ },+ },+ {+ id: 'wedge-chisel-gouache',+ category: 'brush',+ name: 'Wedge & Chisel Painter',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Asymmetric Diagonal Bevel Wedge — Razor Architectural Leading Corner & Soft Feathered Gouache Heel',+ icon: 'paintbrush',+ tipGenerator: generateWedgeChiselTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('fine-cotton'),+ settings: {+ size: 34,+ minSizeFactor: 0.32,+ flow: 0.9,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 2,+ thickness: 0.62,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.05,+ adjustDensityByGap: false,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.18,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.82,+ densityOfPaint: 0.92,+ colorStretch: 0.46,+ surfaceTextureId: 'fine-cotton',+ paperTextureMode: 'multiply',+ grain: 0.24,+ textureDensity: 0.24,+ paperTextureScale: 0.88,+ paperTextureContrast: 14,+ opacitySensor: { usePressure: true, pressureMin: 0.18 },+ useGpu: true,+ },+ },+ {+ id: 'translucent-watercolor-wash',+ category: 'brush',+ name: 'Soft Watercolor Wash',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Organic Translucent Mop Glaze — Wet-Edge Pigment Pooling & Delicate Cold-Press Bloom',+ icon: 'paintbrush',+ tipGenerator: generateWatercolorWashTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),+ settings: {+ size: 52,+ minSizeFactor: 0.34,+ flow: 0.46,+ opacity: 0.82,+ hardness: 0.56,+ antiAlias: 3,+ thickness: 0.9,+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ spacing: 0.075,+ adjustDensityByGap: true,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.25,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.56,+ densityOfPaint: 0.68,+ colorStretch: 0.62,+ wetEdge: 0.42,+ wetEdgeRadius: 2.6,+ wetEdgeAlphaPower: 0.22,+ wetEdgeValuePower: 0.16,+ surfaceTextureId: 'cold-press-watercolor',+ paperTextureMode: 'multiply',+ grain: 0.36,+ textureDensity: 0.36,+ paperTextureScale: 0.92,+ paperTextureContrast: 18,+ opacitySensor: { usePressure: true, pressureMin: 0.12 },+ useGpu: true,+ },+ },+ {+ id: 'pastel-blush-airbrush',+ category: 'brush',+ name: 'Silky Blush & Skin Airbrush',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Perceptual Subsurface Skin Airbrush — Luminous Cheek Blush, Nose Warmth & Silky Atmospheric Halos',+ icon: 'paintbrush',+ settings: {+ size: 54,+ minSizeFactor: 0.5,+ flow: 0.18,+ opacity: 0.96,+ hardness: 0.0,+ antiAlias: 3,+ spacing: 0.055,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ adjustDensityByGap: true,+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.34,+ densityOfPaint: 0.52,+ colorStretch: 0.45,+ opacitySensor: { usePressure: true, pressureMin: 0.04 },+ useGpu: true,+ },+ },+ {+ id: 'metallic-specular-glint',+ category: 'brush',+ name: 'Metallic & Gold Impasto',+ badge: 'Brush',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Crisp Hammered-Facet Lozenge — Gold Coins, Chrome Chokers, Wet Lip Highlights & Eye Catchlights',+ icon: 'paintbrush',+ tipGenerator: generateMetallicGlintTip,+ settings: {+ size: 16,+ minSizeFactor: 0.18,+ flow: 0.98,+ opacity: 1.0,+ hardness: 0.94,+ antiAlias: 2,+ thickness: 0.56,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.04,+ adjustDensityByGap: false,+ stabilization: 10,+ sharpCorners: true,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.94,+ densityOfPaint: 0.98,+ colorStretch: 0.24,+ opacitySensor: { usePressure: true, pressureMin: 0.28 },+ useGpu: true,+ },+ },+];++// =============================================================================+// BLEND SECTION PRO ADDITIONS (+4 — STRICT PURE-SMEAR INVARIANTS)+// =============================================================================++export const PRO_BLEND_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'blend-charcoal-stump',+ category: 'blend',+ name: 'Charcoal Blending Stump',+ badge: 'Blend',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: 'Rolled-Paper Tortillon Stump — Rubs Charcoal & Graphite into Velvety Shadows While Keeping Paper Tooth',+ icon: 'droplets',+ tipGenerator: generateBlendTortillonTip,+ paperTextureGenerator: generateCharcoalPaperTexture,+ settings: {+ size: 38,+ minSizeFactor: 0.34,+ flow: 0.84,+ opacity: 1.0,+ hardness: 0.42,+ antiAlias: 2,+ thickness: 0.74,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.065,+ adjustDensityByGap: false,+ stabilization: 7,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.45,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'smear',+ amountOfPaint: 0.0,+ densityOfPaint: 0.84,+ colorStretch: 0.74,+ useBlur: true,+ blurStrength: 0.26,+ grain: 0.48,+ textureDensity: 0.48,+ paperTextureMode: 'compare',+ paperTextureScale: 0.95,+ paperTextureContrast: 24,+ opacitySensor: { usePressure: true, pressureMin: 0.16 },+ useGpu: true,+ },+ },+ {+ id: 'blend-gouache-softener',+ category: 'blend',+ name: 'Painterly Gouache Melter',+ badge: 'Blend',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: 'Feathered Flat Gouache Blender — Softens Hard Folds & Hair-to-Skin Transitions Without Plastic Blur',+ icon: 'droplets',+ tipGenerator: generateBlendGouachePadTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),+ settings: {+ size: 42,+ minSizeFactor: 0.34,+ flow: 0.84,+ opacity: 1.0,+ hardness: 0.48,+ antiAlias: 3,+ thickness: 0.64,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.06,+ adjustDensityByGap: false,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.15,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'smear',+ amountOfPaint: 0.0,+ densityOfPaint: 0.86,+ colorStretch: 0.8,+ useBlur: true,+ blurStrength: 0.2,+ surfaceTextureId: 'gesso-board',+ paperTextureMode: 'multiply',+ grain: 0.16,+ textureDensity: 0.16,+ paperTextureScale: 0.9,+ paperTextureContrast: 10,+ opacitySensor: { usePressure: true, pressureMin: 0.16 },+ useGpu: true,+ },+ },+ {+ id: 'blend-smoke-wisps',+ category: 'blend',+ name: 'Atmospheric Mist & Smoke Smudge',+ badge: 'Blend',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: 'Turbulent Cloud-Wisp Smudger — Pulls Paint into Curling Dark Smoke, Magic Vapor & Drifting Fog',+ icon: 'droplets',+ tipGenerator: generateBlendSmokeWispTip,+ settings: {+ size: 62,+ minSizeFactor: 0.38,+ flow: 0.82,+ opacity: 1.0,+ hardness: 0.3,+ antiAlias: 3,+ thickness: 0.86,+ customTipAngleDynamics: 'direction-random',+ customTipRotationRandomScale: 0.6,+ flipH: 'random',+ flipV: 'random',+ spacing: 0.075,+ adjustDensityByGap: false,+ stabilization: 6,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'smear',+ amountOfPaint: 0.0,+ densityOfPaint: 0.82,+ colorStretch: 0.9,+ useBlur: true,+ blurStrength: 0.3,+ grain: 0,+ textureDensity: 0,+ opacitySensor: { usePressure: true, pressureMin: 0.14 },+ useGpu: true,+ },+ },+ {+ id: 'blend-palette-knife-smear',+ category: 'blend',+ name: 'Palette Knife Smudge',+ badge: 'Blend',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: 'Sharp-Edged Knife Scraper Blender — Pulls Crisp Architectural Paint Planes, Water & Cloth Streaks',+ icon: 'droplets',+ tipGenerator: generateBlendKnifeSmearTip,+ settings: {+ size: 40,+ minSizeFactor: 0.32,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.84,+ antiAlias: 2,+ thickness: 0.36,+ customTipAngleDynamics: 'direction',+ flipH: 'none',+ flipV: 'none',+ spacing: 0.04,+ adjustDensityByGap: false,+ stabilization: 9,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'smear',+ amountOfPaint: 0.0,+ densityOfPaint: 0.96,+ colorStretch: 0.94,+ useBlur: false,+ grain: 0,+ textureDensity: 0,+ opacitySensor: { usePressure: true, pressureMin: 0.22 },+ useGpu: true,+ },+ },+];++// =============================================================================+// NATURAL PAINT SECTION PRO ADDITIONS (+4 — PHYSICAL BRISTLE-RIBBON & IMPASTO)+// =============================================================================++export const PRO_NATURAL_PAINT_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'wide-hog-flat-oil',+ category: 'natural-paint',+ name: 'Wide Hog-Bristle Flat',+ badge: 'Oil',+ badgeBg: 'bg-rose-500/15',+ badgeText: 'text-rose-300',+ badgeBorder: 'border-rose-500/30',+ desc: 'Broad Chiseled Alla-Prima Hog Flat — Bold Architectural 3D Oil Planes with Crisp Paint Ridges',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('flat'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 56,+ minSizeFactor: 0.36,+ flow: 0.95,+ opacity: 1.0,+ hardness: 0.92,+ antiAlias: 2,+ spacing: 0.048,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'flat',+ count: 38,+ clumping: 0.44,+ stiffness: 0.72,+ length: 0.95,+ splay: 0.3,+ irregularity: 0.36,+ edgeRidge: 0.42,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'impasto_mix',+ amountOfPaint: 0.84,+ densityOfPaint: 0.96,+ colorStretch: 0.72,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.92,+ paintLoad: 0.84,+ depletionRate: 0.24,+ wetness: 0.62,+ viscosity: 0.64,+ autoClean: true,+ chargePerPressure: 0.54,+ dryBrush: 0.38,+ },+ impasto: {+ enabled: true,+ depth: 0.74,+ bristleRelief: 0.8,+ gloss: 0.44,+ reliefContrast: 0.66,+ lightAzimuth: 225,+ lightElevation: 34,+ },+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'canvas-locked',+ grain: 0.42,+ textureDensity: 0.42,+ paperTextureMode: 'compare',+ paperTextureScale: 0.86,+ paperTextureContrast: 24,+ useGpu: true,+ },+ },+ {+ id: 'splayed-fan-foliage',+ category: 'natural-paint',+ name: 'Splayed Bristle Fan',+ badge: 'Fan',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Wide Splayed Physical Fan Brush — Organic Foliage, Pine Needles, Grass & Expressive Hair Sweeps',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('fan'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),+ settings: {+ size: 64,+ minSizeFactor: 0.4,+ flow: 0.92,+ opacity: 1.0,+ hardness: 0.9,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.35,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'fan',+ count: 36,+ clumping: 0.64,+ stiffness: 0.78,+ length: 1.25,+ splay: 0.56,+ irregularity: 0.58,+ edgeRidge: 0.16,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.82,+ densityOfPaint: 0.94,+ colorStretch: 0.64,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.88,+ paintLoad: 0.82,+ depletionRate: 0.3,+ wetness: 0.46,+ viscosity: 0.58,+ autoClean: true,+ chargePerPressure: 0.48,+ dryBrush: 0.48,+ },+ impasto: {+ enabled: true,+ depth: 0.48,+ bristleRelief: 0.78,+ gloss: 0.28,+ reliefContrast: 0.56,+ lightAzimuth: 225,+ lightElevation: 36,+ },+ surfaceTextureId: 'coarse-burlap',+ grainMappingMode: 'canvas-locked',+ grain: 0.46,+ textureDensity: 0.46,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 26,+ useGpu: true,+ },+ },+ {+ id: 'sumi-ink-wash-natural',+ category: 'natural-paint',+ name: 'Sumi Ink Wash',+ badge: 'Ink',+ badgeBg: 'bg-cyan-500/15',+ badgeText: 'text-cyan-300',+ badgeBorder: 'border-cyan-500/30',+ desc: 'Fluid East Asian Sumi Bristle — Rich Wet-Edge Paper Bloom with Dry Flying-White Exhaustion',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('round'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),+ settings: {+ size: 40,+ minSizeFactor: 0.18,+ flow: 0.82,+ opacity: 0.9,+ hardness: 0.76,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 9,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.4,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'round',+ count: 26,+ clumping: 0.32,+ stiffness: 0.42,+ length: 1.4,+ splay: 0.48,+ irregularity: 0.36,+ edgeRidge: 0.08,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.78,+ densityOfPaint: 0.86,+ colorStretch: 0.68,+ wetEdge: 0.48,+ wetEdgeRadius: 2.5,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.9,+ paintLoad: 0.78,+ depletionRate: 0.34,+ wetness: 0.72,+ viscosity: 0.18,+ autoClean: true,+ chargePerPressure: 0.62,+ dryBrush: 0.42,+ granulation: 0.58,+ },+ impasto: {+ enabled: false,+ depth: 0.0,+ bristleRelief: 0.0,+ gloss: 0.0,+ reliefContrast: 0.0,+ lightAzimuth: 225,+ lightElevation: 42,+ },+ surfaceTextureId: 'cold-press-watercolor',+ grainMappingMode: 'canvas-locked',+ grain: 0.5,+ textureDensity: 0.5,+ paperTextureMode: 'multiply',+ paperTextureScale: 0.92,+ paperTextureContrast: 24,+ useGpu: true,+ },+ },+ {+ id: 'matte-casein-tempera',+ category: 'natural-paint',+ name: 'Matte Casein & Tempera',+ badge: 'Matte',+ badgeBg: 'bg-violet-500/15',+ badgeText: 'text-violet-300',+ badgeBorder: 'border-violet-500/30',+ desc: 'Velvety Zero-Gloss Casein Illustration Paint — Opaque Creamy Coverage & Dry Gesso Scumble',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('filbert'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),+ settings: {+ size: 42,+ minSizeFactor: 0.3,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 9,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.1,+ smoothing: true,+ renderMode: 'bristle-hybrid',+ bristle: {+ profile: 'filbert',+ count: 30,+ clumping: 0.28,+ stiffness: 0.62,+ length: 0.95,+ splay: 0.28,+ irregularity: 0.32,+ edgeRidge: 0.14,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.86,+ densityOfPaint: 0.96,+ colorStretch: 0.52,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.92,+ paintLoad: 0.86,+ depletionRate: 0.22,+ wetness: 0.48,+ viscosity: 0.52,+ autoClean: true,+ chargePerPressure: 0.46,+ dryBrush: 0.36,+ },+ impasto: {+ enabled: true,+ depth: 0.24,+ bristleRelief: 0.36,+ gloss: 0.02,+ reliefContrast: 0.34,+ lightAzimuth: 225,+ lightElevation: 42,+ },+ surfaceTextureId: 'gesso-board',+ grainMappingMode: 'canvas-locked',+ grain: 0.36,+ textureDensity: 0.36,+ paperTextureMode: 'compare',+ paperTextureScale: 0.9,+ paperTextureContrast: 20,+ useGpu: true,+ },+ },+];++// =============================================================================+// TEXTURE & FX SECTION (NEW BUILT-IN SECTION — 10 WORLD-CLASS PRO BRUSHES)+// =============================================================================++export const PRO_TEXTURE_FX_BRUSHES: BuiltinBrushDefinition[] = [+ {+ id: 'painterly-foliage-leaves',+ category: 'texture-fx',+ name: 'Painterly Canopy Leaves',+ badge: 'Foliage',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: '4-Tip Hand-Painted Botanical Leaves — Scattered Forest Canopies with Subtle Sunlight Color Jitter',+ icon: 'sparkles',+ subTipGenerators: [+ () => generatePainterlyLeafSubTip(0),+ () => generatePainterlyLeafSubTip(1),+ () => generatePainterlyLeafSubTip(2),+ () => generatePainterlyLeafSubTip(3),+ ],+ settings: {+ size: 64,+ minSizeFactor: 0.35,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 2,+ spacing: 0.34,+ stabilization: 4,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'direction-random',+ customTipRotationRandomScale: 0.55,+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.45 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.38,+ angleJitter: 0.35,+ roundnessJitter: 0.18,+ scatter: 0.72,+ scatterBothAxes: true,+ count: 2,+ flowJitter: 0.18,+ colorJitterEnabled: true,+ hueJitter: 0.05,+ saturationJitter: 0.1,+ brightnessJitter: 0.14,+ temperatureJitter: 0.08,+ foregroundBackgroundJitter: 0.12,+ },+ useGpu: true,+ },+ },+ {+ id: 'bokeh-foreground-leaves',+ category: 'texture-fx',+ name: 'Bokeh Soft Leaves',+ badge: 'Foliage',+ badgeBg: 'bg-emerald-500/15',+ badgeText: 'text-emerald-300',+ badgeBorder: 'border-emerald-500/30',+ desc: 'Out-of-Focus Depth-of-Field Leaves — Cinematic Foreground Framing & Drifting Wind-Blown Foliage',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateBokehLeafSubTip(0),+ () => generateBokehLeafSubTip(1),+ () => generateBokehLeafSubTip(2),+ ],+ settings: {+ size: 92,+ minSizeFactor: 0.42,+ flow: 0.78,+ opacity: 0.96,+ hardness: 0.25,+ antiAlias: 3,+ spacing: 0.52,+ stabilization: 4,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.35 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.45,+ angleJitter: 0.6,+ roundnessJitter: 0.14,+ scatter: 0.95,+ scatterBothAxes: true,+ count: 1,+ flowJitter: 0.24,+ colorJitterEnabled: true,+ hueJitter: 0.03,+ brightnessJitter: 0.1,+ temperatureJitter: 0.05,+ },+ useGpu: true,+ },+ },+ {+ id: 'skin-freckles-pores',+ category: 'texture-fx',+ name: 'Skin Freckles & Pores',+ badge: 'Portrait',+ badgeBg: 'bg-rose-500/15',+ badgeText: 'text-rose-300',+ badgeBorder: 'border-rose-500/30',+ desc: '4-Tip Organic Micro-Constellations — Realistic Portrait Freckles, Nose-Bridge Speckle & Skin Pores',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateSkinFrecklesSubTip(0),+ () => generateSkinFrecklesSubTip(1),+ () => generateSkinFrecklesSubTip(2),+ () => generateSkinFrecklesSubTip(3),+ ],+ settings: {+ size: 64,+ minSizeFactor: 0.55,+ flow: 0.72,+ opacity: 0.9,+ hardness: 0.68,+ antiAlias: 2,+ spacing: 0.38,+ stabilization: 3,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.22 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.34,+ angleJitter: 1.0,+ roundnessJitter: 0.16,+ scatter: 0.52,+ scatterBothAxes: true,+ count: 1,+ flowJitter: 0.28,+ colorJitterEnabled: true,+ brightnessJitter: 0.1,+ temperatureJitter: 0.04,+ },+ useGpu: true,+ },+ },+ {+ id: 'ethereal-smoke-mist',+ category: 'texture-fx',+ name: 'Dark Smoke & Vapor',+ badge: 'FX',+ badgeBg: 'bg-violet-500/15',+ badgeText: 'text-violet-300',+ badgeBorder: 'border-violet-500/30',+ desc: '4-Tip Domain-Warped Turbulent Smoke + Dual Erosion Mask — Necrotic Tendrils, Fog & Magic Mist',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateSmokeTendrilSubTip(0),+ () => generateSmokeTendrilSubTip(1),+ () => generateSmokeTendrilSubTip(2),+ () => generateSmokeTendrilSubTip(3),+ ],+ dualTipGenerator: generateSmokeDualMaskTip,+ settings: {+ size: 110,+ minSizeFactor: 0.38,+ flow: 0.24,+ opacity: 0.92,+ hardness: 0.2,+ antiAlias: 3,+ spacing: 0.16,+ stabilization: 5,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'direction-random',+ customTipRotationRandomScale: 0.72,+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.08 },+ dualBrush: true,+ dualBrushCompositeMode: 'multiply',+ dualLinkSize: true,+ dualScale: 1.05,+ dualSpacing: 0.18,+ dualDensity: 0.9,+ dualAngleDynamics: 'random',+ dualFlipH: 'random',+ dualFlipV: 'random',+ dualBrushConfig: {+ enabled: true,+ compositeMode: 'multiply',+ linkSizeWithMain: true,+ sizeRatio: 1.05,+ spacing: 0.18,+ density: 0.9,+ angleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.28,+ angleJitter: 0.55,+ roundnessJitter: 0.2,+ scatter: 0.24,+ scatterBothAxes: true,+ count: 1,+ flowJitter: 0.22,+ },+ useGpu: true,+ },+ },+ {+ id: 'craggy-rock-bone',+ category: 'texture-fx',+ name: 'Craggy Rock & Weathered Bone',+ badge: 'Texture',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: '4-Tip Fractured Mineral Shards + Dual Tooth — Jagged Mountains, Skull Pauldrons & Ancient Metal',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateCraggyRockSubTip(0),+ () => generateCraggyRockSubTip(1),+ () => generateCraggyRockSubTip(2),+ () => generateCraggyRockSubTip(3),+ ],+ dualTipGenerator: generateMineralGrainDualTip,+ paperTextureGenerator: generatePainterlyChalkGrainTexture,+ settings: {+ size: 76,+ minSizeFactor: 0.34,+ flow: 0.88,+ opacity: 1.0,+ hardness: 0.84,+ antiAlias: 2,+ spacing: 0.22,+ stabilization: 5,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ customTipRotationRandomScale: 0.85,+ flipH: 'random',+ flipV: 'random',+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.84,+ densityOfPaint: 0.92,+ colorStretch: 0.34,+ surfaceTextureId: 'stipple-grain',+ paperTextureMode: 'compare',+ grain: 0.48,+ textureDensity: 0.48,+ paperTextureScale: 0.95,+ paperTextureContrast: 30,+ opacitySensor: { usePressure: true, pressureMin: 0.2 },+ dualBrush: true,+ dualBrushCompositeMode: 'multiply',+ dualLinkSize: true,+ dualScale: 1.15,+ dualSpacing: 0.16,+ dualDensity: 0.92,+ dualAngleDynamics: 'random',+ dualFlipH: 'random',+ dualFlipV: 'random',+ dualBrushConfig: {+ enabled: true,+ compositeMode: 'multiply',+ linkSizeWithMain: true,+ sizeRatio: 1.15,+ spacing: 0.16,+ density: 0.92,+ angleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.26,+ angleJitter: 0.85,+ roundnessJitter: 0.18,+ scatter: 0.14,+ scatterBothAxes: true,+ flowJitter: 0.16,+ colorJitterEnabled: true,+ brightnessJitter: 0.06,+ temperatureJitter: 0.04,+ },+ useGpu: true,+ },+ },+ {+ id: 'ember-ash-spatter',+ category: 'texture-fx',+ name: 'Ash, Embers & Ink Spatter',+ badge: 'FX',+ badgeBg: 'bg-orange-500/15',+ badgeText: 'text-orange-300',+ badgeBorder: 'border-orange-500/30',+ desc: '4-Tip Organic Splatter Constellations — Swirling Fire Embers, Volcanic Ash, Snow & Ink Spray',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateEmberSpatterSubTip(0),+ () => generateEmberSpatterSubTip(1),+ () => generateEmberSpatterSubTip(2),+ () => generateEmberSpatterSubTip(3),+ ],+ settings: {+ size: 76,+ minSizeFactor: 0.4,+ flow: 0.86,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ spacing: 0.42,+ stabilization: 3,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.3 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.48,+ angleJitter: 1.0,+ roundnessJitter: 0.14,+ scatter: 0.82,+ scatterBothAxes: true,+ count: 2,+ flowJitter: 0.28,+ colorJitterEnabled: true,+ hueJitter: 0.03,+ brightnessJitter: 0.14,+ temperatureJitter: 0.06,+ },+ useGpu: true,+ },+ },+ {+ id: 'painterly-clouds',+ category: 'texture-fx',+ name: 'Painterly Cumulus Clouds',+ badge: 'Sky',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: '4-Tip Sculpted Sky Puffs — Crisp Sunlit Upper Billows & Soft Atmospheric Bases for Epic Skies',+ icon: 'sparkles',+ subTipGenerators: [+ () => generatePainterlyCloudSubTip(0),+ () => generatePainterlyCloudSubTip(1),+ () => generatePainterlyCloudSubTip(2),+ () => generatePainterlyCloudSubTip(3),+ ],+ settings: {+ size: 98,+ minSizeFactor: 0.42,+ flow: 0.56,+ opacity: 0.96,+ hardness: 0.44,+ antiAlias: 3,+ spacing: 0.19,+ stabilization: 6,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ customTipRotationRandomScale: 0.22,+ flipH: 'random',+ flipV: 'none',+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.66,+ densityOfPaint: 0.8,+ colorStretch: 0.54,+ opacitySensor: { usePressure: true, pressureMin: 0.16 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.24,+ angleJitter: 0.12,+ roundnessJitter: 0.12,+ scatter: 0.24,+ scatterBothAxes: true,+ count: 1,+ flowJitter: 0.16,+ },+ useGpu: true,+ },+ },+ {+ id: 'woven-brocade-fabric',+ category: 'texture-fx',+ name: 'Woven Cloth & Brocade Grain',+ badge: 'Texture',+ badgeBg: 'bg-violet-500/15',+ badgeText: 'text-violet-300',+ badgeBorder: 'border-violet-500/30',+ desc: 'Cross-Woven Textile & Twill Pad — Embroidered Sleeves, Medieval Cloaks & Tapestry Weave Highlights',+ icon: 'sparkles',+ tipGenerator: generateWovenFabricTip,+ paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),+ settings: {+ size: 48,+ minSizeFactor: 0.38,+ flow: 0.78,+ opacity: 1.0,+ hardness: 0.68,+ antiAlias: 2,+ spacing: 0.1,+ stabilization: 6,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.15,+ smoothing: true,+ customTipAngleDynamics: 'direction-random',+ customTipRotationRandomScale: 0.15,+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.74,+ densityOfPaint: 0.86,+ colorStretch: 0.4,+ surfaceTextureId: 'coarse-burlap',+ paperTextureMode: 'compare',+ grain: 0.64,+ textureDensity: 0.64,+ paperTextureScale: 0.62,+ paperTextureContrast: 32,+ opacitySensor: { usePressure: true, pressureMin: 0.18 },+ useGpu: true,+ },+ },+ {+ id: 'luminous-rim-glow',+ category: 'texture-fx',+ name: 'Luminous Magic & Rim Glow',+ badge: 'Glow',+ badgeBg: 'bg-fuchsia-500/15',+ badgeText: 'text-fuchsia-300',+ badgeBorder: 'border-fuchsia-500/30',+ desc: 'Optical Add-Glow Point-Spread Bloom — Glowing Magic Lanterns, Backlit Rim Light & Sunbeams',+ icon: 'sparkles',+ tipGenerator: generateLuminousBloomTip,+ settings: {+ size: 72,+ minSizeFactor: 0.45,+ flow: 0.22,+ opacity: 0.85,+ hardness: 0.0,+ antiAlias: 3,+ spacing: 0.06,+ adjustDensityByGap: true,+ brushCombineMode: 'add-glow',+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,+ opacitySensor: { usePressure: true, pressureMin: 0.05 },+ useGpu: true,+ },+ },+ {+ id: 'stipple-halftone-grain',+ category: 'texture-fx',+ name: 'Fine Film & Stipple Dust',+ badge: 'Texture',+ badgeBg: 'bg-violet-500/15',+ badgeText: 'text-violet-300',+ badgeBorder: 'border-violet-500/30',+ desc: '3-Tip Stochastic Micro-Stipple Dust — Tactile Portrait Film Grain, Dust Motes & Subtle Finish',+ icon: 'sparkles',+ subTipGenerators: [+ () => generateFineStippleSubTip(0),+ () => generateFineStippleSubTip(1),+ () => generateFineStippleSubTip(2),+ ],+ settings: {+ size: 72,+ minSizeFactor: 0.45,+ flow: 0.68,+ opacity: 0.94,+ hardness: 0.55,+ antiAlias: 2,+ spacing: 0.22,+ stabilization: 4,+ sharpCorners: false,+ usePressure: true,+ useTilt: false,+ smoothing: true,+ subTipOrder: 'random-no-repeat',+ customTipAngleDynamics: 'random',+ flipH: 'random',+ flipV: 'random',+ opacitySensor: { usePressure: true, pressureMin: 0.12 },+ dynamics: {+ ...DEFAULT_BRUSH_DYNAMICS,+ sizeJitter: 0.24,+ angleJitter: 1.0,+ scatter: 0.36,+ scatterBothAxes: true,+ count: 1,+ flowJitter: 0.24,+ },+ useGpu: true,+ },+ },+];diff --git a/src/utils/proProceduralBrushTips.ts b/src/utils/proProceduralBrushTips.tsnew file mode 100644index 0000000..b79fe59--- /dev/null+++ b/src/utils/proProceduralBrushTips.ts@@ -0,0 +1,1542 @@+/**+ * proProceduralBrushTips.ts+ * High-resolution (256x256 & 64x512 ribbon) procedural brush tips for InkStudio's+ * expanded professional artist brush collection:+ * - Portrait & anime-realism painting (Hard Square, Painterly Gouache Flat, Hair Locks,+ * Dry Hair Sheen, Skin Freckles & Pores, Soft Tapered Liner, Hair Strands)+ * - Fantasy & concept illustration (Silk Embroidery Multi-Line Ribbon, Canopy Leaves,+ * Bokeh Soft Leaves, Expressive Concept Bristle, Wedge & Chisel, Metallic Impasto)+ * - Dark fantasy & atmospheric FX (Turbulent Dark Smoke & Vapor, Craggy Rock & Bone,+ * Ash/Ember Spatter, Painterly Cumulus Clouds, Woven Brocade, Optical Luminous Bloom,+ * Fine Film Stipple Dust)+ * - Traditional sketching & blending (Vine Charcoal, Flat Charcoal Block, Conté Crayon,+ * Animation Sketch Pencil, Sumi Brush Pen, Tortillon Stump, Gouache Melter, Smoke Smudge,+ * Palette Knife Smudge)+ */++import {+ HI_TIP_SIZE,+ buildCachedPng,+ buildCachedRectPng,+ clamp01,+ createPrng,+ makeCellularDomeField,+ makePeriodicGrid,+ sampleFieldBilinear,+ samplePeriodic,+ smoothstep,+ writeAlphaPixel,+} from './proceduralBrushTips';++// =============================================================================+// 1. PEN SECTION PRO TIPS+// =============================================================================++/**+ * Soft Tapered Liner (256x256):+ * Silky painted-ink sable nib — dense opaque interior transitioning smoothly+ * with ultra-subtle organic micro-tooth on the outer rim for wispy hair strands,+ * glasses frames, and painterly anime-realism lineart.+ */+export function generateSoftTaperedLinerTip(): string {+ return buildCachedPng('pro:soft-tapered-liner-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x21a01);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.42;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const nx = dx / rx;+ // Subtle teardrop sable point toward +X+ const taper = 1.0 - Math.max(0, nx) * 0.14;+ const ny = dy / (ry * taper);+ const r = Math.hypot(nx, ny);+ if (r >= 1.0) continue;++ let alpha = 1.0 - smoothstep(0.74, 0.995, r);+ if (r > 0.68) {+ const rim = smoothstep(0.68, 0.98, r);+ const tooth = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);+ alpha *= 1.0 - rim * 0.14 * (1.0 - tooth);+ }+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Sumi Brush Pen / Fude Nib (256x256):+ * Pointed wolf-hair sumi-e ink brush oriented along +X: razor-pointed leading tip,+ * full juicy belly, and subtly split dry-ink heel bristles for expressive calligraphy & comic ink.+ */+export function generateSumiBrushTip(): string {+ return buildCachedPng('pro:sumi-fude-brush-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x21b02);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.39;++ // 18 bristle striations concentrating dry splits near the heel (nx < -0.15)+ const numStrands = 18;+ const sY = new Float32Array(numStrands);+ const sW = new Float32Array(numStrands);+ const sReach = new Float32Array(numStrands);+ for (let i = 0; i < numStrands; i++) {+ const u = ((i + 0.5) / numStrands) * 2 - 1;+ sY[i] = u * 0.92 + (rand() - 0.5) * 0.06;+ sW[i] = 0.065 + rand() * 0.06;+ sReach[i] = 0.78 + rand() * 0.24;+ }++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const nyBase = dy / ry;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const nx = dx / rx;+ if (nx < -1.04 || nx > 1.02) continue;++ // Teardrop sumi brush profile: pointed tip at +X, fuller rounded belly at x = -0.25+ const profileHalfH =+ nx >= 0+ ? Math.pow(Math.max(0, 1.0 - nx), 0.72) * (0.96 + 0.14 * (1.0 - nx))+ : Math.sqrt(Math.max(0, 1.0 - Math.pow((nx + 0.15) / 0.92, 2))) * 1.04;+ if (profileHalfH <= 0.01) continue;++ const ny = nyBase / profileHalfH;+ const absNy = Math.abs(ny);+ if (absNy >= 1.08) continue;++ const warp = (samplePeriodic(nMed, 32, x * 0.12, y * 0.22) - 0.5) * 0.09;+ const env = 1.0 - smoothstep(0.84 + warp, 1.01 + warp, absNy);++ let alpha = env;+ // Split dry bristles softly at the rear heel (nx < -0.2)+ if (nx < -0.18) {+ const heelFactor = smoothstep(-0.18, -0.88, nx);+ let strand = 0;+ let reach = 0.85;+ for (let i = 0; i < numStrands; i++) {+ const d = Math.abs(nyBase - sY[i]) / sW[i];+ if (d < 1.0) {+ const v = 1.0 - d * d;+ if (v > strand) {+ strand = v;+ reach = sReach[i];+ }+ }+ }+ const heelCut = 1.0 - smoothstep(reach * 0.75, reach * 1.02, -nx);+ const fine = samplePeriodic(nFine, 64, x * 0.22, y * 0.54);+ const splitMask = smoothstep(0.14 + heelFactor * 0.26, 0.56, strand * 0.75 + fine * 0.25);+ alpha = env * (1.0 - heelFactor * 0.85 + heelFactor * 0.85 * splitMask * heelCut);+ }++ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Silk Thread Multi-Line Ribbon Tip (64x512 seamless vertical strip x 3 variants):+ * Inspired by flowing curved parallel gold/silk veil embroidery lines.+ * Maps Y strictly along the RibbonBrushEngine path and X across width, with exact+ * periodic endpoint matching at v=0 and v=1 for seamless continuous embroidery ribbons.+ */+export function generateSilkThreadRibbonTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 3) + 3) % 3;+ return buildCachedRectPng(`pro:silk-thread-ribbon-v${vIdx}`, 64, 512, (data, width, height) => {+ const rand = createPrng(0x21c03 + vIdx * 0x51a7);+ const nMicro = makePeriodicGrid(64, rand);++ // 5 graceful parallel silk filaments across width (1 prominent hero thread + 4 delicate companion threads)+ const threads = [+ { cx: 0.12, halfW: 0.030, amp: 0.018, freq: 1, phase: 0.4 + vIdx * 1.1, strength: 0.80 },+ { cx: 0.29, halfW: 0.042, amp: 0.022, freq: 2, phase: 1.7 + vIdx * 0.9, strength: 0.96 },+ { cx: 0.49, halfW: 0.052, amp: 0.016, freq: 1, phase: 2.9 + vIdx * 1.4, strength: 1.0 },+ { cx: 0.70, halfW: 0.036, amp: 0.020, freq: 2, phase: 0.9 + vIdx * 1.8, strength: 0.90 },+ { cx: 0.88, halfW: 0.028, amp: 0.016, freq: 1, phase: 4.1 + vIdx * 0.7, strength: 0.76 },+ ];++ for (let y = 0; y < height; y++) {+ const v = y / height;+ const tau = v * Math.PI * 2;+ const seamEnv = Math.sin(v * Math.PI); // 0 at v=0 & v=1 -> exact alignment across tile boundaries+ const row = y * width * 4;++ // Subtle periodic silk-sheen shimmer along thread length+ const shimmer = 0.84 + 0.16 * Math.sin(tau * 2 + vIdx * 1.3);++ for (let x = 0; x < width; x++) {+ const u = (x + 0.5) / width;+ let accum = 0;+ for (let t = 0; t < threads.length; t++) {+ const th = threads[t];+ const center = th.cx + Math.sin(tau * th.freq + th.phase) * th.amp * seamEnv;+ const dist = Math.abs(u - center);+ const localW = th.halfW * (0.86 + 0.24 * Math.sin(tau * (th.freq + 1) + th.phase * 1.7) * seamEnv);+ if (dist < localW * 1.45) {+ const a = (1.0 - smoothstep(localW * 0.42, localW * 1.35, dist)) * th.strength;+ if (a > accum) accum = a;+ }+ }+ if (accum > 0.006) {+ const tooth = 0.88 + 0.12 * samplePeriodic(nMicro, 64, x * 0.5, v * 64);+ writeAlphaPixel(data, row + x * 4, clamp01(accum * shimmer * tooth));+ }+ }+ }+ });+}++/**+ * Hair Strand & Lash Tip (256x256):+ * Expressive 3-strand gossamer hair cluster oriented along +X: 1 crisp primary filament+ * flanked by 2 staggered delicate flyaway companions for instant natural bangs, eyelashes & wisps.+ */+export function generateHairWispTip(): string {+ return buildCachedPng('pro:hair-wisp-256', HI_TIP_SIZE, (data, size) => {+ const half = size * 0.5;+ const strands = [+ { cx: half + 4, cy: half - 4, rx: size * 0.45, ry: size * 0.068, strength: 1.0 },+ { cx: half - 14, cy: half - 62, rx: size * 0.34, ry: size * 0.036, strength: 0.72 },+ { cx: half + 10, cy: half + 68, rx: size * 0.32, ry: size * 0.032, strength: 0.66 },+ ];++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < strands.length; i++) {+ const s = strands[i];+ const dy = Math.abs(y - s.cy);+ if (dy > s.ry * 1.2) continue;+ const dx = Math.abs(x - s.cx);+ if (dx > s.rx * 1.05) continue;+ const nx = dx / s.rx;+ const ny = dy / (s.ry * Math.max(0.2, 1.0 - nx * 0.65));+ const d = Math.hypot(nx * 0.85, ny);+ if (d < 1.0) {+ const v = (1.0 - smoothstep(0.32, 1.0, d)) * s.strength;+ if (v > accum) accum = v;+ }+ }+ if (accum > 0.004) writeAlphaPixel(data, row + x * 4, accum);+ }+ }+ });+}++// =============================================================================+// 2. SKETCH SECTION PRO TIPS+// =============================================================================++/**+ * Vine Charcoal Wash Tip (256x256):+ * Velvety feathered willow charcoal pad for atmospheric shadows, portrait backgrounds,+ * and soft chiaroscuro tonal blocking.+ */+export function generateVineCharcoalTip(): string {+ return buildCachedPng('pro:vine-charcoal-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x31a01);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const domes = makeCellularDomeField(64, 18, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.38;+ const invSize = 1 / size;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp =+ (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * 0.22 ++ (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.10;+ const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));+ if (r >= 1.0) continue;++ const env = Math.pow(0.5 * (1.0 + Math.cos(r * Math.PI)), 1.18);+ const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);+ const fine = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);+ const dust = dome * 0.44 + fine * 0.38 + rand() * 0.18;+ const tooth = smoothstep(0.14 + r * 0.28, 0.62 + r * 0.22, dust);+ const alpha = env * (0.34 + 0.66 * tooth);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Flat Charcoal Block Tip (256x256):+ * Snapped compressed square charcoal stick — razor-crisp chisel corner for bold shadows+ * and brows, fractured matte carbon interior, and loose powder flecks along the trailing edge.+ */+export function generateCharcoalBlockTip(): string {+ return buildCachedPng('pro:charcoal-block-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x31b02);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const domes = makeCellularDomeField(64, 20, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.34;+ const invSize = 1 / size;++ const flecks: Array<{ x: number; y: number; r: number; a: number }> = [];+ for (let i = 0; i < 24; i++) {+ flecks.push({+ x: half + (rand() * 2 - 1) * rx * 0.96,+ y: half + ry * (0.88 + rand() * 0.22) * (rand() > 0.25 ? 1 : -1),+ r: 1.2 + rand() * 2.4,+ a: 0.28 + rand() * 0.48,+ });+ }++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const ySign = dy / ry;+ const trail = clamp01((ySign + 0.2) * 0.75);+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp =+ (samplePeriodic(nCoarse, 16, x * 0.075, y * 0.075) - 0.5) * (0.06 + trail * 0.12) ++ (samplePeriodic(nMed, 32, x * 0.19, y * 0.19) - 0.5) * 0.06;+ const nx = Math.abs(dx) / (rx * (1.0 + warp));+ const ny = Math.abs(dy) / (ry * (1.0 + warp));+ const d = Math.pow(Math.pow(nx, 6.0) + Math.pow(ny, 6.0), 1 / 6.0);++ let alpha = 0;+ if (d < 1.04) {+ const env = 1.0 - smoothstep(0.88 - trail * 0.14, 1.015, d);+ const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);+ const med = samplePeriodic(nMed, 32, x * 0.28, y * 0.28);+ const fracture = dome * 0.52 + med * 0.34 + rand() * 0.14;+ const cutLow = 0.14 + smoothstep(0.55, 1.0, d) * 0.32 + trail * 0.10;+ const body = smoothstep(cutLow, cutLow + 0.22, fracture);+ const leadCore = (1.0 - trail) * (1.0 - smoothstep(0.76, 0.98, d)) * 0.88;+ alpha = env * Math.max(leadCore, body);+ }++ for (let i = 0; i < flecks.length; i++) {+ const fl = flecks[i];+ const fdx = x - fl.x;+ const fdy = y - fl.y;+ if (Math.abs(fdx) > 5 || Math.abs(fdy) > 5) continue;+ const fd = Math.hypot(fdx, fdy) / fl.r;+ if (fd < 1.0) {+ const fa = (1.0 - smoothstep(0.3, 1.0, fd)) * fl.a;+ if (fa > alpha) alpha = fa;+ }+ }++ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Conté Crayon Tip (256x256):+ * Creamy-dry faceted octagonal wax-mineral drawing crayon with crisp edges and fine chalk grit.+ */+export function generateConteCrayonTip(): string {+ return buildCachedPng('pro:conte-crayon-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x31c03);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const domes = makeCellularDomeField(64, 24, rand);+ const half = size * 0.5;+ const rx = size * 0.44;+ const ry = size * 0.38;+ const invSize = 1 / size;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp = (samplePeriodic(nMed, 32, x * 0.12, y * 0.12) - 0.5) * 0.10;+ const nx = Math.abs(dx) / (rx * (1.0 + warp));+ const ny = Math.abs(dy) / (ry * (1.0 + warp));+ const d = Math.pow(Math.pow(nx, 3.8) + Math.pow(ny, 3.8), 1 / 3.8);+ if (d >= 1.03) continue;++ const env = 1.0 - smoothstep(0.78, 1.02, d);+ const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);+ const fine = samplePeriodic(nFine, 64, x * 0.42, y * 0.42);+ const wax = dome * 0.48 + fine * 0.36 + rand() * 0.16;+ const core = (1.0 - smoothstep(0.54, 0.92, d)) * 0.88;+ const tooth = smoothstep(0.14 + d * 0.28, 0.46 + d * 0.24, wax);+ const alpha = env * Math.max(core, tooth);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Animation Sketch Pencil (Col-Erase style, 256x256):+ * Honed smooth waxy-graphite cone with crisp gesture clarity and fine light-touch paper tooth.+ */+export function generateColErasePencilTip(): string {+ return buildCachedPng('pro:col-erase-pencil-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x31d04);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.44;+ const ry = size * 0.40;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp = (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.09;+ const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));+ if (r >= 1.02) continue;++ const env = 1.0 - smoothstep(0.74, 1.01, r);+ const fine = samplePeriodic(nFine, 64, x * 0.48, y * 0.48);+ const grit = 0.72 + 0.22 * fine + 0.06 * rand();+ const rim = r > 0.65 ? smoothstep(0.15, 0.62, fine + (1.0 - r) * 0.9) : 1.0;+ const alpha = env * grit * rim;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++// =============================================================================+// 3. BRUSH SECTION PRO PAINTERLY TIPS+// =============================================================================++/**+ * Hard Square Block-In Tip (256x256):+ * Sculptural architectural flat rectangle (Craig Mullins / Sinix / Ahmed Aldoori style)+ * for carving bold portrait planes, crisp cast shadows, and geometric metallic facets.+ */+export function generateHardSquareTip(): string {+ return buildCachedPng('pro:hard-square-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41a01);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.36;++ for (let y = 0; y < size; y++) {+ const dy = Math.abs(y - half + 0.5);+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = Math.abs(x - half + 0.5);+ const nx = dx / rx;+ const ny = dy / ry;+ // Razor-clean superellipse rectangle (p = 9) with softly anti-aliased bevel corners+ const d = Math.pow(Math.pow(nx, 9.0) + Math.pow(ny, 9.0), 1 / 9.0);+ if (d >= 1.02) continue;++ let alpha = 1.0 - smoothstep(0.935, 1.012, d);+ // Subtle organic painterly rim tooth so strokes never feel cold/vector-sterile+ if (d > 0.86) {+ const micro = samplePeriodic(nFine, 64, x * 0.35, y * 0.35);+ alpha *= 0.90 + 0.10 * micro;+ }+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Painterly Gouache Flat Tip (256x256):+ * Overlapping translucent-to-opaque flat synthetic taklon brush head oriented along +X+ * (inspired by Guweiz / Ruan Jia / CSP Opaque Watercolor square painterly fabric folds).+ */+export function generatePainterlyGouacheFlatTip(): string {+ return buildCachedPng('pro:painterly-gouache-flat-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41b02);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.39;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp =+ (samplePeriodic(nCoarse, 16, x * 0.055, y * 0.055) - 0.5) * 0.055 ++ (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.03;+ const nx = Math.abs(dx) / (rx * (1.0 + warp));+ const ny = Math.abs(dy) / (ry * (1.0 + warp));+ const d = Math.pow(Math.pow(nx, 4.4) + Math.pow(ny, 4.4), 1 / 4.4);+ if (d >= 1.03) continue;++ const env = 1.0 - smoothstep(0.84, 1.015, d);+ // Subtle fine synthetic-bristle longitudinal flow + slight gouache edge load+ const streak = samplePeriodic(nFine, 64, x * 0.10, y * 0.44);+ const edgeLoad = 0.90 + 0.10 * smoothstep(0.50, 0.92, d);+ const body = (0.86 + 0.14 * streak) * edgeLoad;+ const alpha = clamp01(env * body);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Hard Round Pressure Painter / Tapered Painterly Oval (256x256):+ * Classic pro digital-painting workhorse oval with lush solid core, buttery cosine rim,+ * and whisper-subtle organic perimeter variation.+ */+export function generatePainterlyOvalTip(): string {+ return buildCachedPng('pro:painterly-oval-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41c03);+ const nMed = makePeriodicGrid(32, rand);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.41;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp = (samplePeriodic(nMed, 32, x * 0.075, y * 0.075) - 0.5) * 0.04;+ const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));+ if (r >= 1.0) continue;++ let alpha = 1.0;+ if (r > 0.72) {+ const t = (r - 0.72) / 0.28;+ alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));+ }+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Silky Hair & Fur Locks Tip (256x256):+ * Directional multi-strand tapered sable lock head oriented along +X: dense lustrous core+ * tufts flanked by delicate separated hair wisps for painting bangs, locks & fur in one sweep.+ */+export function generateHairLocksTip(): string {+ return buildCachedPng('pro:silky-hair-locks-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41d04);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.41;++ interface LockStrand {+ cx: number;+ cy: number;+ rx: number;+ ry: number;+ strength: number;+ }+ const strands: LockStrand[] = [];+ // 16 deliberately separated silky lock clumps with crisp airy channels between filaments+ const anchors = [+ -0.94, -0.82, -0.68, -0.56, -0.42, -0.30, -0.17, -0.05,+ 0.07, 0.19, 0.32, 0.44, 0.58, 0.71, 0.84, 0.95,+ ];+ for (let i = 0; i < anchors.length; i++) {+ const u = anchors[i] + (rand() - 0.5) * 0.025;+ const absU = Math.abs(u);+ const arch = Math.sqrt(Math.max(0.20, 1.0 - absU * absU * 0.68));+ const isCore = absU < 0.40;+ const isWisp = i === 0 || i === 3 || i === 7 || i === 11 || i === 15;+ strands.push({+ cx: half + (rand() - 0.5) * rx * 0.22,+ cy: half + u * ry * 0.96,+ rx: rx * (0.64 + rand() * 0.34) * arch,+ ry: isWisp ? 2.2 + rand() * 1.8 : isCore ? 4.4 + rand() * 3.0 : 3.0 + rand() * 2.4,+ strength: isWisp ? 0.65 + rand() * 0.30 : 0.86 + rand() * 0.14,+ });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < strands.length; i++) {+ const st = strands[i];+ const dy = Math.abs(y - st.cy);+ if (dy > st.ry * 1.15) continue;+ const dx = Math.abs(x - st.cx);+ if (dx > st.rx * 1.05) continue;+ const nx = dx / st.rx;+ const ny = dy / (st.ry * Math.max(0.28, 1.0 - nx * 0.55));+ const crossEnv = 1.0 - smoothstep(0.32, 1.0, ny);+ const alongEnv = 1.0 - smoothstep(0.28, 1.0, nx);+ const v = crossEnv * alongEnv * st.strength;+ if (v > accum) accum = v;+ }+ if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);+ }+ }+ });+}++/**+ * Dry-Brush Hair Sheen Tip (256x256):+ * Broad flat dry-bristle highlighter oriented along +X with crisp irregular parallel+ * hair-fiber bands and airy gaps — glides across hair crowns & silk for instant specular sheen.+ */+export function generateDryHairSheenTip(): string {+ return buildCachedPng('pro:dry-hair-sheen-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41e05);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.44;+ const ry = size * 0.44;++ interface Band {+ cy: number;+ ry: number;+ rx: number;+ cx: number;+ str: number;+ }+ const bands: Band[] = [];+ // 11 bold separated dry-sheen hair-fiber bands with clear negative-space channels+ const bandAnchors = [-0.90, -0.72, -0.54, -0.35, -0.18, 0.0, 0.19, 0.37, 0.56, 0.74, 0.91];+ for (let i = 0; i < bandAnchors.length; i++) {+ const posU = bandAnchors[i] + (rand() - 0.5) * 0.04;+ const isWide = i === 2 || i === 5 || i === 8;+ bands.push({+ cx: half + (rand() - 0.5) * 28,+ cy: half + posU * ry * 0.96,+ rx: rx * (0.66 + rand() * 0.32) * (1.0 - Math.abs(posU) * 0.18),+ ry: isWide ? 6.2 + rand() * 3.4 : 2.8 + rand() * 2.6,+ str: isWide ? 0.92 + rand() * 0.08 : 0.68 + rand() * 0.28,+ });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < bands.length; i++) {+ const b = bands[i];+ const dy = Math.abs(y - b.cy);+ if (dy > b.ry * 1.15) continue;+ const dx = Math.abs(x - b.cx);+ if (dx > b.rx * 1.05) continue;+ const nx = dx / b.rx;+ const ny = dy / b.ry;+ const v = (1.0 - smoothstep(0.25, 1.0, nx)) * (1.0 - smoothstep(0.45, 1.0, ny)) * b.str;+ if (v > accum) accum = v;+ }+ if (accum > 0.008) {+ const tooth = 0.72 + 0.28 * samplePeriodic(nFine, 64, x * 0.20, y * 0.62);+ writeAlphaPixel(data, row + x * 4, clamp01(accum * tooth));+ }+ }+ }+ });+}++/**+ * Expressive Concept Bristle Multi-Tip (256x256 x 4 variants):+ * Energetic fractured hog-bristle flat daubs oriented along +X (Greg Rutkowski / MTG concept art+ * cloak & sky oil brushwork) with bold varied tuft clusters and organic ragged edges.+ */+export function generateConceptBristleSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:concept-bristle-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x41f06 + vIdx * 0x62d9);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * (0.43 + (vIdx % 2) * 0.025);+ const ry = size * (0.35 + ((vIdx + 1) % 2) * 0.03);++ const numTufts = 26;+ const tY = new Float32Array(numTufts);+ const tW = new Float32Array(numTufts);+ const tStr = new Float32Array(numTufts);+ const tReach = new Float32Array(numTufts);+ for (let i = 0; i < numTufts; i++) {+ const u = ((i + 0.5) / numTufts) * 2 - 1;+ tY[i] = half + u * ry * 0.96 + (rand() - 0.5) * 6.5;+ tW[i] = 3.8 + rand() * 6.2;+ tStr[i] = 0.56 + rand() * 0.44;+ tReach[i] = 0.72 + rand() * 0.30;+ }++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp =+ (samplePeriodic(nCoarse, 16, x * 0.065, y * 0.065) - 0.5) * 0.18 ++ (samplePeriodic(nMed, 32, x * 0.16, y * 0.16) - 0.5) * 0.08;+ const nx = Math.abs(dx) / (rx * (1.0 + warp));+ const ny = Math.abs(dy) / (ry * (1.0 + warp * 0.9));+ const d = Math.pow(Math.pow(nx, 3.4) + Math.pow(ny, 3.4), 1 / 3.4);+ if (d >= 1.06) continue;++ let tuft = 0;+ let reach = 0.88;+ for (let i = 0; i < numTufts; i++) {+ const distY = Math.abs(y - tY[i]) / tW[i];+ if (distY < 1.0) {+ const v = (1.0 - distY * distY) * tStr[i];+ if (v > tuft) {+ tuft = v;+ reach = tReach[i];+ }+ }+ }++ const grain = samplePeriodic(nFine, 64, x * 0.18, y * 0.52);+ const edgeMask = 1.0 - smoothstep(reach * 0.72, reach * 1.04, d);+ const dryPocket = smoothstep(0.18 + d * 0.24, 0.62, tuft * 0.72 + grain * 0.28);+ const alpha = edgeMask * (0.28 + 0.72 * dryPocket);+ if (alpha > 0.005) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Wedge & Chisel Painter Tip (256x256):+ * Asymmetric beveled wedge oriented along +X: razor-crisp architectural edge on top/front+ * tapering smoothly into a softly feathered painterly gouache heel on bottom/back for effortless+ * lost-and-found edges in a single stroke.+ */+export function generateWedgeChiselTip(): string {+ return buildCachedPng('pro:wedge-chisel-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x42007);+ const nCoarse = makePeriodicGrid(16, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.38;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const yNorm = dy / ry; // -1 = crisp wedge apex, +1 = soft feathered heel+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const xNorm = dx / rx;+ // Diagonal sharpness axis: top-front (xNorm - yNorm > 0) is razor crisp, bottom-back fades soft+ const softness = clamp01((yNorm - xNorm * 0.45 + 0.65) * 0.58);+ const warp = (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * (0.04 + softness * 0.14);++ // Angled bevel wedge silhouette+ const widthAtY = 1.0 - Math.max(0, -yNorm) * 0.18;+ const nx = Math.abs(dx) / (rx * widthAtY * (1.0 + warp));+ const ny = Math.abs(dy) / (ry * (1.0 + warp));+ const d = Math.pow(Math.pow(nx, 4.2) + Math.pow(ny, 4.2), 1 / 4.2);+ if (d >= 1.04) continue;++ const edgeStart = 0.92 - softness * 0.52;+ const edgeEnd = 1.008 + softness * 0.02;+ const env = 1.0 - smoothstep(edgeStart, edgeEnd, d);+ const fine = samplePeriodic(nFine, 64, x * 0.24, y * 0.34);+ const alpha = env * (1.0 - softness * 0.35 * (1.0 - fine));+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Soft Watercolor Wash Mop Tip (256x256):+ * Organic translucent watercolor puddle with gentle perimeter undulation and subtly+ * richer outer pigment ring (pairs naturally with wetEdge and cold-press watercolor paper).+ */+export function generateWatercolorWashTip(): string {+ return buildCachedPng('pro:watercolor-wash-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x42108);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const half = size * 0.5;+ const rad = size * 0.45;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warp =+ (samplePeriodic(nCoarse, 16, x * 0.055, y * 0.055) - 0.5) * 0.22 ++ (samplePeriodic(nMed, 32, x * 0.13, y * 0.13) - 0.5) * 0.10;+ const r = Math.hypot(dx, dy) / (rad * (1.0 + warp));+ if (r >= 1.02) continue;++ const env = 1.0 - smoothstep(0.68, 1.01, r);+ // Slightly lighter watery center with subtle pigment settling near rim (0.72..0.92)+ const rimPool = 0.78 + 0.22 * Math.exp(-Math.pow((r - 0.78) * 5.2, 2));+ const bloom = 0.88 + 0.12 * samplePeriodic(nMed, 32, x * 0.16, y * 0.16);+ const alpha = clamp01(env * rimPool * bloom);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Metallic & Gold Impasto Glint Tip (256x256):+ * Crisp high-contrast faceted oval-lozenge with hammered micro-facet texture inside+ * a clean architectural rim for hammered gold coins, bronze cuffs, chrome & eye catchlights.+ */+export function generateMetallicGlintTip(): string {+ return buildCachedPng('pro:metallic-glint-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x42209);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.34;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const nx = Math.abs(dx) / rx;+ const ny = Math.abs(dy) / ry;+ const d = Math.pow(Math.pow(nx, 3.2) + Math.pow(ny, 3.2), 1 / 3.2);+ if (d >= 1.02) continue;++ const env = 1.0 - smoothstep(0.90, 1.01, d);+ // Subtle anisotropic brushed-metal micro sheen+ const brushSheen = 0.86 + 0.14 * samplePeriodic(nFine, 64, x * 0.14, y * 0.55);+ const hammer = 0.92 + 0.08 * samplePeriodic(nMed, 32, x * 0.20, y * 0.20);+ const alpha = clamp01(env * brushSheen * hammer);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++// =============================================================================+// 4. BLEND SECTION PRO PURE-SMEAR TIPS+// =============================================================================++/**+ * Charcoal Blending Stump / Tortillon Tip (256x256):+ * Tapered rolled-paper stump pad oriented along +X with soft porous paper-felt fibers+ * that rub charcoal & graphite into velvety shadows without destroying tooth.+ */+export function generateBlendTortillonTip(): string {+ return buildCachedPng('pro:blend-tortillon-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x51a01);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const domes = makeCellularDomeField(64, 22, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.38;+ const invSize = 1 / size;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const nx = dx / rx;+ const cone = 1.0 - Math.max(0, nx) * 0.28;+ const ny = dy / (ry * cone);+ const r = Math.hypot(nx, ny);+ if (r >= 1.02) continue;++ const env = Math.pow(1.0 - smoothstep(0.20, 1.01, r), 1.15);+ const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);+ const felt = samplePeriodic(nMed, 32, x * 0.10, y * 0.28) * 0.45 + samplePeriodic(nFine, 64, x * 0.38, y * 0.38) * 0.25 + dome * 0.30;+ const alpha = env * (0.52 + 0.48 * smoothstep(0.18, 0.72, felt));+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Painterly Gouache Melter Pad Tip (256x256):+ * Feathered flat rectangular gouache softening pad oriented along +X — melts hard edges+ * into silky anime-realism & painterly gradients while preserving directional brushwork.+ */+export function generateBlendGouachePadTip(): string {+ return buildCachedPng('pro:blend-gouache-pad-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x51b02);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.45;+ const ry = size * 0.39;++ for (let y = 0; y < size; y++) {+ const dy = Math.abs(y - half + 0.5);+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = Math.abs(x - half + 0.5);+ const nx = dx / rx;+ const ny = dy / ry;+ const d = Math.pow(Math.pow(nx, 3.0) + Math.pow(ny, 3.0), 1 / 3.0);+ if (d >= 1.02) continue;++ const env = Math.pow(1.0 - smoothstep(0.28, 1.01, d), 1.08);+ const streak = 0.82 + 0.18 * samplePeriodic(nFine, 64, x * 0.12, y * 0.42);+ const alpha = env * streak;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Atmospheric Mist & Smoke Smudge Tip (256x256):+ * Turbulent multi-lobed wispy cloud head that pulls existing paint into ghostly+ * drifting smoke tendrils, vapor, and cinematic atmospheric haze.+ */+export function generateBlendSmokeWispTip(): string {+ return buildCachedPng('pro:blend-smoke-wisp-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x51c03);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rad = size * 0.46;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const r = Math.hypot(dx, dy) / rad;+ if (r >= 1.02) continue;++ const env = Math.pow(0.5 * (1.0 + Math.cos(Math.min(1, r) * Math.PI)), 1.35);+ // Domain-warped fluid curl for natural wispy smoke eddies+ const wx = (samplePeriodic(nCoarse, 16, x * 0.045, y * 0.045) - 0.5) * 44;+ const wy = (samplePeriodic(nCoarse, 16, x * 0.045 + 7.2, y * 0.045 + 3.9) - 0.5) * 44;+ const curl1 = samplePeriodic(nMed, 32, (x + wx) * 0.09, (y + wy) * 0.09);+ const curl2 = samplePeriodic(nFine, 64, (x - wy * 0.5) * 0.18, (y + wx * 0.5) * 0.18);+ const wisp = smoothstep(0.24, 0.78, curl1 * 0.65 + curl2 * 0.35);+ const alpha = env * (0.18 + 0.82 * wisp);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Palette Knife Smudge Blade Tip (256x256):+ * Asymmetric thin painting-knife scraper oriented along +X: crisp straight edge on top+ * with smooth feathered trail below for razor-clean sculptural paint pulling.+ */+export function generateBlendKnifeSmearTip(): string {+ return buildCachedPng('pro:blend-knife-smear-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x51d04);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * 0.46;+ const ry = size * 0.34;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const ySigned = dy / ry; // -1 = crisp knife blade edge, +1 = soft feathered smear trail+ const trail = clamp01((ySigned + 0.35) / 1.35);+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = Math.abs(x - half + 0.5);+ const nx = dx / rx;+ const ny = Math.abs(ySigned);+ const d = Math.pow(Math.pow(nx, 5.0) + Math.pow(ny, 5.0), 1 / 5.0);+ if (d >= 1.02) continue;++ const envX = 1.0 - smoothstep(0.76, 1.01, nx);+ const envTop = smoothstep(-1.01, -0.84, ySigned);+ const envBot = 1.0 - smoothstep(0.10, 1.01, ySigned);+ const micro = 0.90 + 0.10 * samplePeriodic(nFine, 64, x * 0.14, y * 0.48);+ const alpha = envX * envTop * envBot * (1.0 - trail * 0.25) * micro;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++// =============================================================================+// 5. TEXTURE & FX SECTION PRO TIPS (FOLIAGE, FRECKLES, SMOKE, ROCK, EMBER, CLOUDS, GLOW)+// =============================================================================++/** Helper: evaluates a single sculpted botanical leaf silhouette in local coords. */+function evalLeafShape(+ px: number,+ py: number,+ cx: number,+ cy: number,+ len: number,+ halfW: number,+ angleRad: number,+ bend: number,+ sharpness: number+): number {+ const dx = px - cx;+ const dy = py - cy;+ const c = Math.cos(-angleRad);+ const s = Math.sin(-angleRad);+ const lx = (dx * c - dy * s) / len; // [-1, 1] along leaf spine+ if (lx < -1.04 || lx > 1.04) return 0;+ const bendOffset = bend * (1.0 - lx * lx);+ const ly = (dx * s + dy * c) / halfW - bendOffset;++ // Botanical pointed almond contour: fuller near base (-0.25), pointed at tip (+1)+ const u = (lx + 1.0) * 0.5; // 0 = base, 1 = tip+ const profile = Math.pow(Math.max(0, Math.sin(u * Math.PI)), 0.78) * (1.16 - 0.34 * u);+ if (profile <= 0.005) return 0;+ const dist = Math.abs(ly) / profile;+ if (dist >= 1.08) return 0;++ // Subtle central midrib variation for painted leaf dimensionality+ const midrib = 0.92 + 0.08 * Math.exp(-ly * ly * 22);+ const edge = 1.0 - smoothstep(sharpness, 1.04, dist);+ return edge * midrib;+}++/**+ * Painterly Canopy Leaves Multi-Tip (256x256 x 4 botanical variants):+ * Hand-painted organic forest leaves & twin/triple sprigs for rich fantasy foliage.+ */+export function generatePainterlyLeafSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:painterly-leaf-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61a01 + vIdx * 0x4711);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;++ const specs: Array<Array<{ cx: number; cy: number; len: number; hw: number; ang: number; bend: number; str: number }>> = [+ // v0: Sculpted rainforest broadleaf+ [{ cx: half, cy: half, len: size * 0.43, hw: size * 0.19, ang: -0.22, bend: 0.18, str: 1.0 }],+ // v1: Graceful twin-leaf branchlet+ [+ { cx: half - 22, cy: half - 26, len: size * 0.34, hw: size * 0.14, ang: -0.62, bend: 0.14, str: 0.96 },+ { cx: half + 26, cy: half + 24, len: size * 0.36, hw: size * 0.15, ang: 0.38, bend: -0.16, str: 1.0 },+ ],+ // v2: Broad angled sunlit diamond leaf+ [{ cx: half, cy: half, len: size * 0.41, hw: size * 0.23, ang: 0.18, bend: -0.14, str: 1.0 }],+ // v3: Lush triple-leaf canopy cluster+ [+ { cx: half, cy: half - 40, len: size * 0.28, hw: size * 0.13, ang: -1.25, bend: 0.10, str: 0.94 },+ { cx: half - 42, cy: half + 24, len: size * 0.30, hw: size * 0.13, ang: -2.45, bend: -0.12, str: 0.88 },+ { cx: half + 40, cy: half + 22, len: size * 0.31, hw: size * 0.14, ang: 0.45, bend: 0.12, str: 1.0 },+ ],+ ];+ const leaves = specs[vIdx];++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const wx = (samplePeriodic(nMed, 32, x * 0.08, y * 0.08) - 0.5) * 4.5;+ const wy = (samplePeriodic(nMed, 32, x * 0.08 + 5.1, y * 0.08 + 2.3) - 0.5) * 4.5;+ let accum = 0;+ for (let i = 0; i < leaves.length; i++) {+ const lf = leaves[i];+ const v = evalLeafShape(x + wx, y + wy, lf.cx, lf.cy, lf.len, lf.hw, lf.ang, lf.bend, 0.80) * lf.str;+ if (v > accum) accum = v;+ }+ if (accum > 0.006) {+ const brushTooth = 0.84 + 0.16 * samplePeriodic(nFine, 64, x * 0.22, y * 0.22);+ writeAlphaPixel(data, row + x * 4, clamp01(accum * brushTooth));+ }+ }+ }+ });+}++/**+ * Bokeh Soft Foreground Leaves Multi-Tip (256x256 x 3 variants):+ * Softly defocused optical depth-of-field leaves for cinematic foreground framing & drifting petals.+ */+export function generateBokehLeafSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 3) + 3) % 3;+ return buildCachedPng(`pro:bokeh-leaf-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const half = size * 0.5;+ const cfg = [+ { len: size * 0.42, hw: size * 0.22, ang: -0.30, bend: 0.16 },+ { len: size * 0.44, hw: size * 0.16, ang: 0.42, bend: -0.20 },+ { len: size * 0.38, hw: size * 0.25, ang: 0.05, bend: 0.10 },+ ][vIdx];++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ // Wide soft optical defocus (sharpness = 0.18 -> lush dreamy depth-of-field blur)+ const v = evalLeafShape(x, y, half, half, cfg.len, cfg.hw, cfg.ang, cfg.bend, 0.16);+ if (v > 0.004) {+ writeAlphaPixel(data, row + x * 4, Math.pow(v, 1.18));+ }+ }+ }+ });+}++/**+ * Skin Freckles & Pores Multi-Tip (256x256 x 4 organic micro-constellations):+ * Realistic non-repeating irregular freckle clusters & portrait skin pores (zero grid artifacts).+ */+export function generateSkinFrecklesSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:skin-freckles-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61c03 + vIdx * 0x893b);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;++ interface Freckle {+ x: number;+ y: number;+ rx: number;+ ry: number;+ cos: number;+ sin: number;+ a: number;+ }+ const spots: Freckle[] = [];+ const count = 24 + (vIdx % 2) * 6;+ for (let i = 0; i < count; i++) {+ const ang = rand() * Math.PI * 2;+ // Organic radial spread denser near center, airy sparse edges+ const rad = Math.pow(rand(), 0.70) * (size * 0.43);+ // Calibrated 4.2..11px at 256px tip so 64px strokes render crisp natural freckles & pores+ const baseR = 4.2 + Math.pow(rand(), 1.65) * 6.8;+ const rot = rand() * Math.PI;+ spots.push({+ x: half + Math.cos(ang) * rad,+ y: half + Math.sin(ang) * rad,+ rx: baseR * (0.78 + rand() * 0.44),+ ry: baseR * (0.78 + rand() * 0.44),+ cos: Math.cos(rot),+ sin: Math.sin(rot),+ a: (0.52 + rand() * 0.48) * (1.0 - (rad / (size * 0.48)) * 0.28),+ });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < spots.length; i++) {+ const sp = spots[i];+ const dx = x - sp.x;+ const dy = y - sp.y;+ if (Math.abs(dx) > 16 || Math.abs(dy) > 16) continue;+ const lx = (dx * sp.cos + dy * sp.sin) / sp.rx;+ const ly = (-dx * sp.sin + dy * sp.cos) / sp.ry;+ const d = Math.hypot(lx, ly);+ if (d < 1.08) {+ const wobble = (samplePeriodic(nFine, 64, x * 0.45, y * 0.45) - 0.5) * 0.22;+ const v = (1.0 - smoothstep(0.36 + wobble, 1.02 + wobble, d)) * sp.a;+ if (v > accum) accum = v;+ }+ }+ if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);+ }+ }+ });+}++/**+ * Dark Smoke & Vapor Tendril Multi-Tip (256x256 x 4 domain-warped turbulent plumes):+ * Inspired by MTG dark fantasy swirling necrotic smoke & glowing lantern vapor.+ */+export function generateSmokeTendrilSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:smoke-tendril-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61d04 + vIdx * 0x7a1f);+ const nWarp = makePeriodicGrid(16, rand);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rx = size * (0.46 - (vIdx % 2) * 0.03);+ const ry = size * (0.37 + (vIdx % 2) * 0.05);++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ // Double domain warp produces authentic fluid curling smoke ribbons+ const w1x = (samplePeriodic(nWarp, 16, x * 0.038 + vIdx * 2.1, y * 0.038) - 0.5) * 58;+ const w1y = (samplePeriodic(nWarp, 16, x * 0.038 + 5.7, y * 0.038 + vIdx * 3.3) - 0.5) * 58;+ const px = x + w1x;+ const py = y + w1y;++ const r = Math.hypot((dx + w1x * 0.35) / rx, (dy + w1y * 0.35) / ry);+ if (r >= 1.05) continue;++ const env = Math.pow(0.5 * (1.0 + Math.cos(Math.min(1, r) * Math.PI)), 1.30);+ const f1 = samplePeriodic(nCoarse, 16, px * 0.055, py * 0.055);+ const f2 = samplePeriodic(nMed, 32, px * 0.12, py * 0.12);+ const f3 = samplePeriodic(nFine, 64, px * 0.25, py * 0.25);+ // Ridged billow creates curling translucent smoke tendrils with dark lacy hollows+ const fbm = f1 * 0.50 + f2 * 0.32 + f3 * 0.18;+ const wisp = smoothstep(0.28 + r * 0.16, 0.78, fbm);+ const alpha = env * wisp;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Wispy Smoke Dual Brush Erosion Mask (256x256):+ * Secondary modulation tip for Dark Smoke & Vapor — breaks continuous strokes into+ * organic billowing eddies and ghost-like tendrils.+ */+export function generateSmokeDualMaskTip(): string {+ return buildCachedPng('pro:smoke-dual-mask-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61d99);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const half = size * 0.5;+ const rad = size * 0.48;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const r = Math.hypot(dx, dy) / rad;+ if (r >= 1.0) continue;++ const env = 1.0 - smoothstep(0.58, 1.0, r);+ const wx = (samplePeriodic(nCoarse, 16, x * 0.05, y * 0.05) - 0.5) * 32;+ const wy = (samplePeriodic(nCoarse, 16, x * 0.05 + 4.3, y * 0.05 + 8.1) - 0.5) * 32;+ const cloud = samplePeriodic(nMed, 32, (x + wx) * 0.11, (y + wy) * 0.11);+ const mask = 0.25 + 0.75 * smoothstep(0.20, 0.76, cloud);+ const alpha = env * mask;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Craggy Rock & Weathered Bone Multi-Tip (256x256 x 4 angular fractured variants):+ * Inspired by MTG skull pauldrons, jagged mountain cliffs, ancient stone & hammered rusted metal.+ */+export function generateCraggyRockSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:craggy-rock-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61e05 + vIdx * 0x5c3d);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const nFine = makePeriodicGrid(64, rand);+ const domes = makeCellularDomeField(64, 16 + vIdx * 3, rand);+ const half = size * 0.5;+ const rx = size * (0.44 - (vIdx % 2) * 0.03);+ const ry = size * (0.37 + ((vIdx + 1) % 2) * 0.04);+ const invSize = 1 / size;++ // 5 angular mineral shards composed per variant to eliminate any circular feel+ const shards: Array<{ x: number; y: number; rx: number; ry: number; cos: number; sin: number; w: number }> = [];+ for (let i = 0; i < 5; i++) {+ const th = (i / 5) * Math.PI * 2 + rand() * 0.8;+ const dist = (0.08 + rand() * 0.30) * rx;+ const rot = rand() * Math.PI;+ shards.push({+ x: half + Math.cos(th) * dist,+ y: half + Math.sin(th) * dist * 0.85,+ rx: rx * (0.38 + rand() * 0.30),+ ry: ry * (0.32 + rand() * 0.28),+ cos: Math.cos(rot),+ sin: Math.sin(rot),+ w: 0.74 + rand() * 0.26,+ });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let shape = 0;+ for (let i = 0; i < shards.length; i++) {+ const sh = shards[i];+ const dx = x - sh.x;+ const dy = y - sh.y;+ const lx = Math.abs(dx * sh.cos + dy * sh.sin) / sh.rx;+ const ly = Math.abs(-dx * sh.sin + dy * sh.cos) / sh.ry;+ // Angular faceted diamond-box rock shard (superellipse p = 1.65)+ const d = Math.pow(Math.pow(lx, 1.65) + Math.pow(ly, 1.65), 1 / 1.65);+ if (d < 1.05) {+ const v = (1.0 - smoothstep(0.62, 1.03, d)) * sh.w;+ if (v > shape) shape = v;+ }+ }+ if (shape <= 0.01) continue;++ const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);+ const ridge = 1.0 - Math.abs(samplePeriodic(nCoarse, 16, x * 0.085, y * 0.085) * 2.0 - 1.0);+ const grit = samplePeriodic(nMed, 32, x * 0.22, y * 0.22) * 0.55 + samplePeriodic(nFine, 64, x * 0.45, y * 0.45) * 0.45;+ const crag = dome * 0.42 + ridge * 0.32 + grit * 0.26;+ const cut = 0.22 + (1.0 - shape) * 0.42;+ const alpha = shape * smoothstep(cut, cut + 0.18, crag);+ if (alpha > 0.005) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Ash, Embers & Ink Spatter Multi-Tip (256x256 x 4 organic splatter constellations):+ * Dynamic teardrop ink drops, glowing fire embers, and crisp irregular ash specks.+ */+export function generateEmberSpatterSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:ember-spatter-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x61f06 + vIdx * 0x91e7);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;++ interface Drop {+ x: number;+ y: number;+ rx: number;+ ry: number;+ cos: number;+ sin: number;+ a: number;+ }+ const drops: Drop[] = [];+ // 4 primary elongated splash drops + 24 varied ash/ember sparks+ for (let i = 0; i < 28; i++) {+ const isHero = i < 4;+ const th = rand() * Math.PI * 2;+ const dist = isHero ? (0.06 + rand() * 0.24) * size : (0.10 + Math.pow(rand(), 0.72) * 0.36) * size;+ const r = isHero ? 5.5 + rand() * 7.5 : 1.3 + Math.pow(rand(), 1.7) * 4.2;+ const stretch = isHero ? 1.35 + rand() * 0.85 : 0.9 + rand() * 0.65;+ const rot = th + (rand() - 0.5) * 0.6;+ drops.push({+ x: half + Math.cos(th) * dist,+ y: half + Math.sin(th) * dist,+ rx: r * stretch,+ ry: r,+ cos: Math.cos(rot),+ sin: Math.sin(rot),+ a: isHero ? 0.88 + rand() * 0.12 : 0.45 + rand() * 0.55,+ });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < drops.length; i++) {+ const dr = drops[i];+ const dx = x - dr.x;+ const dy = y - dr.y;+ const bound = dr.rx * 1.2 + 2;+ if (Math.abs(dx) > bound || Math.abs(dy) > bound) continue;+ const lx = (dx * dr.cos + dy * dr.sin) / dr.rx;+ const ly = (-dx * dr.sin + dy * dr.cos) / dr.ry;+ const d = Math.hypot(lx, ly);+ if (d < 1.06) {+ const jagged = (samplePeriodic(nFine, 64, x * 0.35, y * 0.35) - 0.5) * 0.20;+ const v = (1.0 - smoothstep(0.68 + jagged, 1.02 + jagged, d)) * dr.a;+ if (v > accum) accum = v;+ }+ }+ if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);+ }+ }+ });+}++/**+ * Painterly Cumulus Clouds Multi-Tip (256x256 x 4 asymmetric sculpted sky puffs):+ * Crisper sunlit billowing upper domes dissolving into soft misty horizontal bases+ * for dramatic fantasy skies & Studio Ghibli / MTG cloudscapes.+ */+export function generatePainterlyCloudSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;+ return buildCachedPng(`pro:painterly-cloud-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x62007 + vIdx * 0x4b93);+ const nCoarse = makePeriodicGrid(16, rand);+ const nMed = makePeriodicGrid(32, rand);+ const half = size * 0.5;++ interface Puff {+ x: number;+ y: number;+ rx: number;+ ry: number;+ w: number;+ }+ const puffs: Puff[] = [];+ const numPuffs = 6;+ for (let i = 0; i < numPuffs; i++) {+ const u = (i / (numPuffs - 1)) * 2 - 1; // left to right+ const arch = 1.0 - u * u * 0.72;+ puffs.push({+ x: half + u * size * 0.27 + (rand() - 0.5) * 14,+ y: half + size * (0.08 - arch * 0.18) + (rand() - 0.5) * 14,+ rx: size * (0.16 + arch * 0.11 + rand() * 0.05),+ ry: size * (0.14 + arch * 0.11 + rand() * 0.05),+ w: 0.78 + arch * 0.22,+ });+ }++ for (let y = 0; y < size; y++) {+ const yFrac = y / size; // 0 = top sunlit billows, 1 = soft misty base+ const baseFade = 1.0 - smoothstep(0.56, 0.90, yFrac);+ const topCrisp = 1.0 - smoothstep(0.28, 0.65, yFrac); // crisper upper cloud rim+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const wx = (samplePeriodic(nCoarse, 16, x * 0.05, y * 0.05) - 0.5) * 18;+ const wy = (samplePeriodic(nCoarse, 16, x * 0.05 + 6.3, y * 0.05 + 2.7) - 0.5) * 16;+ let shape = 0;+ for (let i = 0; i < puffs.length; i++) {+ const pf = puffs[i];+ const d = Math.hypot((x + wx - pf.x) / pf.rx, (y + wy - pf.y) / pf.ry);+ if (d < 1.05) {+ const edgeStart = 0.26 + topCrisp * 0.44;+ const v = (1.0 - smoothstep(edgeStart, 1.02, d)) * pf.w;+ if (v > shape) shape = v;+ }+ }+ if (shape <= 0.006) continue;+ const billow = 0.78 + 0.22 * samplePeriodic(nMed, 32, x * 0.12, y * 0.12);+ const alpha = shape * billow * (0.18 + 0.82 * baseFade);+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Woven Cloth & Brocade Grain Tip (256x256):+ * Tactile organic textile pad infused with crisp cross-hatched brocade & linen threads+ * for painting embroidered medieval sleeves, tunics, scarves & woven fabric highlights.+ */+export function generateWovenFabricTip(): string {+ return buildCachedPng('pro:woven-fabric-256', HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x62108);+ const nCoarse = makePeriodicGrid(16, rand);+ const nFine = makePeriodicGrid(64, rand);+ const half = size * 0.5;+ const rad = size * 0.46;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ const weft = Math.sin(y * 0.58) * 0.5 + 0.5;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const warpNoise = (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * 0.16;+ const r = Math.hypot(dx, dy) / (rad * (1.0 + warpNoise));+ if (r >= 1.0) continue;++ const env = 1.0 - smoothstep(0.45, 0.99, r);+ const warp = Math.sin(x * 0.58) * 0.5 + 0.5;+ // Subtle diamond brocade twill weave pattern+ const twill = Math.sin((x + y) * 0.29) * Math.cos((x - y) * 0.29) * 0.24;+ const weave = clamp01(warp * 0.44 + weft * 0.44 + 0.12 + twill);+ const yarn = 0.84 + 0.16 * samplePeriodic(nFine, 64, x * 0.34, y * 0.34);+ const alpha = env * (0.28 + 0.72 * smoothstep(0.20, 0.78, weave)) * yarn;+ if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Luminous Magic & Rim Glow Tip (256x256):+ * True optical point-spread bloom core: radiant smooth Gaussian center merging seamlessly+ * into an exponential inverse-square light halo with zero ring banding.+ */+export function generateLuminousBloomTip(): string {+ return buildCachedPng('pro:luminous-bloom-256', HI_TIP_SIZE, (data, size) => {+ const half = size * 0.5;+ const rad = size * 0.49;++ for (let y = 0; y < size; y++) {+ const dy = y - half + 0.5;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const dx = x - half + 0.5;+ const r = Math.hypot(dx, dy) / rad;+ if (r >= 1.0) continue;++ // Smooth optical lens bloom: bright Gaussian center + wide atmospheric halo tapering to 0+ const windowCut = 1.0 - smoothstep(0.84, 1.0, r);+ const core = Math.exp(-r * r * 7.2);+ const halo = Math.pow(1.0 - r, 2.6);+ const alpha = clamp01((core * 0.58 + halo * 0.42) * windowCut);+ if (alpha > 0.003) writeAlphaPixel(data, row + x * 4, alpha);+ }+ }+ });+}++/**+ * Fine Film & Stipple Dust Multi-Tip (256x256 x 3 organic stochastic micro-grain variants):+ * Delicate non-tiling fine stipple dust & photographic film grain for finishing smooth portraits & skies.+ */+export function generateFineStippleSubTip(variant: number = 0): string {+ const vIdx = ((Math.floor(variant) % 3) + 3) % 3;+ return buildCachedPng(`pro:fine-stipple-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {+ const rand = createPrng(0x62209 + vIdx * 0x3b71);+ const half = size * 0.5;+ const maxRad = size * 0.46;++ // Scatter 360 crisp delicate 1.5..3.4px micro-grains directly into buffer (ultra-fast O(360)!)+ const grainCount = 360;+ for (let i = 0; i < grainCount; i++) {+ const th = rand() * Math.PI * 2;+ const rNorm = Math.pow(rand(), 0.62);+ const cx = half + Math.cos(th) * rNorm * maxRad;+ const cy = half + Math.sin(th) * rNorm * maxRad;+ const gRad = 1.5 + Math.pow(rand(), 1.8) * 2.0;+ const env = 0.5 * (1.0 + Math.cos(rNorm * Math.PI));+ const strength = (0.48 + rand() * 0.52) * (0.40 + 0.60 * env);++ const x0 = Math.max(0, Math.floor(cx - gRad - 1));+ const x1 = Math.min(size - 1, Math.ceil(cx + gRad + 1));+ const y0 = Math.max(0, Math.floor(cy - gRad - 1));+ const y1 = Math.min(size - 1, Math.ceil(cy + gRad + 1));+ for (let py = y0; py <= y1; py++) {+ const dy = py - cy;+ const row = py * size * 4;+ for (let px = x0; px <= x1; px++) {+ const dx = px - cx;+ const d = Math.hypot(dx, dy) / gRad;+ if (d < 1.0) {+ const a = (1.0 - smoothstep(0.25, 1.0, d)) * strength;+ const idx = row + px * 4;+ const prevA = data[idx + 3] / 255;+ if (a > prevA) {+ writeAlphaPixel(data, idx, a);+ }+ }+ }+ }+ }+ });+}diff --git a/src/utils/proceduralBrushTips.ts b/src/utils/proceduralBrushTips.tsindex 8dd2fa9..0b6e1a0 100644--- a/src/utils/proceduralBrushTips.ts+++ b/src/utils/proceduralBrushTips.ts@@ -10,7 +10,7 @@import type { BristleProfilePreset, SurfaceTextureId } from '../types/editor';const TIP_SIZE = 128;-const HI_TIP_SIZE = 256;+export const HI_TIP_SIZE = 256;const PAPER_SIZE = 256;export const SURFACE_TEXTURE_SIZE = 1024;/** High-DPI texel density multiplier: 2x oversampled texels per document pixel at scale=1.0 */@@ -18,7 +18,7 @@ export const SURFACE_TEXELS_PER_PX = 2.0;const generatedCache = new Map<string, string>();-function createPrng(seed: number): () => number {+export function createPrng(seed: number): () => number {let a = (seed ^ 0x9e3779b9) | 0;let b = (seed * 1664525 + 1013904223) | 0;let c = (seed ^ 0xb7e15162) | 0;@@ -38,7 +38,7 @@ function createPrng(seed: number): () => number {};}-function makePeriodicGrid(res: number, rand: () => number): Float32Array {+export function makePeriodicGrid(res: number, rand: () => number): Float32Array {const g = new Float32Array(res * res);for (let i = 0; i < g.length; i++) g[i] = rand();return g;@@ -48,7 +48,7 @@ function makePeriodicGrid(res: number, rand: () => number): Float32Array {* Tileable periodic Worley / cellular dome height field.* Models physical 3D cotton paper fiber bumps: rounded peaks with sharp recessed crevices between domes.*/-function makeCellularDomeField(size: number, cells: number, rand: () => number): Float32Array {+export function makeCellularDomeField(size: number, cells: number, rand: () => number): Float32Array {const ptsX = new Float32Array(cells * cells);const ptsY = new Float32Array(cells * cells);const ptsH = new Float32Array(cells * cells);@@ -111,7 +111,7 @@ function makeCellularDomeField(size: number, cells: number, rand: () => number):return out;}-function samplePeriodic(grid: Float32Array, res: number, fx: number, fy: number): number {+export function samplePeriodic(grid: Float32Array, res: number, fx: number, fy: number): number {const mask = res - 1;const x0 = Math.floor(fx);const y0 = Math.floor(fy);@@ -132,11 +132,11 @@ function samplePeriodic(grid: Float32Array, res: number, fx: number, fy: number)return top + (bot - top) * sy;}-function clamp01(v: number): number {+export function clamp01(v: number): number {return v <= 0 ? 0 : v >= 1 ? 1 : v;}-function smoothstep(edge0: number, edge1: number, x: number): number {+export function smoothstep(edge0: number, edge1: number, x: number): number {const t = clamp01((x - edge0) / Math.max(1e-5, edge1 - edge0));return t * t * (3 - 2 * t);}@@ -144,7 +144,7 @@ function smoothstep(edge0: number, edge1: number, x: number): number {/*** Helper: allocates an offscreen rectangular canvas, fills RGBA via callback, and returns a cached PNG data URL.*/-function buildCachedRectPng(+export function buildCachedRectPng(key: string,width: number,height: number,@@ -155,6 +155,7 @@ function buildCachedRectPng(if (typeof document === 'undefined') return '';const canvas = document.createElement('canvas');+ if (typeof canvas.getContext !== 'function') return '';canvas.width = width;canvas.height = height;const ctx = canvas.getContext('2d');@@ -174,7 +175,7 @@ function buildCachedRectPng(/*** Helper: allocates an offscreen square canvas, fills RGBA via callback, and returns a cached PNG data URL.*/-function buildCachedPng(+export function buildCachedPng(key: string,size: number,fill: (data: Uint8ClampedArray, size: number) => void@@ -182,7 +183,7 @@ function buildCachedPng(return buildCachedRectPng(key, size, size, (data, w) => fill(data, w));}-function sampleFieldBilinear(field: Float32Array, fSize: number, u: number, v: number): number {+export function sampleFieldBilinear(field: Float32Array, fSize: number, u: number, v: number): number {const mask = fSize - 1;const fx = u * fSize;const fy = v * fSize;@@ -201,7 +202,7 @@ function sampleFieldBilinear(field: Float32Array, fSize: number, u: number, v: nreturn top + (bot - top) * ty;}-function writeAlphaPixel(data: Uint8ClampedArray, idx: number, alpha: number): void {+export function writeAlphaPixel(data: Uint8ClampedArray, idx: number, alpha: number): void {const a = Math.round(clamp01(alpha) * 255);if (a <= 0) return;data[idx] = 255;diff --git a/src/utils/psdParser.ts b/src/utils/psdParser.tsindex f1b5153..6a74bc2 100644--- a/src/utils/psdParser.ts+++ b/src/utils/psdParser.ts@@ -4,6 +4,7 @@ import { createCanvasThumbnail } from './canvasUtils';import { isNativeRustAvailable, parsePsdNative } from './nativeBackend';import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';import { extractWorkTimeMsFromPsdBuffer, extractWorkTimeMsFromXmp } from './artworkTimeTracker';+import { fromPsdLayerColor } from './layerOrganization';initializeCanvas((w, h) => {@@ -287,6 +288,7 @@ export async function parsePsdFile(const clipped = Boolean(psdLayer.clipping);const alphaLocked = Boolean(psdLayer.protected?.transparency || psdLayer.transparencyProtected);const locked = Boolean(psdLayer.protected?.position || psdLayer.protected?.composite);+ const colorLabel = fromPsdLayerColor(psdLayer.layerColor);const maskFields = importPsdMask(psdLayer.mask, width, height);if (isFolder) {@@ -302,6 +304,7 @@ export async function parsePsdFile(clipped,collapsed: psdLayer.opened === false,parentId,+ ...(colorLabel ? { colorLabel } : {}),...maskFields,};layers.push(folderItem);@@ -348,6 +351,7 @@ export async function parsePsdFile(clipped,parentId,thumbnailUrl: thumb,+ ...(colorLabel ? { colorLabel } : {}),...maskFields,};layers.push(rasterItem);diff --git a/src/utils/quickBrushUtils.ts b/src/utils/quickBrushUtils.tsindex 5249e8a..a8c39fd 100644--- a/src/utils/quickBrushUtils.ts+++ b/src/utils/quickBrushUtils.ts@@ -78,6 +78,12 @@ export function getCategoryAccentStyle(category: QuickBrushCategory): CategoryAccardTint: 'rgba(90, 180, 168, 0.15)',label: 'Natural Paint',};+ case 'texture-fx':+ return {+ barColor: '#b388eb',+ cardTint: 'rgba(179, 136, 235, 0.14)',+ label: 'Texture & FX',+ };case 'deco-background':return {barColor: '#34d399',diff --git a/src/utils/recentDocumentsManager.ts b/src/utils/recentDocumentsManager.tsindex e5248b7..d0d7aba 100644--- a/src/utils/recentDocumentsManager.ts+++ b/src/utils/recentDocumentsManager.ts@@ -4,6 +4,16 @@ import {safeLocalStorageGetItem,safeLocalStorageSetItem,} from './safeStorage';+import { normalizePathForComparison } from './osFileOpen';++function isDeduplicableDiskPath(path: string | undefined): boolean {+ if (!path) return false;+ const trimmed = path.trim();+ if (!trimmed) return false;+ if (trimmed.startsWith('InkStudio\\') || trimmed.startsWith('InkStudio/')) return false;+ if (trimmed.startsWith('C:\\Users\\Artist\\Documents\\InkStudio\\')) return false;+ return /^[a-zA-Z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\\\') || trimmed.startsWith('/');+}export interface FileSystemFileHandleLike {name: string;@@ -173,12 +183,47 @@ export async function saveRecentDocument(lastOpened: doc.lastOpened ?? Date.now(),};+ const dedupTargetPath = isDeduplicableDiskPath(fullDoc.path)+ ? normalizePathForComparison(fullDoc.path)+ : '';+try {const db = await openDB();await new Promise<void>((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readwrite');- const req = tx.objectStore(STORE_NAME).put(fullDoc);- req.onerror = () => reject(req.error);+ const store = tx.objectStore(STORE_NAME);++ const writeDeduped = (existingDocs: RecentDocument[]) => {+ let preservedStarred = fullDoc.isStarred;+ for (const existing of existingDocs) {+ if (existing.id === fullDoc.id) {+ preservedStarred = preservedStarred || Boolean(existing.isStarred);+ continue;+ }+ if (+ dedupTargetPath &&+ isDeduplicableDiskPath(existing.path) &&+ normalizePathForComparison(existing.path) === dedupTargetPath+ ) {+ preservedStarred = preservedStarred || Boolean(existing.isStarred);+ store.delete(existing.id);+ }+ }+ store.put({ ...fullDoc, isStarred: preservedStarred });+ };++ if (dedupTargetPath) {+ const getAllReq = store.getAll();+ getAllReq.onsuccess = () => {+ writeDeduped((getAllReq.result as RecentDocument[]) || []);+ };+ getAllReq.onerror = () => {+ store.put(fullDoc);+ };+ } else {+ store.put(fullDoc);+ }+tx.oncomplete = () => resolve();tx.onerror = () => reject(tx.error);});@@ -201,8 +246,23 @@ export async function saveRecentDocument(}handleIndexedDbError(err, 'recent document thumbnail');// Fallback to localStorage without heavy thumbnail payloads or file handles- const current = getFallbackDocs().filter((d) => d.id !== fullDoc.id);- writeFallbackDocs([stripForLocalStorage(fullDoc), ...current]);+ let preservedStarred = fullDoc.isStarred;+ const current = getFallbackDocs().filter((d) => {+ if (d.id === fullDoc.id) {+ preservedStarred = preservedStarred || Boolean(d.isStarred);+ return false;+ }+ if (+ dedupTargetPath &&+ isDeduplicableDiskPath(d.path) &&+ normalizePathForComparison(d.path) === dedupTargetPath+ ) {+ preservedStarred = preservedStarred || Boolean(d.isStarred);+ return false;+ }+ return true;+ });+ writeFallbackDocs([stripForLocalStorage({ ...fullDoc, isStarred: preservedStarred }), ...current]);}}diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.tsindex f480372..32b23c0 100644--- a/src/utils/saveManager.ts+++ b/src/utils/saveManager.ts@@ -50,3 +50,13 @@ export {saveToExistingHandle,promptExportPngImage,} from './saveManager/fileActions';++export {+ KNOWN_DOCUMENT_EXTENSIONS,+ normalizeExtension,+ stripDocumentExtensions,+ sanitizeDocumentStem,+ buildCleanFileName,+ normalizeSavedFileName,+ getParentDirectory,+} from './saveManager/fileNameUtils';diff --git a/src/utils/saveManager/cpuComposite.ts b/src/utils/saveManager/cpuComposite.tsindex 4ccefc8..ed56122 100644--- a/src/utils/saveManager/cpuComposite.ts+++ b/src/utils/saveManager/cpuComposite.ts@@ -141,12 +141,16 @@ export function compositeCanvasCpuFallback(for (const frame of frames) {renderFrameBorder(fCtx, frame, false);}+ const maskedFolder = getMaskedLayerCanvas(baseLayer, folderCanvas);targetCtx.save();targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);- targetCtx.drawImage(folderCanvas, 0, 0);+ targetCtx.drawImage(maskedFolder.canvas, 0, 0);targetCtx.restore();+ if (maskedFolder.isTemporary) {+ releaseTemporaryCanvas(maskedFolder.canvas);+ }}releaseTemporaryCanvas(folderCanvas);continue;@@ -154,7 +158,8 @@ export function compositeCanvasCpuFallback(if (baseLayer.type === 'folder') {const folderAlpha = opacityMul * baseLayer.opacity;- if (baseLayer.blendMode === 'pass-through') {+ const hasFolderMask = Boolean(baseLayer.maskCanvas && baseLayer.maskEnabled !== false);+ if (baseLayer.blendMode === 'pass-through' && !hasFolderMask) {if (baseNode.children.length > 0) {renderTreeNodes(targetCtx, baseNode.children, folderAlpha);}@@ -167,11 +172,16 @@ export function compositeCanvasCpuFallback(if (baseNode.children.length > 0) {renderTreeNodes(fCtx, baseNode.children, 1.0);}+ const maskedFolder = getMaskedLayerCanvas(baseLayer, folderCanvas);targetCtx.save();targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);- targetCtx.drawImage(folderCanvas, 0, 0);+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);+ targetCtx.drawImage(maskedFolder.canvas, 0, 0);targetCtx.restore();+ if (maskedFolder.isTemporary) {+ releaseTemporaryCanvas(maskedFolder.canvas);+ }}releaseTemporaryCanvas(folderCanvas);}diff --git a/src/utils/saveManager/fileActions.ts b/src/utils/saveManager/fileActions.tsindex b84b6f6..62176ea 100644--- a/src/utils/saveManager/fileActions.ts+++ b/src/utils/saveManager/fileActions.ts@@ -16,6 +16,69 @@ import { hydratePagedTilesForLayers } from './exportGridPrep';import { buildPsdLayerTree } from './psdExport';import { compositeCanvasAsync } from './gpuComposite';import { serializeInkProject } from './inkSerialize';+import {+ getRememberedSaveDir,+ rememberSaveDir,+} from '../fileSaveDialog';+import {+ buildCleanFileName,+ getParentDirectory,+ normalizeExtension,+ normalizeSavedFileName,+ sanitizeDocumentStem,+} from './fileNameUtils';++interface NativePickSavePathResponse {+ canceled: boolean;+ fileName?: string | null;+ path?: string | null;+ directory?: string | null;+ extension?: string | null;+ filterIndex?: number;+}++interface SaveFilterSpec {+ name: string;+ extensions: string[];+}++function isTauriDesktopEnv(): boolean {+ return (+ typeof window !== 'undefined' &&+ Boolean((window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__)+ );+}++async function toRawBytes(serialized: {+ data: Blob | ArrayBuffer;+ rawBytes?: Uint8Array;+}): Promise<Uint8Array> {+ if (serialized.rawBytes) return serialized.rawBytes;+ if (serialized.data instanceof Blob) {+ return new Uint8Array(await serialized.data.arrayBuffer());+ }+ return new Uint8Array(serialized.data);+}++const PROJECT_SAVE_FILTERS: SaveFilterSpec[] = [+ { name: 'Ink Studio Project', extensions: ['ink'] },+ { name: 'Photoshop Document with Layers', extensions: ['psd'] },+ { name: 'PNG Image', extensions: ['png'] },+ { name: 'JPEG Image', extensions: ['jpg', 'jpeg'] },+ { name: 'WebP Image', extensions: ['webp'] },+];++const IMAGE_EXPORT_FILTERS: SaveFilterSpec[] = [+ { name: 'PNG Image', extensions: ['png'] },+ { name: 'JPEG Image', extensions: ['jpg', 'jpeg'] },+ { name: 'WebP Image', extensions: ['webp'] },+];++function findFilterIndexForExt(filters: SaveFilterSpec[], ext: string): number {+ const bare = ext.replace(/^\./, '').toLowerCase();+ const idx = filters.findIndex((f) => f.extensions.includes(bare));+ return idx >= 0 ? idx : 0;+}/*** Pixel-accurate tiled GPU image exporter (PNG / JPEG / WebP) with automatic@@ -86,7 +149,12 @@ export async function exportImage(export async function serializeDocument(data: SaveDocumentData,extension: string-): Promise<{ data: Blob | ArrayBuffer; mimeType: string; previewDataUrl?: string }> {+): Promise<{+ data: Blob | ArrayBuffer;+ rawBytes?: Uint8Array;+ mimeType: string;+ previewDataUrl?: string;+}> {const ext = extension.toLowerCase();const tileGrid =data.tileGrid ??@@ -134,6 +202,7 @@ export async function serializeDocument(return {data: psdBuffer,+ rawBytes: new Uint8Array(psdBuffer),mimeType: 'image/vnd.adobe.photoshop',};} finally {@@ -151,6 +220,7 @@ export async function serializeDocument(const result = await serializeInkProject(data, tileGrid);return {data: new Blob([result.bytes as BlobPart], { type: 'application/octet-stream' }),+ rawBytes: result.bytes,mimeType: 'application/octet-stream',previewDataUrl: result.previewDataUrl,};@@ -208,54 +278,136 @@ function getSerializedByteSize(content: Blob | ArrayBuffer): number {}/**- * Prompts user to select save location and extension via File System Access API or fallback.+ * Prompts user to select save location and format via native OS dialog (Tauri Desktop),+ * File System Access API (`showSaveFilePicker`), or anchor download fallback.+ *+ * Always picks the target path & format FIRST before serializing so Cancel does zero work+ * and the saved bytes always match the chosen format with a single clean extension.*/export async function promptSaveAs(data: SaveDocumentData,defaultExtension: string = PRIMARY_PROJECT_EXTENSION,- fallbackToDownload: boolean = true+ fallbackToDownload: boolean = true,+ options?: { initialDir?: string }): Promise<SavedFileInfo> {- const resolvedDefaultExt =- defaultExtension.toLowerCase() === '.sora' ? PRIMARY_PROJECT_EXTENSION : defaultExtension;- const safeName = data.name.trim().replace(/[^a-zA-Z0-9_\- ]/g, '_') || 'Untitled';- const suggestedName = `${safeName}${resolvedDefaultExt}`;+ const resolvedDefaultExt = normalizeExtension(+ defaultExtension.toLowerCase() === '.sora' ? PRIMARY_PROJECT_EXTENSION : defaultExtension,+ PRIMARY_PROJECT_EXTENSION+ );+ const cleanStem = sanitizeDocumentStem(data.name, 'Untitled');+ const suggestedName = buildCleanFileName(cleanStem, resolvedDefaultExt, 'Untitled');- const types = [+ // 1. Native OS Save As dialog in Tauri Desktop (pick path FIRST -> serialize ONCE -> atomic write)+ if (isTauriDesktopEnv()) {+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const initialDir = options?.initialDir || getRememberedSaveDir('project') || undefined;+ const defaultFilterIndex = findFilterIndexForExt(PROJECT_SAVE_FILTERS, resolvedDefaultExt);++ const picked = await invoke<NativePickSavePathResponse>('native_pick_save_path', {+ suggestedName: cleanStem,+ filters: PROJECT_SAVE_FILTERS,+ defaultFilterIndex,+ title: 'Save As',+ initialDir: initialDir ?? null,+ });++ if (picked?.canceled) {+ throw new Error('Save canceled');+ }+ if (picked?.path) {+ const chosenPath = picked.path;+ const normalized = normalizeSavedFileName(+ picked.fileName || suggestedName,+ picked.extension || resolvedDefaultExt+ );+ const serialized = await serializeDocument(+ { ...data, name: normalized.stem },+ normalized.extension+ );+ const rawBytes = await toRawBytes(serialized);+ await invoke<number>('write_allowed_file_binary', rawBytes, {+ headers: {+ 'x-path': encodeURIComponent(chosenPath),+ },+ });++ const dir = picked.directory || getParentDirectory(chosenPath);+ if (dir) {+ rememberSaveDir('project', dir);+ }+ if (data.tabId) {+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);+ }++ return {+ name: normalized.fileName,+ path: chosenPath,+ extension: normalized.extension,+ size: rawBytes.byteLength,+ previewDataUrl: serialized.previewDataUrl,+ };+ }+ } catch (err: unknown) {+ if (err instanceof Error && err.message === 'Save canceled') {+ throw err;+ }+ console.warn('Native pick-and-save dialog failed, falling back:', err);+ }+ }++ const allPickerTypes = [{+ ext: '.ink',description: 'Ink Studio Project (*.ink)',accept: { 'application/octet-stream': ['.ink'] },},{+ ext: '.psd',description: 'Photoshop Document with Layers (*.psd)',accept: { 'image/vnd.adobe.photoshop': ['.psd'] },},{+ ext: '.png',description: 'PNG Image (*.png)',accept: { 'image/png': ['.png'] },},{+ ext: '.jpg',description: 'JPEG Image (*.jpg, *.jpeg)',accept: { 'image/jpeg': ['.jpg', '.jpeg'] },},{+ ext: '.webp',description: 'WebP Image (*.webp)',accept: { 'image/webp': ['.webp'] },},];+ // Put the active format first so Chromium's save picker defaults to it cleanly+ const preferredKey = resolvedDefaultExt === '.jpeg' ? '.jpg' : resolvedDefaultExt;+ const types = [+ ...allPickerTypes.filter((t) => t.ext === preferredKey),+ ...allPickerTypes.filter((t) => t.ext !== preferredKey),+ ].map(({ description, accept }) => ({ description, accept }));+ // 2. Browser File System Access API (`showSaveFilePicker`)if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {try {const handle = await (window as any).showSaveFilePicker({suggestedName,+ id: 'inkstudio-project',types,});- const fileName = handle.name;- const ext = fileName.includes('.')- ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()- : resolvedDefaultExt;+ const normalized = normalizeSavedFileName(+ handle.name || suggestedName,+ resolvedDefaultExt+ );- const serialized = await serializeDocument(data, ext);+ const serialized = await serializeDocument(+ { ...data, name: normalized.stem },+ normalized.extension+ );const writable = await handle.createWritable();await writable.write(serialized.data);await writable.close();@@ -266,8 +418,8 @@ export async function promptSaveAs(return {handle,- name: fileName,- extension: ext,+ name: handle.name || normalized.fileName,+ extension: normalized.extension,size: getSerializedByteSize(serialized.data),previewDataUrl: serialized.previewDataUrl,};@@ -279,9 +431,12 @@ export async function promptSaveAs(}}+ // 3. Anchor download fallbackif (fallbackToDownload) {- const ext = resolvedDefaultExt;- const serialized = await serializeDocument(data, ext);+ const serialized = await serializeDocument(+ { ...data, name: cleanStem },+ resolvedDefaultExt+ );downloadFile(serialized.data, suggestedName, serialized.mimeType);if (data.tabId) {@@ -290,7 +445,7 @@ export async function promptSaveAs(return {name: suggestedName,- extension: ext,+ extension: resolvedDefaultExt,size: getSerializedByteSize(serialized.data),previewDataUrl: serialized.previewDataUrl,};@@ -300,17 +455,59 @@ export async function promptSaveAs(}/**- * Writes directly to an already selected FileSystemFileHandle without prompting.+ * Writes directly to an already selected FileSystemFileHandle or authorized Tauri disk path without prompting.*/export async function saveToExistingHandle(data: SaveDocumentData,fileInfo: SavedFileInfo): Promise<{ size: number; previewDataUrl?: string }> {- if (!fileInfo.handle || typeof fileInfo.handle.createWritable !== 'function') {- throw new Error('No valid file handle to save to');+ const hasWebHandle = Boolean(+ fileInfo.handle && typeof fileInfo.handle.createWritable === 'function'+ );+ const hasNativePath = Boolean(+ isTauriDesktopEnv() && fileInfo.path && fileInfo.path.trim().length > 0+ );++ if (!hasWebHandle && !hasNativePath) {+ throw new Error('No valid file handle or disk path to save to');+ }++ const cleanStem = sanitizeDocumentStem(fileInfo.name || data.name, 'Untitled');+ const targetExt = normalizeExtension(fileInfo.extension, PRIMARY_PROJECT_EXTENSION);++ // Prefer native atomic Tauri disk write when running on desktop with a real file path+ if (hasNativePath) {+ const serialized = await serializeDocument({ ...data, name: cleanStem }, targetExt);+ const { invoke } = await import('@tauri-apps/api/core');+ const bytes = await toRawBytes(serialized);+ await invoke<number>('write_allowed_file_binary', bytes, {+ headers: {+ 'x-path': encodeURIComponent(fileInfo.path!),+ },+ });++ if (data.tabId) {+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);+ }++ return {+ size: bytes.byteLength,+ previewDataUrl: serialized.previewDataUrl,+ };}- const serialized = await serializeDocument(data, fileInfo.extension);+ // Web File System Access API: verify/request readwrite permission before serializing+ if (typeof fileInfo.handle.queryPermission === 'function') {+ let perm = await fileInfo.handle.queryPermission({ mode: 'readwrite' });+ if (perm !== 'granted' && typeof fileInfo.handle.requestPermission === 'function') {+ perm = await fileInfo.handle.requestPermission({ mode: 'readwrite' });+ }+ if (perm !== 'granted') {+ throw new Error('Write permission denied for file handle');+ }+ }++ const serialized = await serializeDocument({ ...data, name: cleanStem }, targetExt);const writable = await fileInfo.handle.createWritable();await writable.write(serialized.data);await writable.close();@@ -326,14 +523,63 @@ export async function saveToExistingHandle(}/**- * Prompts user to choose a download/save path specifically for an exported image (PNG / JPG / WebP).+ * Prompts user to choose a save path specifically for an exported flattened image (PNG / JPG / WebP).*/export async function promptExportPngImage(data: SaveDocumentData,- defaultName?: string+ defaultName?: string,+ options?: { initialDir?: string }): Promise<string> {- const safeName = (defaultName || data.name || 'artwork').trim().replace(/[^a-zA-Z0-9_\- ]/g, '_');- const suggestedName = `${safeName}.png`;+ const cleanStem = sanitizeDocumentStem(defaultName || data.name, 'artwork');+ const suggestedName = buildCleanFileName(cleanStem, '.png', 'artwork');++ // 1. Native OS Save As dialog in Tauri Desktop (pick path & format FIRST -> serialize ONCE -> atomic write)+ if (isTauriDesktopEnv()) {+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const initialDir = options?.initialDir || getRememberedSaveDir('project') || undefined;+ const picked = await invoke<NativePickSavePathResponse>('native_pick_save_path', {+ suggestedName: cleanStem,+ filters: IMAGE_EXPORT_FILTERS,+ defaultFilterIndex: 0,+ title: 'Export Image As',+ initialDir: initialDir ?? null,+ });+ if (picked?.canceled) {+ throw new Error('Export canceled');+ }+ if (picked?.path) {+ const chosenPath = picked.path;+ const normalized = normalizeSavedFileName(+ picked.fileName || suggestedName,+ picked.extension || '.png'+ );+ const exportExt =+ normalized.extension === '.jpg' ||+ normalized.extension === '.jpeg' ||+ normalized.extension === '.webp'+ ? normalized.extension+ : '.png';+ const serialized = await serializeDocument({ ...data, name: normalized.stem }, exportExt);+ const rawBytes = await toRawBytes(serialized);+ await invoke<number>('write_allowed_file_binary', rawBytes, {+ headers: {+ 'x-path': encodeURIComponent(chosenPath),+ },+ });+ const dir = picked.directory || getParentDirectory(chosenPath);+ if (dir) {+ rememberSaveDir('project', dir);+ }+ return normalized.fileName;+ }+ } catch (err: unknown) {+ if (err instanceof Error && err.message === 'Export canceled') {+ throw err;+ }+ console.warn('Native export dialog unavailable, falling back:', err);+ }+ }const types = [{@@ -350,23 +596,28 @@ export async function promptExportPngImage(},];+ // 2. Browser File System Access APIif (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {try {const handle = await (window as any).showSaveFilePicker({suggestedName,+ id: 'inkstudio-export-image',types,});- const fileName: string = handle.name;- const ext = fileName.includes('.')- ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()- : '.png';- const serialized = await serializeDocument(data, ext);+ const normalized = normalizeSavedFileName(handle.name || suggestedName, '.png');+ const exportExt =+ normalized.extension === '.jpg' ||+ normalized.extension === '.jpeg' ||+ normalized.extension === '.webp'+ ? normalized.extension+ : '.png';+ const serialized = await serializeDocument({ ...data, name: normalized.stem }, exportExt);const writable = await handle.createWritable();await writable.write(serialized.data);await writable.close();- return fileName;+ return handle.name || normalized.fileName;} catch (err: any) {if (err.name === 'AbortError') {throw new Error('Export canceled');@@ -375,7 +626,8 @@ export async function promptExportPngImage(}}- const serialized = await serializeDocument(data, '.png');+ // 3. Anchor download fallback+ const serialized = await serializeDocument({ ...data, name: cleanStem }, '.png');downloadFile(serialized.data, suggestedName, 'image/png');return suggestedName;}diff --git a/src/utils/saveManager/fileNameUtils.ts b/src/utils/saveManager/fileNameUtils.tsnew file mode 100644index 0000000..641baab--- /dev/null+++ b/src/utils/saveManager/fileNameUtils.ts@@ -0,0 +1,166 @@+/**+ * Canonical filename and extension hygiene utilities for Ink Studio saves, resaves, and exports.+ *+ * Guarantees that repeated Save / Save As / Export / Reopen cycles never accumulate chained+ * extensions like `Artwork.ink.ink.ink.png.ink`, while preserving Unicode names and intentional+ * dots inside titles (e.g. `Chapter 1.2`, `Page v2.0`).+ */++export const KNOWN_DOCUMENT_EXTENSIONS = new Set([+ '.ink',+ '.sora',+ '.psd',+ '.psb',+ '.clip',+ '.csp',+ '.lip',+ '.png',+ '.jpg',+ '.jpeg',+ '.webp',+ '.bmp',+ '.gif',+ '.svg',+]);++function extractBaseName(raw: string): string {+ const normalized = raw.replace(/\\/g, '/');+ const slash = normalized.lastIndexOf('/');+ return slash >= 0 ? normalized.slice(slash + 1) : normalized;+}++function stripIllegalFileChars(raw: string): string {+ let out = '';+ for (let i = 0; i < raw.length; i++) {+ const ch = raw[i];+ const code = raw.charCodeAt(i);+ if (code < 0x20 || code === 0x7f) continue;+ if (+ ch === '<' ||+ ch === '>' ||+ ch === ':' ||+ ch === '"' ||+ ch === '/' ||+ ch === '\\' ||+ ch === '|' ||+ ch === '?' ||+ ch === '*'+ ) {+ continue;+ }+ out += ch;+ }+ return out;+}++/**+ * Normalizes an extension string to lowercase with a single leading dot (e.g. `'INK'` -> `'.ink'`).+ */+export function normalizeExtension(ext: string, fallback: string = '.ink'): string {+ const cleaned = (ext || '')+ .trim()+ .toLowerCase()+ .replace(/^\.+/, '')+ .replace(/[^a-z0-9_-]/g, '');+ if (!cleaned) return fallback;+ return `.${cleaned}`;+}++/**+ * Strips any directory prefix, trailing unsaved `*` markers, and ALL chained trailing known+ * document/image extensions (e.g. `"Hero.ink.ink.png.ink*"` -> `"Hero"`), while preserving+ * non-extension dots like `"Chapter 1.2"`.+ */+export function stripDocumentExtensions(rawName: string | null | undefined): string {+ if (!rawName || typeof rawName !== 'string') return '';+ let current = extractBaseName(rawName).trim().replace(/\*+$/g, '').trim();++ while (current.length > 0) {+ const lastDot = current.lastIndexOf('.');+ if (lastDot <= 0) break;+ const tail = current.slice(lastDot).toLowerCase();+ if (KNOWN_DOCUMENT_EXTENSIONS.has(tail)) {+ const next = current.slice(0, lastDot).replace(/[.\s]+$/g, '');+ if (!next) break;+ current = next;+ } else {+ break;+ }+ }++ return current;+}++/**+ * Produces a filesystem-safe document stem with all chained known extensions stripped.+ * Preserves Unicode characters, spaces, hyphens, underscores, and dots in version numbers.+ */+export function sanitizeDocumentStem(+ rawName: string | null | undefined,+ fallback: string = 'Untitled'+): string {+ const stripped = stripDocumentExtensions(rawName);+ const safe = stripIllegalFileChars(stripped)+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/^\.+|\.+$/g, '')+ .trim();+ return safe || fallback;+}++/**+ * Builds a clean `stem.ext` filename guaranteed to have exactly one clean extension.+ */+export function buildCleanFileName(+ rawName: string | null | undefined,+ extension: string,+ fallback: string = 'Untitled'+): string {+ const stem = sanitizeDocumentStem(rawName, fallback);+ const ext = normalizeExtension(extension);+ return `${stem}${ext}`;+}++/**+ * Extracts the final known extension and clean stem from an opened or saved filename.+ * Collapses accidental chained extensions (e.g. `Hero.ink.png` -> stem `Hero`, ext `.png`, fileName `Hero.png`).+ */+export function normalizeSavedFileName(+ rawFileName: string,+ fallbackExt: string = '.ink'+): { fileName: string; stem: string; extension: string } {+ const base = extractBaseName(rawFileName).trim().replace(/\*+$/g, '').trim();+ const lastDot = base.lastIndexOf('.');+ let ext = '';+ if (lastDot > 0) {+ const candidate = base.slice(lastDot).toLowerCase();+ if (KNOWN_DOCUMENT_EXTENSIONS.has(candidate)) {+ ext = candidate;+ }+ }+ const resolvedExt = ext || (fallbackExt ? normalizeExtension(fallbackExt) : '');+ const stem = sanitizeDocumentStem(base, 'Untitled');+ return {+ fileName: resolvedExt ? `${stem}${resolvedExt}` : stem,+ stem,+ extension: resolvedExt,+ };+}++/**+ * Returns the parent directory of a native filesystem path, or `undefined` if none.+ */+export function getParentDirectory(filePath: string | null | undefined): string | undefined {+ if (!filePath || typeof filePath !== 'string') return undefined;+ const trimmed = filePath.trim();+ if (!trimmed) return undefined;+ const lastBack = trimmed.lastIndexOf('\\');+ const lastFwd = trimmed.lastIndexOf('/');+ const idx = Math.max(lastBack, lastFwd);+ if (idx <= 0) return undefined;+ // Preserve Windows drive root `C:\`+ if (idx === 2 && /^[a-zA-Z]:/.test(trimmed)) {+ return trimmed.slice(0, 3);+ }+ return trimmed.slice(0, idx);+}diff --git a/src/utils/saveManager/gpuComposite.ts b/src/utils/saveManager/gpuComposite.tsindex 619f363..88b38da 100644--- a/src/utils/saveManager/gpuComposite.ts+++ b/src/utils/saveManager/gpuComposite.ts@@ -81,6 +81,7 @@ function tryCompositeCanvasGpuSync(colorMode: options?.colorMode,showCheckerboard: false,transparentBackground: !fillWhiteBackground,+ hideArtboardChrome: true,bypassStackCache: true,devicePixelRatio: 1,});@@ -186,6 +187,7 @@ export async function compositeCanvasAsync(colorMode: options?.colorMode,showCheckerboard: false,transparentBackground: !fillWhiteBackground,+ hideArtboardChrome: true,bypassStackCache: true,devicePixelRatio: 1,});@@ -353,6 +355,7 @@ export function createDocumentRegionRenderer(colorMode: options?.colorMode,showCheckerboard: false,transparentBackground: !fillWhiteBackground,+ hideArtboardChrome: true,bypassStackCache: true,devicePixelRatio: 1,});diff --git a/src/utils/saveManager/inkCodec.ts b/src/utils/saveManager/inkCodec.tsindex 00933ff..9fa0c7e 100644--- a/src/utils/saveManager/inkCodec.ts+++ b/src/utils/saveManager/inkCodec.ts@@ -17,14 +17,28 @@ import {} from './types';export function encodeNativeTileRecord(tile: TileBuffer, rawBytes: Uint8Array): Uint8Array {- const fmtByte = INK_TILE_FORMAT_TO_BYTE[tile.format] ?? 2;const out = new Uint8Array(TILE_BINARY_HEADER_BYTES + rawBytes.byteLength);- const view = new DataView(out.buffer, out.byteOffset, out.byteLength);+ return encodeNativeTileRecordInto(tile, rawBytes, out);+}++/**+ * Encodes a tile record into a reusable scratch buffer to avoid allocating a fresh 256 KB+ * Uint8Array per tile on every `.ink` save/resave.+ */+export function encodeNativeTileRecordInto(+ tile: TileBuffer,+ rawBytes: Uint8Array,+ scratch: Uint8Array+): Uint8Array {+ const required = TILE_BINARY_HEADER_BYTES + rawBytes.byteLength;+ const target = scratch.byteLength >= required ? scratch : new Uint8Array(required);+ const fmtByte = INK_TILE_FORMAT_TO_BYTE[tile.format] ?? 2;+ const view = new DataView(target.buffer, target.byteOffset, required);view.setUint8(0, fmtByte);view.setUint32(1, tile.version >>> 0, true);view.setUint32(5, rawBytes.byteLength >>> 0, true);- out.set(rawBytes, TILE_BINARY_HEADER_BYTES);- return out;+ target.set(rawBytes, TILE_BINARY_HEADER_BYTES);+ return target.byteLength === required ? target : target.subarray(0, required);}export function decodeNativeTileRecord(diff --git a/src/utils/saveManager/inkParse.ts b/src/utils/saveManager/inkParse.tsindex 70077b9..bb8f6e4 100644--- a/src/utils/saveManager/inkParse.ts+++ b/src/utils/saveManager/inkParse.ts@@ -383,23 +383,67 @@ export async function parseInkZipBytes(let parsedTimelapse: InkTimelapseMetadata | null = null;if (rawTimelapse) {const hasEmbeddedFrames = sanitizedFrameMetas.length > 0;+ const rawRecordingId =+ typeof rawTimelapse.recordingId === 'string' &&+ rawTimelapse.recordingId.trim().length > 0 &&+ rawTimelapse.recordingId.length <= 128+ ? rawTimelapse.recordingId.trim()+ : undefined;+ const rawStorageMode =+ rawTimelapse.storageMode === 'external' || rawTimelapse.storageMode === 'embedded'+ ? rawTimelapse.storageMode+ : undefined;+ const rawCaptureArea =+ rawTimelapse.captureArea === 'artwork' ||+ rawTimelapse.captureArea === 'canvas-view' ||+ rawTimelapse.captureArea === 'app-window'+ ? rawTimelapse.captureArea+ : undefined;+ const rawCaptureResolution =+ rawTimelapse.captureResolution === '720p' ||+ rawTimelapse.captureResolution === '1080p' ||+ rawTimelapse.captureResolution === '2k' ||+ rawTimelapse.captureResolution === '4k'+ ? rawTimelapse.captureResolution+ : undefined;+ const rawResolution =+ rawTimelapse.resolution === '720p' ||+ rawTimelapse.resolution === '1080p' ||+ rawTimelapse.resolution === '2k' ||+ rawTimelapse.resolution === '4k'+ ? rawTimelapse.resolution+ : undefined;+ const rawAspectRatio =+ rawTimelapse.aspectRatio === 'original' ||+ rawTimelapse.aspectRatio === '16:9' ||+ rawTimelapse.aspectRatio === '9:16' ||+ rawTimelapse.aspectRatio === '1:1' ||+ rawTimelapse.aspectRatio === '4:5'+ ? rawTimelapse.aspectRatio+ : undefined;+ const rawQuality =+ rawTimelapse.quality === 'standard' ||+ rawTimelapse.quality === 'high' ||+ rawTimelapse.quality === 'ultra' ||+ rawTimelapse.quality === 'lossless'+ ? rawTimelapse.quality+ : undefined;+const baseMeta: InkTimelapseMetadata = {+ ...(rawRecordingId ? { recordingId: rawRecordingId } : {}),+ ...(rawStorageMode ? { storageMode: rawStorageMode } : {}),enabled: Boolean(rawTimelapse.enabled),frameCount: hasEmbeddedFrames? sanitizedFrameMetas.length: Math.max(0, Math.floor(Number(rawTimelapse.frameCount) || 0)),+ ...(rawCaptureArea ? { captureArea: rawCaptureArea } : {}),+ ...(rawCaptureResolution ? { captureResolution: rawCaptureResolution } : {}),...(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 }- : {}),+ ...(rawResolution ? { resolution: rawResolution } : {}),+ ...(rawAspectRatio ? { aspectRatio: rawAspectRatio } : {}),+ ...(rawQuality ? { quality: rawQuality } : {}),...(typeof rawTimelapse.nextIndex === 'number' &&Number.isSafeInteger(rawTimelapse.nextIndex) &&rawTimelapse.nextIndex >= 0diff --git a/src/utils/saveManager/inkSerialize.ts b/src/utils/saveManager/inkSerialize.tsindex 6336139..d2eca2a 100644--- a/src/utils/saveManager/inkSerialize.ts+++ b/src/utils/saveManager/inkSerialize.ts@@ -28,9 +28,11 @@ import {import { inferLayerTileFormat } from './exportGridPrep';import {encodeMaskBinary,- encodeNativeTileRecord,+ encodeNativeTileRecordInto,generatePreviewPng,} from './inkCodec';+import { sanitizeDocumentStem } from './fileNameUtils';+import { TILE_BINARY_HEADER_BYTES } from './types';/*** Serializes a document into the native binary `.ink` ZIP container:@@ -50,7 +52,9 @@ export async function serializeInkProject(manifest: InkProjectManifest;}> {const onProgress = data.onProgress;- const tileCompressionLevel = data.compressionLevel ?? 3;+ // Level 1 DEFLATE in fflate is ~2.5-3.5x faster than level 3 on RGBA tile buffers with+ // nearly identical file size, making repeated Ctrl+S resaves snappy.+ const tileCompressionLevel = data.compressionLevel ?? 1;const resolvedGrid =tileGrid ??data.tileGrid ??@@ -147,18 +151,24 @@ export async function serializeInkProject(});const preview = await generatePreviewPng(data, resolvedGrid);- // Wait for any in-flight timelapse keyframe capture so the latest stroke is included in the save+ // Time-lapse keyframes are persisted in external local storage rather than embedded inside .ink+ // archives (keeping saves fast and project files lightweight). Legacy embedding only runs if+ // `embedTimelapseFrames` is explicitly requested.+ const shouldEmbedFrames = Boolean(data.embedTimelapseFrames);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 explicitTimelapseFrames =+ shouldEmbedFrames && Array.isArray(data.timelapseFrames) ? data.timelapseFrames : null;+ const timelapseFramesSourceCount = shouldEmbedFrames+ ? explicitTimelapseFrames+ ? explicitTimelapseFrames.length+ : tlSnapshot+ ? tlSnapshot.frames.length+ : 0+ : 0;const hasTimelapseFramesToWrite = timelapseFramesSourceCount > 0;const tilesEndPct = hasTimelapseFramesToWrite ? 70 : 85;@@ -185,6 +195,10 @@ export async function serializeInkProject(}const totalTiles = pendingTiles.length;+ // Reuse a single scratch buffer across tiles to eliminate per-tile 256 KB GC allocations+ let tileScratch = new Uint8Array(0);+ const zeroFallbackByFormat = new Map<TileFormat, Uint8Array>();+for (let i = 0; i < totalTiles; i++) {const { tile, sourceGrid, path } = pendingTiles[i];@@ -196,10 +210,19 @@ export async function serializeInkProject(}}if (!rawBytes) {- rawBytes = new Uint8Array(getTileByteSize(tile.format));+ let zeros = zeroFallbackByFormat.get(tile.format);+ if (!zeros) {+ zeros = new Uint8Array(getTileByteSize(tile.format));+ zeroFallbackByFormat.set(tile.format, zeros);+ }+ rawBytes = zeros;}- const record = encodeNativeTileRecord(tile, rawBytes);+ const requiredScratch = TILE_BINARY_HEADER_BYTES + rawBytes.byteLength;+ if (tileScratch.byteLength < requiredScratch) {+ tileScratch = new Uint8Array(requiredScratch);+ }+ const record = encodeNativeTileRecordInto(tile, rawBytes, tileScratch);const entry = new ZipDeflate(path, { level: tileCompressionLevel });zip.add(entry);entry.push(record, true);@@ -326,10 +349,11 @@ export async function serializeInkProject(}let manifestTimelapse: InkTimelapseMetadata | null;- if (explicitTimelapseFrames !== null || tlProvider !== null) {+ if (shouldEmbedFrames && (explicitTimelapseFrames !== null || tlProvider !== null)) {const enabled = tlSnapshot? Boolean(tlSnapshot.enabled): Boolean(data.timelapse?.enabled);+ const recordingId = tlSnapshot?.recordingId ?? data.timelapse?.recordingId;if (enabled || savedTimelapseFrames.length > 0) {const maxSavedNextIndex = savedTimelapseFrames.reduce((max, f) => Math.max(max, f.index + 1),@@ -341,6 +365,7 @@ export async function serializeInkProject(maxSavedNextIndex);manifestTimelapse = {+ ...(recordingId ? { recordingId } : {}),...(data.timelapse?.fps !== undefined ? { fps: data.timelapse.fps } : {}),...(data.timelapse?.resolution !== undefined? { resolution: data.timelapse.resolution }@@ -348,16 +373,63 @@ export async function serializeInkProject(...(data.timelapse?.aspectRatio !== undefined? { aspectRatio: data.timelapse.aspectRatio }: {}),+ ...(data.timelapse?.quality !== undefined ? { quality: data.timelapse.quality } : {}),+ ...(tlSnapshot?.captureArea ?? data.timelapse?.captureArea+ ? { captureArea: tlSnapshot?.captureArea ?? data.timelapse?.captureArea }+ : {}),+ ...(tlSnapshot?.captureResolution ?? data.timelapse?.captureResolution+ ? {+ captureResolution:+ tlSnapshot?.captureResolution ?? data.timelapse?.captureResolution,+ }+ : {}),enabled,frameCount: savedTimelapseFrames.length,nextIndex,- ...(savedTimelapseFrames.length > 0 ? { frames: savedTimelapseFrames } : {}),+ ...(savedTimelapseFrames.length > 0+ ? { storageMode: 'embedded', frames: savedTimelapseFrames }+ : {}),+ };+ } else {+ manifestTimelapse = null;+ }+ } else if (tlSnapshot) {+ const enabled = Boolean(tlSnapshot.enabled);+ const frameCount = tlSnapshot.frames.length;+ const recordingId = tlSnapshot.recordingId ?? data.timelapse?.recordingId;+ if (enabled || frameCount > 0) {+ manifestTimelapse = {+ ...(recordingId ? { recordingId, storageMode: 'external' as const } : {}),+ enabled,+ frameCount,+ nextIndex: Math.max(tlSnapshot.nextIndex, data.timelapse?.nextIndex ?? 0),+ ...(tlSnapshot.captureArea ?? data.timelapse?.captureArea+ ? { captureArea: tlSnapshot.captureArea ?? data.timelapse?.captureArea }+ : {}),+ ...(tlSnapshot.captureResolution ?? data.timelapse?.captureResolution+ ? {+ captureResolution:+ tlSnapshot.captureResolution ?? data.timelapse?.captureResolution,+ }+ : {}),+ ...(data.timelapse?.fps !== undefined ? { fps: data.timelapse.fps } : {}),+ ...(data.timelapse?.resolution !== undefined+ ? { resolution: data.timelapse.resolution }+ : {}),+ ...(data.timelapse?.aspectRatio !== undefined+ ? { aspectRatio: data.timelapse.aspectRatio }+ : {}),+ ...(data.timelapse?.quality !== undefined ? { quality: data.timelapse.quality } : {}),};} else {manifestTimelapse = null;}+ } else if (data.timelapse) {+ // Strip any embedded frame descriptors when writing lightweight external reference metadata+ const { frames: _stripFrames, ...lightweightMeta } = data.timelapse;+ manifestTimelapse = lightweightMeta;} else {- manifestTimelapse = data.timelapse ?? null;+ manifestTimelapse = null;}const manifest: InkProjectManifest = {@@ -365,7 +437,7 @@ export async function serializeInkProject(app: 'Ink Studio',version: '2.0',tileSize: TILE_SIZE,- name: data.name,+ name: sanitizeDocumentStem(data.name, 'Untitled'),dimensions: {width: data.dimensions.width,height: data.dimensions.height,diff --git a/src/utils/saveManager/psdExport.ts b/src/utils/saveManager/psdExport.tsindex 41fbbba..bcbc292 100644--- a/src/utils/saveManager/psdExport.ts+++ b/src/utils/saveManager/psdExport.ts@@ -13,6 +13,7 @@ import {import type { LayerTreeNode } from '../compositor';import { SparseTileGrid, TILE_SIZE } from '../tileEngine';import { acquireLayerExportCanvas } from './exportGridPrep';+import { toPsdLayerColor } from '../layerOrganization';/*** Maps Ink Studio BlendMode to ag-psd BlendMode format.@@ -193,6 +194,11 @@ export function buildPsdLayerTree(psdLayer.clipping = true;}+ const psdColor = toPsdLayerColor(layer.colorLabel);+ if (psdColor) {+ psdLayer.layerColor = psdColor;+ }+if (layer.alphaLocked || layer.locked) {psdLayer.protected = {transparency: Boolean(layer.alphaLocked),diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.tsindex ceff779..de5d159 100644--- a/src/utils/saveManager/types.ts+++ b/src/utils/saveManager/types.ts@@ -8,6 +8,7 @@ import type {} from '../../types/editor';import type { PerspectiveRuler } from '../../types/perspective';import type { SparseTileGrid, TileFormat } from '../tileEngine';+import { normalizeLayerColorLabel } from '../layerOrganization';export const PRIMARY_PROJECT_EXTENSION = '.ink';@@ -21,8 +22,11 @@ export interface TimelapsePersistenceFrameMeta {}export interface TimelapsePersistenceSnapshot {+ recordingId?: string;enabled: boolean;nextIndex: number;+ captureArea?: import('../../types/editor').TimelapseCaptureArea;+ captureResolution?: import('../../types/editor').TimelapseCaptureResolution;frames: TimelapsePersistenceFrameMeta[];}@@ -34,6 +38,7 @@ export interface TimelapsePersistenceProvider {export interface SavedFileInfo {handle?: any; // FileSystemFileHandle+ path?: string; // Native desktop filesystem path (Tauri)name: string;extension: string;size?: number;@@ -70,8 +75,11 @@ export interface SaveDocumentData {perspectiveRuler?: PerspectiveRuler | null;animationTimeline?: AnimationTimeline | null;timelapse?: InkTimelapseMetadata | null;+ /** Legacy embedded frames (only written if `embedTimelapseFrames` is explicitly true). */timelapseFrames?: InkTimelapseFrameData[] | null;timelapseFrameProvider?: TimelapsePersistenceProvider | null;+ /** Defaults to false: time-lapse frames live in external persistent storage rather than bloating .ink files. */+ embedTimelapseFrames?: boolean;workTimeMs?: number;onProgress?: (progress: SaveProgress) => void;compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;@@ -253,6 +261,9 @@ export function sanitizeJsonLayer(raw: any): LayerItem {if (normalized.maskCanvas && typeof normalized.maskCanvas.getContext !== 'function') {normalized.maskCanvas = undefined;}+ if (normalized.colorLabel !== undefined) {+ normalized.colorLabel = normalizeLayerColorLabel(normalized.colorLabel);+ }return normalized;}diff --git a/src/utils/subViewEngine.ts b/src/utils/subViewEngine.tsnew file mode 100644index 0000000..9341efb--- /dev/null+++ b/src/utils/subViewEngine.ts@@ -0,0 +1,933 @@+import { computePerceptualLuminanceByte, clampNavigatorSplitRatio } from './valueCheck';++export const SUB_VIEW_MIN_ZOOM = 0.05;+export const SUB_VIEW_MAX_ZOOM = 16.0;+export const BOARD_MIN_CARD_SCALE = 0.04;+export const BOARD_MAX_CARD_SCALE = 12.0;+export const DEFAULT_BOARD_CARD_TARGET_DIM = 220;++export type SubViewMode = 'board' | 'single';+export type SubViewBoardTool = 'eyedrop' | 'select' | 'pan';+export type SubViewValueSteps = 0 | 2 | 3 | 5;+export type SubViewGridMode = 'none' | 'thirds' | 'grid4' | 'grid8' | 'crosshair' | 'golden';+export type SubViewBoardLayoutMode = 'grid' | 'row' | 'column';++export interface SubViewTransform {+ zoom: number;+ pan: { x: number; y: number };+ rotation: number; // degrees+ flipX: boolean;+}++export interface SubViewStudyFilter {+ grayscale: boolean;+ valueSteps: SubViewValueSteps;+ notanThreshold: number; // 0..255+ squintBlur: boolean;+ brightness: number; // -100..100+ contrast: number; // -100..100+ gridMode: SubViewGridMode;+ splitBw: boolean;+ splitRatio: number; // 0.05..0.95+}++export const DEFAULT_SUB_VIEW_TRANSFORM: SubViewTransform = {+ zoom: 1,+ pan: { x: 0, y: 0 },+ rotation: 0,+ flipX: false,+};++export const DEFAULT_SUB_VIEW_STUDY_FILTER: SubViewStudyFilter = {+ grayscale: false,+ valueSteps: 0,+ notanThreshold: 128,+ squintBlur: false,+ brightness: 0,+ contrast: 0,+ gridMode: 'none',+ splitBw: false,+ splitRatio: 0.5,+};++export interface PixelCoord {+ x: number;+ y: number;+}++export interface BoardPoint {+ x: number;+ y: number;+}++export interface BoardCardGeometry {+ id: string;+ width: number;+ height: number;+ boardX: number;+ boardY: number;+ boardScale: number;+ boardRotation: number;+ boardFlipX: boolean;+ boardFlipY: boolean;+ zIndex: number;+ locked?: boolean;+}++export type CardHandleKind = 'tl' | 'tr' | 'br' | 'bl' | 'rotate';++export interface CardStageOverlay {+ tl: BoardPoint;+ tr: BoardPoint;+ br: BoardPoint;+ bl: BoardPoint;+ center: BoardPoint;+ topMid: BoardPoint;+ rotHandle: BoardPoint;+}++export interface BoardHitResult<T extends BoardCardGeometry> {+ card: T;+ pixel: PixelCoord;+ local: BoardPoint;+}++export interface ExtractedSwatch {+ hex: string;+ luminance: number; // 0..100 perceptual value %+ ratio: number; // 0..1 pixel share+}++export function clampSubViewZoom(z: number): number {+ if (!Number.isFinite(z)) return 1;+ return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, z));+}++export function clampBoardCardScale(scale: number): number {+ if (!Number.isFinite(scale)) return 1;+ return Math.max(BOARD_MIN_CARD_SCALE, Math.min(BOARD_MAX_CARD_SCALE, scale));+}++export function clampNotanThreshold(val: number): number {+ if (!Number.isFinite(val)) return 128;+ return Math.max(10, Math.min(245, Math.round(val)));+}++export function clampBrightnessContrast(val: number): number {+ if (!Number.isFinite(val)) return 0;+ return Math.max(-100, Math.min(100, Math.round(val)));+}++export function sanitizeStudyFilter(raw?: Partial<SubViewStudyFilter> | null): SubViewStudyFilter {+ if (!raw || typeof raw !== 'object') {+ return { ...DEFAULT_SUB_VIEW_STUDY_FILTER };+ }+ const valueSteps: SubViewValueSteps =+ raw.valueSteps === 2 || raw.valueSteps === 3 || raw.valueSteps === 5 ? raw.valueSteps : 0;+ const gridMode: SubViewGridMode =+ raw.gridMode === 'thirds' ||+ raw.gridMode === 'grid4' ||+ raw.gridMode === 'grid8' ||+ raw.gridMode === 'crosshair' ||+ raw.gridMode === 'golden'+ ? raw.gridMode+ : 'none';+ return {+ grayscale: Boolean(raw.grayscale),+ valueSteps,+ notanThreshold: clampNotanThreshold(+ typeof raw.notanThreshold === 'number' ? raw.notanThreshold : 128+ ),+ squintBlur: Boolean(raw.squintBlur),+ brightness: clampBrightnessContrast(typeof raw.brightness === 'number' ? raw.brightness : 0),+ contrast: clampBrightnessContrast(typeof raw.contrast === 'number' ? raw.contrast : 0),+ gridMode,+ splitBw: Boolean(raw.splitBw),+ splitRatio: clampNavigatorSplitRatio(+ typeof raw.splitRatio === 'number' ? raw.splitRatio : 0.5+ ),+ };+}++/**+ * Inverse-maps a point `(localX, localY)` inside the Single-mode stage into+ * integer source image pixel coordinates `(x, y)` accounting for pan, zoom, rotation, and flipX.+ * Returns `null` if the point lies outside the image bounds.+ */+export function subViewPointToImagePixel(+ localX: number,+ localY: number,+ stageW: number,+ stageH: number,+ imgW: number,+ imgH: number,+ transform: SubViewTransform+): PixelCoord | null {+ if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return null;+ const safeZoom = Math.max(1e-4, transform.zoom);+ const dx = localX - (stageW / 2 + transform.pan.x);+ const dy = localY - (stageH / 2 + transform.pan.y);++ const rad = (transform.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);++ const unrotX = dx * cos + dy * sin;+ const unrotY = -dx * sin + dy * cos;+ const fx = transform.flipX ? -1 : 1;++ const px = Math.floor(imgW / 2 + (fx * unrotX) / safeZoom);+ const py = Math.floor(imgH / 2 + unrotY / safeZoom);++ if (px < 0 || py < 0 || px >= imgW || py >= imgH) return null;+ return { x: px, y: py };+}++export function computeSubViewFitZoom(+ stageW: number,+ stageH: number,+ imgW: number,+ imgH: number,+ padding = 12+): number {+ if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return 1;+ const availW = Math.max(16, stageW - padding * 2);+ const availH = Math.max(16, stageH - padding * 2);+ const fit = Math.min(availW / imgW, availH / imgH);+ return clampSubViewZoom(fit);+}++/**+ * Maps a point in PureRef board space into stage pixel coordinates.+ */+export function boardPointToStagePoint(+ bx: number,+ by: number,+ stageW: number,+ stageH: number,+ boardTransform: SubViewTransform+): BoardPoint {+ const fx = boardTransform.flipX ? -1 : 1;+ const sx = fx * boardTransform.zoom * bx;+ const sy = boardTransform.zoom * by;+ const rad = (boardTransform.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ return {+ x: stageW / 2 + boardTransform.pan.x + (sx * cos - sy * sin),+ y: stageH / 2 + boardTransform.pan.y + (sx * sin + sy * cos),+ };+}++/**+ * Inverse-maps a stage pixel coordinate into PureRef board space.+ */+export function stagePointToBoardPoint(+ localX: number,+ localY: number,+ stageW: number,+ stageH: number,+ boardTransform: SubViewTransform+): BoardPoint {+ const safeZoom = Math.max(1e-4, boardTransform.zoom);+ const dx = localX - (stageW / 2 + boardTransform.pan.x);+ const dy = localY - (stageH / 2 + boardTransform.pan.y);+ const rad = (boardTransform.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const unrotX = dx * cos + dy * sin;+ const unrotY = -dx * sin + dy * cos;+ const fx = boardTransform.flipX ? -1 : 1;+ return {+ x: (fx * unrotX) / safeZoom,+ y: unrotY / safeZoom,+ };+}++/**+ * Converts a delta in stage pixels into a delta in board space (accounting for zoom, rotation, flipX).+ */+export function stageDeltaToBoardDelta(+ dx: number,+ dy: number,+ boardTransform: SubViewTransform+): BoardPoint {+ const safeZoom = Math.max(1e-4, boardTransform.zoom);+ const rad = (boardTransform.rotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const unrotX = dx * cos + dy * sin;+ const unrotY = -dx * sin + dy * cos;+ const fx = boardTransform.flipX ? -1 : 1;+ return {+ x: (fx * unrotX) / safeZoom,+ y: unrotY / safeZoom,+ };+}++/**+ * Maps a point in card-local space (center = 0,0) into board space.+ */+export function cardLocalToBoardPoint(+ lx: number,+ ly: number,+ card: Pick<BoardCardGeometry, 'boardX' | 'boardY' | 'boardScale' | 'boardRotation' | 'boardFlipX' | 'boardFlipY'>+): BoardPoint {+ const sx = (card.boardFlipX ? -1 : 1) * card.boardScale * lx;+ const sy = (card.boardFlipY ? -1 : 1) * card.boardScale * ly;+ const rad = (card.boardRotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ return {+ x: card.boardX + (sx * cos - sy * sin),+ y: card.boardY + (sx * sin + sy * cos),+ };+}++/**+ * Inverse-maps a board point into card-local pixel-offset coordinates (center = 0,0).+ */+export function boardPointToCardLocal(+ bx: number,+ by: number,+ card: Pick<BoardCardGeometry, 'boardX' | 'boardY' | 'boardScale' | 'boardRotation' | 'boardFlipX' | 'boardFlipY'>+): BoardPoint {+ const safeScale = Math.max(1e-4, card.boardScale);+ const dx = bx - card.boardX;+ const dy = by - card.boardY;+ const rad = (card.boardRotation * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const unrotX = dx * cos + dy * sin;+ const unrotY = -dx * sin + dy * cos;+ return {+ x: ((card.boardFlipX ? -1 : 1) * unrotX) / safeScale,+ y: ((card.boardFlipY ? -1 : 1) * unrotY) / safeScale,+ };+}++/**+ * Computes screen-space corner and rotation handle positions for a card on the PureRef board.+ */+export function getCardStageOverlay(+ card: BoardCardGeometry,+ stageW: number,+ stageH: number,+ boardTransform: SubViewTransform,+ rotHandleOffsetPx = 18+): CardStageOverlay {+ const hw = card.width / 2;+ const hh = card.height / 2;+ // Use unflipped corner geometry so handles stay attached visually to TL/TR/BR/BL+ const baseCard = { ...card, boardFlipX: false, boardFlipY: false };+ const tlB = cardLocalToBoardPoint(-hw, -hh, baseCard);+ const trB = cardLocalToBoardPoint(hw, -hh, baseCard);+ const brB = cardLocalToBoardPoint(hw, hh, baseCard);+ const blB = cardLocalToBoardPoint(-hw, hh, baseCard);+ const topMidB = cardLocalToBoardPoint(0, -hh, baseCard);++ const tl = boardPointToStagePoint(tlB.x, tlB.y, stageW, stageH, boardTransform);+ const tr = boardPointToStagePoint(trB.x, trB.y, stageW, stageH, boardTransform);+ const br = boardPointToStagePoint(brB.x, brB.y, stageW, stageH, boardTransform);+ const bl = boardPointToStagePoint(blB.x, blB.y, stageW, stageH, boardTransform);+ const center = boardPointToStagePoint(card.boardX, card.boardY, stageW, stageH, boardTransform);+ const topMid = boardPointToStagePoint(topMidB.x, topMidB.y, stageW, stageH, boardTransform);++ // Compute outward normal along (topMid - center) in stage pixels so handle offset is crisp at all zooms+ const nx = topMid.x - center.x;+ const ny = topMid.y - center.y;+ const nLen = Math.hypot(nx, ny);+ const rotHandle: BoardPoint =+ nLen > 1e-4+ ? {+ x: topMid.x + (nx / nLen) * rotHandleOffsetPx,+ y: topMid.y + (ny / nLen) * rotHandleOffsetPx,+ }+ : { x: topMid.x, y: topMid.y - rotHandleOffsetPx };++ return { tl, tr, br, bl, center, topMid, rotHandle };+}++export function hitTestCardHandle(+ localX: number,+ localY: number,+ card: BoardCardGeometry,+ stageW: number,+ stageH: number,+ boardTransform: SubViewTransform,+ hitRadius = 9+): CardHandleKind | null {+ if (card.locked) return null;+ const overlay = getCardStageOverlay(card, stageW, stageH, boardTransform);+ const r2 = hitRadius * hitRadius;+ const check = (p: BoardPoint) => {+ const dx = localX - p.x;+ const dy = localY - p.y;+ return dx * dx + dy * dy <= r2;+ };+ if (check(overlay.rotHandle)) return 'rotate';+ if (check(overlay.tl)) return 'tl';+ if (check(overlay.tr)) return 'tr';+ if (check(overlay.br)) return 'br';+ if (check(overlay.bl)) return 'bl';+ return null;+}++/**+ * Hit-tests cards on the PureRef board from top zIndex to bottom, returning the topmost card+ * and exact source image pixel coordinates under `(localX, localY)`.+ */+export function hitTestBoardCards<T extends BoardCardGeometry>(+ localX: number,+ localY: number,+ cards: readonly T[],+ stageW: number,+ stageH: number,+ boardTransform: SubViewTransform+): BoardHitResult<T> | null {+ if (cards.length === 0 || stageW <= 0 || stageH <= 0) return null;+ const bp = stagePointToBoardPoint(localX, localY, stageW, stageH, boardTransform);++ const sorted = cards+ .map((card, idx) => ({ card, idx }))+ .sort((a, b) => b.card.zIndex - a.card.zIndex || b.idx - a.idx);++ for (const { card } of sorted) {+ if (card.width <= 0 || card.height <= 0) continue;+ const lp = boardPointToCardLocal(bp.x, bp.y, card);+ const px = Math.floor(card.width / 2 + lp.x);+ const py = Math.floor(card.height / 2 + lp.y);+ if (px >= 0 && py >= 0 && px < card.width && py < card.height) {+ return { card, pixel: { x: px, y: py }, local: lp };+ }+ }+ return null;+}++/**+ * Computes the world-space axis-aligned bounding box of one or more board cards.+ */+export function computeBoardBounds(+ cards: readonly BoardCardGeometry[]+): { minX: number; minY: number; maxX: number; maxY: number; width: number; height: number; cx: number; cy: number } | null {+ if (cards.length === 0) return null;+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const card of cards) {+ const hw = Math.max(1, card.width) / 2;+ const hh = Math.max(1, card.height) / 2;+ const corners = [+ cardLocalToBoardPoint(-hw, -hh, card),+ cardLocalToBoardPoint(hw, -hh, card),+ cardLocalToBoardPoint(hw, hh, card),+ cardLocalToBoardPoint(-hw, hh, card),+ ];+ for (const c of corners) {+ if (c.x < minX) minX = c.x;+ if (c.y < minY) minY = c.y;+ if (c.x > maxX) maxX = c.x;+ if (c.y > maxY) maxY = c.y;+ }+ }++ if (!Number.isFinite(minX)) return null;+ const width = Math.max(1, maxX - minX);+ const height = Math.max(1, maxY - minY);+ return {+ minX,+ minY,+ maxX,+ maxY,+ width,+ height,+ cx: (minX + maxX) / 2,+ cy: (minY + maxY) / 2,+ };+}++/**+ * Computes a board camera transform that fits all given cards cleanly inside the stage.+ */+export function computeBoardFitTransform(+ cards: readonly BoardCardGeometry[],+ stageW: number,+ stageH: number,+ padding = 18+): SubViewTransform {+ const bounds = computeBoardBounds(cards);+ if (!bounds || stageW <= 0 || stageH <= 0) {+ return { ...DEFAULT_SUB_VIEW_TRANSFORM, pan: { x: 0, y: 0 } };+ }+ const availW = Math.max(20, stageW - padding * 2);+ const availH = Math.max(20, stageH - padding * 2);+ const zoom = clampSubViewZoom(Math.min(availW / bounds.width, availH / bounds.height));+ return {+ zoom,+ pan: {+ x: -bounds.cx * zoom,+ y: -bounds.cy * zoom,+ },+ rotation: 0,+ flipX: false,+ };+}++export function computeNormalizedBoardScale(+ width: number,+ height: number,+ targetDim = DEFAULT_BOARD_CARD_TARGET_DIM+): number {+ const longEdge = Math.max(1, width, height);+ return clampBoardCardScale(targetDim / longEdge);+}++/**+ * Computes clean, non-overlapping PureRef board placements for all items in a given layout.+ */+export function computeBoardAutoLayout(+ items: ReadonlyArray<{ id: string; width: number; height: number }>,+ mode: SubViewBoardLayoutMode = 'grid',+ gap = 14,+ targetDim = DEFAULT_BOARD_CARD_TARGET_DIM+): Map<string, { boardX: number; boardY: number; boardScale: number; boardRotation: number }> {+ const result = new Map<+ string,+ { boardX: number; boardY: number; boardScale: number; boardRotation: number }+ >();+ if (items.length === 0) return result;++ const sized = items.map((it) => {+ const w = Math.max(1, it.width);+ const h = Math.max(1, it.height);+ const scale = computeNormalizedBoardScale(w, h, targetDim);+ return {+ id: it.id,+ scale,+ dw: w * scale,+ dh: h * scale,+ };+ });++ if (mode === 'row') {+ const totalW = sized.reduce((acc, s) => acc + s.dw, 0) + gap * Math.max(0, sized.length - 1);+ let cursorX = -totalW / 2;+ for (const s of sized) {+ result.set(s.id, {+ boardX: cursorX + s.dw / 2,+ boardY: 0,+ boardScale: s.scale,+ boardRotation: 0,+ });+ cursorX += s.dw + gap;+ }+ return result;+ }++ if (mode === 'column') {+ const totalH = sized.reduce((acc, s) => acc + s.dh, 0) + gap * Math.max(0, sized.length - 1);+ let cursorY = -totalH / 2;+ for (const s of sized) {+ result.set(s.id, {+ boardX: 0,+ boardY: cursorY + s.dh / 2,+ boardScale: s.scale,+ boardRotation: 0,+ });+ cursorY += s.dh + gap;+ }+ return result;+ }++ // 'grid' — neat balanced row-packed grid (PureRef style)+ const cols = Math.max(1, Math.ceil(Math.sqrt(sized.length)));+ const rows: Array<typeof sized> = [];+ for (let i = 0; i < sized.length; i += cols) {+ rows.push(sized.slice(i, i + cols));+ }++ const rowHeights = rows.map((r) => Math.max(...r.map((s) => s.dh)));+ const rowWidths = rows.map(+ (r) => r.reduce((acc, s) => acc + s.dw, 0) + gap * Math.max(0, r.length - 1)+ );+ const totalH = rowHeights.reduce((a, b) => a + b, 0) + gap * Math.max(0, rows.length - 1);++ let cursorY = -totalH / 2;+ rows.forEach((row, rIdx) => {+ const rh = rowHeights[rIdx];+ const rw = rowWidths[rIdx];+ let cursorX = -rw / 2;+ for (const s of row) {+ result.set(s.id, {+ boardX: cursorX + s.dw / 2,+ boardY: cursorY + rh / 2,+ boardScale: s.scale,+ boardRotation: 0,+ });+ cursorX += s.dw + gap;+ }+ cursorY += rh + gap;+ });++ return result;+}++/**+ * Computes initial board positions for newly added images without overlapping existing cards.+ */+export function computePlacementForNewBoardItems(+ existingCards: readonly BoardCardGeometry[],+ incoming: ReadonlyArray<{ width: number; height: number }>,+ dropBoardPoint?: BoardPoint | null,+ gap = 14+): Array<{ boardX: number; boardY: number; boardScale: number }> {+ if (incoming.length === 0) return [];++ if (existingCards.length === 0 && !dropBoardPoint) {+ const tempItems = incoming.map((it, idx) => ({ id: String(idx), width: it.width, height: it.height }));+ const layout = computeBoardAutoLayout(tempItems, 'grid', gap);+ return tempItems.map((it) => {+ const p = layout.get(it.id)!;+ return { boardX: p.boardX, boardY: p.boardY, boardScale: p.boardScale };+ });+ }++ const existingBounds = computeBoardBounds(existingCards);+ let cursorX = dropBoardPoint+ ? dropBoardPoint.x+ : existingBounds+ ? existingBounds.maxX + gap+ : 0;+ const anchorY = dropBoardPoint ? dropBoardPoint.y : existingBounds ? existingBounds.cy : 0;++ return incoming.map((it, idx) => {+ const w = Math.max(1, it.width);+ const h = Math.max(1, it.height);+ const scale = computeNormalizedBoardScale(w, h);+ const dw = w * scale;+ const bx = dropBoardPoint && idx === 0 ? cursorX : cursorX + dw / 2;+ cursorX = bx + dw / 2 + gap;+ return {+ boardX: bx,+ boardY: anchorY,+ boardScale: scale,+ };+ });+}++/**+ * Applies artist light & shape study filters in-place on an ImageData buffer:+ * - Brightness & Contrast adjustment+ * - True linear-light Rec.709 perceptual B/W luminance+ * - Value grouping / Notan posterization (2-value Notan, 3-value, 5-value)+ */+export function applyStudyFilterToImageData(+ imageData: Pick<ImageData, 'data' | 'width' | 'height'>,+ filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'brightness' | 'contrast'>,+ forceGrayscale = false+): void {+ const { data } = imageData;+ const useGray = forceGrayscale || filter.grayscale || filter.valueSteps > 0;+ const brightness = clampBrightnessContrast(filter.brightness);+ const contrast = clampBrightnessContrast(filter.contrast);+ const hasToneAdjust = brightness !== 0 || contrast !== 0;++ if (!useGray && !hasToneAdjust) return;++ // Standard contrast factor mapping [-100..100] -> [0..~4]+ const cVal = contrast * 2.55;+ const contrastFactor = contrast === 0 ? 1 : (259 * (cVal + 255)) / (255 * Math.max(1, 259 - cVal));+ const brightOffset = brightness * 1.28;+ const threshold = clampNotanThreshold(filter.notanThreshold);+ const thresholdShift = (threshold - 128) * 0.6;+ const steps = filter.valueSteps;++ for (let i = 0; i < data.length; i += 4) {+ if (data[i + 3] === 0) continue;++ let r = data[i];+ let g = data[i + 1];+ let b = data[i + 2];++ if (hasToneAdjust) {+ r = Math.max(0, Math.min(255, Math.round(contrastFactor * (r - 128) + 128 + brightOffset)));+ g = Math.max(0, Math.min(255, Math.round(contrastFactor * (g - 128) + 128 + brightOffset)));+ b = Math.max(0, Math.min(255, Math.round(contrastFactor * (b - 128) + 128 + brightOffset)));+ }++ if (useGray) {+ let lum = computePerceptualLuminanceByte(r, g, b);+ if (steps === 2) {+ // 2-Value Notan (pure shadow / light mass study)+ lum = lum >= threshold ? 248 : 16;+ } else if (steps === 3) {+ // 3-Value study (Shadow / Midtone / Light)+ const t1 = Math.max(20, Math.min(200, 85 + thresholdShift));+ const t2 = Math.max(t1 + 20, Math.min(240, 170 + thresholdShift));+ lum = lum < t1 ? 24 : lum < t2 ? 132 : 242;+ } else if (steps === 5) {+ // 5-Value study (0%, 25%, 50%, 75%, 100%)+ const shifted = Math.max(0, Math.min(255, lum - thresholdShift * 0.5));+ const bucket = Math.min(4, Math.floor((shifted / 256) * 5));+ lum = Math.round((bucket / 4) * 236 + 12);+ }+ data[i] = lum;+ data[i + 1] = lum;+ data[i + 2] = lum;+ } else {+ data[i] = r;+ data[i + 1] = g;+ data[i + 2] = b;+ }+ }+}++export function getStudyFilterSignature(+ filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'squintBlur' | 'brightness' | 'contrast'>,+ itemGrayscale = false+): string {+ const effGray = filter.grayscale || itemGrayscale;+ return `${effGray ? 1 : 0}:${filter.valueSteps}:${filter.notanThreshold}:${filter.squintBlur ? 1 : 0}:${filter.brightness}:${filter.contrast}`;+}++export function isStudyFilterVisualActive(+ filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'squintBlur' | 'brightness' | 'contrast'>,+ itemGrayscale = false+): boolean {+ return (+ filter.grayscale ||+ itemGrayscale ||+ filter.valueSteps > 0 ||+ filter.squintBlur ||+ filter.brightness !== 0 ||+ filter.contrast !== 0+ );+}++/**+ * Produces a filtered offscreen canvas from a source canvas (used for cached 60fps rendering+ * of perceptual B/W, Notan, value grouping, brightness/contrast, and squint blur).+ */+export function buildFilteredReferenceCanvas(+ sourceCanvas: HTMLCanvasElement,+ filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'squintBlur' | 'brightness' | 'contrast'>,+ itemGrayscale = false+): HTMLCanvasElement {+ if (!isStudyFilterVisualActive(filter, itemGrayscale)) {+ return sourceCanvas;+ }++ const w = Math.max(1, sourceCanvas.width);+ const h = Math.max(1, sourceCanvas.height);++ // Cap processing resolution for very large photos while preserving crisp reference detail+ const maxWorkDim = 1024;+ const downScale = Math.min(1, maxWorkDim / Math.max(w, h));+ const workW = Math.max(1, Math.round(w * downScale));+ const workH = Math.max(1, Math.round(h * downScale));++ const out = document.createElement('canvas');+ out.width = workW;+ out.height = workH;+ const ctx = out.getContext('2d', { willReadFrequently: true });+ if (!ctx) return sourceCanvas;++ if (filter.squintBlur) {+ // Fast squint-blur via multi-step downscale/upscale (works consistently across all Canvas2D engines)+ const blurScale = Math.max(0.06, Math.min(0.18, 42 / Math.max(workW, workH)));+ const smallW = Math.max(2, Math.round(workW * blurScale));+ const smallH = Math.max(2, Math.round(workH * blurScale));+ const tiny = document.createElement('canvas');+ tiny.width = smallW;+ tiny.height = smallH;+ const tCtx = tiny.getContext('2d');+ if (tCtx) {+ tCtx.imageSmoothingEnabled = true;+ tCtx.drawImage(sourceCanvas, 0, 0, smallW, smallH);+ ctx.imageSmoothingEnabled = true;+ ctx.drawImage(tiny, 0, 0, workW, workH);+ } else {+ ctx.drawImage(sourceCanvas, 0, 0, workW, workH);+ }+ } else {+ ctx.drawImage(sourceCanvas, 0, 0, workW, workH);+ }++ const needsPixelPass =+ filter.grayscale ||+ itemGrayscale ||+ filter.valueSteps > 0 ||+ filter.brightness !== 0 ||+ filter.contrast !== 0;++ if (needsPixelPass && typeof ctx.getImageData === 'function' && typeof ctx.putImageData === 'function') {+ try {+ const imgData = ctx.getImageData(0, 0, workW, workH);+ applyStudyFilterToImageData(imgData, filter, itemGrayscale);+ ctx.putImageData(imgData, 0, 0);+ } catch {+ // Guard against tainted canvas in unusual browser contexts+ }+ }++ return out;+}++/**+ * Extracts a curated dominant color palette (up to `maxColors` distinct colors) from a reference canvas.+ * Useful for instant color-key and light-study swatch extraction.+ */+export function extractDominantColorsFromCanvas(+ canvas: HTMLCanvasElement | null,+ maxColors = 7+): ExtractedSwatch[] {+ if (!canvas || canvas.width <= 0 || canvas.height <= 0) return [];+ try {+ const sampleSize = 48;+ const scale = Math.min(1, sampleSize / Math.max(canvas.width, canvas.height));+ const sw = Math.max(1, Math.round(canvas.width * scale));+ const sh = Math.max(1, Math.round(canvas.height * scale));++ const tmp = document.createElement('canvas');+ tmp.width = sw;+ tmp.height = sh;+ const tCtx = tmp.getContext('2d', { willReadFrequently: true });+ if (!tCtx) return [];+ tCtx.drawImage(canvas, 0, 0, sw, sh);+ const data = tCtx.getImageData(0, 0, sw, sh).data;++ // 4-bit-per-channel quantized bins (16x16x16 = 4096 max bins)+ const buckets = new Map<number, { rSum: number; gSum: number; bSum: number; count: number }>();+ let totalOpaque = 0;++ for (let i = 0; i < data.length; i += 4) {+ if (data[i + 3] < 128) continue;+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4);+ const existing = buckets.get(key);+ if (existing) {+ existing.rSum += r;+ existing.gSum += g;+ existing.bSum += b;+ existing.count += 1;+ } else {+ buckets.set(key, { rSum: r, gSum: g, bSum: b, count: 1 });+ }+ totalOpaque += 1;+ }++ if (totalOpaque === 0) return [];++ const sortedBuckets = Array.from(buckets.values())+ .map((b) => ({+ r: Math.round(b.rSum / b.count),+ g: Math.round(b.gSum / b.count),+ b: Math.round(b.bSum / b.count),+ count: b.count,+ }))+ .sort((a, b) => b.count - a.count);++ // Greedy perceptual-distance selection so extracted palette has distinct, useful hues & values+ const chosen: Array<{ r: number; g: number; b: number; count: number }> = [];+ const minDistSq = 38 * 38;++ for (const cand of sortedBuckets) {+ if (chosen.length >= maxColors) break;+ const tooClose = chosen.some((c) => {+ const dr = cand.r - c.r;+ const dg = cand.g - c.g;+ const db = cand.b - c.b;+ return dr * dr * 0.3 + dg * dg * 0.59 + db * db * 0.11 < minDistSq * 0.34;+ });+ if (!tooClose) {+ chosen.push(cand);+ }+ }++ // Fallback if image is nearly monochrome / flat color so we still return at least 1 swatch+ if (chosen.length === 0 && sortedBuckets.length > 0) {+ chosen.push(sortedBuckets[0]);+ }++ return chosen+ .map((c) => {+ const hex = `#${c.r.toString(16).padStart(2, '0')}${c.g.toString(16).padStart(2, '0')}${c.b.toString(16).padStart(2, '0')}`;+ const lumByte = computePerceptualLuminanceByte(c.r, c.g, c.b);+ return {+ hex,+ luminance: Math.round((lumByte / 255) * 100),+ ratio: c.count / totalOpaque,+ };+ })+ .sort((a, b) => a.luminance - b.luminance);+ } catch {+ return [];+ }+}++/**+ * Draws a crisp proportional study grid overlay inside a centered rectangle `[-w/2, -h/2, w, h]`+ * in the current transformed canvas context.+ */+export function drawProportionalGrid(+ ctx: CanvasRenderingContext2D,+ w: number,+ h: number,+ gridMode: SubViewGridMode,+ screenScale: number+): void {+ if (gridMode === 'none' || w <= 0 || h <= 0) return;++ const x0 = -w / 2;+ const y0 = -h / 2;+ const invScale = 1 / Math.max(0.05, Math.abs(screenScale));++ ctx.save();+ ctx.beginPath();++ const addLine = (ax: number, ay: number, bx: number, by: number) => {+ ctx.moveTo(ax, ay);+ ctx.lineTo(bx, by);+ };++ if (gridMode === 'thirds') {+ for (let i = 1; i <= 2; i++) {+ addLine(x0 + (w * i) / 3, y0, x0 + (w * i) / 3, y0 + h);+ addLine(x0, y0 + (h * i) / 3, x0 + w, y0 + (h * i) / 3);+ }+ } else if (gridMode === 'grid4' || gridMode === 'grid8') {+ const div = gridMode === 'grid4' ? 4 : 8;+ for (let i = 1; i < div; i++) {+ addLine(x0 + (w * i) / div, y0, x0 + (w * i) / div, y0 + h);+ addLine(x0, y0 + (h * i) / div, x0 + w, y0 + (h * i) / div);+ }+ } else if (gridMode === 'crosshair') {+ addLine(0, y0, 0, y0 + h);+ addLine(x0, 0, x0 + w, 0);+ // Subtle diagonals for angle & center checking+ addLine(x0, y0, x0 + w, y0 + h);+ addLine(x0 + w, y0, x0, y0 + h);+ } else if (gridMode === 'golden') {+ const phiA = 0.381966;+ const phiB = 1 - phiA;+ addLine(x0 + w * phiA, y0, x0 + w * phiA, y0 + h);+ addLine(x0 + w * phiB, y0, x0 + w * phiB, y0 + h);+ addLine(x0, y0 + h * phiA, x0 + w, y0 + h * phiA);+ addLine(x0, y0 + h * phiB, x0 + w, y0 + h * phiB);+ }++ // Dual-contrast hairline (subtle dark shadow + crisp light line) so grid stays readable on both bright & dark refs+ ctx.strokeStyle = 'rgba(0, 0, 0, 0.45)';+ ctx.lineWidth = 2 * invScale;+ ctx.stroke();++ ctx.strokeStyle = 'rgba(255, 255, 255, 0.72)';+ ctx.lineWidth = 1 * invScale;+ ctx.stroke();++ ctx.restore();+}diff --git a/src/utils/textSettings.ts b/src/utils/textSettings.tsnew file mode 100644index 0000000..f4f5ece--- /dev/null+++ b/src/utils/textSettings.ts@@ -0,0 +1,282 @@+import { TextSettings } from '../types/editor';+import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';++export const TEXT_SETTINGS_STORAGE_KEY = 'ink_studio_text_settings';++export interface TextFontOption {+ value: string;+ label: string;+ category: 'Sans' | 'Serif' | 'Manga' | 'Display' | 'Mono' | 'System';+}++export const TEXT_FONT_PRESETS: ReadonlyArray<TextFontOption> = [+ {+ value: "Inter, 'Segoe UI', system-ui, -apple-system, sans-serif",+ label: 'Sans Clean',+ category: 'Sans',+ },+ {+ value: "'Segoe UI', Roboto, Helvetica, Arial, sans-serif",+ label: 'Segoe UI / System',+ category: 'Sans',+ },+ {+ value: "Arial, 'Helvetica Neue', Helvetica, sans-serif",+ label: 'Arial / Helvetica',+ category: 'Sans',+ },+ {+ value: 'Verdana, Geneva, sans-serif',+ label: 'Verdana',+ category: 'Sans',+ },+ {+ value: "'Trebuchet MS', 'Gill Sans', sans-serif",+ label: 'Trebuchet MS',+ category: 'Sans',+ },+ {+ value: "Georgia, 'Times New Roman', serif",+ label: 'Georgia Serif',+ category: 'Serif',+ },+ {+ value: "'Times New Roman', Times, serif",+ label: 'Times New Roman',+ category: 'Serif',+ },+ {+ value: "'Palatino Linotype', 'Book Antiqua', Palatino, serif",+ label: 'Palatino',+ category: 'Serif',+ },+ {+ value: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",+ label: 'Manga / Comic',+ category: 'Manga',+ },+ {+ value: "'Anime Ace', 'Comic Sans MS', sans-serif",+ label: 'Anime Ace',+ category: 'Manga',+ },+ {+ value: "Impact, 'Arial Black', sans-serif",+ label: 'Impact (SFX)',+ category: 'Display',+ },+ {+ value: "'JetBrains Mono', Consolas, 'Courier New', monospace",+ label: 'Monospace',+ category: 'Mono',+ },+];++export const TEXT_QUICK_COLORS: ReadonlyArray<{ hex: string; label: string }> = [+ { hex: '#ffffff', label: 'White' },+ { hex: '#000000', label: 'Black' },+ { hex: '#f4f4f5', label: 'Soft White' },+ { hex: '#ef4444', label: 'Red' },+ { hex: '#f59e0b', label: 'Amber' },+ { hex: '#38bdf8', label: 'Sky' },+];++export const TEXT_FONT_SIZE_PRESETS: ReadonlyArray<number> = [+ 14, 18, 24, 32, 36, 48, 64, 84, 120,+];++/**+ * Standard Ink Studio Text Tool defaults:+ * plain white text without outlines and clean proportional sans typography.+ */+export const DEFAULT_TEXT_SETTINGS: TextSettings = {+ text: '',+ fontFamily: "Inter, 'Segoe UI', system-ui, -apple-system, sans-serif",+ fontSize: 36,+ lineSpacing: 1.25,+ letterSpacing: 0,+ bold: false,+ italic: false,+ underline: false,+ align: 'left',+ outline: false,+ outlineColor: '#000000',+ outlineWidth: 3,+ color: '#ffffff',+ writingMode: 'horizontal-tb',+ opacity: 1,+ maxWidth: null,+};++function clampFinite(value: unknown, min: number, max: number, fallback: number): number {+ const n = typeof value === 'number' ? value : Number(value);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, n));+}++function normalizeColor(value: unknown, fallback: string): string {+ if (typeof value === 'string') {+ const trimmed = value.trim();+ if (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(trimmed)) {+ return trimmed.toLowerCase();+ }+ }+ return fallback;+}++/**+ * Extracts only the reusable typography/style fields from a TextSettings patch+ * (omitting transient draft `text` and per-instance `maxWidth`).+ */+export function extractPersistableTextStyle(+ settings: Partial<TextSettings>+): Partial<TextSettings> {+ const out: Partial<TextSettings> = {};+ if (typeof settings.fontFamily === 'string' && settings.fontFamily.trim()) {+ out.fontFamily = settings.fontFamily.trim();+ }+ if (settings.fontSize !== undefined) {+ out.fontSize = Math.round(clampFinite(settings.fontSize, 6, 400, DEFAULT_TEXT_SETTINGS.fontSize));+ }+ if (settings.lineSpacing !== undefined) {+ out.lineSpacing = Number(+ clampFinite(settings.lineSpacing, 0.7, 3.0, DEFAULT_TEXT_SETTINGS.lineSpacing ?? 1.25).toFixed(2)+ );+ }+ if (settings.letterSpacing !== undefined) {+ out.letterSpacing = Number(+ clampFinite(settings.letterSpacing, -10, 60, DEFAULT_TEXT_SETTINGS.letterSpacing ?? 0).toFixed(1)+ );+ }+ if (typeof settings.bold === 'boolean') out.bold = settings.bold;+ if (typeof settings.italic === 'boolean') out.italic = settings.italic;+ if (typeof settings.underline === 'boolean') out.underline = settings.underline;+ if (settings.align === 'left' || settings.align === 'center' || settings.align === 'right') {+ out.align = settings.align;+ }+ if (typeof settings.outline === 'boolean') out.outline = settings.outline;+ if (settings.outlineColor !== undefined) {+ out.outlineColor = normalizeColor(settings.outlineColor, DEFAULT_TEXT_SETTINGS.outlineColor);+ }+ if (settings.outlineWidth !== undefined) {+ out.outlineWidth = Math.round(+ clampFinite(settings.outlineWidth, 1, 24, DEFAULT_TEXT_SETTINGS.outlineWidth)+ );+ }+ if (settings.color !== undefined) {+ out.color = normalizeColor(settings.color, DEFAULT_TEXT_SETTINGS.color);+ }+ if (settings.writingMode === 'horizontal-tb' || settings.writingMode === 'vertical-rl') {+ out.writingMode = settings.writingMode;+ }+ if (settings.opacity !== undefined) {+ out.opacity = Number(clampFinite(settings.opacity, 0.05, 1, 1).toFixed(2));+ }+ return out;+}++export function normalizeTextSettings(raw?: Partial<TextSettings> | null): TextSettings {+ const safeStyle = raw ? extractPersistableTextStyle(raw) : {};+ const maxWidth =+ raw && typeof raw.maxWidth === 'number' && Number.isFinite(raw.maxWidth) && raw.maxWidth >= 24+ ? Math.round(raw.maxWidth)+ : null;+ return {+ ...DEFAULT_TEXT_SETTINGS,+ ...safeStyle,+ text: typeof raw?.text === 'string' ? raw.text : '',+ maxWidth,+ };+}++export function loadInitialTextSettings(): TextSettings {+ try {+ const saved = safeLocalStorageGetItem(TEXT_SETTINGS_STORAGE_KEY);+ if (saved) {+ const parsed = JSON.parse(saved) as Partial<TextSettings>;+ return normalizeTextSettings({ ...parsed, text: '', maxWidth: null });+ }+ } catch {+ // Ignore storage / parse errors and use defaults+ }+ return { ...DEFAULT_TEXT_SETTINGS };+}++export function saveTextSettings(settings: TextSettings): void {+ const persistable = extractPersistableTextStyle(settings);+ safeLocalStorageSetItem(+ TEXT_SETTINGS_STORAGE_KEY,+ JSON.stringify(persistable),+ 'text settings'+ );+}++/**+ * Returns font options ensuring the currently selected fontFamily (e.g. from an opened+ * .ink file or local system font) is always present in the dropdown.+ */+export function getTextFontOptions(+ currentFontFamily?: string,+ extraSystemFonts?: ReadonlyArray<string>+): TextFontOption[] {+ const options: TextFontOption[] = [...TEXT_FONT_PRESETS];+ const seenValues = new Set(options.map((o) => o.value));+ const seenLabels = new Set(options.map((o) => o.label.toLowerCase()));++ if (extraSystemFonts && extraSystemFonts.length > 0) {+ for (const family of extraSystemFonts) {+ const clean = family.trim();+ if (!clean) continue;+ const value = clean.includes(',') ? clean : `'${clean.replace(/'/g, '')}', sans-serif`;+ if (seenValues.has(value) || seenLabels.has(clean.toLowerCase())) continue;+ seenValues.add(value);+ seenLabels.add(clean.toLowerCase());+ options.push({ value, label: clean, category: 'System' });+ }+ }++ if (currentFontFamily && currentFontFamily.trim() && !seenValues.has(currentFontFamily)) {+ const primaryName =+ currentFontFamily+ .split(',')[0]+ ?.trim()+ .replace(/^['"]|['"]$/g, '') || currentFontFamily;+ options.unshift({+ value: currentFontFamily,+ label: primaryName,+ category: 'System',+ });+ }++ return options;+}++let cachedSystemFonts: string[] | null = null;++/**+ * Best-effort discovery of installed system fonts using the Local Font Access API+ * when supported by the host WebView/browser.+ */+export async function queryInstalledSystemFonts(): Promise<string[]> {+ if (cachedSystemFonts) return cachedSystemFonts;+ if (typeof window === 'undefined') return [];+ const queryLocalFonts = (+ window as unknown as {+ queryLocalFonts?: () => Promise<Array<{ family?: string }>>;+ }+ ).queryLocalFonts;+ if (typeof queryLocalFonts !== 'function') return [];+ try {+ const fonts = await queryLocalFonts();+ const families = new Set<string>();+ for (const font of fonts) {+ if (font?.family && typeof font.family === 'string') {+ families.add(font.family.trim());+ }+ }+ cachedSystemFonts = Array.from(families).sort((a, b) => a.localeCompare(b));+ return cachedSystemFonts;+ } catch {+ return [];+ }+}diff --git a/src/utils/timelapseCanvasView.ts b/src/utils/timelapseCanvasView.tsnew file mode 100644index 0000000..d35b475--- /dev/null+++ b/src/utils/timelapseCanvasView.ts@@ -0,0 +1,428 @@+/**+ * Optimized Time-lapse Capture Area Renderers+ *+ * Supports three capture areas with zero WebGL readPixels stalls:+ * 1. `artwork` – Flat document composite using SparseTileGrid mipmap LOD tiles+ * 2. `canvas-view` – Frustum-culled adaptive-LOD viewport renderer replicating pan, zoom,+ * rotation, flipX/flipY, matte background, checkerboard, and value check+ * 3. `app-window` – Native off-main-thread Windows GDI PrintWindow (PW_RENDERFULLCONTENT)+ * via Tauri Rust backend, gracefully falling back to `canvas-view` elsewhere.+ */++import {+ CanvasDimensions,+ LayerItem,+ isFolderLikeLayer,+ resolveToneDensityType,+} from '../types/editor';+import { getCanvasCompositeOperation } from './canvasUtils';+import { calculateVisibleDocumentBounds } from './compositor/bounds';+import { buildLayerTree, groupTreeNodesForCompositing } from './compositor/layerTree';+import { LayerTreeNode, ViewportTransform } from './compositor/types';+import { applyMultiFrameClip, renderFrameBorder } from './frameEngine';+import { SparseTileGrid, TILE_SIZE } from './tileEngine';+import { applyAdjustment } from './tonalEngine';+import { invokeTauri, isTauriRuntime, toArrayBuffer } from './timelapseStorage';++export interface TimelapseLiveCaptureContext {+ viewportElement?: HTMLElement | null;+ camera?: ViewportTransform | null;+ showCheckerboard?: boolean;+ valueCheckEnabled?: boolean;+ matteColor?: string;+ isDrawingActive?: () => boolean;+ documentName?: string;+}++// Reusable scratch buffers for zero per-capture allocation+let cvTileCanvas: HTMLCanvasElement | null = null;+let cvTileImgData: ImageData | null = null;+let cvScratchCanvas: HTMLCanvasElement | null = null;+let cvFolderPool: HTMLCanvasElement[] = [];++function acquireFolderScratch(depth: number, w: number, h: number): HTMLCanvasElement {+ let c = cvFolderPool[depth];+ if (!c) {+ c = document.createElement('canvas');+ cvFolderPool[depth] = c;+ }+ if (c.width !== w) c.width = w;+ if (c.height !== h) c.height = h;+ return c;+}++function resolveCanvasMatteColor(explicit?: string): string {+ if (explicit) return explicit;+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ try {+ const val = getComputedStyle(document.documentElement)+ .getPropertyValue('--ui-canvas-matte')+ .trim();+ if (val) return val;+ } catch {+ // fallback below+ }+ }+ return '#161616';+}++/**+ * Computes optimal even output dimensions for `canvas-view` matching the current viewport aspect ratio.+ */+export function computeCanvasViewDimensions(+ viewportW: number,+ viewportH: number,+ maxCaptureDim: number+): { width: number; height: number } {+ const safeW = Math.max(64, viewportW);+ const safeH = Math.max(64, viewportH);+ const scale = Math.min(1, maxCaptureDim / Math.max(safeW, safeH));+ return {+ width: Math.max(2, Math.round((safeW * scale) / 2) * 2),+ height: Math.max(2, Math.round((safeH * scale) / 2) * 2),+ };+}++/**+ * Frustum-culled adaptive-LOD Canvas View renderer.+ * Only touches tiles intersecting the visible viewport frustum at the exact mipmap LOD needed for+ * `camera.zoom * outputScale`, avoiding GPU readback stalls completely.+ */+export function renderCanvasViewToCanvas(+ targetCanvas: HTMLCanvasElement,+ layers: LayerItem[],+ dimensions: CanvasDimensions,+ tileGrid: SparseTileGrid,+ viewportW: number,+ viewportH: number,+ camera: ViewportTransform,+ options?: {+ showCheckerboard?: boolean;+ valueCheckEnabled?: boolean;+ matteColor?: string;+ }+): boolean {+ if (typeof document === 'undefined') return false;+ const ctx = targetCanvas.getContext('2d');+ if (!ctx) return false;++ const outW = Math.max(2, Math.floor(targetCanvas.width));+ const outH = Math.max(2, Math.floor(targetCanvas.height));+ const safeVpW = Math.max(1, viewportW);+ const safeVpH = Math.max(1, viewportH);+ const docW = Math.max(1, dimensions.width);+ const docH = Math.max(1, dimensions.height);++ const scaleX = outW / safeVpW;+ const scaleY = outH / safeVpH;+ const effectiveZoom = Math.max(0.01, camera.zoom * Math.min(scaleX, scaleY));++ // Pick optimal mipmap LOD strictly from effective screen-pixel density+ const targetLod =+ effectiveZoom <= 0.14+ ? 3+ : effectiveZoom <= 0.28+ ? 2+ : effectiveZoom <= 0.55+ ? 1+ : 0;+ const lodDocSize = TILE_SIZE << targetLod;++ // Frustum-cull tiles to only what's currently visible on screen!+ const frustum = calculateVisibleDocumentBounds(safeVpW, safeVpH, camera, docW, docH);+ const minTx = Math.floor(frustum.minX / lodDocSize);+ const maxTx = Math.floor(frustum.maxX / lodDocSize);+ const minTy = Math.floor(frustum.minY / lodDocSize);+ const maxTy = Math.floor(frustum.maxY / lodDocSize);++ const matteColor = resolveCanvasMatteColor(options?.matteColor);++ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalAlpha = 1;+ ctx.globalCompositeOperation = 'source-over';+ ctx.filter = options?.valueCheckEnabled ? 'grayscale(100%)' : 'none';+ ctx.fillStyle = matteColor;+ ctx.fillRect(0, 0, outW, outH);++ // Apply exact ViewportCompositor affine camera transform scaled to output buffer+ const applyCameraTransform = (c: CanvasRenderingContext2D) => {+ c.setTransform(1, 0, 0, 1, 0, 0);+ c.scale(scaleX, scaleY);+ c.translate(camera.pan.x, camera.pan.y);+ c.rotate((camera.rotation * Math.PI) / 180);+ c.scale((camera.flipX ? -1 : 1) * camera.zoom, (camera.flipY ? -1 : 1) * camera.zoom);+ c.translate(-docW / 2, -docH / 2);+ };++ applyCameraTransform(ctx);++ // Subtle artboard drop shadow & crisp paper/checkerboard backdrop+ ctx.save();+ ctx.shadowColor = 'rgba(0, 0, 0, 0.45)';+ ctx.shadowBlur = 18 / Math.max(0.1, camera.zoom);+ ctx.shadowOffsetY = 4 / Math.max(0.1, camera.zoom);+ ctx.fillStyle = options?.showCheckerboard ? '#222222' : '#ffffff';+ ctx.fillRect(0, 0, docW, docH);+ ctx.restore();++ // Clip artwork strictly to document bounds+ ctx.beginPath();+ ctx.rect(0, 0, docW, docH);+ ctx.clip();++ if (options?.showCheckerboard) {+ const cell = Math.max(8, Math.round(16 / Math.max(0.1, effectiveZoom)));+ ctx.fillStyle = '#2c2c2c';+ const sx = Math.max(0, Math.floor(frustum.minX / cell) * cell);+ const sy = Math.max(0, Math.floor(frustum.minY / cell) * cell);+ const ex = Math.min(docW, frustum.maxX);+ const ey = Math.min(docH, frustum.maxY);+ for (let y = sy; y < ey; y += cell) {+ const rowOffset = (Math.floor(y / cell) & 1) * cell;+ for (let x = sx + rowOffset; x < ex; x += cell * 2) {+ ctx.fillRect(x, y, cell, cell);+ }+ }+ }++ if (!cvTileCanvas) {+ cvTileCanvas = document.createElement('canvas');+ cvTileCanvas.width = TILE_SIZE;+ cvTileCanvas.height = TILE_SIZE;+ }+ const tileCanvas = cvTileCanvas;+ const tileCtx = tileCanvas.getContext('2d', { willReadFrequently: true });+ if (!tileCtx) {+ ctx.restore();+ return false;+ }+ if (!cvTileImgData) {+ cvTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);+ }+ const reusableImgData = cvTileImgData;++ const drawSingleLayer = (+ dstCtx: CanvasRenderingContext2D,+ layer: LayerItem,+ opacityMul: number,+ compositeOverride?: GlobalCompositeOperation+ ) => {+ const toneDensityMul =+ layer.toneEnabled && resolveToneDensityType(layer) === 'specified'+ ? Math.max(0, Math.min(1, (layer.toneDensity ?? 40) / 100))+ : 1.0;+ const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul * toneDensityMul));+ if (alpha <= 0.001) return;++ const allTiles = tileGrid.getOrBuildLodTiles(layer.id, targetLod);+ if (allTiles.length === 0) return;++ dstCtx.save();+ dstCtx.globalAlpha = alpha;+ dstCtx.globalCompositeOperation =+ compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);+ dstCtx.imageSmoothingEnabled = effectiveZoom < 2.0;++ for (const tile of allTiles) {+ // Frustum culling!+ if (+ tile.tileX < minTx ||+ tile.tileX > maxTx ||+ tile.tileY < minTy ||+ tile.tileY > maxTy+ ) {+ continue;+ }+ const rgba = tileGrid.getTileAsRGBA(tile);+ reusableImgData.data.set(rgba);+ tileCtx.putImageData(reusableImgData, 0, 0);+ dstCtx.drawImage(+ tileCanvas,+ tile.tileX * lodDocSize,+ tile.tileY * lodDocSize,+ lodDocSize,+ lodDocSize+ );+ }+ dstCtx.restore();+ };++ const renderNodes = (+ dstCtx: CanvasRenderingContext2D,+ nodes: LayerTreeNode[],+ opacityMul: number,+ depth = 0+ ) => {+ const renderOrder = nodes.slice().reverse();+ const groups = groupTreeNodesForCompositing(renderOrder);++ for (const group of groups) {+ const baseNode = group.baseNode;+ const baseLayer = baseNode.layer;+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;++ if (baseLayer.type === 'frame-folder') {+ const folderOpacity = opacityMul * baseLayer.opacity;+ const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);+ const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);+ const tmp = acquireFolderScratch(depth, outW, outH);+ const tmpCtx = tmp.getContext('2d');+ if (tmpCtx) {+ tmpCtx.setTransform(1, 0, 0, 1, 0, 0);+ tmpCtx.clearRect(0, 0, outW, outH);+ applyCameraTransform(tmpCtx);+ tmpCtx.save();+ if (shouldClip) applyMultiFrameClip(tmpCtx, frames);+ for (const f of frames) {+ if (f.fillBackground !== false) {+ tmpCtx.fillStyle = f.fillColor || '#ffffff';+ tmpCtx.beginPath();+ tmpCtx.moveTo(f.polygon[0].x, f.polygon[0].y);+ for (let i = 1; i < f.polygon.length; i++) {+ tmpCtx.lineTo(f.polygon[i].x, f.polygon[i].y);+ }+ tmpCtx.closePath();+ tmpCtx.fill();+ }+ }+ if (baseNode.children.length > 0) {+ renderNodes(tmpCtx, baseNode.children, 1.0, depth + 1);+ }+ tmpCtx.restore();+ for (const f of frames) {+ renderFrameBorder(tmpCtx, f, false);+ }+ dstCtx.save();+ dstCtx.setTransform(1, 0, 0, 1, 0, 0);+ dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);+ dstCtx.drawImage(tmp, 0, 0);+ dstCtx.restore();+ }+ continue;+ }++ if (baseLayer.type === 'folder') {+ const folderOpacity = opacityMul * baseLayer.opacity;+ if (baseLayer.blendMode === 'pass-through') {+ if (baseNode.children.length > 0) {+ renderNodes(dstCtx, baseNode.children, folderOpacity, depth);+ }+ } else {+ const tmp = acquireFolderScratch(depth, outW, outH);+ const tmpCtx = tmp.getContext('2d');+ if (tmpCtx) {+ tmpCtx.setTransform(1, 0, 0, 1, 0, 0);+ tmpCtx.clearRect(0, 0, outW, outH);+ applyCameraTransform(tmpCtx);+ if (baseNode.children.length > 0) {+ renderNodes(tmpCtx, baseNode.children, 1.0, depth + 1);+ }+ dstCtx.save();+ dstCtx.setTransform(1, 0, 0, 1, 0, 0);+ dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);+ dstCtx.drawImage(tmp, 0, 0);+ dstCtx.restore();+ }+ }+ continue;+ }++ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {+ try {+ const imgData = dstCtx.getImageData(0, 0, outW, outH);+ applyAdjustment(imgData, baseLayer.adjustmentData, undefined, baseLayer.opacity * opacityMul);+ dstCtx.putImageData(imgData, 0, 0);+ } catch {+ // ignore mock context+ }+ continue;+ }++ const activeClipped = group.clippedNodes.filter(+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)+ );++ if (activeClipped.length === 0) {+ drawSingleLayer(dstCtx, baseLayer, opacityMul);+ } else {+ if (!cvScratchCanvas) cvScratchCanvas = document.createElement('canvas');+ if (cvScratchCanvas.width !== outW) cvScratchCanvas.width = outW;+ if (cvScratchCanvas.height !== outH) cvScratchCanvas.height = outH;+ const grpCtx = cvScratchCanvas.getContext('2d');+ if (!grpCtx) {+ drawSingleLayer(dstCtx, baseLayer, opacityMul);+ continue;+ }+ grpCtx.setTransform(1, 0, 0, 1, 0, 0);+ grpCtx.clearRect(0, 0, outW, outH);+ applyCameraTransform(grpCtx);+ drawSingleLayer(grpCtx, baseLayer, 1.0, 'source-over');+ for (const cn of activeClipped) {+ drawSingleLayer(grpCtx, cn.layer, 1.0, 'source-atop');+ }+ dstCtx.save();+ dstCtx.setTransform(1, 0, 0, 1, 0, 0);+ dstCtx.globalAlpha = Math.max(0, Math.min(1, opacityMul));+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);+ dstCtx.drawImage(cvScratchCanvas, 0, 0);+ dstCtx.restore();+ }+ }+ };++ const tree = buildLayerTree(layers);+ renderNodes(ctx, tree, 1.0);+ ctx.restore();+ return true;+}++/**+ * Captures the live native desktop InkStudio app window (UI + panels + live WebGL canvas)+ * off the main JS thread using Rust's Win32 `PrintWindow(PW_CLIENTONLY | PW_RENDERFULLCONTENT)`.+ * Returns `{ width, height }` if captured, or `null` when unavailable (caller falls back smoothly).+ */+export async function captureNativeAppWindowToCanvas(+ targetCanvas: HTMLCanvasElement,+ maxCaptureDim: number+): Promise<{ width: number; height: number } | null> {+ if (!isTauriRuntime() || typeof document === 'undefined') return null;+ try {+ const raw = await invokeTauri<ArrayBuffer | Uint8Array | number[]>(+ 'timelapse_capture_app_window',+ { maxDim: Math.max(320, Math.min(3840, Math.round(maxCaptureDim))) }+ );+ const buf = toArrayBuffer(raw);+ if (buf.byteLength < 12) return null;++ const view = new DataView(buf);+ const width = view.getUint32(0, true);+ const height = view.getUint32(4, true);+ if (width < 2 || height < 2 || width > 4096 || height > 4096) return null;++ const expectedBytes = width * height * 4;+ if (buf.byteLength < 8 + expectedBytes) return null;++ targetCanvas.width = width;+ targetCanvas.height = height;+ const ctx = targetCanvas.getContext('2d');+ if (!ctx) return null;++ const rgba = new Uint8ClampedArray(buf, 8, expectedBytes);+ const imgData =+ typeof ImageData !== 'undefined'+ ? new ImageData(rgba, width, height)+ : (() => {+ const d = ctx.createImageData(width, height);+ d.data.set(rgba);+ return d;+ })();+ ctx.putImageData(imgData, 0, 0);+ return { width, height };+ } catch {+ return null;+ }+}diff --git a/src/utils/timelapseEngine.ts b/src/utils/timelapseEngine.tsindex 8ee142b..dd3536a 100644--- a/src/utils/timelapseEngine.ts+++ b/src/utils/timelapseEngine.ts@@ -1,10 +1,13 @@/**- * Time-lapse Recording & Export Engine+ * Time-lapse Recording, Persistent Storage, Preview & Export Engine*- * Captures lightweight throttled WebP/JPEG keyframes after stroke/action commits using- * SparseTileGrid LOD mipmaps (zero GPU readPixels stall), offloads to Tauri scratch disk- * when available or enforces bounded RAM thinning in browser, and exports 15s / 30s / 60s / Full- * videos via MediaRecorder or native FFmpeg (when installed in Tauri).+ * - Persists keyframes in external local storage (Tauri `%LOCALAPPDATA%/inkstudio_timelapse` or+ * browser IndexedDB) rather than bloating `.ink` project files — `.ink` only stores a tiny+ * `recordingId` reference so recordings survive restarts and resume seamlessly.+ * - Supports three optimized capture areas (`artwork`, `canvas-view`, `app-window`) up to 4K with+ * idle/trailing coalescing, active-stroke deferral, frustum culling, and change deduplication.+ * - Shares WYSIWYG composition, duration/FPS timeline sampling, and watermark rendering across+ * the in-app preview player, full-screen viewer, MediaRecorder, and native FFmpeg exports.*/import {@@ -13,14 +16,62 @@ import {InkTimelapseFrameMetadata,InkTimelapseMetadata,LayerItem,+ TimelapseCaptureArea,+ TimelapseCaptureResolution,+ TimelapseExportAspectRatio,+ TimelapseExportResolution,+ TimelapseQualityPreset,} from '../types/editor';import { ViewportCompositor } from './compositor';import { SparseTileGrid } from './tileEngine';import { canvasToBlob, TimelapsePersistenceProvider } from './saveManager';--export type TimelapseDurationPreset = '15s' | '30s' | '60s' | 'full';-export type TimelapseAspectRatio = 'original' | '16:9' | '9:16' | '1:1';-export type TimelapseResolution = '720p' | '1080p';+import {+ captureNativeAppWindowToCanvas,+ computeCanvasViewDimensions,+ renderCanvasViewToCanvas,+ TimelapseLiveCaptureContext,+} from './timelapseCanvasView';+import {+ deletePersistedRecording,+ generateRecordingId,+ invokeTauri,+ invokeTauriRaw,+ isIndexedDbAvailable,+ isTauriRuntime,+ listPersistedRecordings,+ loadPersistedSession,+ lookupLinkedRecordingId,+ PersistentFrameRecord,+ PersistentTimelapseMeta,+ persistSessionMeta,+ persistSingleFrame,+ readPersistedFrame,+ saveDocumentRecordingLink,+ StoredRecordingSummary,+ toArrayBuffer,+} from './timelapseStorage';+import {+ loadWatermarkImageElement,+ renderTimelapseOutputFrame,+ renderWatermarkOverlayPng,+ TimelapseBackgroundMode,+ TimelapseWatermarkConfig,+} from './timelapseWatermark';++export type {+ TimelapseCaptureArea,+ TimelapseCaptureResolution,+ TimelapseQualityPreset,+ TimelapseLiveCaptureContext,+ StoredRecordingSummary,+ TimelapseBackgroundMode,+ TimelapseWatermarkConfig,+};++export type TimelapseDurationPreset = '15s' | '30s' | '60s' | '120s' | 'full' | 'custom';+export type TimelapseAspectRatio = TimelapseExportAspectRatio;+export type TimelapseResolution = TimelapseExportResolution;+export type TimelapseFps = 24 | 30 | 60;export interface TimelapseFrameEntry {id: string;@@ -31,23 +82,33 @@ export interface TimelapseFrameEntry {mimeType: 'image/webp' | 'image/jpeg';bytes: number;offloadedToDisk: boolean;+ captureArea?: TimelapseCaptureArea;blob?: Blob;}export interface TimelapseSessionStats {documentId: string;+ recordingId: string | null;enabled: boolean;frameCount: number;memoryBytes: number;diskFrames: number;+ storageBytes: number;+ captureArea: TimelapseCaptureArea;+ captureResolution: TimelapseCaptureResolution;+ storageBackend: 'disk' | 'indexeddb' | 'memory';}export interface TimelapseExportOptions {duration: TimelapseDurationPreset;+ customDurationSec?: number;aspectRatio: TimelapseAspectRatio;resolution: TimelapseResolution;fps?: number;+ quality?: TimelapseQualityPreset;+ backgroundMode?: TimelapseBackgroundMode;backgroundColor?: string;+ watermark?: TimelapseWatermarkConfig | null;preferFfmpeg?: boolean;}@@ -59,28 +120,41 @@ export interface TimelapseExportResult {durationSec: number;}+export interface AttachOrRestoreOptions {+ documentName?: string;+ metadata?: InkTimelapseMetadata | null;+ legacyFrames?: InkTimelapseFrameData[] | null;+ linkedDocId?: string | null;+ sourcePath?: string | null;+ fallbackRecordingId?: string | null;+ fallbackDims?: CanvasDimensions;+ onProgress?: (done: number, total: number) => void;+}+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 DEFAULT_MAX_RAM_BYTES = 48 * 1024 * 1024; // 48 MB RAM cap only when no persistent storage existsconst TAURI_BATCH_MAX_FRAMES = 128;const TAURI_BATCH_MAX_BYTES = 16 * 1024 * 1024; // 16 MB per IPC batch-function isTauriRuntime(): boolean {- return typeof window !== 'undefined' && Boolean((window as unknown as Record<string, unknown>).__TAURI_INTERNALS__);-}--async function invokeTauri<T>(cmd: string, args: Record<string, unknown>): Promise<T> {- const { invoke } = await import('@tauri-apps/api/core');- return invoke<T>(cmd, args);+export function captureResolutionToMaxDim(res: TimelapseCaptureResolution): number {+ switch (res) {+ case '720p':+ return 1280;+ case '2k':+ return 2560;+ case '4k':+ return 3840;+ default:+ return 1920; // '1080p'+ }}-async function invokeTauriRaw<T>(- cmd: string,- body: Uint8Array | ArrayBuffer | undefined,- headers: Record<string, string>-): Promise<T> {- const { invoke } = await import('@tauri-apps/api/core');- return invoke<T>(cmd, body, { headers });+export function formatTimelapseBytes(bytes: number): string {+ const safe = Math.max(0, Number(bytes) || 0);+ if (safe < 1024) return `${safe} B`;+ if (safe < 1024 * 1024) return `${(safe / 1024).toFixed(1)} KB`;+ if (safe < 1024 * 1024 * 1024) return `${(safe / (1024 * 1024)).toFixed(1)} MB`;+ return `${(safe / (1024 * 1024 * 1024)).toFixed(2)} GB`;}function packFrameIndices(indices: number[]): Uint8Array {@@ -118,17 +192,6 @@ export function packTimelapseFrameBatch(return out;}-function toArrayBuffer(raw: ArrayBuffer | Uint8Array | number[]): ArrayBuffer {- if (raw instanceof ArrayBuffer) return raw;- if (raw instanceof Uint8Array) {- if (raw.buffer instanceof ArrayBuffer && raw.byteOffset === 0 && raw.byteLength === raw.buffer.byteLength) {- return raw.buffer;- }- return raw.slice().buffer;- }- return new Uint8Array(raw).buffer;-}-async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {const buf = await blob.arrayBuffer();return new Uint8Array(buf);@@ -143,7 +206,14 @@ export function computeTimelapseDimensions(aspectRatio: TimelapseAspectRatio,resolution: TimelapseResolution): { width: number; height: number } {- const targetShort = resolution === '1080p' ? 1080 : 720;+ const targetShort =+ resolution === '4k'+ ? 2160+ : resolution === '2k'+ ? 1440+ : resolution === '1080p'+ ? 1080+ : 720;const toEven = (n: number) => Math.max(2, Math.round(n / 2) * 2);if (aspectRatio === '16:9') {@@ -160,11 +230,23 @@ export function computeTimelapseDimensions(const s = toEven(targetShort);return { width: s, height: s };}+ if (aspectRatio === '4:5') {+ const w = toEven(targetShort);+ const h = toEven((w * 5) / 4);+ return { width: w, height: h };+ }- // Original aspect ratio fitted inside targetShort on the shorter/bounded side+ // Original aspect ratio fitted cleanly within longest-edge budgetconst safeW = Math.max(1, srcWidth);const safeH = Math.max(1, srcHeight);- const maxDim = resolution === '1080p' ? 1920 : 1280;+ const maxDim =+ resolution === '4k'+ ? 3840+ : resolution === '2k'+ ? 2560+ : resolution === '1080p'+ ? 1920+ : 1280;const scale = Math.min(1, maxDim / Math.max(safeW, safeH));return {width: toEven(safeW * scale),@@ -173,19 +255,44 @@ export function computeTimelapseDimensions(}/**- * Maps captured frames onto output timeline frame indices for the selected duration preset.+ * Computes target output video duration in seconds for a duration preset.+ */+export function resolveTimelapseTargetSeconds(+ totalCapturedFrames: number,+ duration: TimelapseDurationPreset,+ fps = 30,+ customDurationSec = 30+): number {+ if (totalCapturedFrames <= 0) return 0;+ const safeFps = Math.max(1, Math.min(60, fps));+ if (duration === 'full') {+ const repeat = totalCapturedFrames < safeFps * 5 ? 2 : 1;+ return (totalCapturedFrames * repeat) / safeFps;+ }+ if (duration === 'custom') {+ return Math.max(2, Math.min(600, Number(customDurationSec) || 30));+ }+ if (duration === '15s') return 15;+ if (duration === '30s') return 30;+ if (duration === '60s') return 60;+ if (duration === '120s') return 120;+ return 30;+}++/**+ * Maps captured frames onto output timeline frame indices for the selected duration preset and FPS.*/export function sampleTimelapseFrameIndices(totalCapturedFrames: number,duration: TimelapseDurationPreset,- fps = 30+ fps = 30,+ customDurationSec = 30): number[] {if (totalCapturedFrames <= 0) return [];if (totalCapturedFrames === 1) return [0];const safeFps = Math.max(1, Math.min(60, fps));if (duration === 'full') {- // Play each captured frame smoothly (at ~10-15 steps/sec -> 2 video frames per capture if short)const out: number[] = [];const repeat = totalCapturedFrames < safeFps * 5 ? 2 : 1;for (let i = 0; i < totalCapturedFrames; i++) {@@ -194,7 +301,12 @@ export function sampleTimelapseFrameIndices(return out;}- const seconds = duration === '15s' ? 15 : duration === '30s' ? 30 : 60;+ const seconds = resolveTimelapseTargetSeconds(+ totalCapturedFrames,+ duration,+ safeFps,+ customDurationSec+ );const targetOutFrames = Math.max(1, Math.round(seconds * safeFps));const indices: number[] = [];for (let i = 0; i < targetOutFrames; i++) {@@ -208,15 +320,103 @@ export function sampleTimelapseFrameIndices(return indices;}+/**+ * Computes recommended MediaRecorder video bitrate from resolution, FPS, and quality preset.+ */+export function computeMediaRecorderBitrate(+ resolution: TimelapseResolution,+ fps: number,+ quality: TimelapseQualityPreset = 'high'+): number {+ const baseByRes =+ resolution === '4k'+ ? 18_000_000+ : resolution === '2k'+ ? 10_000_000+ : resolution === '1080p'+ ? 6_000_000+ : 3_500_000;+ const fpsFactor = fps >= 50 ? 1.45 : fps <= 24 ? 0.85 : 1.0;+ const qualityFactor =+ quality === 'standard'+ ? 0.6+ : quality === 'ultra'+ ? 1.65+ : quality === 'lossless'+ ? 2.4+ : 1.0;+ return Math.round(baseByRes * fpsFactor * qualityFactor);+}++function buildVisualSignature(+ captureArea: TimelapseCaptureArea,+ layers: LayerItem[],+ dimensions: CanvasDimensions,+ tileGrid: SparseTileGrid,+ liveCtx?: TimelapseLiveCaptureContext+): string {+ const contentVer =+ typeof tileGrid.getContentVersion === 'function' ? tileGrid.getContentVersion() : 0;+ const gridEpoch = typeof tileGrid.getGridEpoch === 'function' ? tileGrid.getGridEpoch() : 0;+ let layerSig = '';+ for (let i = 0; i < layers.length; i++) {+ const l = layers[i];+ layerSig += `${l.id}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.clipped ? 1 : 0}:${l.parentId ?? ''}:${l.maskVersion ?? 0};`;+ }+ let viewSig = '';+ if (captureArea === 'canvas-view' && liveCtx?.camera) {+ const c = liveCtx.camera;+ const vw = liveCtx.viewportElement?.clientWidth ?? 0;+ const vh = liveCtx.viewportElement?.clientHeight ?? 0;+ viewSig = `|cv:${vw}x${vh}:${Math.round(c.pan.x)},${Math.round(c.pan.y)},${c.zoom.toFixed(3)},${Math.round(c.rotation)},${c.flipX ? 1 : 0},${c.flipY ? 1 : 0}:${liveCtx.valueCheckEnabled ? 1 : 0}`;+ } else if (captureArea === 'app-window') {+ const ww = typeof window !== 'undefined' ? window.innerWidth : 0;+ const wh = typeof window !== 'undefined' ? window.innerHeight : 0;+ viewSig = `|aw:${ww}x${wh}:${Date.now() >> 8}`;+ }+ return `${captureArea}|${dimensions.width}x${dimensions.height}|${gridEpoch}:${contentVer}|${layerSig}${viewSig}`;+}++function scheduleIdleYield(timeoutMs = 180): Promise<void> {+ return new Promise<void>((resolve) => {+ const g = globalThis as unknown as {+ requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;+ };+ if (typeof g.requestIdleCallback === 'function') {+ g.requestIdleCallback(() => resolve(), { timeout: timeoutMs });+ } else {+ setTimeout(resolve, 0);+ }+ });+}++interface TrailingCaptureArgs {+ layers: LayerItem[];+ dimensions: CanvasDimensions;+ tileGrid: SparseTileGrid;+ liveCtx?: TimelapseLiveCaptureContext;+}+interface InternalSession {documentId: string;+ recordingId: string;+ documentName: string;enabled: boolean;+ captureArea: TimelapseCaptureArea;+ captureResolution: TimelapseCaptureResolution;frames: TimelapseFrameEntry[];nextIndex: number;lastCaptureAt: number;+ lastCaptureSig: string | null;pendingCapture: boolean;pendingCapturePromise: Promise<boolean> | null;+ trailingTimer: ReturnType<typeof setTimeout> | null;+ pendingTrailingArgs: TrailingCaptureArgs | null;+ writeQueue: Promise<void>;memoryBytes: number;+ storageBytes: number;+ createdAt: number;+ updatedAt: number;generation: number;}@@ -225,31 +425,57 @@ export class TimelapseRecorderManager {private captureCanvas: HTMLCanvasElement | null = null;private listeners = new Set<() => void>();private minIntervalMs: number;- private maxCaptureDim: number;+ private defaultCaptureResolution: TimelapseCaptureResolution;private maxRamBytes: number;constructor(options?: {minIntervalMs?: number;maxCaptureDim?: number;+ captureResolution?: TimelapseCaptureResolution;maxRamBytes?: number;}) {this.minIntervalMs = options?.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;- this.maxCaptureDim = options?.maxCaptureDim ?? DEFAULT_MAX_CAPTURE_DIM;this.maxRamBytes = options?.maxRamBytes ?? DEFAULT_MAX_RAM_BYTES;+ if (options?.captureResolution) {+ this.defaultCaptureResolution = options.captureResolution;+ } else if (options?.maxCaptureDim) {+ this.defaultCaptureResolution =+ options.maxCaptureDim >= 3200+ ? '4k'+ : options.maxCaptureDim >= 2200+ ? '2k'+ : options.maxCaptureDim <= 1280+ ? '720p'+ : '1080p';+ } else {+ this.defaultCaptureResolution = '1080p';+ }}- private getOrCreate(documentId: string): InternalSession {+ private getOrCreate(documentId: string, recordingIdOverride?: string): InternalSession {let sess = this.sessions.get(documentId);if (!sess) {+ const now = Date.now();sess = {documentId,+ recordingId: recordingIdOverride || generateRecordingId(),+ documentName: 'Untitled',enabled: false,+ captureArea: 'artwork',+ captureResolution: this.defaultCaptureResolution,frames: [],nextIndex: 0,lastCaptureAt: 0,+ lastCaptureSig: null,pendingCapture: false,pendingCapturePromise: null,+ trailingTimer: null,+ pendingTrailingArgs: null,+ writeQueue: Promise.resolve(),memoryBytes: 0,+ storageBytes: 0,+ createdAt: now,+ updatedAt: now,generation: 0,};this.sessions.set(documentId, sess);@@ -257,6 +483,28 @@ export class TimelapseRecorderManager {return sess;}+ private buildPersistentMeta(sess: InternalSession): PersistentTimelapseMeta {+ return {+ recordingId: sess.recordingId,+ documentName: sess.documentName || 'Untitled',+ enabled: sess.enabled,+ captureArea: sess.captureArea,+ captureResolution: sess.captureResolution,+ nextIndex: sess.nextIndex,+ createdAt: sess.createdAt,+ updatedAt: sess.updatedAt,+ };+ }++ private enqueueMetaPersist(sess: InternalSession): void {+ if (!sess.enabled && sess.frames.length === 0) return;+ const meta = this.buildPersistentMeta(sess);+ sess.writeQueue = sess.writeQueue+ .then(() => persistSessionMeta(meta))+ .then(() => {})+ .catch(() => {});+ }+public subscribe(listener: () => void): () => void {this.listeners.add(listener);return () => this.listeners.delete(listener);@@ -271,47 +519,140 @@ export class TimelapseRecorderManager {return this.sessions.get(documentId)?.enabled ?? false;}- public setRecording(documentId: string, enabled: boolean): void {+ public getRecordingId(documentId: string | null): string | null {+ if (!documentId) return null;+ const sess = this.sessions.get(documentId);+ if (!sess || (!sess.enabled && sess.frames.length === 0)) return null;+ return sess.recordingId;+ }++ public setDocumentName(documentId: string, name: string): void {+ const sess = this.sessions.get(documentId);+ if (!sess) return;+ const clean = (name || 'Untitled').replace(/\*+$/, '').trim() || 'Untitled';+ if (sess.documentName === clean) return;+ sess.documentName = clean;+ sess.updatedAt = Date.now();+ this.enqueueMetaPersist(sess);+ }++ public linkDocumentSave(+ documentId: string | null,+ opts: { documentName?: string; sourcePath?: string | null }+ ): void {+ if (!documentId) return;+ const sess = this.sessions.get(documentId);+ if (!sess || (!sess.enabled && sess.frames.length === 0)) return;+ if (opts.documentName) {+ sess.documentName = opts.documentName.replace(/\*+$/, '').trim() || sess.documentName;+ sess.updatedAt = Date.now();+ this.enqueueMetaPersist(sess);+ }+ saveDocumentRecordingLink({+ recordingId: sess.recordingId,+ docId: documentId,+ sourcePath: opts.sourcePath,+ });+ }++ public setRecording(documentId: string, enabled: boolean, documentName?: string): void {const sess = this.getOrCreate(documentId);+ if (documentName) {+ sess.documentName = documentName.replace(/\*+$/, '').trim() || sess.documentName;+ }if (sess.enabled === enabled) return;sess.enabled = enabled;+ sess.updatedAt = Date.now();+ if (!enabled && sess.trailingTimer !== null) {+ clearTimeout(sess.trailingTimer);+ sess.trailingTimer = null;+ sess.pendingTrailingArgs = null;+ }+ if (enabled || sess.frames.length > 0) {+ saveDocumentRecordingLink({ recordingId: sess.recordingId, docId: documentId });+ this.enqueueMetaPersist(sess);+ }this.notify();}- public toggleRecording(documentId: string): boolean {+ public toggleRecording(documentId: string, documentName?: string): boolean {+ const sess = this.getOrCreate(documentId);+ const next = !sess.enabled;+ this.setRecording(documentId, next, documentName);+ return next;+ }++ public setCaptureArea(documentId: string, captureArea: TimelapseCaptureArea): void {const sess = this.getOrCreate(documentId);- sess.enabled = !sess.enabled;+ if (sess.captureArea === captureArea) return;+ sess.captureArea = captureArea;+ sess.lastCaptureSig = null;+ sess.updatedAt = Date.now();+ this.enqueueMetaPersist(sess);+ this.notify();+ }++ public setCaptureResolution(+ documentId: string,+ captureResolution: TimelapseCaptureResolution+ ): void {+ const sess = this.getOrCreate(documentId);+ if (sess.captureResolution === captureResolution) return;+ sess.captureResolution = captureResolution;+ sess.lastCaptureSig = null;+ sess.updatedAt = Date.now();+ this.enqueueMetaPersist(sess);this.notify();- return sess.enabled;}public getStats(documentId: string | null): TimelapseSessionStats {+ const backend: 'disk' | 'indexeddb' | 'memory' = isTauriRuntime()+ ? 'disk'+ : isIndexedDbAvailable()+ ? 'indexeddb'+ : 'memory';+if (!documentId) {return {documentId: '',+ recordingId: null,enabled: false,frameCount: 0,memoryBytes: 0,diskFrames: 0,+ storageBytes: 0,+ captureArea: 'artwork',+ captureResolution: this.defaultCaptureResolution,+ storageBackend: backend,};}const sess = this.sessions.get(documentId);if (!sess) {return {documentId,+ recordingId: null,enabled: false,frameCount: 0,memoryBytes: 0,diskFrames: 0,+ storageBytes: 0,+ captureArea: 'artwork',+ captureResolution: this.defaultCaptureResolution,+ storageBackend: backend,};}const diskFrames = sess.frames.filter((f) => f.offloadedToDisk).length;return {documentId,+ recordingId: sess.enabled || sess.frames.length > 0 ? sess.recordingId : null,enabled: sess.enabled,frameCount: sess.frames.length,memoryBytes: sess.memoryBytes,diskFrames,+ storageBytes: sess.storageBytes,+ captureArea: sess.captureArea,+ captureResolution: sess.captureResolution,+ storageBackend: backend,};}@@ -321,219 +662,483 @@ export class TimelapseRecorderManager {public async waitForPendingCapture(documentId: string): Promise<void> {const sess = this.sessions.get(documentId);- if (sess?.pendingCapturePromise) {+ if (!sess) return;+ if (sess.trailingTimer !== null) {+ clearTimeout(sess.trailingTimer);+ sess.trailingTimer = null;+ sess.pendingTrailingArgs = null;+ }+ if (sess.pendingCapturePromise) {await sess.pendingCapturePromise.catch(() => {});}+ await sess.writeQueue.catch(() => {});}+ /**+ * Explicitly deletes all recorded frames for this document from memory AND persistent storage.+ */public async clearSession(documentId: string): Promise<void> {const sess = this.sessions.get(documentId);+ const recordingId = sess?.recordingId;if (sess) {sess.generation++;+ if (sess.trailingTimer !== null) {+ clearTimeout(sess.trailingTimer);+ sess.trailingTimer = null;+ sess.pendingTrailingArgs = null;+ }const inFlight = sess.pendingCapturePromise;if (inFlight) {await inFlight.catch(() => {});}+ await sess.writeQueue.catch(() => {});sess.frames = [];sess.nextIndex = 0;sess.memoryBytes = 0;+ sess.storageBytes = 0;sess.lastCaptureAt = 0;+ sess.lastCaptureSig = null;+ sess.updatedAt = Date.now();}- if (isTauriRuntime()) {- await invokeTauri('timelapse_clear', { sessionId: documentId }).catch(() => {});+ if (recordingId) {+ await deletePersistedRecording(recordingId);+ }+ if (sess && sess.enabled) {+ // Keep fresh metadata if recording remains armed+ this.enqueueMetaPersist(sess);+ }+ this.notify();+ }++ /**+ * Detaches a document's time-lapse session from RAM on tab close or app exit while+ * PRESERVING all recorded keyframes and metadata in external persistent storage so+ * recording seamlessly continues after app restart or document reopen.+ */+ public async detachSession(documentId: string): Promise<void> {+ const sess = this.sessions.get(documentId);+ if (!sess) return;+ if (sess.trailingTimer !== null) {+ clearTimeout(sess.trailingTimer);+ sess.trailingTimer = null;+ sess.pendingTrailingArgs = null;+ }+ const inFlight = sess.pendingCapturePromise;+ if (inFlight) {+ await inFlight.catch(() => {});}+ if (sess.enabled || sess.frames.length > 0) {+ this.enqueueMetaPersist(sess);+ await sess.writeQueue.catch(() => {});+ }+ sess.generation++;+ this.sessions.delete(documentId);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).+ * Permanently removes a session from memory AND deletes its persistent recording from storage+ * (used when explicitly discarding a crashed unsaved session or wiping data).*/public async removeSession(documentId: string): Promise<void> {const sess = this.sessions.get(documentId);+ const recordingId = sess?.recordingId ?? documentId;if (sess) {sess.generation++;+ if (sess.trailingTimer !== null) {+ clearTimeout(sess.trailingTimer);+ sess.trailingTimer = null;+ sess.pendingTrailingArgs = null;+ }const inFlight = sess.pendingCapturePromise;this.sessions.delete(documentId);if (inFlight) {await inFlight.catch(() => {});}+ await sess.writeQueue.catch(() => {});}- if (isTauriRuntime()) {- await invokeTauri('timelapse_clear', { sessionId: documentId }).catch(() => {});+ await deletePersistedRecording(recordingId);+ this.notify();+ }++ /**+ * Lists all time-lapse recordings stored persistently in local app storage / IndexedDB.+ */+ public async listStoredRecordings(): Promise<StoredRecordingSummary[]> {+ return listPersistedRecordings();+ }++ /**+ * Deletes an arbitrary stored recording by `recordingId` (detaching if currently active).+ */+ public async deleteStoredRecording(recordingId: string): Promise<void> {+ for (const [docId, sess] of this.sessions.entries()) {+ if (sess.recordingId === recordingId) {+ await this.clearSession(docId);+ return;+ }}+ await deletePersistedRecording(recordingId);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.+ * Attaches an existing persisted local recording (e.g. from the Local Recordings drawer)+ * onto `documentId` so the artist can preview, export, or continue recording on it.*/- public async restoreSession(+ public async attachExistingRecording(documentId: string,- metadata: InkTimelapseMetadata | null | undefined,- frames?: InkTimelapseFrameData[] | null,- onProgress?: (done: number, total: number) => void+ recordingId: string,+ documentName?: string+ ): Promise<{ enabled: boolean; frameCount: number }> {+ return this.attachOrRestoreSession(documentId, {+ documentName,+ fallbackRecordingId: recordingId,+ });+ }++ /**+ * Restores or reconnects a document's time-lapse session from external persistent storage+ * (by `.ink` `recordingId`, saved path/recent-doc link, or crash-recovery ID), migrating+ * any legacy embedded `.ink` frames automatically into external storage.+ */+ public async attachOrRestoreSession(+ documentId: string,+ options: AttachOrRestoreOptions): Promise<{ enabled: boolean; frameCount: number }> {const existing = this.sessions.get(documentId);const nextGen = (existing?.generation ?? 0) + 1;if (existing) {existing.generation = nextGen;+ if (existing.trailingTimer !== null) {+ clearTimeout(existing.trailingTimer);+ existing.trailingTimer = null;+ existing.pendingTrailingArgs = null;+ }if (existing.pendingCapturePromise) {await existing.pendingCapturePromise.catch(() => {});}+ await existing.writeQueue.catch(() => {});}- if (isTauriRuntime()) {- await invokeTauri('timelapse_clear', { sessionId: documentId }).catch(() => {});- }-- const validFrames = Array.isArray(frames)- ? frames+ const meta = options.metadata ?? null;+ const validLegacyFrames = Array.isArray(options.legacyFrames)+ ? options.legacyFrames.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) {+ const linkedId = lookupLinkedRecordingId({+ docId: options.linkedDocId ?? documentId,+ sourcePath: options.sourcePath,+ });++ const candidateRecordingId =+ meta?.recordingId ||+ options.fallbackRecordingId ||+ linkedId ||+ null;++ // 1. Try loading from external persistent storage (Tauri disk / Browser IndexedDB)+ let persisted = candidateRecordingId+ ? await loadPersistedSession(candidateRecordingId)+ : null;++ // Also try fallbackRecordingId if different from meta.recordingId and primary was empty+ if (+ (!persisted || (!persisted.meta && persisted.frames.length === 0)) &&+ options.fallbackRecordingId &&+ options.fallbackRecordingId !== candidateRecordingId+ ) {+ const alt = await loadPersistedSession(options.fallbackRecordingId);+ if (alt && (alt.meta || alt.frames.length > 0)) {+ persisted = alt;+ }+ }++ const hasPersisted = Boolean(persisted && (persisted.meta || persisted.frames.length > 0));+ const hasLegacy = validLegacyFrames.length > 0;+ const desiredEnabled = Boolean(meta?.enabled ?? persisted?.meta?.enabled ?? false);++ if (!hasPersisted && !hasLegacy && !desiredEnabled) {this.sessions.delete(documentId);this.notify();return { enabled: false, frameCount: 0 };}+ const resolvedRecordingId =+ persisted?.meta?.recordingId ||+ candidateRecordingId ||+ generateRecordingId();++ const now = Date.now();+ const cleanDocName =+ (options.documentName || persisted?.meta?.documentName || 'Untitled')+ .replace(/\*+$/, '')+ .trim() || 'Untitled';++ const captureArea: TimelapseCaptureArea =+ meta?.captureArea ?? persisted?.meta?.captureArea ?? 'artwork';+ const captureResolution: TimelapseCaptureResolution =+ meta?.captureResolution ?? persisted?.meta?.captureResolution ?? this.defaultCaptureResolution;+const sess: InternalSession = {documentId,- enabled,+ recordingId: resolvedRecordingId,+ documentName: cleanDocName,+ enabled: desiredEnabled,+ captureArea,+ captureResolution,frames: [],nextIndex: 0,lastCaptureAt: 0,+ lastCaptureSig: null,pendingCapture: false,pendingCapturePromise: null,+ trailingTimer: null,+ pendingTrailingArgs: null,+ writeQueue: Promise.resolve(),memoryBytes: 0,+ storageBytes: 0,+ createdAt: persisted?.meta?.createdAt || now,+ updatedAt: now,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,- };- });+ const fallbackW = Math.max(2, Math.round(options.fallbackDims?.width || 1080));+ const fallbackH = Math.max(2, Math.round(options.fallbackDims?.height || 1080));- 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++;+ // 2. Populate frame index from external persistent storage (0 RAM used for image bytes!)+ if (persisted && persisted.frames.length > 0) {+ const metaFramesByIndex = new Map<number, InkTimelapseFrameMetadata>();+ if (Array.isArray(meta?.frames)) {+ for (const fm of meta.frames) {+ if (fm && Number.isSafeInteger(fm.index) && fm.index >= 0) {+ metaFramesByIndex.set(fm.index, fm);}+ }+ }+ let maxIdx = -1;+ let totalBytes = 0;+ for (const pf of persisted.frames) {+ const fallbackFm = metaFramesByIndex.get(pf.index);+ const bytes = pf.bytes || fallbackFm?.bytes || 0;+ totalBytes += bytes;+ sess.frames.push({+ id: `tl-${resolvedRecordingId}-${pf.index}`,+ index: pf.index,+ timestamp: pf.timestamp || fallbackFm?.timestamp || 0,+ width: pf.width || fallbackFm?.width || fallbackW,+ height: pf.height || fallbackFm?.height || fallbackH,+ mimeType: pf.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp',+ bytes,+ offloadedToDisk: true,+ captureArea: pf.captureArea,+ });+ if (pf.index > maxIdx) maxIdx = pf.index;+ }+ sess.storageBytes = persisted.totalBytes || totalBytes;+ sess.nextIndex = Math.max(+ maxIdx + 1,+ persisted.meta?.nextIndex ?? 0,+ meta?.nextIndex ?? 0+ );+ options.onProgress?.(sess.frames.length, sess.frames.length);+ } else if (hasLegacy) {+ // 3. Migrate legacy embedded `.ink` frames into external persistent storage seamlessly+ await this.migrateFramesIntoPersistentStorage(+ sess,+ nextGen,+ validLegacyFrames,+ options.onProgress+ );+ if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {+ return { enabled: false, frameCount: 0 };+ }+ } else {+ sess.nextIndex = Math.max(persisted?.meta?.nextIndex ?? 0, meta?.nextIndex ?? 0);+ }- 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;- }+ saveDocumentRecordingLink({+ recordingId: resolvedRecordingId,+ docId: documentId,+ sourcePath: options.sourcePath,+ });+ if (options.linkedDocId && options.linkedDocId !== documentId) {+ saveDocumentRecordingLink({+ recordingId: resolvedRecordingId,+ docId: options.linkedDocId,+ });+ }+ this.enqueueMetaPersist(sess);- if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {- return { enabled: false, frameCount: 0 };- }+ this.notify();+ return { enabled: sess.enabled, frameCount: sess.frames.length };+ }- 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,- });- }+ private async migrateFramesIntoPersistentStorage(+ sess: InternalSession,+ expectedGen: number,+ validFrames: InkTimelapseFrameData[],+ onProgress?: (done: number, total: number) => void+ ): Promise<void> {+ const total = validFrames.length;+ 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,+ captureArea: f.captureArea,+ };+ });++ if (isTauriRuntime()) {+ let cursor = 0;+ while (cursor < total) {+ if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {+ return;+ }+ 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(sess.recordingId),+ });+ batchOffloaded = true;+ } catch {+ batchOffloaded = false;+ }- onProgress?.(cursor, total);+ if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {+ return;}- } 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;++ for (const item of batch) {+ let offloaded = batchOffloaded;+ if (!offloaded) {+ offloaded = await persistSingleFrame(+ sess.recordingId,+ {+ index: item.index,+ timestamp: item.timestamp,+ width: item.width,+ height: item.height,+ mimeType: item.mimeType,+ bytes: item.bytes.byteLength,+ captureArea: item.captureArea,+ },+ item.bytes,+ this.buildPersistentMeta(sess)+ );+ }+ const blob = offloaded+ ? undefined+ : new Blob([item.bytes as BlobPart], { type: item.mimeType });+ if (blob) sess.memoryBytes += blob.size;+ sess.storageBytes += item.bytes.byteLength;sess.frames.push({- id: `tl-${documentId}-${item.index}`,+ id: `tl-${sess.recordingId}-${item.index}`,index: item.index,timestamp: item.timestamp,width: item.width,height: item.height,mimeType: item.mimeType,- bytes: blob.size,- offloadedToDisk: false,+ bytes: item.bytes.byteLength,+ offloadedToDisk: offloaded,+ captureArea: item.captureArea,blob,});}- onProgress?.(total, total);+ onProgress?.(cursor, total);+ }+ } else {+ for (let i = 0; i < total; i++) {+ if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {+ return;+ }+ const item = normalized[i];+ const record: PersistentFrameRecord = {+ index: item.index,+ timestamp: item.timestamp,+ width: item.width,+ height: item.height,+ mimeType: item.mimeType,+ bytes: item.bytes.byteLength,+ captureArea: item.captureArea,+ };+ const persisted = await persistSingleFrame(+ sess.recordingId,+ record,+ item.bytes,+ this.buildPersistentMeta(sess)+ );+ const blob = persisted+ ? undefined+ : new Blob([item.bytes as BlobPart], { type: item.mimeType });+ if (blob) sess.memoryBytes += blob.size;+ sess.storageBytes += item.bytes.byteLength;+ sess.frames.push({+ id: `tl-${sess.recordingId}-${item.index}`,+ index: item.index,+ timestamp: item.timestamp,+ width: item.width,+ height: item.height,+ mimeType: item.mimeType,+ bytes: item.bytes.byteLength,+ offloadedToDisk: persisted,+ captureArea: item.captureArea,+ blob,+ });+ onProgress?.(i + 1, total);}-- sess.nextIndex = sess.frames.length;}- this.notify();- return { enabled: sess.enabled, frameCount: sess.frames.length };+ sess.nextIndex = sess.frames.length;+ }++ /**+ * Backward-compatible restore alias that delegates to `attachOrRestoreSession`.+ */+ public async restoreSession(+ documentId: string,+ metadata: InkTimelapseMetadata | null | undefined,+ frames?: InkTimelapseFrameData[] | null,+ onProgress?: (done: number, total: number) => void+ ): Promise<{ enabled: boolean; frameCount: number }> {+ return this.attachOrRestoreSession(documentId, {+ metadata,+ legacyFrames: frames,+ onProgress,+ });}/*** 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.+ * and persisted keyframes in local storage.*/public async restoreFromScratchDisk(documentId: string,@@ -543,114 +1148,35 @@ export class TimelapseRecorderManager {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 };+ return this.attachOrRestoreSession(documentId, {+ metadata,+ fallbackRecordingId: metadata.recordingId || documentId,+ fallbackDims,+ });}/**- * Returns lightweight JSON metadata for crash-recovery WAL manifests (no binary frame data).+ * Returns lightweight JSON metadata for `.ink` manifests and crash-recovery WAL manifests+ * (zero binary frame payloads).*/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 {+ recordingId: sess.recordingId,+ storageMode: 'external',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,- })),- }- : {}),+ captureArea: sess.captureArea,+ captureResolution: sess.captureResolution,};}/**- * Builds a lazy persistence provider used by `serializeInkProject` to stream- * keyframes into a `.ink` archive only when saving in `.ink` format.+ * Builds a lightweight persistence provider used by `serializeInkProject` so `.ink` saves+ * record the external `recordingId` reference without embedding frame binaries.*/public createPersistenceProvider(documentId: string | null): TimelapsePersistenceProvider | null {if (!documentId) return null;@@ -676,8 +1202,11 @@ export class TimelapseRecorderManager {};});return {+ recordingId: sess.recordingId,enabled: sess.enabled,nextIndex: sess.nextIndex,+ captureArea: sess.captureArea,+ captureResolution: sess.captureResolution,frames,};},@@ -691,15 +1220,42 @@ export class TimelapseRecorderManager {};}+ private scheduleTrailingCapture(+ documentId: string,+ sess: InternalSession,+ args: TrailingCaptureArgs,+ delayMs: number+ ): void {+ sess.pendingTrailingArgs = args;+ if (sess.trailingTimer !== null) return;+ sess.trailingTimer = setTimeout(() => {+ sess.trailingTimer = null;+ const latest = sess.pendingTrailingArgs;+ sess.pendingTrailingArgs = null;+ if (!latest || this.sessions.get(documentId) !== sess || !sess.enabled) return;+ void this.captureKeyframe(+ documentId,+ latest.layers,+ latest.dimensions,+ latest.tileGrid,+ false,+ latest.liveCtx+ );+ }, Math.max(24, delayMs));+ }+/**- * Captures a throttled low/medium-res WebP/JPEG snapshot of the composited document.+ * Captures a throttled, deduplicated, off-frame WebP/JPEG keyframe according to the selected+ * capture area (`artwork`, `canvas-view`, `app-window`) and capture resolution (`720p`..`4k`),+ * offloading immediately to external persistent storage.*/public async captureKeyframe(documentId: string,layers: LayerItem[],dimensions: CanvasDimensions,tileGrid: SparseTileGrid,- force = false+ force = false,+ liveCtx?: TimelapseLiveCaptureContext): Promise<boolean> {const sess = this.sessions.get(documentId);if (!sess || !sess.enabled) return false;@@ -707,8 +1263,46 @@ export class TimelapseRecorderManager {return false;}+ if (liveCtx?.documentName) {+ const cleanName = liveCtx.documentName.replace(/\*+$/, '').trim();+ if (cleanName) sess.documentName = cleanName;+ }++ // Never compete with active stylus/pointer strokes — defer cleanly to trailing capture!+ if (!force && liveCtx?.isDrawingActive?.()) {+ this.scheduleTrailingCapture(+ documentId,+ sess,+ { layers, dimensions, tileGrid, liveCtx },+ Math.max(120, this.minIntervalMs)+ );+ return false;+ }+const now = Date.now();- if (!force && (sess.pendingCapture || now - sess.lastCaptureAt < this.minIntervalMs)) {+ const elapsed = now - sess.lastCaptureAt;+ if (!force && (sess.pendingCapture || elapsed < this.minIntervalMs)) {+ const waitMs = sess.pendingCapture+ ? Math.max(120, this.minIntervalMs)+ : Math.max(32, this.minIntervalMs - elapsed + 16);+ this.scheduleTrailingCapture(+ documentId,+ sess,+ { layers, dimensions, tileGrid, liveCtx },+ waitMs+ );+ return false;+ }++ // Fast duplicate check so no-op steps skip encoding and disk I/O completely+ const visualSig = buildVisualSignature(+ sess.captureArea,+ layers,+ dimensions,+ tileGrid,+ liveCtx+ );+ if (!force && sess.lastCaptureSig === visualSig) {return false;}@@ -719,44 +1313,108 @@ export class TimelapseRecorderManager {let run: Promise<boolean> | null = null;run = (async (): Promise<boolean> => {try {- // Yield out of the synchronous React commit frame on large canvases so timelapse capture never hitches stroke commit- if (!force && dimensions.width * dimensions.height >= 12_000_000) {- await new Promise<void>((resolve) => setTimeout(resolve, 0));- if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ // Yield out of the synchronous stroke commit frame so drawing latency stays 0ms+ if (!force) {+ await scheduleIdleYield(160);+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen || !sess.enabled) {+ return false;+ }+ // If the artist immediately started another stroke before idle ran, defer again+ if (liveCtx?.isDrawingActive?.()) {+ this.scheduleTrailingCapture(+ documentId,+ sess,+ { layers, dimensions, tileGrid, liveCtx },+ Math.max(140, this.minIntervalMs)+ );return false;}}- 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 }- );+ const maxCaptureDim = captureResolutionToMaxDim(sess.captureResolution);+ const area = sess.captureArea;+ let outW = 0;+ let outH = 0;+ let capturedAreaUsed: TimelapseCaptureArea = area;++ if (area === 'app-window') {+ const nativeRes = await captureNativeAppWindowToCanvas(+ this.captureCanvas,+ maxCaptureDim+ );+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }+ if (nativeRes) {+ outW = nativeRes.width;+ outH = nativeRes.height;+ capturedAreaUsed = 'app-window';+ }+ }++ if (outW === 0 && (area === 'canvas-view' || area === 'app-window')) {+ const vp = liveCtx?.viewportElement;+ const cam = liveCtx?.camera;+ const vpW = vp?.clientWidth ?? 0;+ const vpH = vp?.clientHeight ?? 0;+ if (vpW >= 32 && vpH >= 32 && cam) {+ const cvDims = computeCanvasViewDimensions(vpW, vpH, maxCaptureDim);+ this.captureCanvas.width = cvDims.width;+ this.captureCanvas.height = cvDims.height;+ const rendered = renderCanvasViewToCanvas(+ this.captureCanvas,+ layers,+ dimensions,+ tileGrid,+ vpW,+ vpH,+ cam,+ {+ showCheckerboard: liveCtx?.showCheckerboard,+ valueCheckEnabled: liveCtx?.valueCheckEnabled,+ matteColor: liveCtx?.matteColor,+ }+ );+ if (rendered) {+ outW = cvDims.width;+ outH = cvDims.height;+ capturedAreaUsed = area === 'app-window' ? 'canvas-view' : 'canvas-view';+ }+ }+ }++ // Default or fallback: optimized Artwork only LOD capture+ if (outW === 0) {+ const scale = Math.min(1, maxCaptureDim / Math.max(dimensions.width, dimensions.height));+ outW = Math.max(2, Math.round((dimensions.width * scale) / 2) * 2);+ outH = Math.max(2, Math.round((dimensions.height * scale) / 2) * 2);+ this.captureCanvas.width = outW;+ this.captureCanvas.height = outH;+ ViewportCompositor.renderLowResPreview(+ this.captureCanvas,+ layers,+ dimensions,+ tileGrid,+ { showCheckerboard: false }+ );+ capturedAreaUsed = 'artwork';+ }++ const encodeQuality = maxCaptureDim >= 2560 ? 0.80 : 0.82;let mimeType: 'image/webp' | 'image/jpeg' = 'image/webp';let blob: Blob;try {- blob = await canvasToBlob(this.captureCanvas, 'image/webp', 0.82);+ blob = await canvasToBlob(this.captureCanvas, 'image/webp', encodeQuality);if (blob.type !== 'image/webp') {mimeType = 'image/jpeg';}} catch {mimeType = 'image/jpeg';- blob = await canvasToBlob(this.captureCanvas, 'image/jpeg', 0.82);+ blob = await canvasToBlob(this.captureCanvas, 'image/jpeg', encodeQuality);}if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {@@ -764,8 +1422,11 @@ export class TimelapseRecorderManager {}const idx = sess.nextIndex++;+ sess.lastCaptureSig = visualSig;+ sess.updatedAt = now;+const entry: TimelapseFrameEntry = {- id: `tl-${documentId}-${idx}`,+ id: `tl-${sess.recordingId}-${idx}`,index: idx,timestamp: now,width: outW,@@ -773,52 +1434,69 @@ export class TimelapseRecorderManager {mimeType,bytes: blob.size,offloadedToDisk: false,+ captureArea: capturedAreaUsed,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;- }+ const metaSnapshot = this.buildPersistentMeta(sess);+ const frameRecord: PersistentFrameRecord = {+ index: idx,+ timestamp: now,+ width: outW,+ height: outH,+ mimeType,+ bytes: blob.size,+ captureArea: capturedAreaUsed,+ };++ const frameBytes = await blobToUint8Array(blob);+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }++ // Persist immediately to external storage (Tauri persistent disk or Browser IndexedDB)+ const persisted = await persistSingleFrame(+ sess.recordingId,+ frameRecord,+ frameBytes,+ metaSnapshot+ );+ if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {+ return false;+ }++ if (persisted) {+ entry.offloadedToDisk = true;+ entry.blob = undefined; // Keep JS heap RAM usage at 0} else {sess.memoryBytes += entry.bytes;}+ sess.storageBytes += 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) {+ // Save persistent metadata on first frame or periodically so meta.json stays fresh+ if (sess.frames.length === 1 || sess.frames.length % 10 === 0) {+ this.enqueueMetaPersist(sess);+ }++ // Bounded RAM thinning ONLY when running without any persistent backend (e.g. headless fallback)+ if (!persisted && sess.memoryBytes > this.maxRamBytes && sess.frames.length > 8) {const thinned: TimelapseFrameEntry[] = [];- let bytes = 0;+ let memBytes = 0;+ let totalBytes = 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;+ totalBytes += f.bytes;+ memBytes += f.offloadedToDisk ? 0 : f.bytes;}}sess.frames = thinned;- sess.memoryBytes = bytes;+ sess.memoryBytes = memBytes;+ sess.storageBytes = totalBytes;}this.notify();@@ -836,7 +1514,7 @@ export class TimelapseRecorderManager {}/**- * Resolves a frame entry into raw binary bytes (reading back from Tauri scratch disk if offloaded).+ * Resolves a frame entry into raw binary bytes (reading back from external persistent storage if offloaded).*/public async loadFrameBytes(documentId: string,@@ -849,27 +1527,16 @@ export class TimelapseRecorderManager {return null;}}- if (frame.offloadedToDisk && isTauriRuntime()) {- try {- const raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>(- 'timelapse_read_frame',- undefined,- {- 'x-session-id': encodeURIComponent(documentId),- 'x-frame-index': String(frame.index),- 'x-ext': frame.mimeType === 'image/webp' ? 'webp' : 'jpg',- }- );- return new Uint8Array(toArrayBuffer(raw));- } catch {- return null;- }+ const sess = this.sessions.get(documentId);+ const recordingId = sess?.recordingId ?? documentId;+ if (frame.offloadedToDisk) {+ return readPersistedFrame(recordingId, frame.index, frame.mimeType);}return null;}/**- * Resolves a frame entry into a Blob (reading back from Tauri scratch disk if offloaded).+ * Resolves a frame entry into a Blob (reading back from external persistent storage if offloaded).*/public async loadFrameBlob(documentId: string,@@ -891,34 +1558,42 @@ export class TimelapseRecorderManager {}/**- * Renders captured keyframes into a downloadable WebM or MP4 video.+ * Renders captured keyframes into a downloadable WebM or MP4 video with full FPS, quality,+ * duration, resolution, aspect ratio, background mode, and watermark fidelity.*/public async exportVideo(documentId: string,options: TimelapseExportOptions,onProgress?: (progress: number) => void): Promise<TimelapseExportResult> {+ await this.waitForPendingCapture(documentId);const sess = this.sessions.get(documentId);if (!sess || sess.frames.length === 0) {throw new Error('No time-lapse frames recorded for this document.');}- const fps = options.fps ?? 30;- const firstFrame = sess.frames[0];+ const fps = Math.max(1, Math.min(60, Math.round(options.fps ?? 30)));+ const quality: TimelapseQualityPreset = options.quality ?? 'high';+ const bgMode: TimelapseBackgroundMode = options.backgroundMode ?? (options.backgroundColor === '#141414' ? 'dark' : 'white');+ const bgColor =+ options.backgroundColor || (bgMode === 'dark' ? '#141414' : '#ffffff');++ // Use the latest frame dimensions for 'original' aspect ratio so recent capture-area choices define aspect cleanly+ const refFrame = sess.frames[sess.frames.length - 1] ?? sess.frames[0];const targetDims = computeTimelapseDimensions(- firstFrame.width,- firstFrame.height,+ refFrame.width,+ refFrame.height,options.aspectRatio,options.resolution);const sampledIndices = sampleTimelapseFrameIndices(sess.frames.length,options.duration,- fps+ fps,+ options.customDurationSec);- const bgColor = options.backgroundColor || '#ffffff';- // Try native FFmpeg export in Tauri when requested and frames are on disk+ // 1. Native FFmpeg hardware-friendly MP4 export in Tauri when frames are persisted on diskif (options.preferFfmpeg &&isTauriRuntime() &&@@ -926,20 +1601,48 @@ export class TimelapseRecorderManager {) {const hasFfmpeg = await this.checkFfmpegAvailable();if (hasFfmpeg) {- onProgress?.(0.2);+ onProgress?.(0.15);const packedIndices = packFrameIndices(sampledIndices.map((idx) => sess.frames[idx].index));++ let wmOverlay: { bytes: Uint8Array; x: number; y: number } | null = null;+ if (options.watermark?.enabled) {+ wmOverlay = await renderWatermarkOverlayPng(+ targetDims.width,+ targetDims.height,+ options.watermark+ ).catch(() => null);+ }++ let body: Uint8Array;+ const headers: Record<string, string> = {+ 'x-session-id': encodeURIComponent(sess.recordingId),+ 'x-ext': refFrame.mimeType === 'image/webp' ? 'webp' : 'jpg',+ 'x-fps': String(fps),+ 'x-width': String(targetDims.width),+ 'x-height': String(targetDims.height),+ 'x-bg-color': encodeURIComponent(bgColor),+ 'x-bg-blur': bgMode === 'blur' ? '1' : '0',+ 'x-quality': quality,+ };++ if (wmOverlay && wmOverlay.bytes.byteLength > 0) {+ body = new Uint8Array(packedIndices.byteLength + wmOverlay.bytes.byteLength);+ body.set(packedIndices, 0);+ body.set(wmOverlay.bytes, packedIndices.byteLength);+ headers['x-watermark-bytes'] = String(wmOverlay.bytes.byteLength);+ headers['x-watermark-x'] = String(wmOverlay.x);+ headers['x-watermark-y'] = String(wmOverlay.y);+ } else {+ body = packedIndices;+ }++ onProgress?.(0.3);const mp4Raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>('timelapse_export_ffmpeg',- packedIndices,- {- 'x-session-id': encodeURIComponent(documentId),- 'x-ext': firstFrame.mimeType === 'image/webp' ? 'webp' : 'jpg',- 'x-fps': String(fps),- 'x-width': String(targetDims.width),- 'x-height': String(targetDims.height),- }+ body,+ headers);onProgress?.(1);return {@@ -952,7 +1655,7 @@ export class TimelapseRecorderManager {}}- // Browser / WebView MediaRecorder video pipeline+ // 2. Browser / WebView MediaRecorder video pipelineif (typeof document === 'undefined' || typeof MediaRecorder === 'undefined') {throw new Error('Video recording is not supported in this environment.');}@@ -973,10 +1676,17 @@ export class TimelapseRecorderManager {candidateMimes.find((m) => MediaRecorder.isTypeSupported(m)) || 'video/webm';const extension = mimeType.includes('mp4') ? '.mp4' : '.webm';+ const wmImg =+ options.watermark?.enabled &&+ options.watermark.mode === 'image' &&+ options.watermark.imageDataUrl+ ? await loadWatermarkImageElement(options.watermark.imageDataUrl)+ : null;+const stream = canvas.captureStream(fps);const recorder = new MediaRecorder(stream, {mimeType,- videoBitsPerSecond: options.resolution === '1080p' ? 6_000_000 : 3_500_000,+ videoBitsPerSecond: computeMediaRecorderBitrate(options.resolution, fps, quality),});const chunks: BlobPart[] = [];@@ -989,62 +1699,87 @@ export class TimelapseRecorderManager {recorder.onerror = () => reject(new Error('MediaRecorder encoding failed.'));});- // Cache decoded ImageBitmaps by source frame index to avoid redundant decodes on repeated frames- const imageCache = new Map<number, HTMLImageElement>();- const loadImage = async (srcIdx: number): Promise<HTMLImageElement | null> => {- const cached = imageCache.get(srcIdx);+ // Bounded LRU cache of decoded frames (prefers off-main-thread ImageBitmap)+ const decodedCache = new Map<number, ImageBitmap | HTMLImageElement>();+ const canUseBitmap = typeof createImageBitmap === 'function';++ const decodeSource = async (+ srcIdx: number+ ): Promise<ImageBitmap | HTMLImageElement | null> => {+ const cached = decodedCache.get(srcIdx);if (cached) return cached;const frame = sess.frames[srcIdx];if (!frame) return null;const blob = await this.loadFrameBlob(documentId, frame);if (!blob) return null;- const url = URL.createObjectURL(blob);- const img = await new Promise<HTMLImageElement | null>((resolve) => {- const el = new Image();- el.onload = () => {- URL.revokeObjectURL(url);- resolve(el);- };- el.onerror = () => {- URL.revokeObjectURL(url);- resolve(null);- };- el.src = url;- });- if (img) {- if (imageCache.size > 12) {- const firstKey = imageCache.keys().next().value;- if (firstKey !== undefined) imageCache.delete(firstKey);++ let decoded: ImageBitmap | HTMLImageElement | null = null;+ if (canUseBitmap) {+ try {+ decoded = await createImageBitmap(blob);+ } catch {+ decoded = null;}- imageCache.set(srcIdx, img);}- return img;+ if (!decoded) {+ const url = URL.createObjectURL(blob);+ decoded = await new Promise<HTMLImageElement | null>((resolve) => {+ const el = new Image();+ el.onload = () => {+ URL.revokeObjectURL(url);+ resolve(el);+ };+ el.onerror = () => {+ URL.revokeObjectURL(url);+ resolve(null);+ };+ el.src = url;+ });+ }+ if (decoded) {+ if (decodedCache.size >= 14) {+ const oldestKey = decodedCache.keys().next().value;+ if (oldestKey !== undefined) {+ const oldest = decodedCache.get(oldestKey);+ if (oldest && 'close' in oldest && typeof oldest.close === 'function') {+ oldest.close();+ }+ decodedCache.delete(oldestKey);+ }+ }+ decodedCache.set(srcIdx, decoded);+ }+ return decoded;};recorder.start();const frameIntervalMs = Math.max(16, Math.round(1000 / fps));+ let lastDrawnSrcIdx = -1;- for (let i = 0; i < sampledIndices.length; i++) {- const srcIdx = sampledIndices[i];- const img = await loadImage(srcIdx);-- ctx.fillStyle = bgColor;- ctx.fillRect(0, 0, targetDims.width, targetDims.height);-- if (img) {- const scale = Math.min(- targetDims.width / Math.max(1, img.naturalWidth || img.width),- targetDims.height / Math.max(1, img.naturalHeight || img.height)- );- const drawW = (img.naturalWidth || img.width) * scale;- const drawH = (img.naturalHeight || img.height) * scale;- const dx = (targetDims.width - drawW) * 0.5;- const dy = (targetDims.height - drawH) * 0.5;- ctx.drawImage(img, dx, dy, drawW, drawH);+ try {+ for (let i = 0; i < sampledIndices.length; i++) {+ const srcIdx = sampledIndices[i];+ // Optimization: skip redundant canvas redraw when consecutive timeline frames share the same keyframe+ if (srcIdx !== lastDrawnSrcIdx) {+ const img = await decodeSource(srcIdx);+ renderTimelapseOutputFrame(ctx, img, targetDims.width, targetDims.height, {+ backgroundMode: bgMode,+ backgroundColor: bgColor,+ watermark: options.watermark,+ watermarkImage: wmImg,+ });+ lastDrawnSrcIdx = srcIdx;+ }+ onProgress?.((i + 1) / sampledIndices.length);+ await new Promise((r) => setTimeout(r, frameIntervalMs));}-- onProgress?.((i + 1) / sampledIndices.length);- await new Promise((r) => setTimeout(r, frameIntervalMs));+ } finally {+ for (const item of decodedCache.values()) {+ if ('close' in item && typeof item.close === 'function') {+ item.close();+ }+ }+ decodedCache.clear();}recorder.stop();diff --git a/src/utils/timelapseStorage.ts b/src/utils/timelapseStorage.tsnew file mode 100644index 0000000..0489253--- /dev/null+++ b/src/utils/timelapseStorage.ts@@ -0,0 +1,649 @@+/**+ * External Persistent Time-lapse Storage Adapter+ *+ * Keeps time-lapse keyframes out of `.ink` project files while persisting them reliably across+ * app restarts, tab closes, and crashes:+ * - Tauri Desktop: `%LOCALAPPDATA%/inkstudio_timelapse/<recordingId>/` (append-only `frames.ndjson` + atomic `meta.json`)+ * - Browser / WebView fallback: IndexedDB (`InkStudioTimelapseDB`) so frames consume zero JS heap RAM+ * and survive page reloads / restarts+ * - Document-to-recording link index in safe localStorage so even non-`.ink` files (.psd, .png) and+ * Recent Documents seamlessly reconnect to their time-lapse recording on reopen.+ */++import {+ TimelapseCaptureArea,+ TimelapseCaptureResolution,+} from '../types/editor';+import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';++export interface PersistentTimelapseMeta {+ recordingId: string;+ documentName: string;+ enabled: boolean;+ captureArea: TimelapseCaptureArea;+ captureResolution: TimelapseCaptureResolution;+ nextIndex: number;+ createdAt: number;+ updatedAt: number;+}++export interface PersistentFrameRecord {+ index: number;+ timestamp: number;+ width: number;+ height: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: number;+ captureArea?: TimelapseCaptureArea;+}++export interface LoadedPersistentSession {+ meta: PersistentTimelapseMeta | null;+ frames: PersistentFrameRecord[];+ totalBytes: number;+}++export interface StoredRecordingSummary {+ recordingId: string;+ documentName: string;+ enabled: boolean;+ captureArea: TimelapseCaptureArea;+ captureResolution: TimelapseCaptureResolution;+ frameCount: number;+ totalBytes: number;+ createdAt: number;+ updatedAt: number;+}++export interface DocumentRecordingLinkMap {+ byDocId: Record<string, string>;+ byPath: Record<string, string>;+ lastActiveRecordingId?: string;+}++const DOC_LINK_LS_KEY = 'inkstudio_timelapse_doc_links_v1';+const MAX_LINK_ENTRIES = 200;++const IDB_NAME = 'InkStudioTimelapseDB';+const IDB_VERSION = 1;+const IDB_SESSIONS_STORE = 'sessions';+const IDB_FRAMES_STORE = 'frames';++export function isTauriRuntime(): boolean {+ return (+ typeof window !== 'undefined' &&+ Boolean((window as unknown as Record<string, unknown>).__TAURI_INTERNALS__)+ );+}++let cachedTauriInvokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;++function getTauriInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {+ if (!cachedTauriInvokePromise) {+ cachedTauriInvokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);+ }+ return cachedTauriInvokePromise;+}++export async function invokeTauri<T>(cmd: string, args: Record<string, unknown>): Promise<T> {+ const invoke = await getTauriInvoke();+ return invoke<T>(cmd, args);+}++export async function invokeTauriRaw<T>(+ cmd: string,+ body: Uint8Array | ArrayBuffer | undefined,+ headers: Record<string, string>+): Promise<T> {+ const invoke = await getTauriInvoke();+ return invoke<T>(cmd, body, { headers });+}++export function toArrayBuffer(raw: ArrayBuffer | Uint8Array | number[]): ArrayBuffer {+ if (raw instanceof ArrayBuffer) return raw;+ if (raw instanceof Uint8Array) {+ if (+ raw.buffer instanceof ArrayBuffer &&+ raw.byteOffset === 0 &&+ raw.byteLength === raw.buffer.byteLength+ ) {+ return raw.buffer;+ }+ return raw.slice().buffer;+ }+ return new Uint8Array(raw).buffer;+}++export function generateRecordingId(): string {+ try {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ return `tl-${crypto.randomUUID()}`;+ }+ } catch {+ // fallback below+ }+ return `tl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+}++export function normalizeLinkPath(rawPath: string | undefined | null): string | null {+ if (!rawPath || typeof rawPath !== 'string') return null;+ const trimmed = rawPath.trim().replace(/\\/g, '/').toLowerCase();+ if (!trimmed || trimmed.endsWith('*')) return null;+ return trimmed;+}++function readLinkMap(): DocumentRecordingLinkMap {+ try {+ const raw = safeLocalStorageGetItem(DOC_LINK_LS_KEY);+ if (!raw) return { byDocId: {}, byPath: {} };+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return { byDocId: {}, byPath: {} };+ return {+ byDocId: parsed.byDocId && typeof parsed.byDocId === 'object' ? { ...parsed.byDocId } : {},+ byPath: parsed.byPath && typeof parsed.byPath === 'object' ? { ...parsed.byPath } : {},+ ...(typeof parsed.lastActiveRecordingId === 'string'+ ? { lastActiveRecordingId: parsed.lastActiveRecordingId }+ : {}),+ };+ } catch {+ return { byDocId: {}, byPath: {} };+ }+}++function pruneMapKeys(map: Record<string, string>): Record<string, string> {+ const keys = Object.keys(map);+ if (keys.length <= MAX_LINK_ENTRIES) return map;+ const trimmed: Record<string, string> = {};+ for (const k of keys.slice(keys.length - MAX_LINK_ENTRIES)) {+ trimmed[k] = map[k];+ }+ return trimmed;+}++function writeLinkMap(map: DocumentRecordingLinkMap): void {+ const compact: DocumentRecordingLinkMap = {+ byDocId: pruneMapKeys(map.byDocId),+ byPath: pruneMapKeys(map.byPath),+ ...(map.lastActiveRecordingId ? { lastActiveRecordingId: map.lastActiveRecordingId } : {}),+ };+ safeLocalStorageSetItem(DOC_LINK_LS_KEY, JSON.stringify(compact), 'timelapse document links');+}++export function saveDocumentRecordingLink(opts: {+ recordingId: string;+ docId?: string | null;+ sourcePath?: string | null;+}): void {+ if (!opts.recordingId) return;+ const map = readLinkMap();+ if (opts.docId) {+ map.byDocId[opts.docId] = opts.recordingId;+ }+ const normPath = normalizeLinkPath(opts.sourcePath);+ if (normPath) {+ map.byPath[normPath] = opts.recordingId;+ }+ map.lastActiveRecordingId = opts.recordingId;+ writeLinkMap(map);+}++export function lookupLinkedRecordingId(opts: {+ docId?: string | null;+ sourcePath?: string | null;+}): string | null {+ const map = readLinkMap();+ if (opts.docId && map.byDocId[opts.docId]) {+ return map.byDocId[opts.docId];+ }+ const normPath = normalizeLinkPath(opts.sourcePath);+ if (normPath && map.byPath[normPath]) {+ return map.byPath[normPath];+ }+ return null;+}++export function removeRecordingLinks(recordingId: string): void {+ const map = readLinkMap();+ let changed = false;+ for (const [k, v] of Object.entries(map.byDocId)) {+ if (v === recordingId) {+ delete map.byDocId[k];+ changed = true;+ }+ }+ for (const [k, v] of Object.entries(map.byPath)) {+ if (v === recordingId) {+ delete map.byPath[k];+ changed = true;+ }+ }+ if (map.lastActiveRecordingId === recordingId) {+ delete map.lastActiveRecordingId;+ changed = true;+ }+ if (changed) {+ writeLinkMap(map);+ }+}++// --- IndexedDB persistent fallback for Browser / Web environments ---++interface IdbStoredSessionRecord extends PersistentTimelapseMeta {+ frames: PersistentFrameRecord[];+ totalBytes: number;+}++interface IdbStoredFrameRow {+ key: string;+ recordingId: string;+ index: number;+ mimeType: 'image/webp' | 'image/jpeg';+ bytes: Uint8Array;+}++let cachedIdbPromise: Promise<IDBDatabase | null> | null = null;++function getIndexedDbApi(): IDBFactory | null {+ if (typeof indexedDB !== 'undefined' && indexedDB) return indexedDB;+ if (typeof window !== 'undefined' && window.indexedDB) return window.indexedDB;+ return null;+}++function openTimelapseIdb(): Promise<IDBDatabase | null> {+ const idb = getIndexedDbApi();+ if (!idb) return Promise.resolve(null);+ if (cachedIdbPromise) return cachedIdbPromise;++ cachedIdbPromise = new Promise<IDBDatabase | null>((resolve) => {+ try {+ const req = idb.open(IDB_NAME, IDB_VERSION);+ req.onupgradeneeded = () => {+ const db = req.result;+ if (!db.objectStoreNames.contains(IDB_SESSIONS_STORE)) {+ db.createObjectStore(IDB_SESSIONS_STORE, { keyPath: 'recordingId' });+ }+ if (!db.objectStoreNames.contains(IDB_FRAMES_STORE)) {+ const store = db.createObjectStore(IDB_FRAMES_STORE, { keyPath: 'key' });+ store.createIndex('recordingId', 'recordingId', { unique: false });+ }+ };+ req.onsuccess = () => resolve(req.result);+ req.onerror = () => {+ cachedIdbPromise = null;+ resolve(null);+ };+ } catch {+ cachedIdbPromise = null;+ resolve(null);+ }+ });+ return cachedIdbPromise;+}++export function isIndexedDbAvailable(): boolean {+ return Boolean(getIndexedDbApi());+}++async function idbSaveMeta(meta: PersistentTimelapseMeta): Promise<boolean> {+ const db = await openTimelapseIdb();+ if (!db) return false;+ return new Promise<boolean>((resolve) => {+ try {+ const tx = db.transaction(IDB_SESSIONS_STORE, 'readwrite');+ const store = tx.objectStore(IDB_SESSIONS_STORE);+ const getReq = store.get(meta.recordingId);+ getReq.onsuccess = () => {+ const existing = getReq.result as IdbStoredSessionRecord | undefined;+ const merged: IdbStoredSessionRecord = {+ ...meta,+ frames: existing?.frames ?? [],+ totalBytes: existing?.totalBytes ?? 0,+ };+ store.put(merged);+ };+ tx.oncomplete = () => resolve(true);+ tx.onerror = () => resolve(false);+ } catch {+ resolve(false);+ }+ });+}++async function idbWriteFrame(+ recordingId: string,+ record: PersistentFrameRecord,+ bytes: Uint8Array,+ metaFallback?: PersistentTimelapseMeta+): Promise<boolean> {+ const db = await openTimelapseIdb();+ if (!db) return false;+ return new Promise<boolean>((resolve) => {+ try {+ const tx = db.transaction([IDB_FRAMES_STORE, IDB_SESSIONS_STORE], 'readwrite');+ const frameStore = tx.objectStore(IDB_FRAMES_STORE);+ const sessionStore = tx.objectStore(IDB_SESSIONS_STORE);++ const frameRow: IdbStoredFrameRow = {+ key: `${recordingId}:${record.index}`,+ recordingId,+ index: record.index,+ mimeType: record.mimeType,+ bytes,+ };+ frameStore.put(frameRow);++ const getReq = sessionStore.get(recordingId);+ getReq.onsuccess = () => {+ const existing = getReq.result as IdbStoredSessionRecord | undefined;+ const base: IdbStoredSessionRecord = existing ?? {+ recordingId,+ documentName: metaFallback?.documentName ?? 'Untitled',+ enabled: metaFallback?.enabled ?? true,+ captureArea: metaFallback?.captureArea ?? 'artwork',+ captureResolution: metaFallback?.captureResolution ?? '1080p',+ nextIndex: record.index + 1,+ createdAt: metaFallback?.createdAt ?? Date.now(),+ updatedAt: Date.now(),+ frames: [],+ totalBytes: 0,+ };+ const existingIdx = base.frames.findIndex((f) => f.index === record.index);+ if (existingIdx >= 0) {+ base.totalBytes = Math.max(0, base.totalBytes - base.frames[existingIdx].bytes) + record.bytes;+ base.frames[existingIdx] = record;+ } else {+ base.frames.push(record);+ base.frames.sort((a, b) => a.index - b.index);+ base.totalBytes += record.bytes;+ }+ base.nextIndex = Math.max(base.nextIndex, record.index + 1);+ base.updatedAt = Date.now();+ sessionStore.put(base);+ };++ tx.oncomplete = () => resolve(true);+ tx.onerror = () => resolve(false);+ } catch {+ resolve(false);+ }+ });+}++async function idbReadFrame(recordingId: string, index: number): Promise<Uint8Array | null> {+ const db = await openTimelapseIdb();+ if (!db) return null;+ return new Promise<Uint8Array | null>((resolve) => {+ try {+ const tx = db.transaction(IDB_FRAMES_STORE, 'readonly');+ const req = tx.objectStore(IDB_FRAMES_STORE).get(`${recordingId}:${index}`);+ req.onsuccess = () => {+ const row = req.result as IdbStoredFrameRow | undefined;+ if (!row?.bytes) {+ resolve(null);+ return;+ }+ resolve(row.bytes instanceof Uint8Array ? row.bytes : new Uint8Array(row.bytes));+ };+ req.onerror = () => resolve(null);+ } catch {+ resolve(null);+ }+ });+}++async function idbLoadSession(recordingId: string): Promise<LoadedPersistentSession | null> {+ const db = await openTimelapseIdb();+ if (!db) return null;+ return new Promise<LoadedPersistentSession | null>((resolve) => {+ try {+ const tx = db.transaction(IDB_SESSIONS_STORE, 'readonly');+ const req = tx.objectStore(IDB_SESSIONS_STORE).get(recordingId);+ req.onsuccess = () => {+ const rec = req.result as IdbStoredSessionRecord | undefined;+ if (!rec) {+ resolve({ meta: null, frames: [], totalBytes: 0 });+ return;+ }+ const { frames, totalBytes, ...meta } = rec;+ resolve({+ meta,+ frames: Array.isArray(frames) ? frames : [],+ totalBytes: Number.isFinite(totalBytes) ? totalBytes : 0,+ });+ };+ req.onerror = () => resolve(null);+ } catch {+ resolve(null);+ }+ });+}++async function idbListSessions(): Promise<StoredRecordingSummary[]> {+ const db = await openTimelapseIdb();+ if (!db) return [];+ return new Promise<StoredRecordingSummary[]>((resolve) => {+ try {+ const tx = db.transaction(IDB_SESSIONS_STORE, 'readonly');+ const req = tx.objectStore(IDB_SESSIONS_STORE).getAll();+ req.onsuccess = () => {+ const rows = (req.result as IdbStoredSessionRecord[] | undefined) ?? [];+ const summaries: StoredRecordingSummary[] = rows+ .filter((r) => r && (r.frames.length > 0 || r.enabled))+ .map((r) => ({+ recordingId: r.recordingId,+ documentName: r.documentName || 'Untitled',+ enabled: Boolean(r.enabled),+ captureArea: r.captureArea || 'artwork',+ captureResolution: r.captureResolution || '1080p',+ frameCount: r.frames.length,+ totalBytes: r.totalBytes || 0,+ createdAt: r.createdAt || 0,+ updatedAt: r.updatedAt || 0,+ }))+ .sort((a, b) => b.updatedAt - a.updatedAt);+ resolve(summaries);+ };+ req.onerror = () => resolve([]);+ } catch {+ resolve([]);+ }+ });+}++async function idbClearSession(recordingId: string): Promise<void> {+ const db = await openTimelapseIdb();+ if (!db) return;+ await new Promise<void>((resolve) => {+ try {+ const tx = db.transaction([IDB_SESSIONS_STORE, IDB_FRAMES_STORE], 'readwrite');+ tx.objectStore(IDB_SESSIONS_STORE).delete(recordingId);+ const frameStore = tx.objectStore(IDB_FRAMES_STORE);+ const idx = frameStore.index('recordingId');+ const cursorReq = idx.openCursor(IDBKeyRange.only(recordingId));+ cursorReq.onsuccess = () => {+ const cursor = cursorReq.result;+ if (cursor) {+ cursor.delete();+ cursor.continue();+ }+ };+ tx.oncomplete = () => resolve();+ tx.onerror = () => resolve();+ } catch {+ resolve();+ }+ });+}++// --- Unified Persistent Backend API ---++function sanitizeCaptureArea(raw: unknown): TimelapseCaptureArea {+ if (raw === 'canvas-view' || raw === 'app-window') return raw;+ return 'artwork';+}++function sanitizeCaptureResolution(raw: unknown): TimelapseCaptureResolution {+ if (raw === '720p' || raw === '1080p' || raw === '2k' || raw === '4k') return raw;+ return '1080p';+}++export async function persistSessionMeta(meta: PersistentTimelapseMeta): Promise<boolean> {+ if (isTauriRuntime()) {+ try {+ await invokeTauri('timelapse_save_meta', {+ sessionId: meta.recordingId,+ metaJson: JSON.stringify(meta),+ });+ return true;+ } catch {+ return false;+ }+ }+ return idbSaveMeta(meta);+}++export async function persistSingleFrame(+ recordingId: string,+ record: PersistentFrameRecord,+ bytes: Uint8Array,+ metaFallback?: PersistentTimelapseMeta+): Promise<boolean> {+ if (isTauriRuntime()) {+ try {+ const ext = record.mimeType === 'image/jpeg' ? 'jpg' : 'webp';+ const headers: Record<string, string> = {+ 'x-session-id': encodeURIComponent(recordingId),+ 'x-frame-index': String(record.index),+ 'x-ext': ext,+ 'x-timestamp': String(Math.max(0, Math.round(record.timestamp))),+ 'x-width': String(Math.max(2, Math.round(record.width))),+ 'x-height': String(Math.max(2, Math.round(record.height))),+ };+ if (record.captureArea) {+ headers['x-capture-area'] = encodeURIComponent(record.captureArea);+ }+ await invokeTauriRaw('timelapse_write_frame', bytes, headers);+ return true;+ } catch {+ return false;+ }+ }+ return idbWriteFrame(recordingId, record, bytes, metaFallback);+}++export async function loadPersistedSession(+ recordingId: string+): Promise<LoadedPersistentSession | null> {+ if (isTauriRuntime()) {+ try {+ const raw = await invokeTauri<{+ meta?: Record<string, unknown> | null;+ frames?: Array<Record<string, unknown>>;+ totalBytes?: number;+ }>('timelapse_load_session', { sessionId: recordingId });+ if (!raw) return null;+ const meta: PersistentTimelapseMeta | null = raw.meta+ ? {+ recordingId: String(raw.meta.recordingId || recordingId),+ documentName: String(raw.meta.documentName || ''),+ enabled: Boolean(raw.meta.enabled),+ captureArea: sanitizeCaptureArea(raw.meta.captureArea),+ captureResolution: sanitizeCaptureResolution(raw.meta.captureResolution),+ nextIndex: Math.max(0, Number(raw.meta.nextIndex) || 0),+ createdAt: Number(raw.meta.createdAt) || 0,+ updatedAt: Number(raw.meta.updatedAt) || 0,+ }+ : null;+ const frames: PersistentFrameRecord[] = Array.isArray(raw.frames)+ ? raw.frames.map((f) => ({+ index: Math.max(0, Number(f.index) || 0),+ timestamp: Number(f.timestamp) || 0,+ width: Math.max(0, Number(f.width) || 0),+ height: Math.max(0, Number(f.height) || 0),+ mimeType: f.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp',+ bytes: Math.max(0, Number(f.bytes) || 0),+ ...(f.captureArea ? { captureArea: sanitizeCaptureArea(f.captureArea) } : {}),+ }))+ : [];+ return {+ meta,+ frames,+ totalBytes: Math.max(0, Number(raw.totalBytes) || 0),+ };+ } catch {+ // Fallback to legacy `timelapse_list_frames` if running against an older backend mock+ try {+ const list = await invokeTauri<Array<[number, string]>>('timelapse_list_frames', {+ sessionId: recordingId,+ });+ const frames: PersistentFrameRecord[] = (list || []).map(([idx, ext]) => ({+ index: idx,+ timestamp: 0,+ width: 0,+ height: 0,+ mimeType: ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : 'image/webp',+ bytes: 0,+ }));+ return { meta: null, frames, totalBytes: 0 };+ } catch {+ return null;+ }+ }+ }+ return idbLoadSession(recordingId);+}++export async function readPersistedFrame(+ recordingId: string,+ index: number,+ mimeType: 'image/webp' | 'image/jpeg'+): Promise<Uint8Array | null> {+ if (isTauriRuntime()) {+ try {+ const raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>(+ 'timelapse_read_frame',+ undefined,+ {+ 'x-session-id': encodeURIComponent(recordingId),+ 'x-frame-index': String(index),+ 'x-ext': mimeType === 'image/jpeg' ? 'jpg' : 'webp',+ }+ );+ return new Uint8Array(toArrayBuffer(raw));+ } catch {+ return null;+ }+ }+ return idbReadFrame(recordingId, index);+}++export async function listPersistedRecordings(): Promise<StoredRecordingSummary[]> {+ if (isTauriRuntime()) {+ try {+ const rows = await invokeTauri<Array<Record<string, unknown>>>('timelapse_list_sessions', {});+ return (rows || []).map((r) => ({+ recordingId: String(r.recordingId || ''),+ documentName: String(r.documentName || 'Untitled'),+ enabled: Boolean(r.enabled),+ captureArea: sanitizeCaptureArea(r.captureArea),+ captureResolution: sanitizeCaptureResolution(r.captureResolution),+ frameCount: Math.max(0, Number(r.frameCount) || 0),+ totalBytes: Math.max(0, Number(r.totalBytes) || 0),+ createdAt: Number(r.createdAt) || 0,+ updatedAt: Number(r.updatedAt) || 0,+ }));+ } catch {+ return [];+ }+ }+ return idbListSessions();+}++export async function deletePersistedRecording(recordingId: string): Promise<void> {+ removeRecordingLinks(recordingId);+ if (isTauriRuntime()) {+ await invokeTauri('timelapse_clear', { sessionId: recordingId }).catch(() => {});+ return;+ }+ await idbClearSession(recordingId);+}diff --git a/src/utils/timelapseWatermark.ts b/src/utils/timelapseWatermark.tsnew file mode 100644index 0000000..028b3b0--- /dev/null+++ b/src/utils/timelapseWatermark.ts@@ -0,0 +1,447 @@+/**+ * Time-lapse Frame Compositor & Watermark Engine+ *+ * Shared WYSIWYG renderer used across:+ * 1. In-app preview player (modal + full-screen)+ * 2. MediaRecorder video export (.webm/.mp4)+ * 3. Transparent PNG overlay generation for native FFmpeg `.mp4` export+ */++import { canvasToBlob } from './saveManager';+import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';++export type TimelapseWatermarkMode = 'text' | 'image';+export type TimelapseWatermarkFontStyle = 'sans' | 'bold' | 'mono' | 'serif';+export type TimelapseWatermarkPosition =+ | 'top-left'+ | 'top-center'+ | 'top-right'+ | 'center'+ | 'bottom-left'+ | 'bottom-center'+ | 'bottom-right';++export type TimelapseBackgroundMode = 'white' | 'dark' | 'blur' | 'custom';++export interface TimelapseWatermarkConfig {+ enabled: boolean;+ mode: TimelapseWatermarkMode;+ text: string;+ fontStyle: TimelapseWatermarkFontStyle;+ textColor: string;+ showBackdrop: boolean;+ imageDataUrl: string | null;+ position: TimelapseWatermarkPosition;+ /** Size scale relative to output frame width (5..40, default 14). */+ scale: number;+ /** Opacity (0.1..1, default 0.78). */+ opacity: number;+ /** Edge padding percentage of shorter frame dimension (1..12, default 3). */+ margin: number;+}++export const DEFAULT_TIMELAPSE_WATERMARK: TimelapseWatermarkConfig = {+ enabled: false,+ mode: 'text',+ text: 'Ink Studio',+ fontStyle: 'sans',+ textColor: '#ffffff',+ showBackdrop: true,+ imageDataUrl: null,+ position: 'bottom-right',+ scale: 14,+ opacity: 0.78,+ margin: 3,+};++const WATERMARK_PREFS_LS_KEY = 'inkstudio_timelapse_watermark_v1';++export function sanitizeWatermarkConfig(+ raw: Partial<TimelapseWatermarkConfig> | null | undefined,+ fallbackText?: string+): TimelapseWatermarkConfig {+ const base: TimelapseWatermarkConfig = {+ ...DEFAULT_TIMELAPSE_WATERMARK,+ ...(fallbackText && fallbackText.trim() ? { text: fallbackText.trim() } : {}),+ };+ if (!raw || typeof raw !== 'object') return base;++ const mode: TimelapseWatermarkMode = raw.mode === 'image' ? 'image' : 'text';+ const fontStyle: TimelapseWatermarkFontStyle =+ raw.fontStyle === 'bold' || raw.fontStyle === 'mono' || raw.fontStyle === 'serif'+ ? raw.fontStyle+ : 'sans';+ const validPositions: TimelapseWatermarkPosition[] = [+ 'top-left',+ 'top-center',+ 'top-right',+ 'center',+ 'bottom-left',+ 'bottom-center',+ 'bottom-right',+ ];+ const position = validPositions.includes(raw.position as TimelapseWatermarkPosition)+ ? (raw.position as TimelapseWatermarkPosition)+ : base.position;++ const textColor =+ typeof raw.textColor === 'string' && /^#[0-9a-fA-F]{6}$/.test(raw.textColor.trim())+ ? raw.textColor.trim()+ : base.textColor;++ return {+ enabled: Boolean(raw.enabled),+ mode,+ text: typeof raw.text === 'string' ? raw.text.slice(0, 80) : base.text,+ fontStyle,+ textColor,+ showBackdrop: raw.showBackdrop !== false,+ imageDataUrl:+ typeof raw.imageDataUrl === 'string' && raw.imageDataUrl.startsWith('data:image/')+ ? raw.imageDataUrl+ : null,+ position,+ scale: Math.max(5, Math.min(40, Number(raw.scale) || base.scale)),+ opacity: Math.max(0.1, Math.min(1, Number(raw.opacity) || base.opacity)),+ margin: Math.max(0, Math.min(15, Number(raw.margin ?? base.margin))),+ };+}++export function loadSavedWatermarkConfig(fallbackText?: string): TimelapseWatermarkConfig {+ try {+ const raw = safeLocalStorageGetItem(WATERMARK_PREFS_LS_KEY);+ if (!raw) return sanitizeWatermarkConfig(null, fallbackText);+ return sanitizeWatermarkConfig(JSON.parse(raw), fallbackText);+ } catch {+ return sanitizeWatermarkConfig(null, fallbackText);+ }+}++export function saveWatermarkConfig(config: TimelapseWatermarkConfig): void {+ const clean = sanitizeWatermarkConfig(config);+ safeLocalStorageSetItem(WATERMARK_PREFS_LS_KEY, JSON.stringify(clean), 'timelapse watermark');+}++export function computeWatermarkPosition(+ frameW: number,+ frameH: number,+ boxW: number,+ boxH: number,+ position: TimelapseWatermarkPosition,+ marginPct: number+): { x: number; y: number } {+ const pad = Math.round(Math.min(frameW, frameH) * (Math.max(0, Math.min(20, marginPct)) / 100));+ let x = pad;+ let y = pad;++ if (position === 'top-center' || position === 'center' || position === 'bottom-center') {+ x = Math.round((frameW - boxW) * 0.5);+ } else if (position === 'top-right' || position === 'bottom-right') {+ x = Math.round(frameW - boxW - pad);+ }++ if (position === 'center') {+ y = Math.round((frameH - boxH) * 0.5);+ } else if (+ position === 'bottom-left' ||+ position === 'bottom-center' ||+ position === 'bottom-right'+ ) {+ y = Math.round(frameH - boxH - pad);+ }++ return {+ x: Math.max(0, Math.min(Math.max(0, frameW - boxW), x)),+ y: Math.max(0, Math.min(Math.max(0, frameH - boxH), y)),+ };+}++function resolveWatermarkFont(style: TimelapseWatermarkFontStyle, pxSize: number): string {+ const size = Math.max(10, Math.round(pxSize));+ switch (style) {+ case 'bold':+ return `800 ${size}px Inter, "Segoe UI", system-ui, sans-serif`;+ case 'mono':+ return `600 ${size}px "JetBrains Mono", "Cascadia Code", Consolas, monospace`;+ case 'serif':+ return `600 ${size}px Georgia, "Times New Roman", serif`;+ default:+ return `600 ${size}px Inter, "Segoe UI", system-ui, sans-serif`;+ }+}++function drawRoundedRectPath(+ ctx: CanvasRenderingContext2D,+ x: number,+ y: number,+ w: number,+ h: number,+ r: number+): void {+ const radius = Math.max(0, Math.min(r, Math.min(w, h) * 0.5));+ if (typeof ctx.roundRect === 'function') {+ ctx.beginPath();+ ctx.roundRect(x, y, w, h, radius);+ return;+ }+ ctx.beginPath();+ ctx.moveTo(x + radius, y);+ ctx.lineTo(x + w - radius, y);+ ctx.quadraticCurveTo(x + w, y, x + w, y + radius);+ ctx.lineTo(x + w, y + h - radius);+ ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);+ ctx.lineTo(x + radius, y + h);+ ctx.quadraticCurveTo(x, y + h, x, y + h - radius);+ ctx.lineTo(x, y + radius);+ ctx.quadraticCurveTo(x, y, x + radius, y);+ ctx.closePath();+}++export function loadWatermarkImageElement(dataUrl: string | null): Promise<HTMLImageElement | null> {+ if (!dataUrl || typeof Image === 'undefined') return Promise.resolve(null);+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => resolve(img);+ img.onerror = () => resolve(null);+ img.src = dataUrl;+ });+}++/**+ * Downscales an uploaded logo/signature image cleanly to <= 512px PNG data URL for persistence.+ */+export async function prepareWatermarkImageDataUrl(file: File): Promise<string> {+ const url = URL.createObjectURL(file);+ try {+ const img = await new Promise<HTMLImageElement>((resolve, reject) => {+ const el = new Image();+ el.onload = () => resolve(el);+ el.onerror = () => reject(new Error('Unsupported watermark image file'));+ el.src = url;+ });+ const maxDim = 512;+ const natW = Math.max(1, img.naturalWidth || img.width);+ const natH = Math.max(1, img.naturalHeight || img.height);+ const scale = Math.min(1, maxDim / Math.max(natW, natH));+ const w = Math.max(1, Math.round(natW * scale));+ const h = Math.max(1, Math.round(natH * scale));+ const c = document.createElement('canvas');+ c.width = w;+ c.height = h;+ const ctx = c.getContext('2d');+ if (!ctx) throw new Error('Failed to process watermark image');+ ctx.drawImage(img, 0, 0, w, h);+ return c.toDataURL('image/png');+ } finally {+ URL.revokeObjectURL(url);+ }+}++/**+ * Draws the configured watermark directly onto `ctx` at coordinates matching `frameW x frameH`.+ */+export function drawWatermarkOnContext(+ ctx: CanvasRenderingContext2D,+ frameW: number,+ frameH: number,+ config: TimelapseWatermarkConfig | null | undefined,+ loadedImage?: HTMLImageElement | null+): { x: number; y: number; width: number; height: number } | null {+ if (!config || !config.enabled || frameW <= 0 || frameH <= 0) return null;++ const opacity = Math.max(0.1, Math.min(1, config.opacity));+ const scaleFraction = Math.max(0.05, Math.min(0.4, config.scale / 100));++ if (config.mode === 'image' && loadedImage) {+ const natW = Math.max(1, loadedImage.naturalWidth || loadedImage.width);+ const natH = Math.max(1, loadedImage.naturalHeight || loadedImage.height);+ const targetW = Math.max(16, Math.round(frameW * scaleFraction));+ const ratio = targetW / natW;+ let drawW = targetW;+ let drawH = Math.max(16, Math.round(natH * ratio));+ const maxH = Math.round(frameH * 0.4);+ if (drawH > maxH) {+ const hScale = maxH / drawH;+ drawH = maxH;+ drawW = Math.max(16, Math.round(drawW * hScale));+ }++ const pos = computeWatermarkPosition(frameW, frameH, drawW, drawH, config.position, config.margin);+ ctx.save();+ ctx.globalAlpha = opacity;+ ctx.imageSmoothingEnabled = true;+ ctx.drawImage(loadedImage, pos.x, pos.y, drawW, drawH);+ ctx.restore();+ return { x: pos.x, y: pos.y, width: drawW, height: drawH };+ }++ const label = (config.text || '').trim();+ if (!label) return null;++ const fontSize = Math.max(12, Math.round(Math.min(frameW, frameH) * scaleFraction * 0.22));+ const font = resolveWatermarkFont(config.fontStyle, fontSize);++ ctx.save();+ ctx.font = font;+ ctx.textBaseline = 'middle';+ ctx.textAlign = 'left';++ const metrics = typeof ctx.measureText === 'function' ? ctx.measureText(label) : { width: label.length * fontSize * 0.6 };+ const textW = Math.ceil(metrics.width || label.length * fontSize * 0.6);+ const padX = config.showBackdrop ? Math.round(fontSize * 0.65) : Math.round(fontSize * 0.2);+ const padY = config.showBackdrop ? Math.round(fontSize * 0.36) : Math.round(fontSize * 0.15);+ const boxW = Math.min(frameW, textW + padX * 2);+ const boxH = Math.min(frameH, Math.round(fontSize * 1.25) + padY * 2);++ const pos = computeWatermarkPosition(frameW, frameH, boxW, boxH, config.position, config.margin);++ ctx.globalAlpha = opacity;+ if (config.showBackdrop) {+ // Pick contrasting subtle translucent pill so watermark remains crisp on both white and dark art+ const isDarkText = isColorDark(config.textColor);+ ctx.fillStyle = isDarkText ? 'rgba(255, 255, 255, 0.72)' : 'rgba(12, 12, 14, 0.58)';+ drawRoundedRectPath(ctx, pos.x, pos.y, boxW, boxH, Math.round(boxH * 0.28));+ ctx.fill();+ } else {+ ctx.shadowColor = isColorDark(config.textColor)+ ? 'rgba(255, 255, 255, 0.75)'+ : 'rgba(0, 0, 0, 0.78)';+ ctx.shadowBlur = Math.max(2, Math.round(fontSize * 0.18));+ ctx.shadowOffsetX = 0;+ ctx.shadowOffsetY = Math.max(1, Math.round(fontSize * 0.06));+ }++ ctx.fillStyle = config.textColor || '#ffffff';+ ctx.fillText(label, pos.x + padX, pos.y + boxH * 0.5 + 0.5, Math.max(1, boxW - padX * 2));+ ctx.restore();++ return { x: pos.x, y: pos.y, width: boxW, height: boxH };+}++function isColorDark(hex: string): boolean {+ const clean = (hex || '').replace('#', '').trim();+ if (clean.length !== 6) return false;+ const r = parseInt(clean.slice(0, 2), 16);+ const g = parseInt(clean.slice(2, 4), 16);+ const b = parseInt(clean.slice(4, 6), 16);+ if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return false;+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255 < 0.45;+}++/**+ * Generates a compact transparent PNG containing only the rendered watermark, plus its exact `(x, y)`+ * coordinates in the target output video frame, for FFmpeg `-filter_complex overlay=X:Y`.+ */+export async function renderWatermarkOverlayPng(+ frameW: number,+ frameH: number,+ config: TimelapseWatermarkConfig | null | undefined+): Promise<{ bytes: Uint8Array; x: number; y: number } | null> {+ if (!config || !config.enabled || typeof document === 'undefined') return null;++ const loadedImg =+ config.mode === 'image' && config.imageDataUrl+ ? await loadWatermarkImageElement(config.imageDataUrl)+ : null;+ if (config.mode === 'image' && !loadedImg) return null;+ if (config.mode === 'text' && !config.text.trim()) return null;++ const full = document.createElement('canvas');+ full.width = Math.max(2, frameW);+ full.height = Math.max(2, frameH);+ const ctx = full.getContext('2d');+ if (!ctx) return null;++ const rect = drawWatermarkOnContext(ctx, full.width, full.height, config, loadedImg);+ if (!rect) return null;++ // Crop strictly around the watermark bounding box (+ shadow margin) so PNG is tiny (~3-20 KB)+ const pad = config.showBackdrop ? 4 : 14;+ const cx = Math.max(0, Math.floor(rect.x - pad));+ const cy = Math.max(0, Math.floor(rect.y - pad));+ const cw = Math.max(2, Math.min(full.width - cx, Math.ceil(rect.width + pad * 2)));+ const ch = Math.max(2, Math.min(full.height - cy, Math.ceil(rect.height + pad * 2)));++ const cropped = document.createElement('canvas');+ cropped.width = cw;+ cropped.height = ch;+ const cCtx = cropped.getContext('2d');+ if (!cCtx) return null;+ cCtx.drawImage(full, cx, cy, cw, ch, 0, 0, cw, ch);++ const blob = await canvasToBlob(cropped, 'image/png');+ const buf = await blob.arrayBuffer();+ return { bytes: new Uint8Array(buf), x: cx, y: cy };+}++export interface RenderOutputFrameOptions {+ backgroundMode?: TimelapseBackgroundMode;+ backgroundColor?: string;+ watermark?: TimelapseWatermarkConfig | null;+ watermarkImage?: HTMLImageElement | null;+}++/**+ * Renders a single decoded keyframe (`HTMLImageElement` or `ImageBitmap`) onto an output canvas+ * with exact aspect-ratio letterboxing (solid or blurred backdrop) and optional watermark.+ */+export function renderTimelapseOutputFrame(+ ctx: CanvasRenderingContext2D,+ source: HTMLImageElement | ImageBitmap | HTMLCanvasElement | null,+ targetW: number,+ targetH: number,+ options: RenderOutputFrameOptions = {}+): void {+ const bgMode = options.backgroundMode ?? 'white';+ const bgColor =+ options.backgroundColor ||+ (bgMode === 'dark' ? '#141414' : '#ffffff');++ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalAlpha = 1;+ ctx.globalCompositeOperation = 'source-over';+ ctx.filter = 'none';++ ctx.fillStyle = bgMode === 'blur' ? '#141414' : bgColor;+ ctx.fillRect(0, 0, targetW, targetH);++ if (source) {+ const srcW = Math.max(+ 1,+ 'naturalWidth' in source ? source.naturalWidth || source.width : source.width+ );+ const srcH = Math.max(+ 1,+ 'naturalHeight' in source ? source.naturalHeight || source.height : source.height+ );++ const fitScale = Math.min(targetW / srcW, targetH / srcH);+ const drawW = srcW * fitScale;+ const drawH = srcH * fitScale;+ const dx = (targetW - drawW) * 0.5;+ const dy = (targetH - drawH) * 0.5;++ // Optional blurred cover backdrop when aspect ratios differ+ if (bgMode === 'blur' && (Math.abs(drawW - targetW) > 2 || Math.abs(drawH - targetH) > 2)) {+ const coverScale = Math.max(targetW / srcW, targetH / srcH) * 1.08;+ const bw = srcW * coverScale;+ const bh = srcH * coverScale;+ const bx = (targetW - bw) * 0.5;+ const by = (targetH - bh) * 0.5;+ ctx.save();+ ctx.filter = `blur(${Math.max(8, Math.round(Math.min(targetW, targetH) * 0.025))}px) brightness(0.68)`;+ ctx.drawImage(source, bx, by, bw, bh);+ ctx.restore();+ }++ ctx.imageSmoothingEnabled = true;+ ctx.drawImage(source, dx, dy, drawW, drawH);+ }++ if (options.watermark?.enabled) {+ drawWatermarkOnContext(ctx, targetW, targetH, options.watermark, options.watermarkImage);+ }++ ctx.restore();+}diff --git a/src/utils/vectorLayerRenderer.ts b/src/utils/vectorLayerRenderer.tsindex 905242b..20f95f2 100644--- a/src/utils/vectorLayerRenderer.ts+++ b/src/utils/vectorLayerRenderer.ts@@ -22,12 +22,16 @@ export function renderTextLayerData(writingMode: textData.writingMode || 'horizontal-tb',bold: textData.bold,italic: textData.italic,+ underline: textData.underline,align: textData.align,color: textData.color,outline: textData.outline,outlineColor: textData.outlineColor,outlineWidth: textData.outlineWidth,lineHeightRatio: textData.lineSpacing,+ letterSpacing: textData.letterSpacing,+ opacity: textData.opacity,+ maxWidth: textData.maxWidth,anchorTopLeft: true,});}@@ -57,15 +61,18 @@ export function getTextLayerBounds(textData: TextLayerData): {writingMode: textData.writingMode || 'horizontal-tb',bold: textData.bold,italic: textData.italic,+ underline: textData.underline,align: textData.align,lineHeightRatio: textData.lineSpacing,+ letterSpacing: textData.letterSpacing,+ maxWidth: textData.maxWidth,anchorTopLeft: true,});return {x: textData.x,y: textData.y,- width: Math.max(24, layout.width + 16),- height: Math.max(24, layout.height + 16),+ width: Math.max(24, Math.ceil(layout.width)),+ height: Math.max(24, Math.ceil(layout.height)),};}diff --git a/src/utils/webtoonExporter.ts b/src/utils/webtoonExporter.tsindex 9cdda92..b7e0315 100644--- a/src/utils/webtoonExporter.ts+++ b/src/utils/webtoonExporter.ts@@ -10,6 +10,7 @@import { zipSync } from 'fflate';import { releaseTemporaryCanvas } from './tileEngine';+import { saveFileWithDialog, SaveFileDialogResult } from './fileSaveDialog';export interface WebtoonSliceOptions {sliceWidth?: number;@@ -182,6 +183,24 @@ export async function exportWebtoonChapterZipFromRenderer(}}+/**+ * Prompts the user to choose where to save the generated Webtoon ZIP package.+ */+export async function saveWebtoonZipWithDialog(+ zipBytes: Uint8Array,+ filename = 'webtoon_chapter.zip'+): Promise<SaveFileDialogResult> {+ return saveFileWithDialog({+ data: zipBytes,+ suggestedName: filename,+ mimeType: 'application/zip',+ description: 'Webtoon Slices Archive',+ extensions: ['.zip'],+ category: 'webtoon',+ title: 'Save Webtoon Slices As',+ });+}+/*** Triggers a browser download of the generated Webtoon ZIP package.*/